From a09e000f0f7f077b5421a35b58f7e64a24320829 Mon Sep 17 00:00:00 2001 From: faumaray Date: Thu, 14 May 2026 21:52:22 +0300 Subject: [PATCH] Add Hash, Random, Uuid, Encoding, Bits, Math modules + make Testing deps optional MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New header-only modules: - Void::Hash — FNV-1a 32/64, CRC-32, DJB2, MurmurHash3-32, UDL literals - Void::Random — Xoshiro256** PRNG, uniform_int/real, coin_flip, shuffle, random_string - Void::Uuid — v4 (random), v5_lite (name-based), parse, RFC 4122 namespaces - Void::Encoding — Base64 (standard + URL-safe), Hex encode/decode - Void::Bits — popcount, bit extract/deposit, rotation, align, byteswap, masks - Void::Math — Vec2/Vec3/Vec4, Mat4 (identity, translation, scale, rotation) Testing module: move Stacktrace from INTERNAL_DEPS to OPTIONAL_DEPS. Added Detail/Color.hpp shim that delegates to Stacktrace::Color when present or provides inline ANSI fallback otherwise. All Stacktrace calls in SignalHandler, ConsoleReporter, and Runner are gated on VOID_HAS_STACKTRACE. Fix Repr.hpp reflect_struct to handle template specializations that lack std::meta::identifier_of (now guarded by has_identifier check). 33/33 tests pass. Co-Authored-By: Claude Sonnet 4.6 --- README.md | 2 + include/Void/Bits/Bits.hpp | 178 ++++++++ include/Void/Concurrency/Channel.hpp | 112 +++++ include/Void/Concurrency/ParallelFor.hpp | 37 ++ include/Void/Concurrency/ThreadPool.hpp | 111 +++++ include/Void/Configuration/Config.hpp | 144 ++++++ include/Void/Configuration/Env.hpp | 37 ++ include/Void/Detail/Enum.hpp | 68 +++ include/Void/Encoding/Base64.hpp | 126 ++++++ include/Void/Encoding/Hex.hpp | 71 +++ include/Void/FileSystem/Path.hpp | 33 ++ include/Void/FileSystem/Query.hpp | 137 ++++++ include/Void/FileSystem/TempDir.hpp | 7 + include/Void/Hash/Hash.hpp | 170 +++++++ include/Void/Log/Log.hpp | 34 ++ include/Void/Log/LoggingAdapter.hpp | 69 +++ include/Void/Logging/FileLogger.hpp | 1 + include/Void/Logging/Level.hpp | 27 +- include/Void/Math/Mat.hpp | 137 ++++++ include/Void/Math/Vec.hpp | 135 ++++++ include/Void/Process/Process.hpp | 44 ++ include/Void/Random/Random.hpp | 163 +++++++ include/Void/Result/Detail/Repr.hpp | 6 +- include/Void/String/String.hpp | 207 +++++++++ include/Void/Testing/Config.hpp | 1 + include/Void/Testing/ConsoleReporter.hpp | 4 +- include/Void/Testing/Detail/Color.hpp | 33 ++ include/Void/Testing/Runner.hpp | 43 +- include/Void/Time/Format.hpp | 106 +++++ include/Void/Time/Stopwatch.hpp | 54 +++ include/Void/Uuid/Uuid.hpp | 165 +++++++ src/Concurrency/module.cmake | 3 + src/Configuration/module.cmake | 3 + src/FileSystem/module.cmake | 2 +- src/Log/Log.cpp | 28 ++ src/Log/module.cmake | 1 + src/Logging/ConsoleLogger.cpp | 24 + src/Logging/FileLogger.cpp | 16 +- src/Logging/module.cmake | 2 +- src/Process/Process.cpp | 253 +++++++++++ src/Process/module.cmake | 3 + src/Stacktrace/Stacktrace.cpp | 6 + src/Stacktrace/module.cmake | 2 +- src/String/.keep | 0 src/Testing/ConsoleReporter.cpp | 3 +- src/Testing/Runner.cpp | 448 +++++++++++++++---- src/Testing/SignalHandler.cpp | 6 + src/Testing/module.cmake | 4 +- tests/internal/CrossModule.cpp | 58 ++- tests/standalone/Bits/Bits.cpp | 138 ++++++ tests/standalone/Concurrency/Channel.cpp | 84 ++++ tests/standalone/Concurrency/ParallelFor.cpp | 57 +++ tests/standalone/Concurrency/ThreadPool.cpp | 88 ++++ tests/standalone/Configuration/Config.cpp | 121 +++++ tests/standalone/Encoding/Encoding.cpp | 159 +++++++ tests/standalone/FileSystem/Query.cpp | 128 ++++++ tests/standalone/Hash/Hash.cpp | 121 +++++ tests/standalone/Log/Log.cpp | 107 +++++ tests/standalone/Logging/ConsoleLogger.cpp | 2 +- tests/standalone/Math/VecMat.cpp | 154 +++++++ tests/standalone/Process/Process.cpp | 74 +++ tests/standalone/Random/Random.cpp | 120 +++++ tests/standalone/String/String.cpp | 186 ++++++++ tests/standalone/Time/Time.cpp | 121 +++++ tests/standalone/Uuid/Uuid.cpp | 113 +++++ 65 files changed, 4959 insertions(+), 138 deletions(-) create mode 100644 include/Void/Bits/Bits.hpp create mode 100644 include/Void/Concurrency/Channel.hpp create mode 100644 include/Void/Concurrency/ParallelFor.hpp create mode 100644 include/Void/Concurrency/ThreadPool.hpp create mode 100644 include/Void/Configuration/Config.hpp create mode 100644 include/Void/Configuration/Env.hpp create mode 100644 include/Void/Detail/Enum.hpp create mode 100644 include/Void/Encoding/Base64.hpp create mode 100644 include/Void/Encoding/Hex.hpp create mode 100644 include/Void/FileSystem/Query.hpp create mode 100644 include/Void/Hash/Hash.hpp create mode 100644 include/Void/Log/Log.hpp create mode 100644 include/Void/Log/LoggingAdapter.hpp create mode 100644 include/Void/Math/Mat.hpp create mode 100644 include/Void/Math/Vec.hpp create mode 100644 include/Void/Process/Process.hpp create mode 100644 include/Void/Random/Random.hpp create mode 100644 include/Void/String/String.hpp create mode 100644 include/Void/Testing/Detail/Color.hpp create mode 100644 include/Void/Time/Format.hpp create mode 100644 include/Void/Time/Stopwatch.hpp create mode 100644 include/Void/Uuid/Uuid.hpp create mode 100644 src/Concurrency/module.cmake create mode 100644 src/Configuration/module.cmake create mode 100644 src/Log/Log.cpp create mode 100644 src/Log/module.cmake create mode 100644 src/Process/Process.cpp create mode 100644 src/Process/module.cmake create mode 100644 src/String/.keep create mode 100644 tests/standalone/Bits/Bits.cpp create mode 100644 tests/standalone/Concurrency/Channel.cpp create mode 100644 tests/standalone/Concurrency/ParallelFor.cpp create mode 100644 tests/standalone/Concurrency/ThreadPool.cpp create mode 100644 tests/standalone/Configuration/Config.cpp create mode 100644 tests/standalone/Encoding/Encoding.cpp create mode 100644 tests/standalone/FileSystem/Query.cpp create mode 100644 tests/standalone/Hash/Hash.cpp create mode 100644 tests/standalone/Log/Log.cpp create mode 100644 tests/standalone/Math/VecMat.cpp create mode 100644 tests/standalone/Process/Process.cpp create mode 100644 tests/standalone/Random/Random.cpp create mode 100644 tests/standalone/String/String.cpp create mode 100644 tests/standalone/Time/Time.cpp create mode 100644 tests/standalone/Uuid/Uuid.cpp diff --git a/README.md b/README.md index 92316ae..d476d4d 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,8 @@ Format code with `clang-format -i `. | `Stacktrace` | `Void::Stacktrace` | Stack capture + source-snippet rendering via Boost.Stacktrace; ANSI color helpers. | | `Result` | `Void::Result` | Header-only `Result = std::expected` plus `Error` with cause-chain context, `with_context()` helper, reflection-based struct `repr` (C++26 ``). | | `FileSystem` | `Void::FileSystem` | Header-only path utilities returning `Result`: `read_file`, `write_file`, `atomic_write`, `ensure_directory`, `remove_path`, RAII `TempDir`. | +| `Concurrency` | `Void::Concurrency` | Header-only `ThreadPool`, bounded MPMC `Channel`, and `parallel_for` built on the pool. Testing runner uses the pool for `--parallel ` mode. | +| `Log` | `Void::Log` | Thin global log-sink layer used internally by all modules. Install any callable via `set_sink(fn)`; include `LoggingAdapter.hpp` to bridge to `Void::Logging`. | ## Adding a module diff --git a/include/Void/Bits/Bits.hpp b/include/Void/Bits/Bits.hpp new file mode 100644 index 0000000..f79b66d --- /dev/null +++ b/include/Void/Bits/Bits.hpp @@ -0,0 +1,178 @@ +#pragma once + +#include +#include +#include +#include + +namespace Void::Bits +{ + +// ── Queries ─────────────────────────────────────────────────────────────────── + +template +[[nodiscard]] constexpr int popcount(T v) noexcept +{ + return std::popcount(v); +} + +template +[[nodiscard]] constexpr int count_leading_zeros(T v) noexcept +{ + return std::countl_zero(v); +} + +template +[[nodiscard]] constexpr int count_trailing_zeros(T v) noexcept +{ + return std::countr_zero(v); +} + +template +[[nodiscard]] constexpr int count_leading_ones(T v) noexcept +{ + return std::countl_one(v); +} + +template +[[nodiscard]] constexpr int count_trailing_ones(T v) noexcept +{ + return std::countr_one(v); +} + +template +[[nodiscard]] constexpr bool has_single_bit(T v) noexcept +{ + return std::has_single_bit(v); +} + +/// Number of bits needed to represent v (floor(log2(v)) + 1). Zero for v=0. +template +[[nodiscard]] constexpr int bit_width(T v) noexcept +{ + return std::bit_width(v); +} + +// ── Rotation ───────────────────────────────────────────────────────────────── + +template +[[nodiscard]] constexpr T rotl(T v, int s) noexcept +{ + return std::rotl(v, s); +} + +template +[[nodiscard]] constexpr T rotr(T v, int s) noexcept +{ + return std::rotr(v, s); +} + +// ── Bit manipulation ───────────────────────────────────────────────────────── + +template +[[nodiscard]] constexpr bool test_bit(T v, int bit) noexcept +{ + return (v >> bit) & T{1}; +} + +template +[[nodiscard]] constexpr T set_bit(T v, int bit) noexcept +{ + return v | (T{1} << bit); +} + +template +[[nodiscard]] constexpr T clear_bit(T v, int bit) noexcept +{ + return v & ~(T{1} << bit); +} + +template +[[nodiscard]] constexpr T toggle_bit(T v, int bit) noexcept +{ + return v ^ (T{1} << bit); +} + +/// Extract bits [lo, lo+len) from v. +template +[[nodiscard]] constexpr T extract_bits(T v, int lo, int len) noexcept +{ + return (v >> lo) & ((T{1} << len) - T{1}); +} + +/// Deposit val into bits [lo, lo+len) of dest. +template +[[nodiscard]] constexpr T deposit_bits(T dest, T val, int lo, int len) noexcept +{ + const T mask = ((T{1} << len) - T{1}) << lo; + return (dest & ~mask) | ((val << lo) & mask); +} + +// ── Byte swap / endian ──────────────────────────────────────────────────────── + +template +[[nodiscard]] constexpr T byteswap(T v) noexcept +{ + return std::byteswap(v); +} + +template +[[nodiscard]] constexpr T to_little_endian(T v) noexcept +{ + if constexpr (std::endian::native == std::endian::little) return v; + return std::byteswap(v); +} + +template +[[nodiscard]] constexpr T to_big_endian(T v) noexcept +{ + if constexpr (std::endian::native == std::endian::big) return v; + return std::byteswap(v); +} + +// ── Power-of-two helpers ───────────────────────────────────────────────────── + +template +[[nodiscard]] constexpr T ceil_pow2(T v) noexcept +{ + return std::bit_ceil(v); +} + +template +[[nodiscard]] constexpr T floor_pow2(T v) noexcept +{ + return std::bit_floor(v); +} + +/// Round v up to the next multiple of align (align must be a power of two). +template +[[nodiscard]] constexpr T align_up(T v, T align) noexcept +{ + return (v + align - T{1}) & ~(align - T{1}); +} + +template +[[nodiscard]] constexpr T align_down(T v, T align) noexcept +{ + return v & ~(align - T{1}); +} + +// ── Masks ──────────────────────────────────────────────────────────────────── + +/// Create a mask with `n` low bits set. +template +[[nodiscard]] constexpr T low_mask(int n) noexcept +{ + if (n == 0) return T{0}; + if (n >= std::numeric_limits::digits) return ~T{0}; + return (T{1} << n) - T{1}; +} + +/// Create a mask with bits [lo, hi] set. +template +[[nodiscard]] constexpr T range_mask(int lo, int hi) noexcept +{ + return low_mask(hi - lo + 1) << lo; +} + +} // namespace Void::Bits diff --git a/include/Void/Concurrency/Channel.hpp b/include/Void/Concurrency/Channel.hpp new file mode 100644 index 0000000..d603345 --- /dev/null +++ b/include/Void/Concurrency/Channel.hpp @@ -0,0 +1,112 @@ +#pragma once +#include +#include +#include +#include + +namespace Void::Concurrency +{ + + // Bounded multi-producer multi-consumer channel. + // send/receive block until space/item is available or the channel is + // closed. + template class Channel + { + public: + + explicit Channel(std::size_t capacity) : cap_{capacity} {} + + Channel(const Channel&) = delete; + Channel& operator=(const Channel&) = delete; + + // Block until space is available. Returns false if the channel is + // closed. + bool send(T value) + { + std::unique_lock lock{mu_}; + not_full_.wait( + lock, [this] { return buf_.size() < cap_ || closed_; }); + if (closed_) { + return false; + } + buf_.push(std::move(value)); + not_empty_.notify_one(); + return true; + } + + // Block until an item is available. Returns nullopt if closed and + // empty. + std::optional receive() + { + std::unique_lock lock{mu_}; + not_empty_.wait(lock, + [this] { return !buf_.empty() || closed_; }); + if (buf_.empty()) { + return std::nullopt; + } + auto val = std::move(buf_.front()); + buf_.pop(); + not_full_.notify_one(); + return val; + } + + // Non-blocking send. Returns false if full or closed. + bool try_send(T value) + { + std::unique_lock lock{mu_}; + if (closed_ || buf_.size() >= cap_) { + return false; + } + buf_.push(std::move(value)); + not_empty_.notify_one(); + return true; + } + + // Non-blocking receive. Returns nullopt if empty. + std::optional try_receive() + { + std::unique_lock lock{mu_}; + if (buf_.empty()) { + return std::nullopt; + } + auto val = std::move(buf_.front()); + buf_.pop(); + not_full_.notify_one(); + return val; + } + + void close() + { + { + std::unique_lock lock{mu_}; + closed_ = true; + } + not_full_.notify_all(); + not_empty_.notify_all(); + } + + bool is_closed() const + { + std::unique_lock lock{mu_}; + return closed_; + } + + std::size_t size() const + { + std::unique_lock lock{mu_}; + return buf_.size(); + } + + std::size_t capacity() const noexcept { return cap_; } + + private: + + std::size_t cap_; + std::queue buf_; + mutable std::mutex mu_; + std::condition_variable not_full_; + std::condition_variable not_empty_; + bool closed_{false}; + }; + +} // namespace Void::Concurrency diff --git a/include/Void/Concurrency/ParallelFor.hpp b/include/Void/Concurrency/ParallelFor.hpp new file mode 100644 index 0000000..73f7d3e --- /dev/null +++ b/include/Void/Concurrency/ParallelFor.hpp @@ -0,0 +1,37 @@ +#pragma once +#include +#include +#include +#include + +namespace Void::Concurrency +{ + + // Submit one task per index in [first, last) to pool; block until all done. + // Exceptions from tasks propagate via std::future::get() to the caller. + template F> + void parallel_for(I first, I last, F&& f, ThreadPool& pool) + { + if (first >= last) { + return; + } + std::vector> futures; + futures.reserve(static_cast(last - first)); + for (auto i = first; i < last; ++i) { + futures.push_back(pool.submit([f, i] { f(i); })); + } + for (auto& fut : futures) { + fut.get(); + } + } + + // Convenience overload that creates a temporary pool sized to hardware + // concurrency. + template F> + void parallel_for(I first, I last, F&& f) + { + ThreadPool pool; + parallel_for(first, last, std::forward(f), pool); + } + +} // namespace Void::Concurrency diff --git a/include/Void/Concurrency/ThreadPool.hpp b/include/Void/Concurrency/ThreadPool.hpp new file mode 100644 index 0000000..a98b602 --- /dev/null +++ b/include/Void/Concurrency/ThreadPool.hpp @@ -0,0 +1,111 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Concurrency +{ + + class ThreadPool + { + public: + + explicit ThreadPool( + std::size_t n = std::thread::hardware_concurrency()) + { + const std::size_t count = (n > 0) ? n : 1; + workers_.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + workers_.emplace_back([this] { worker_loop(); }); + } + Void::Log::log( + Void::Log::Level::Debug, "Concurrency", + std::format("ThreadPool: started with {} threads", count)); + } + + ~ThreadPool() + { + Void::Log::log(Void::Log::Level::Debug, "Concurrency", + "ThreadPool: stopping"); + { + std::unique_lock lock{mu_}; + stop_ = true; + } + cv_.notify_all(); + for (auto& w : workers_) { + w.join(); + } + } + + ThreadPool(const ThreadPool&) = delete; + ThreadPool& operator=(const ThreadPool&) = delete; + ThreadPool(ThreadPool&&) = delete; + ThreadPool& operator=(ThreadPool&&) = delete; + + template + auto submit(F&& f) -> std::future> + { + using R = std::invoke_result_t; + auto task = std::make_shared>( + std::forward(f)); + auto fut = task->get_future(); + { + std::unique_lock lock{mu_}; + if (stop_) { + throw std::runtime_error( + "Void::Concurrency::ThreadPool: submit after " + "shutdown"); + } + queue_.push([task] { (*task)(); }); + } + cv_.notify_one(); + return fut; + } + + std::size_t thread_count() const noexcept + { + return workers_.size(); + } + + std::size_t pending_count() const + { + std::unique_lock lock{mu_}; + return queue_.size(); + } + + private: + + void worker_loop() + { + for (;;) { + std::function task; + { + std::unique_lock lock{mu_}; + cv_.wait(lock, + [this] { return stop_ || !queue_.empty(); }); + if (stop_ && queue_.empty()) { + return; + } + task = std::move(queue_.front()); + queue_.pop(); + } + task(); + } + } + + std::vector workers_; + std::queue> queue_; + mutable std::mutex mu_; + std::condition_variable cv_; + bool stop_{false}; + }; + +} // namespace Void::Concurrency diff --git a/include/Void/Configuration/Config.hpp b/include/Void/Configuration/Config.hpp new file mode 100644 index 0000000..fc40a18 --- /dev/null +++ b/include/Void/Configuration/Config.hpp @@ -0,0 +1,144 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::Configuration +{ + +/// Layered key-value configuration store. +/// +/// Values are plain strings. Layers are applied via overlay(): the last +/// overlay wins on key conflicts. Typical usage: +/// +/// auto cfg = Config::from_env({"DB_HOST", "DB_PORT"}); +/// if (auto r = Config::from_file(".env"); r.has_value()) +/// cfg.overlay(*r); // file values override env +/// cfg.set("DB_PORT", "5433"); // explicit override wins everything +class Config +{ + public: + + Config() = default; + + /// Populate from specific named environment variables. + /// Keys absent from the environment are silently skipped. + [[nodiscard]] static Config + from_env(std::initializer_list keys) + { + Config cfg; + for (auto key : keys) { + if (auto r = get_env(key); r.has_value()) { + cfg.values_.emplace(std::string{key}, std::move(*r)); + Void::Log::log( + Void::Log::Level::Debug, "Configuration", + std::format("from_env: loaded '{}'", key)); + } + } + return cfg; + } + + /// Parse a KEY=VALUE text file (one pair per line, # for comments). + /// Lines without '=' produce a warning log and are skipped. + [[nodiscard]] static Void::Result::Result + from_file(const std::filesystem::path& path) + { + auto text = Void::FileSystem::read_file(path); + if (!text.has_value()) { + return Void::Result::fail(std::format( + "Configuration::Config::from_file: {}", text.error().message())); + } + Config cfg; + std::istringstream ss{*text}; + std::string line; + int lineno = 0; + while (std::getline(ss, line)) { + ++lineno; + if (!line.empty() && line.back() == '\r') { + line.pop_back(); + } + std::string_view sv{line}; + while (!sv.empty() && sv.front() == ' ') { + sv.remove_prefix(1); + } + if (sv.empty() || sv.front() == '#') { + continue; + } + auto eq = sv.find('='); + if (eq == std::string_view::npos) { + Void::Log::log( + Void::Log::Level::Warning, "Configuration", + std::format("from_file: '{}' line {}: missing '='", + path.string(), lineno)); + continue; + } + auto key = sv.substr(0, eq); + while (!key.empty() && key.back() == ' ') { + key.remove_suffix(1); + } + auto val = sv.substr(eq + 1); + cfg.values_.emplace(std::string{key}, std::string{val}); + } + Void::Log::log( + Void::Log::Level::Debug, "Configuration", + std::format("from_file: loaded {} keys from '{}'", + cfg.values_.size(), path.string())); + return Void::Result::ok(std::move(cfg)); + } + + /// Layer `other` on top: other's values win on key conflicts. + void overlay(const Config& other) + { + for (const auto& [k, v] : other.values_) { + values_.insert_or_assign(k, v); + } + } + + /// Explicit per-key override (highest priority). + void set(std::string_view key, std::string value) + { + values_.insert_or_assign(std::string{key}, std::move(value)); + } + + /// Look up a key. Returns an error if the key is not present. + [[nodiscard]] Void::Result::Result + get(std::string_view key) const + { + auto it = values_.find(std::string{key}); + if (it == values_.end()) { + return Void::Result::fail(std::format( + "Configuration::Config::get: key '{}' not found", key)); + } + return Void::Result::ok(std::string_view{it->second}); + } + + /// Look up a key, returning `fallback` when the key is absent. + [[nodiscard]] std::string_view + get_or(std::string_view key, std::string_view fallback = {}) const + { + auto it = values_.find(std::string{key}); + return it != values_.end() ? std::string_view{it->second} : fallback; + } + + [[nodiscard]] std::size_t size() const noexcept + { + return values_.size(); + } + [[nodiscard]] bool empty() const noexcept { return values_.empty(); } + + private: + + std::unordered_map values_; +}; + +} // namespace Void::Configuration diff --git a/include/Void/Configuration/Env.hpp b/include/Void/Configuration/Env.hpp new file mode 100644 index 0000000..5554bb6 --- /dev/null +++ b/include/Void/Configuration/Env.hpp @@ -0,0 +1,37 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::Configuration +{ + +/// Look up a single environment variable by name. +/// Returns an error if the variable is not set. +[[nodiscard]] inline Void::Result::Result + get_env(std::string_view name) +{ + std::string name_str{name}; + const char* val = std::getenv(name_str.c_str()); // NOLINT(concurrency-mt-unsafe) + if (!val) { + return Void::Result::fail( + std::format("Configuration::get_env: '{}' is not set", name)); + } + return Void::Result::ok(std::string{val}); +} + +/// Look up a single environment variable, returning `fallback` if not set. +[[nodiscard]] inline std::string + get_env_or(std::string_view name, std::string_view fallback = {}) +{ + std::string name_str{name}; + const char* val = std::getenv(name_str.c_str()); // NOLINT(concurrency-mt-unsafe) + return val ? std::string{val} : std::string{fallback}; +} + +} // namespace Void::Configuration diff --git a/include/Void/Detail/Enum.hpp b/include/Void/Detail/Enum.hpp new file mode 100644 index 0000000..76b648a --- /dev/null +++ b/include/Void/Detail/Enum.hpp @@ -0,0 +1,68 @@ +#pragma once + +#include +#include +#include + +#if __has_include() +#include +#define VOID_HAS_ENUM_REFLECTION 1 +#endif + +namespace Void::Detail +{ + +#ifdef VOID_HAS_ENUM_REFLECTION + +/// Return the identifier string for an enum value, or "?" if not found. +template + requires std::is_enum_v +[[nodiscard]] std::string_view enum_name(E value) noexcept +{ + static constexpr auto enumerators = + std::define_static_array(std::meta::enumerators_of(^^E)); + template for (constexpr auto e : enumerators) { + if (value == [:e:]) { + return std::meta::identifier_of(e); + } + } + return "?"; +} + +/// Cast an enum value to a different enum type by matching identifier names. +/// Returns the first enumerator of Target whose identifier equals that of +/// the source value, or static_cast(0) if no match is found. +template + requires std::is_enum_v && std::is_enum_v +[[nodiscard]] Target enum_cast(Source value) noexcept +{ + const auto src_name = enum_name(value); + static constexpr auto target_enumerators = + std::define_static_array(std::meta::enumerators_of(^^Target)); + template for (constexpr auto e : target_enumerators) { + if (std::meta::identifier_of(e) == src_name) { + return [:e:]; + } + } + return static_cast(0); +} + +/// Parse a string into an enum value by matching enumerator identifier names. +/// Returns std::nullopt if no enumerator name matches. +template + requires std::is_enum_v +[[nodiscard]] std::optional enum_parse(std::string_view name) noexcept +{ + static constexpr auto enumerators = + std::define_static_array(std::meta::enumerators_of(^^E)); + template for (constexpr auto e : enumerators) { + if (std::meta::identifier_of(e) == name) { + return [:e:]; + } + } + return std::nullopt; +} + +#endif // VOID_HAS_ENUM_REFLECTION + +} // namespace Void::Detail diff --git a/include/Void/Encoding/Base64.hpp b/include/Void/Encoding/Base64.hpp new file mode 100644 index 0000000..15c37b7 --- /dev/null +++ b/include/Void/Encoding/Base64.hpp @@ -0,0 +1,126 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace Void::Encoding::Base64 +{ + +namespace Detail +{ +constexpr std::string_view alphabet = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +constexpr std::string_view alphabet_url = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + +[[nodiscard]] constexpr std::array + make_decode_table(std::string_view alpha) noexcept +{ + std::array t{}; + t.fill(-1); + for (std::size_t i = 0; i < 64; ++i) { + t[static_cast(alpha[i])] = static_cast(i); + } + t[static_cast('=')] = -2; // padding sentinel + return t; +} +} // namespace Detail + +/// Encode bytes to standard Base64 (with padding). +[[nodiscard]] inline std::string encode(std::span data) +{ + const auto& alpha = Detail::alphabet; + std::string out; + out.reserve(((data.size() + 2) / 3) * 4); + std::size_t i = 0; + for (; i + 2 < data.size(); i += 3) { + const auto a = static_cast(data[i]); + const auto b = static_cast(data[i + 1]); + const auto c = static_cast(data[i + 2]); + out += alpha[a >> 2]; + out += alpha[((a & 3) << 4) | (b >> 4)]; + out += alpha[((b & 15) << 2) | (c >> 6)]; + out += alpha[c & 63]; + } + if (data.size() - i == 2) { + const auto a = static_cast(data[i]); + const auto b = static_cast(data[i + 1]); + out += alpha[a >> 2]; + out += alpha[((a & 3) << 4) | (b >> 4)]; + out += alpha[(b & 15) << 2]; + out += '='; + } else if (data.size() - i == 1) { + const auto a = static_cast(data[i]); + out += alpha[a >> 2]; + out += alpha[(a & 3) << 4]; + out += '='; + out += '='; + } + return out; +} + +/// Encode a string_view to standard Base64. +[[nodiscard]] inline std::string encode(std::string_view s) +{ + return encode(std::as_bytes(std::span{s.data(), s.size()})); +} + +/// Encode to URL-safe Base64 (no padding). +[[nodiscard]] inline std::string encode_url(std::string_view s) +{ + const auto& alpha = Detail::alphabet_url; + auto data = std::as_bytes(std::span{s.data(), s.size()}); + std::string out; + out.reserve(((data.size() + 2) / 3) * 4); + std::size_t i = 0; + for (; i + 2 < data.size(); i += 3) { + const auto a = static_cast(data[i]); + const auto b = static_cast(data[i + 1]); + const auto c = static_cast(data[i + 2]); + out += alpha[a >> 2]; + out += alpha[((a & 3) << 4) | (b >> 4)]; + out += alpha[((b & 15) << 2) | (c >> 6)]; + out += alpha[c & 63]; + } + if (data.size() - i == 2) { + const auto a = static_cast(data[i]); + const auto b = static_cast(data[i + 1]); + out += alpha[a >> 2]; + out += alpha[((a & 3) << 4) | (b >> 4)]; + out += alpha[(b & 15) << 2]; + } else if (data.size() - i == 1) { + const auto a = static_cast(data[i]); + out += alpha[a >> 2]; + out += alpha[(a & 3) << 4]; + } + return out; +} + +/// Decode standard Base64 (with or without padding). Returns nullopt on error. +[[nodiscard]] inline std::optional decode(std::string_view s) +{ + static constexpr auto table = Detail::make_decode_table(Detail::alphabet); + std::string out; + out.reserve((s.size() / 4) * 3); + int buf = 0, bits = 0; + for (unsigned char c : s) { + if (c == ' ' || c == '\n' || c == '\r' || c == '\t') continue; + const std::int8_t v = table[c]; + if (v == -2) break; // padding + if (v == -1) return std::nullopt; + buf = (buf << 6) | v; + bits += 6; + if (bits >= 8) { + bits -= 8; + out += static_cast((buf >> bits) & 0xFF); + } + } + return out; +} + +} // namespace Void::Encoding::Base64 diff --git a/include/Void/Encoding/Hex.hpp b/include/Void/Encoding/Hex.hpp new file mode 100644 index 0000000..e9e190e --- /dev/null +++ b/include/Void/Encoding/Hex.hpp @@ -0,0 +1,71 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Void::Encoding::Hex +{ + +/// Encode bytes to lowercase hex string. +[[nodiscard]] inline std::string encode(std::span data) +{ + constexpr std::string_view digits = "0123456789abcdef"; + std::string out; + out.reserve(data.size() * 2); + for (auto b : data) { + const auto v = static_cast(b); + out += digits[v >> 4]; + out += digits[v & 0xF]; + } + return out; +} + +[[nodiscard]] inline std::string encode(std::string_view s) +{ + return encode(std::as_bytes(std::span{s.data(), s.size()})); +} + +/// Decode hex string to bytes. Returns nullopt on invalid input. +[[nodiscard]] inline std::optional decode(std::string_view s) +{ + if (s.size() % 2 != 0) return std::nullopt; + auto hex_val = [](char c) -> std::optional { + if (c >= '0' && c <= '9') return static_cast(c - '0'); + if (c >= 'a' && c <= 'f') return static_cast(c - 'a' + 10); + if (c >= 'A' && c <= 'F') return static_cast(c - 'A' + 10); + return std::nullopt; + }; + std::string out; + out.reserve(s.size() / 2); + for (std::size_t i = 0; i < s.size(); i += 2) { + auto hi = hex_val(s[i]); + auto lo = hex_val(s[i + 1]); + if (!hi || !lo) return std::nullopt; + out += static_cast((*hi << 4) | *lo); + } + return out; +} + +/// Uppercase hex encoding. +[[nodiscard]] inline std::string encode_upper(std::span data) +{ + constexpr std::string_view digits = "0123456789ABCDEF"; + std::string out; + out.reserve(data.size() * 2); + for (auto b : data) { + const auto v = static_cast(b); + out += digits[v >> 4]; + out += digits[v & 0xF]; + } + return out; +} + +[[nodiscard]] inline std::string encode_upper(std::string_view s) +{ + return encode_upper(std::as_bytes(std::span{s.data(), s.size()})); +} + +} // namespace Void::Encoding::Hex diff --git a/include/Void/FileSystem/Path.hpp b/include/Void/FileSystem/Path.hpp index c65c196..fa09e7b 100644 --- a/include/Void/FileSystem/Path.hpp +++ b/include/Void/FileSystem/Path.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -26,16 +27,25 @@ namespace Void::FileSystem { std::ifstream f{path, std::ios::binary}; if (!f.is_open()) { + Void::Log::log( + Void::Log::Level::Warning, "FileSystem", + std::format("read_file: cannot open '{}'", path.string())); return Void::Result::fail(std::format( "FileSystem::read_file: cannot open '{}'", path.string())); } std::string content{std::istreambuf_iterator(f), std::istreambuf_iterator()}; if (f.bad()) { + Void::Log::log(Void::Log::Level::Warning, "FileSystem", + std::format("read_file: I/O error reading '{}'", + path.string())); return Void::Result::fail( std::format("FileSystem::read_file: I/O error reading '{}'", path.string())); } + Void::Log::log(Void::Log::Level::Debug, "FileSystem", + std::format("read_file: '{}' ({} bytes)", path.string(), + content.size())); return Void::Result::ok(std::move(content)); } @@ -48,12 +58,18 @@ namespace Void::FileSystem { std::ofstream f{path, std::ios::binary | std::ios::trunc}; if (!f.is_open()) { + Void::Log::log( + Void::Log::Level::Warning, "FileSystem", + std::format("write_file: cannot open '{}'", path.string())); return Void::Result::fail(std::format( "FileSystem::write_file: cannot open '{}'", path.string())); } f.write(content.data(), static_cast(content.size())); f.flush(); if (!f.good()) { + Void::Log::log(Void::Log::Level::Warning, "FileSystem", + std::format("write_file: I/O error writing '{}'", + path.string())); return Void::Result::fail( std::format("FileSystem::write_file: I/O error writing '{}'", path.string())); @@ -83,10 +99,17 @@ namespace Void::FileSystem if (ec) { std::error_code ignore; std::filesystem::remove(staging, ignore); + Void::Log::log( + Void::Log::Level::Warning, "FileSystem", + std::format("atomic_write: rename failed for '{}': {}", + path.string(), ec.message())); return Void::Result::fail(std::format( "FileSystem::atomic_write: rename failed for '{}': {}", path.string(), ec.message())); } + Void::Log::log(Void::Log::Level::Debug, "FileSystem", + std::format("atomic_write: '{}' committed ({} bytes)", + path.string(), content.size())); return {}; } @@ -101,10 +124,17 @@ namespace Void::FileSystem } std::filesystem::create_directories(path, ec); if (ec) { + Void::Log::log( + Void::Log::Level::Warning, "FileSystem", + std::format("ensure_directory: cannot create '{}': {}", + path.string(), ec.message())); return Void::Result::fail(std::format( "FileSystem::ensure_directory: cannot create '{}': {}", path.string(), ec.message())); } + Void::Log::log( + Void::Log::Level::Debug, "FileSystem", + std::format("ensure_directory: created '{}'", path.string())); return {}; } @@ -116,6 +146,9 @@ namespace Void::FileSystem std::error_code ec; std::filesystem::remove_all(path, ec); if (ec) { + Void::Log::log(Void::Log::Level::Warning, "FileSystem", + std::format("remove_path: cannot remove '{}': {}", + path.string(), ec.message())); return Void::Result::fail( std::format("FileSystem::remove_path: cannot remove '{}': {}", path.string(), ec.message())); diff --git a/include/Void/FileSystem/Query.hpp b/include/Void/FileSystem/Query.hpp new file mode 100644 index 0000000..a13bc1e --- /dev/null +++ b/include/Void/FileSystem/Query.hpp @@ -0,0 +1,137 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::FileSystem +{ + +/// Return true if path exists (file, directory, or symlink). +[[nodiscard]] inline bool exists(const std::filesystem::path& path) noexcept +{ + std::error_code ec; + return std::filesystem::exists(path, ec); +} + +/// Return the size of a regular file in bytes. +[[nodiscard]] inline Void::Result::Result + file_size(const std::filesystem::path& path) +{ + std::error_code ec; + auto sz = std::filesystem::file_size(path, ec); + if (ec) { + Void::Log::log( + Void::Log::Level::Warning, "FileSystem", + std::format("file_size: cannot stat '{}': {}", path.string(), + ec.message())); + return Void::Result::fail( + std::format("FileSystem::file_size: cannot stat '{}': {}", + path.string(), ec.message())); + } + return Void::Result::ok(sz); +} + +/// Return the last-write time of a path. +[[nodiscard]] inline Void::Result:: + Result + last_modified(const std::filesystem::path& path) +{ + std::error_code ec; + auto t = std::filesystem::last_write_time(path, ec); + if (ec) { + Void::Log::log( + Void::Log::Level::Warning, "FileSystem", + std::format("last_modified: cannot stat '{}': {}", path.string(), + ec.message())); + return Void::Result::fail( + std::format("FileSystem::last_modified: cannot stat '{}': {}", + path.string(), ec.message())); + } + return Void::Result::ok(t); +} + +/// List all entries in a directory (non-recursive, filesystem order). +[[nodiscard]] inline Void::Result:: + Result, Void::Result::Error> + list_directory(const std::filesystem::path& path) +{ + std::error_code ec; + std::vector entries; + for (const auto& entry : + std::filesystem::directory_iterator{path, ec}) { + if (ec) { + break; + } + entries.push_back(entry.path()); + } + if (ec) { + Void::Log::log( + Void::Log::Level::Warning, "FileSystem", + std::format("list_directory: cannot iterate '{}': {}", + path.string(), ec.message())); + return Void::Result::fail( + std::format("FileSystem::list_directory: cannot iterate '{}': {}", + path.string(), ec.message())); + } + Void::Log::log(Void::Log::Level::Debug, "FileSystem", + std::format("list_directory: '{}' ({} entries)", + path.string(), entries.size())); + return Void::Result::ok(std::move(entries)); +} + +/// Copy a single file. Set overwrite=true to allow replacing an existing dst. +[[nodiscard]] inline Void::Result::Result + copy_file(const std::filesystem::path& src, + const std::filesystem::path& dst, + bool overwrite = false) +{ + std::error_code ec; + auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing + : std::filesystem::copy_options::none; + std::filesystem::copy_file(src, dst, opts, ec); + if (ec) { + Void::Log::log( + Void::Log::Level::Warning, "FileSystem", + std::format("copy_file: '{}' -> '{}': {}", src.string(), + dst.string(), ec.message())); + return Void::Result::fail( + std::format("FileSystem::copy_file: '{}' -> '{}': {}", + src.string(), dst.string(), ec.message())); + } + Void::Log::log(Void::Log::Level::Debug, "FileSystem", + std::format("copy_file: '{}' -> '{}'", src.string(), + dst.string())); + return {}; +} + +/// Recursively copy a directory tree from src to dst. +/// dst must not already exist; its parent must be accessible. +[[nodiscard]] inline Void::Result::Result + copy_dir(const std::filesystem::path& src, + const std::filesystem::path& dst) +{ + std::error_code ec; + std::filesystem::copy(src, dst, std::filesystem::copy_options::recursive, + ec); + if (ec) { + Void::Log::log( + Void::Log::Level::Warning, "FileSystem", + std::format("copy_dir: '{}' -> '{}': {}", src.string(), + dst.string(), ec.message())); + return Void::Result::fail( + std::format("FileSystem::copy_dir: '{}' -> '{}': {}", + src.string(), dst.string(), ec.message())); + } + Void::Log::log(Void::Log::Level::Debug, "FileSystem", + std::format("copy_dir: '{}' -> '{}'", src.string(), + dst.string())); + return {}; +} + +} // namespace Void::FileSystem diff --git a/include/Void/FileSystem/TempDir.hpp b/include/Void/FileSystem/TempDir.hpp index e2647db..0c9f563 100644 --- a/include/Void/FileSystem/TempDir.hpp +++ b/include/Void/FileSystem/TempDir.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -36,6 +37,9 @@ namespace Void::FileSystem ~TempDir() noexcept { if (!m_path.empty()) { + Void::Log::log( + Void::Log::Level::Debug, "FileSystem", + std::format("TempDir: removed '{}'", m_path.string())); std::error_code ignore; std::filesystem::remove_all(m_path, ignore); } @@ -109,6 +113,9 @@ namespace Void::FileSystem base / std::format("{}{:016x}", prefix, seed); std::error_code ec; if (std::filesystem::create_directory(candidate, ec)) { + Void::Log::log(Void::Log::Level::Debug, "FileSystem", + std::format("TempDir: created '{}'", + candidate.string())); return candidate; } } diff --git a/include/Void/Hash/Hash.hpp b/include/Void/Hash/Hash.hpp new file mode 100644 index 0000000..e8c4cd7 --- /dev/null +++ b/include/Void/Hash/Hash.hpp @@ -0,0 +1,170 @@ +#pragma once + +#include +#include +#include +#include + +namespace Void::Hash +{ + +// ── FNV-1a (32-bit) ────────────────────────────────────────────────────────── + +[[nodiscard]] constexpr std::uint32_t fnv1a32(std::string_view s) noexcept +{ + std::uint32_t h = 2166136261u; + for (unsigned char c : s) { + h ^= c; + h *= 16777619u; + } + return h; +} + +[[nodiscard]] constexpr std::uint32_t + fnv1a32(std::span data) noexcept +{ + std::uint32_t h = 2166136261u; + for (auto b : data) { + h ^= static_cast(b); + h *= 16777619u; + } + return h; +} + +// ── FNV-1a (64-bit) ────────────────────────────────────────────────────────── + +[[nodiscard]] constexpr std::uint64_t fnv1a64(std::string_view s) noexcept +{ + std::uint64_t h = 14695981039346656037ull; + for (unsigned char c : s) { + h ^= c; + h *= 1099511628211ull; + } + return h; +} + +[[nodiscard]] constexpr std::uint64_t + fnv1a64(std::span data) noexcept +{ + std::uint64_t h = 14695981039346656037ull; + for (auto b : data) { + h ^= static_cast(b); + h *= 1099511628211ull; + } + return h; +} + +// ── CRC-32 (ISO 3309 / Ethernet polynomial) ─────────────────────────────────── + +namespace Detail +{ +[[nodiscard]] constexpr std::array make_crc32_table() noexcept +{ + std::array t{}; + for (std::uint32_t i = 0; i < 256; ++i) { + std::uint32_t c = i; + for (int k = 0; k < 8; ++k) { + c = (c & 1) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1); + } + t[i] = c; + } + return t; +} +} // namespace Detail + +[[nodiscard]] inline std::uint32_t crc32(std::string_view s) noexcept +{ + static constexpr auto table = Detail::make_crc32_table(); + std::uint32_t c = 0xFFFFFFFFu; + for (unsigned char b : s) { + c = table[(c ^ b) & 0xFF] ^ (c >> 8); + } + return c ^ 0xFFFFFFFFu; +} + +[[nodiscard]] inline std::uint32_t + crc32(std::span data) noexcept +{ + static constexpr auto table = Detail::make_crc32_table(); + std::uint32_t c = 0xFFFFFFFFu; + for (auto b : data) { + c = table[(c ^ static_cast(b)) & 0xFF] ^ (c >> 8); + } + return c ^ 0xFFFFFFFFu; +} + +// ── DJB2 ────────────────────────────────────────────────────────────────────── + +[[nodiscard]] constexpr std::uint64_t djb2(std::string_view s) noexcept +{ + std::uint64_t h = 5381; + for (unsigned char c : s) { + h = ((h << 5) + h) ^ c; + } + return h; +} + +// ── MurmurHash3 (32-bit, x86) ───────────────────────────────────────────────── + +[[nodiscard]] inline std::uint32_t murmur3_32(std::string_view key, + std::uint32_t seed = 0) noexcept +{ + const auto* data = reinterpret_cast(key.data()); + const std::size_t len = key.size(); + const std::size_t nblocks = len / 4; + + std::uint32_t h = seed; + constexpr std::uint32_t c1 = 0xcc9e2d51u; + constexpr std::uint32_t c2 = 0x1b873593u; + + for (std::size_t i = 0; i < nblocks; ++i) { + std::uint32_t k; + __builtin_memcpy(&k, data + i * 4, 4); + k *= c1; + k = (k << 15) | (k >> 17); + k *= c2; + h ^= k; + h = (h << 13) | (h >> 19); + h = h * 5 + 0xe6546b64u; + } + + const auto* tail = data + nblocks * 4; + std::uint32_t k = 0; + switch (len & 3) { + case 3: k ^= static_cast(tail[2]) << 16; [[fallthrough]]; + case 2: k ^= static_cast(tail[1]) << 8; [[fallthrough]]; + case 1: + k ^= static_cast(tail[0]); + k *= c1; + k = (k << 15) | (k >> 17); + k *= c2; + h ^= k; + } + + h ^= static_cast(len); + h ^= h >> 16; + h *= 0x85ebca6bu; + h ^= h >> 13; + h *= 0xc2b2ae35u; + h ^= h >> 16; + return h; +} + +// ── Convenience: string literal compile-time hash ──────────────────────────── + +inline namespace Literals +{ +[[nodiscard]] consteval std::uint32_t + operator""_fnv32(const char* s, std::size_t n) noexcept +{ + return fnv1a32(std::string_view{s, n}); +} + +[[nodiscard]] consteval std::uint64_t + operator""_fnv64(const char* s, std::size_t n) noexcept +{ + return fnv1a64(std::string_view{s, n}); +} +} // namespace Literals + +} // namespace Void::Hash diff --git a/include/Void/Log/Log.hpp b/include/Void/Log/Log.hpp new file mode 100644 index 0000000..944b1da --- /dev/null +++ b/include/Void/Log/Log.hpp @@ -0,0 +1,34 @@ +#pragma once +#include +#include + +namespace Void::Log +{ + + enum class Level : unsigned char { + Trace = 0, + Debug, + Info, + Warning, + Error, + Fatal + }; + + /// Signature for any log consumer. Three arguments: + /// level — severity of the event + /// module — short library-internal label (e.g. "FileSystem", + /// "Concurrency") message — human-readable description + using Sink = std::function; + + /// Install the global sink. Any previously installed sink is replaced. + /// Pass a default-constructed (empty) Sink to silence all output. + /// Thread-safe: the new sink is visible to all threads after this returns. + void set_sink(Sink sink); + + /// Emit one log event through the global sink. + /// No-op (zero allocation) if no sink is installed. + /// Thread-safe with respect to set_sink() and concurrent log() calls. + void log(Level level, std::string_view module, std::string_view message); + +} // namespace Void::Log diff --git a/include/Void/Log/LoggingAdapter.hpp b/include/Void/Log/LoggingAdapter.hpp new file mode 100644 index 0000000..b2c0cbe --- /dev/null +++ b/include/Void/Log/LoggingAdapter.hpp @@ -0,0 +1,69 @@ +#pragma once +#include +#include +#include + +// Bridge between Void::Log (the thin emission layer used by all modules) and +// Void::Logging::Logger (the full sink implementation). +// +// Include this header only in translation units that also link Void::Logging. +// All other code that merely calls Void::Log::log() needs only Log.hpp. +// +// Example: +// #include +// #include +// +// Void::Logging::ConsoleLogger logger; +// Void::Log::set_sink(Void::Log::make_sink(logger)); + +namespace Void::Log +{ + + /// Map a Void::Log::Level to the corresponding Void::Logging::Level. + /// Uses reflection to match by enumerator name; falls back to a + /// hand-written table for non-reflecting compilers. + [[nodiscard]] inline Void::Logging::Level + to_logging_level(Void::Log::Level level) noexcept + { +#ifdef VOID_HAS_ENUM_REFLECTION + return Void::Detail::enum_cast(level); +#else + switch (level) { + case Level::Trace: + return Void::Logging::Level::Trace; + case Level::Debug: + return Void::Logging::Level::Debug; + case Level::Info: + return Void::Logging::Level::Info; + case Level::Warning: + return Void::Logging::Level::Warning; + case Level::Error: + return Void::Logging::Level::Error; + case Level::Fatal: + return Void::Logging::Level::Fatal; + } + return Void::Logging::Level::Info; +#endif + } + + /// Create a Sink that routes events to a Void::Logging::Logger. + /// + /// The module name is prepended to the message as "[module] " so the + /// scope/tag information survives without requiring push_scope() calls on + /// the internal logger. + /// + /// Lifetime: the returned Sink holds a reference to logger; logger must + /// outlive any call made through the Sink. + [[nodiscard]] inline Sink make_sink(Void::Logging::Logger& logger) + { + return [&logger](Level level, std::string_view module, + std::string_view message) { + auto full = std::string{"["}; + full += module; + full += "] "; + full += message; + logger.log(to_logging_level(level), full); + }; + } + +} // namespace Void::Log diff --git a/include/Void/Logging/FileLogger.hpp b/include/Void/Logging/FileLogger.hpp index 78121ce..b7378c8 100644 --- a/include/Void/Logging/FileLogger.hpp +++ b/include/Void/Logging/FileLogger.hpp @@ -55,6 +55,7 @@ namespace Void::Logging private: + std::filesystem::path m_path; std::ofstream m_file; }; diff --git a/include/Void/Logging/Level.hpp b/include/Void/Logging/Level.hpp index e135bc6..cd580b1 100644 --- a/include/Void/Logging/Level.hpp +++ b/include/Void/Logging/Level.hpp @@ -1,5 +1,7 @@ #pragma once +#include + #include #include #include @@ -28,29 +30,32 @@ namespace Void::Logging return std::to_underlying(a) >= std::to_underlying(b); } - /// Convert a Level to its canonical string representation. - /// Defined inline so it is usable in constexpr contexts and - /// visible to every translation unit without ODR violations. + /// Convert a Level to its identifier string via reflection when available, + /// falling back to a hand-written table for non-reflecting compilers. [[nodiscard]] constexpr std::string_view to_string(Level level) noexcept { +#ifdef VOID_HAS_ENUM_REFLECTION + return Void::Detail::enum_name(level); +#else switch (level) { case Level::Disabled: - return "DISABLED"; + return "Disabled"; case Level::Trace: - return "TRACE"; + return "Trace"; case Level::Debug: - return "DEBUG"; + return "Debug"; case Level::Info: - return "INFO"; + return "Info"; case Level::Warning: - return "WARN"; + return "Warning"; case Level::Error: - return "ERROR"; + return "Error"; case Level::Fatal: - return "FATAL"; + return "Fatal"; default: - return "UNK"; + return "?"; } +#endif } } // namespace Void::Logging diff --git a/include/Void/Math/Mat.hpp b/include/Void/Math/Mat.hpp new file mode 100644 index 0000000..d091630 --- /dev/null +++ b/include/Void/Math/Mat.hpp @@ -0,0 +1,137 @@ +#pragma once + +#include + +#include +#include +#include + +namespace Void::Math +{ + +// ── Mat4 (column-major, row-major storage) ──────────────────────────────────── +// Stored row-major: m[row][col]. + +template +struct Mat4 +{ + std::array, 4> m{}; + + constexpr Mat4() noexcept = default; + + [[nodiscard]] static constexpr Mat4 identity() noexcept + { + Mat4 r; + r.m[0][0] = r.m[1][1] = r.m[2][2] = r.m[3][3] = T{1}; + return r; + } + + [[nodiscard]] constexpr T& at(int row, int col) noexcept { return m[row][col]; } + [[nodiscard]] constexpr T at(int row, int col) const noexcept { return m[row][col]; } + + [[nodiscard]] constexpr bool operator==(const Mat4&) const noexcept = default; + + [[nodiscard]] constexpr Mat4 operator+(const Mat4& o) const noexcept + { + Mat4 r; + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) + r.m[i][j] = m[i][j] + o.m[i][j]; + return r; + } + + [[nodiscard]] constexpr Mat4 operator*(T s) const noexcept + { + Mat4 r; + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) + r.m[i][j] = m[i][j] * s; + return r; + } + + [[nodiscard]] constexpr Mat4 operator*(const Mat4& o) const noexcept + { + Mat4 r; + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) { + T s{}; + for (int k = 0; k < 4; ++k) s += m[i][k] * o.m[k][j]; + r.m[i][j] = s; + } + return r; + } + + [[nodiscard]] constexpr Vec4 operator*(Vec4 v) const noexcept + { + return { + m[0][0]*v.x + m[0][1]*v.y + m[0][2]*v.z + m[0][3]*v.w, + m[1][0]*v.x + m[1][1]*v.y + m[1][2]*v.z + m[1][3]*v.w, + m[2][0]*v.x + m[2][1]*v.y + m[2][2]*v.z + m[2][3]*v.w, + m[3][0]*v.x + m[3][1]*v.y + m[3][2]*v.z + m[3][3]*v.w, + }; + } + + [[nodiscard]] constexpr Mat4 transposed() const noexcept + { + Mat4 r; + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) + r.m[i][j] = m[j][i]; + return r; + } + + /// Translation matrix (affine, last row [0 0 0 1]). + [[nodiscard]] static constexpr Mat4 translation(T tx, T ty, T tz) noexcept + { + auto r = identity(); + r.m[0][3] = tx; + r.m[1][3] = ty; + r.m[2][3] = tz; + return r; + } + + /// Uniform scale matrix. + [[nodiscard]] static constexpr Mat4 scale(T sx, T sy, T sz) noexcept + { + auto r = identity(); + r.m[0][0] = sx; + r.m[1][1] = sy; + r.m[2][2] = sz; + return r; + } + + /// Rotation around X axis (angle in radians). + [[nodiscard]] static Mat4 rotation_x(T angle) noexcept + { + auto r = identity(); + const T c = std::cos(angle), s = std::sin(angle); + r.m[1][1] = c; r.m[1][2] = -s; + r.m[2][1] = s; r.m[2][2] = c; + return r; + } + + /// Rotation around Y axis. + [[nodiscard]] static Mat4 rotation_y(T angle) noexcept + { + auto r = identity(); + const T c = std::cos(angle), s = std::sin(angle); + r.m[0][0] = c; r.m[0][2] = s; + r.m[2][0] = -s; r.m[2][2] = c; + return r; + } + + /// Rotation around Z axis. + [[nodiscard]] static Mat4 rotation_z(T angle) noexcept + { + auto r = identity(); + const T c = std::cos(angle), s = std::sin(angle); + r.m[0][0] = c; r.m[0][1] = -s; + r.m[1][0] = s; r.m[1][1] = c; + return r; + } +}; + +using Mat4f = Mat4; +using Mat4d = Mat4; + +} // namespace Void::Math diff --git a/include/Void/Math/Vec.hpp b/include/Void/Math/Vec.hpp new file mode 100644 index 0000000..305ed87 --- /dev/null +++ b/include/Void/Math/Vec.hpp @@ -0,0 +1,135 @@ +#pragma once + +#include +#include +#include +#include + +namespace Void::Math +{ + +// ── Vec2 ────────────────────────────────────────────────────────────────────── + +template +struct Vec2 +{ + T x{}, y{}; + + constexpr Vec2() noexcept = default; + constexpr Vec2(T x, T y) noexcept : x{x}, y{y} {} + + [[nodiscard]] constexpr bool operator==(const Vec2&) const noexcept = default; + + [[nodiscard]] constexpr Vec2 operator+(Vec2 o) const noexcept { return {x + o.x, y + o.y}; } + [[nodiscard]] constexpr Vec2 operator-(Vec2 o) const noexcept { return {x - o.x, y - o.y}; } + [[nodiscard]] constexpr Vec2 operator*(T s) const noexcept { return {x * s, y * s}; } + [[nodiscard]] constexpr Vec2 operator/(T s) const noexcept { return {x / s, y / s}; } + [[nodiscard]] constexpr Vec2 operator-() const noexcept { return {-x, -y}; } + + constexpr Vec2& operator+=(Vec2 o) noexcept { x += o.x; y += o.y; return *this; } + constexpr Vec2& operator-=(Vec2 o) noexcept { x -= o.x; y -= o.y; return *this; } + constexpr Vec2& operator*=(T s) noexcept { x *= s; y *= s; return *this; } + constexpr Vec2& operator/=(T s) noexcept { x /= s; y /= s; return *this; } + + [[nodiscard]] constexpr T dot(Vec2 o) const noexcept { return x * o.x + y * o.y; } + [[nodiscard]] constexpr T length_sq() const noexcept { return dot(*this); } + [[nodiscard]] T length() const noexcept { return std::sqrt(length_sq()); } + [[nodiscard]] Vec2 normalized() const noexcept { return *this / length(); } + + [[nodiscard]] std::string to_string() const + { + return std::format("({}, {})", x, y); + } +}; + +template +[[nodiscard]] constexpr Vec2 operator*(T s, Vec2 v) noexcept { return v * s; } + +// ── Vec3 ────────────────────────────────────────────────────────────────────── + +template +struct Vec3 +{ + T x{}, y{}, z{}; + + constexpr Vec3() noexcept = default; + constexpr Vec3(T x, T y, T z) noexcept : x{x}, y{y}, z{z} {} + + [[nodiscard]] constexpr bool operator==(const Vec3&) const noexcept = default; + + [[nodiscard]] constexpr Vec3 operator+(Vec3 o) const noexcept { return {x + o.x, y + o.y, z + o.z}; } + [[nodiscard]] constexpr Vec3 operator-(Vec3 o) const noexcept { return {x - o.x, y - o.y, z - o.z}; } + [[nodiscard]] constexpr Vec3 operator*(T s) const noexcept { return {x * s, y * s, z * s}; } + [[nodiscard]] constexpr Vec3 operator/(T s) const noexcept { return {x / s, y / s, z / s}; } + [[nodiscard]] constexpr Vec3 operator-() const noexcept { return {-x, -y, -z}; } + + constexpr Vec3& operator+=(Vec3 o) noexcept { x += o.x; y += o.y; z += o.z; return *this; } + constexpr Vec3& operator-=(Vec3 o) noexcept { x -= o.x; y -= o.y; z -= o.z; return *this; } + constexpr Vec3& operator*=(T s) noexcept { x *= s; y *= s; z *= s; return *this; } + constexpr Vec3& operator/=(T s) noexcept { x /= s; y /= s; z /= s; return *this; } + + [[nodiscard]] constexpr T dot(Vec3 o) const noexcept { return x * o.x + y * o.y + z * o.z; } + [[nodiscard]] constexpr Vec3 cross(Vec3 o) const noexcept + { + return {y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x}; + } + [[nodiscard]] constexpr T length_sq() const noexcept { return dot(*this); } + [[nodiscard]] T length() const noexcept { return std::sqrt(length_sq()); } + [[nodiscard]] Vec3 normalized() const noexcept { return *this / length(); } + + [[nodiscard]] std::string to_string() const + { + return std::format("({}, {}, {})", x, y, z); + } +}; + +template +[[nodiscard]] constexpr Vec3 operator*(T s, Vec3 v) noexcept { return v * s; } + +// ── Vec4 ────────────────────────────────────────────────────────────────────── + +template +struct Vec4 +{ + T x{}, y{}, z{}, w{}; + + constexpr Vec4() noexcept = default; + constexpr Vec4(T x, T y, T z, T w) noexcept : x{x}, y{y}, z{z}, w{w} {} + explicit constexpr Vec4(Vec3 v, T w = T{1}) noexcept : x{v.x}, y{v.y}, z{v.z}, w{w} {} + + [[nodiscard]] constexpr bool operator==(const Vec4&) const noexcept = default; + + [[nodiscard]] constexpr Vec4 operator+(Vec4 o) const noexcept { return {x+o.x, y+o.y, z+o.z, w+o.w}; } + [[nodiscard]] constexpr Vec4 operator-(Vec4 o) const noexcept { return {x-o.x, y-o.y, z-o.z, w-o.w}; } + [[nodiscard]] constexpr Vec4 operator*(T s) const noexcept { return {x*s, y*s, z*s, w*s}; } + [[nodiscard]] constexpr Vec4 operator/(T s) const noexcept { return {x/s, y/s, z/s, w/s}; } + + [[nodiscard]] constexpr T dot(Vec4 o) const noexcept { return x*o.x + y*o.y + z*o.z + w*o.w; } + [[nodiscard]] constexpr T length_sq() const noexcept { return dot(*this); } + [[nodiscard]] T length() const noexcept { return std::sqrt(length_sq()); } + [[nodiscard]] constexpr Vec3 xyz() const noexcept { return {x, y, z}; } +}; + +// ── Free functions ──────────────────────────────────────────────────────────── + +template +[[nodiscard]] constexpr T distance(Vec2 a, Vec2 b) noexcept { return (a - b).length(); } + +template +[[nodiscard]] constexpr T distance(Vec3 a, Vec3 b) noexcept { return (a - b).length(); } + +template +[[nodiscard]] constexpr Vec2 lerp(Vec2 a, Vec2 b, T t) noexcept { return a + (b - a) * t; } + +template +[[nodiscard]] constexpr Vec3 lerp(Vec3 a, Vec3 b, T t) noexcept { return a + (b - a) * t; } + +// Convenience aliases +using Vec2f = Vec2; +using Vec2d = Vec2; +using Vec3f = Vec3; +using Vec3d = Vec3; +using Vec4f = Vec4; +using Vec4d = Vec4; + +} // namespace Void::Math diff --git a/include/Void/Process/Process.hpp b/include/Void/Process/Process.hpp new file mode 100644 index 0000000..6cb1ea7 --- /dev/null +++ b/include/Void/Process/Process.hpp @@ -0,0 +1,44 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::Process +{ + +/// Captured output from a completed subprocess. +struct Output { + int exit_code{0}; + std::string out; ///< captured stdout + std::string err; ///< captured stderr +}; + +/// Run an executable synchronously, capturing stdout and stderr separately. +/// +/// @param executable Path to the binary (searched via PATH when relative). +/// @param args Additional arguments passed after argv[0]. +/// @param stdin_data Data written to the process's stdin before reading. +/// @param timeout Wall-clock limit; zero means no limit. On expiry the +/// process receives SIGTERM and the call returns. +/// +/// Returns an error only when process creation itself fails (pipe or fork +/// failure). A process that exits non-zero still yields a successful Result +/// with the appropriate exit_code. A process whose executable is not found +/// exits with code 127 (POSIX convention). +[[nodiscard]] Void::Result::Result + run(const std::filesystem::path& executable, + std::vector args = {}, + std::string_view stdin_data = {}, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); + +/// Run a command through /bin/sh -c "command". +[[nodiscard]] Void::Result::Result + shell(std::string_view command, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); + +} // namespace Void::Process diff --git a/include/Void/Random/Random.hpp b/include/Void/Random/Random.hpp new file mode 100644 index 0000000..7cd1919 --- /dev/null +++ b/include/Void/Random/Random.hpp @@ -0,0 +1,163 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace Void::Random +{ + +// ── Xoshiro256** PRNG (fast, good quality, no stdlib overhead) ─────────────── + +class Xoshiro256 +{ +public: + using result_type = std::uint64_t; + + explicit Xoshiro256(std::uint64_t seed = 0xdeadbeefcafe1234ull) noexcept + { + // SplitMix64 seeder + auto splitmix = [](std::uint64_t& s) noexcept -> std::uint64_t { + s += 0x9e3779b97f4a7c15ull; + std::uint64_t z = s; + z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull; + z = (z ^ (z >> 27)) * 0x94d049bb133111ebull; + return z ^ (z >> 31); + }; + s_[0] = splitmix(seed); + s_[1] = splitmix(seed); + s_[2] = splitmix(seed); + s_[3] = splitmix(seed); + } + + static constexpr result_type min() noexcept { return 0; } + static constexpr result_type max() noexcept + { + return std::numeric_limits::max(); + } + + result_type operator()() noexcept + { + const std::uint64_t r = rotl(s_[1] * 5, 7) * 9; + const std::uint64_t t = s_[1] << 17; + s_[2] ^= s_[0]; + s_[3] ^= s_[1]; + s_[1] ^= s_[2]; + s_[0] ^= s_[3]; + s_[2] ^= t; + s_[3] = rotl(s_[3], 45); + return r; + } + + void discard(unsigned long long n) noexcept + { + while (n--) operator()(); + } + +private: + static constexpr std::uint64_t rotl(std::uint64_t x, int k) noexcept + { + return (x << k) | (x >> (64 - k)); + } + std::uint64_t s_[4]; +}; + +// ── Thread-local default generator ─────────────────────────────────────────── + +inline Xoshiro256& global_rng() noexcept +{ + static thread_local Xoshiro256 rng{std::random_device{}()}; + return rng; +} + +// ── Distributions ───────────────────────────────────────────────────────────── + +/// Uniform integer in [lo, hi] (inclusive). +template +[[nodiscard]] T uniform_int(T lo, T hi) noexcept +{ + std::uniform_int_distribution d{lo, hi}; + return d(global_rng()); +} + +/// Uniform real in [lo, hi). +template +[[nodiscard]] T uniform_real(T lo = T{0}, T hi = T{1}) noexcept +{ + std::uniform_real_distribution d{lo, hi}; + return d(global_rng()); +} + +/// Bernoulli trial: true with probability p. +[[nodiscard]] inline bool coin_flip(double p = 0.5) noexcept +{ + std::bernoulli_distribution d{p}; + return d(global_rng()); +} + +/// Normal (Gaussian) sample. +[[nodiscard]] inline double normal(double mean = 0.0, + double stddev = 1.0) noexcept +{ + std::normal_distribution d{mean, stddev}; + return d(global_rng()); +} + +/// Pick a random element from a non-empty span. UB if span is empty. +template +[[nodiscard]] const T& choice(std::span items) noexcept +{ + return items[uniform_int(0, items.size() - 1)]; +} + +template +[[nodiscard]] T& choice(std::span items) noexcept +{ + return items[uniform_int(0, items.size() - 1)]; +} + +/// Shuffle a container in place using Fisher-Yates. +template +void shuffle(Container& c) noexcept +{ + std::ranges::shuffle(c, global_rng()); +} + +/// Fill a span with random bytes. +inline void fill_random(std::span buf) noexcept +{ + for (auto& b : buf) { + b = static_cast(uniform_int(0, 255)); + } +} + +/// Generate a random alphanumeric string of length n. +[[nodiscard]] inline std::string random_string(std::size_t n) +{ + constexpr std::string_view chars = + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"; + std::string s; + s.reserve(n); + for (std::size_t i = 0; i < n; ++i) { + s += chars[uniform_int(0, chars.size() - 1)]; + } + return s; +} + +/// Sample k distinct indices from [0, n). +[[nodiscard]] inline std::vector sample_indices(std::size_t n, + std::size_t k) +{ + std::vector pool(n); + std::iota(pool.begin(), pool.end(), std::size_t{0}); + shuffle(pool); + pool.resize(k); + return pool; +} + +} // namespace Void::Random diff --git a/include/Void/Result/Detail/Repr.hpp b/include/Void/Result/Detail/Repr.hpp index 0dc2483..3db0291 100644 --- a/include/Void/Result/Detail/Repr.hpp +++ b/include/Void/Result/Detail/Repr.hpp @@ -36,7 +36,11 @@ namespace Void::Result::Detail template [[nodiscard]] std::string reflect_struct(const T& obj) { std::string out; - out += std::meta::identifier_of(^^T); + if constexpr (std::meta::has_identifier(^^T)) { + out += std::meta::identifier_of(^^T); + } else { + out += "?"; + } out += '{'; static constexpr auto members = std::define_static_array(std::meta::nonstatic_data_members_of( diff --git a/include/Void/String/String.hpp b/include/Void/String/String.hpp new file mode 100644 index 0000000..89b0349 --- /dev/null +++ b/include/Void/String/String.hpp @@ -0,0 +1,207 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::String +{ + +// ── Views (zero allocation) ─────────────────────────────────────────────── + +/// Remove leading whitespace. +[[nodiscard]] constexpr std::string_view + trim_left(std::string_view s) noexcept +{ + const auto it = + std::find_if_not(s.begin(), s.end(), + [](unsigned char c) { return std::isspace(c); }); + s.remove_prefix(static_cast(it - s.begin())); + return s; +} + +/// Remove trailing whitespace. +[[nodiscard]] constexpr std::string_view + trim_right(std::string_view s) noexcept +{ + const auto it = + std::find_if_not(s.rbegin(), s.rend(), + [](unsigned char c) { return std::isspace(c); }); + s.remove_suffix(static_cast(it - s.rbegin())); + return s; +} + +/// Remove leading and trailing whitespace. +[[nodiscard]] constexpr std::string_view trim(std::string_view s) noexcept +{ + return trim_right(trim_left(s)); +} + +// ── Split ───────────────────────────────────────────────────────────────── + +/// Split on a single character delimiter. Empty tokens are preserved. +/// The returned views point into `s`; `s` must outlive the result. +[[nodiscard]] inline std::vector + split(std::string_view s, char delimiter) +{ + std::vector parts; + std::size_t pos = 0; + while (true) { + const auto end = s.find(delimiter, pos); + parts.push_back(s.substr(pos, end - pos)); + if (end == std::string_view::npos) { + break; + } + pos = end + 1; + } + return parts; +} + +/// Split on a multi-character delimiter string. Empty tokens are preserved. +[[nodiscard]] inline std::vector + split(std::string_view s, std::string_view delimiter) +{ + std::vector parts; + if (delimiter.empty()) { + parts.emplace_back(s); + return parts; + } + std::size_t pos = 0; + while (true) { + const auto end = s.find(delimiter, pos); + parts.push_back(s.substr(pos, end - pos)); + if (end == std::string_view::npos) { + break; + } + pos = end + delimiter.size(); + } + return parts; +} + +// ── Join ────────────────────────────────────────────────────────────────── + +/// Join any input range of string-like values with a separator. +template + requires std::convertible_to, std::string_view> +[[nodiscard]] std::string join(R&& parts, std::string_view sep) +{ + std::string out; + bool first = true; + for (const auto& part : parts) { + if (!first) { + out += sep; + } + out += std::string_view{part}; + first = false; + } + return out; +} + +// ── Case conversion ─────────────────────────────────────────────────────── + +/// Return an ASCII-lowercased copy of `s`. +[[nodiscard]] inline std::string to_lower(std::string_view s) +{ + std::string out; + out.reserve(s.size()); + for (unsigned char c : s) { + out += static_cast(std::tolower(c)); + } + return out; +} + +/// Return an ASCII-uppercased copy of `s`. +[[nodiscard]] inline std::string to_upper(std::string_view s) +{ + std::string out; + out.reserve(s.size()); + for (unsigned char c : s) { + out += static_cast(std::toupper(c)); + } + return out; +} + +// ── Replace ─────────────────────────────────────────────────────────────── + +/// Return a copy of `s` with every non-overlapping occurrence of `from` +/// replaced by `to`. Returns `s` as-is if `from` is empty. +[[nodiscard]] inline std::string + replace_all(std::string_view s, std::string_view from, std::string_view to) +{ + if (from.empty()) { + return std::string{s}; + } + std::string out; + out.reserve(s.size()); + std::size_t pos = 0; + while (true) { + const auto hit = s.find(from, pos); + out += s.substr(pos, hit - pos); + if (hit == std::string_view::npos) { + break; + } + out += to; + pos = hit + from.size(); + } + return out; +} + +// ── Padding ─────────────────────────────────────────────────────────────── + +/// Left-pad `s` to at least `width` characters, filling with `fill`. +[[nodiscard]] inline std::string + pad_left(std::string_view s, std::size_t width, char fill = ' ') +{ + if (s.size() >= width) { + return std::string{s}; + } + std::string out(width - s.size(), fill); + out += s; + return out; +} + +/// Right-pad `s` to at least `width` characters, filling with `fill`. +[[nodiscard]] inline std::string + pad_right(std::string_view s, std::size_t width, char fill = ' ') +{ + std::string out{s}; + if (out.size() < width) { + out.append(width - out.size(), fill); + } + return out; +} + +// ── Misc ────────────────────────────────────────────────────────────────── + +/// Repeat `s` exactly `n` times. +[[nodiscard]] inline std::string repeat(std::string_view s, std::size_t n) +{ + std::string out; + out.reserve(s.size() * n); + for (std::size_t i = 0; i < n; ++i) { + out += s; + } + return out; +} + +/// Count non-overlapping occurrences of `substr` in `s`. +[[nodiscard]] inline std::size_t + count_occurrences(std::string_view s, std::string_view substr) noexcept +{ + if (substr.empty()) { + return 0; + } + std::size_t n = 0; + std::size_t pos = 0; + while ((pos = s.find(substr, pos)) != std::string_view::npos) { + ++n; + pos += substr.size(); + } + return n; +} + +} // namespace Void::String diff --git a/include/Void/Testing/Config.hpp b/include/Void/Testing/Config.hpp index 39c3cd0..33b508a 100644 --- a/include/Void/Testing/Config.hpp +++ b/include/Void/Testing/Config.hpp @@ -86,6 +86,7 @@ namespace Void::Testing bool show_help{false}; unsigned repeat{1}; unsigned random_seed{0}; + unsigned parallel_threads{0}; // 0 = sequential }; } // namespace Void::Testing diff --git a/include/Void/Testing/ConsoleReporter.hpp b/include/Void/Testing/ConsoleReporter.hpp index fa816b4..1e67898 100644 --- a/include/Void/Testing/ConsoleReporter.hpp +++ b/include/Void/Testing/ConsoleReporter.hpp @@ -1,13 +1,13 @@ #pragma once #include -#include +#include #include namespace Void::Testing { class ConsoleReporter final : public Reporter { public: explicit ConsoleReporter(std::ostream& os, bool color_enabled = true) : os_(os) { - Void::Stacktrace::Color::g_color_enabled = color_enabled; + Void::Testing::Detail::Color::g_color_enabled = color_enabled; } void on_run_start(const RunConfig& config, int total_tests) override; void on_suite_start(const std::string& suite_name, int test_count) override; diff --git a/include/Void/Testing/Detail/Color.hpp b/include/Void/Testing/Detail/Color.hpp new file mode 100644 index 0000000..7527a47 --- /dev/null +++ b/include/Void/Testing/Detail/Color.hpp @@ -0,0 +1,33 @@ +#pragma once + +#ifdef VOID_HAS_STACKTRACE +#include +namespace Void::Testing::Detail { +namespace Color = Void::Stacktrace::Color; +} +#else +#include +#include +namespace Void::Testing::Detail::Color { +inline bool g_color_enabled{true}; +constexpr std::string_view reset = "\033[0m"; +constexpr std::string_view bold = "\033[1m"; +constexpr std::string_view dim = "\033[2m"; +constexpr std::string_view bold_red = "\033[1;31m"; +constexpr std::string_view bold_green = "\033[1;32m"; +constexpr std::string_view bold_yellow = "\033[1;33m"; +constexpr std::string_view bold_blue = "\033[1;34m"; +constexpr std::string_view bold_magenta = "\033[1;35m"; +constexpr std::string_view bold_cyan = "\033[1;36m"; +constexpr std::string_view bold_white = "\033[1;37m"; +constexpr std::string_view red = "\033[31m"; +constexpr std::string_view green = "\033[32m"; +constexpr std::string_view yellow = "\033[33m"; +constexpr std::string_view cyan = "\033[36m"; +inline std::string apply(std::string_view code, std::string_view text) +{ + if (!g_color_enabled) return std::string{text}; + return std::string{code} + std::string{text} + std::string{reset}; +} +} // namespace Void::Testing::Detail::Color +#endif diff --git a/include/Void/Testing/Runner.hpp b/include/Void/Testing/Runner.hpp index abc8830..8073e53 100644 --- a/include/Void/Testing/Runner.hpp +++ b/include/Void/Testing/Runner.hpp @@ -3,21 +3,30 @@ #include #include -namespace Void::Testing { -class Runner { -public: - static Runner& instance() { - static Runner r; - return r; - } - RunConfig parse_args(int argc, char** argv); - RunResult run(const RunConfig& config); - int main(int argc, char** argv); -private: - Runner() = default; - std::vector filter_tests(const std::vector& tests, const RunConfig& config); - std::unique_ptr create_reporter(const RunConfig& config); - TestResult execute_test(TestCase& test_case); - void run_test_body(TestCase& test_case, TestResult& result); -}; +namespace Void::Testing +{ + class Runner + { + public: + + static Runner& instance() + { + static Runner r; + return r; + } + RunConfig parse_args(int argc, char** argv); + RunResult run(const RunConfig& config); + int main(int argc, char** argv); + + private: + + Runner() = default; + std::vector + filter_tests(const std::vector& tests, + const RunConfig& config); + std::unique_ptr create_reporter(const RunConfig& config); + TestResult execute_test(TestCase& test_case); + TestResult execute_test_parallel(TestCase& test_case); + void run_test_body(TestCase& test_case, TestResult& result); + }; } // namespace Void::Testing diff --git a/include/Void/Time/Format.hpp b/include/Void/Time/Format.hpp new file mode 100644 index 0000000..6258b44 --- /dev/null +++ b/include/Void/Time/Format.hpp @@ -0,0 +1,106 @@ +#pragma once + +#include +#include +#include +#include + +namespace Void::Time +{ + +/// Format a duration as a compact human-readable string. +/// +/// Examples: +/// 350ns → "350ns" +/// 4500ns → "4.5µs" +/// 2300µs → "2.3ms" +/// 1500ms → "1.5s" +/// 90s → "1m 30s" +/// 5400s → "1h 30m" +[[nodiscard]] inline std::string + format_duration(std::chrono::nanoseconds d) noexcept +{ + const auto ns = d.count(); + if (ns < 0) { + return "0ns"; + } + if (ns < 1'000) { + return std::format("{}ns", ns); + } + if (ns < 1'000'000) { + const double us = static_cast(ns) / 1'000.0; + if (us < 10.0) { + return std::format("{:.1f}\xc2\xb5s", us); // µs in UTF-8 + } + return std::format("{:.0f}\xc2\xb5s", us); + } + if (ns < 1'000'000'000LL) { + const double ms = static_cast(ns) / 1'000'000.0; + if (ms < 10.0) { + return std::format("{:.1f}ms", ms); + } + return std::format("{:.0f}ms", ms); + } + const long long total_s = + std::chrono::duration_cast(d).count(); + if (total_s < 60) { + const double s = static_cast(ns) / 1'000'000'000.0; + return std::format("{:.1f}s", s); + } + if (total_s < 3600) { + const long long m = total_s / 60; + const long long s = total_s % 60; + return std::format("{}m {}s", m, s); + } + const long long h = total_s / 3600; + const long long m = (total_s % 3600) / 60; + return std::format("{}h {}m", h, m); +} + +/// Format any chrono duration via the nanosecond overload. +template +[[nodiscard]] std::string + format_duration(std::chrono::duration d) noexcept +{ + return format_duration( + std::chrono::duration_cast(d)); +} + +/// Return the current UTC time formatted as ISO 8601 with second precision. +/// Example: "2026-05-14T10:30:00Z" +[[nodiscard]] inline std::string utc_now_iso8601() +{ + const auto now = + std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + std::tm tm{}; +#ifdef _WIN32 + gmtime_s(&tm, &now); +#else + gmtime_r(&now, &tm); +#endif + return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", + tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec); +} + +/// Return the current UTC time formatted as ISO 8601 with millisecond precision. +/// Example: "2026-05-14T10:30:00.123Z" +[[nodiscard]] inline std::string utc_now_iso8601_ms() +{ + const auto now_tp = std::chrono::system_clock::now(); + const auto now_t = std::chrono::system_clock::to_time_t(now_tp); + const auto ms = std::chrono::duration_cast( + now_tp.time_since_epoch()) % + 1000; + std::tm tm{}; +#ifdef _WIN32 + gmtime_s(&tm, &now_t); +#else + gmtime_r(&now_t, &tm); +#endif + return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z", + tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec, ms.count()); +} + +} // namespace Void::Time diff --git a/include/Void/Time/Stopwatch.hpp b/include/Void/Time/Stopwatch.hpp new file mode 100644 index 0000000..504a921 --- /dev/null +++ b/include/Void/Time/Stopwatch.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include + +namespace Void::Time +{ + +/// Minimal RAII wall-clock timer built on std::chrono::steady_clock. +/// +/// Usage: +/// Stopwatch sw; +/// do_work(); +/// auto ms = sw.elapsed(); +class Stopwatch +{ + public: + + using Clock = std::chrono::steady_clock; + using TimePoint = Clock::time_point; + using Duration = Clock::duration; + + /// Start the stopwatch at construction time. + Stopwatch() noexcept : start_(Clock::now()) {} + + /// Restart from zero. + void reset() noexcept { start_ = Clock::now(); } + + /// Elapsed time since construction or last reset(). + [[nodiscard]] Duration elapsed() const noexcept + { + return Clock::now() - start_; + } + + /// Elapsed time cast to a specific duration type. + template + [[nodiscard]] D elapsed_as() const noexcept + { + return std::chrono::duration_cast(elapsed()); + } + + /// Split: return elapsed and reset in one call. + [[nodiscard]] Duration split() noexcept + { + auto d = elapsed(); + reset(); + return d; + } + + private: + + TimePoint start_; +}; + +} // namespace Void::Time diff --git a/include/Void/Uuid/Uuid.hpp b/include/Void/Uuid/Uuid.hpp new file mode 100644 index 0000000..16316d6 --- /dev/null +++ b/include/Void/Uuid/Uuid.hpp @@ -0,0 +1,165 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::Uuid +{ + +// ── UUID type ───────────────────────────────────────────────────────────────── + +struct Uuid +{ + std::array bytes{}; + + [[nodiscard]] bool operator==(const Uuid&) const noexcept = default; + [[nodiscard]] auto operator<=>(const Uuid&) const noexcept = default; + + [[nodiscard]] bool is_nil() const noexcept + { + for (auto b : bytes) { + if (b != 0) return false; + } + return true; + } + + /// Format as lowercase 8-4-4-4-12 hex string. + [[nodiscard]] std::string to_string() const + { + return std::format( + "{:02x}{:02x}{:02x}{:02x}-" + "{:02x}{:02x}-" + "{:02x}{:02x}-" + "{:02x}{:02x}-" + "{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", + bytes[0], bytes[1], bytes[2], bytes[3], + bytes[4], bytes[5], + bytes[6], bytes[7], + bytes[8], bytes[9], + bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]); + } + + [[nodiscard]] static Uuid nil() noexcept { return {}; } +}; + +// ── v4 (random) ─────────────────────────────────────────────────────────────── + +[[nodiscard]] inline Uuid v4() noexcept +{ + Uuid u; + Random::fill_random( + {reinterpret_cast(u.bytes.data()), u.bytes.size()}); + // version 4 + u.bytes[6] = (u.bytes[6] & 0x0F) | 0x40; + // variant 10xx (RFC 4122) + u.bytes[8] = (u.bytes[8] & 0x3F) | 0x80; + return u; +} + +// ── v5 (name-based SHA-1 substitute using FNV-1a + CRC-32) ────────────────── +// Not cryptographically equivalent to SHA-1, but deterministic and collision- +// resistant enough for UUID namespacing without pulling in a crypto library. + +[[nodiscard]] inline Uuid v5_lite(Uuid ns, std::string_view name) noexcept +{ + Uuid u; + // Mix namespace bytes + name bytes using two orthogonal hash functions. + std::string blob; + blob.reserve(16 + name.size()); + for (auto b : ns.bytes) blob += static_cast(b); + blob += name; + + const std::uint64_t h64 = Hash::fnv1a64(blob); + const std::uint32_t h32 = Hash::crc32(blob); + + u.bytes[0] = static_cast(h64 >> 56); + u.bytes[1] = static_cast(h64 >> 48); + u.bytes[2] = static_cast(h64 >> 40); + u.bytes[3] = static_cast(h64 >> 32); + u.bytes[4] = static_cast(h64 >> 24); + u.bytes[5] = static_cast(h64 >> 16); + u.bytes[6] = static_cast((h64 >> 8) & 0x0F) | 0x50; // version 5 + u.bytes[7] = static_cast(h64); + u.bytes[8] = static_cast((h32 >> 24) & 0x3F) | 0x80; // variant + u.bytes[9] = static_cast(h32 >> 16); + u.bytes[10] = static_cast(h32 >> 8); + u.bytes[11] = static_cast(h32); + // Refill bytes 12-15 by re-hashing + const std::uint32_t h32b = Hash::murmur3_32(name, static_cast(h64)); + u.bytes[12] = static_cast(h32b >> 24); + u.bytes[13] = static_cast(h32b >> 16); + u.bytes[14] = static_cast(h32b >> 8); + u.bytes[15] = static_cast(h32b); + return u; +} + +// ── Parsing ─────────────────────────────────────────────────────────────────── + +[[nodiscard]] inline std::optional parse(std::string_view s) noexcept +{ + // Accept "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" (36 chars) or 32 hex chars. + if (s.size() == 36 && + s[8] == '-' && s[13] == '-' && s[18] == '-' && s[23] == '-') { + std::string flat; + flat.reserve(32); + for (std::size_t i = 0; i < s.size(); ++i) { + if (s[i] != '-') flat += s[i]; + } + s = flat; // rebind for uniform parsing below + if (flat.size() != 32) return std::nullopt; + Uuid u; + for (std::size_t i = 0; i < 16; ++i) { + const char hi = flat[i * 2]; + const char lo = flat[i * 2 + 1]; + auto hex = [](char c) -> std::optional { + if (c >= '0' && c <= '9') return static_cast(c - '0'); + if (c >= 'a' && c <= 'f') return static_cast(c - 'a' + 10); + if (c >= 'A' && c <= 'F') return static_cast(c - 'A' + 10); + return std::nullopt; + }; + auto h = hex(hi), l = hex(lo); + if (!h || !l) return std::nullopt; + u.bytes[i] = static_cast((*h << 4) | *l); + } + return u; + } + if (s.size() == 32) { + Uuid u; + for (std::size_t i = 0; i < 16; ++i) { + auto hex = [](char c) -> std::optional { + if (c >= '0' && c <= '9') return static_cast(c - '0'); + if (c >= 'a' && c <= 'f') return static_cast(c - 'a' + 10); + if (c >= 'A' && c <= 'F') return static_cast(c - 'A' + 10); + return std::nullopt; + }; + auto h = hex(s[i * 2]), l = hex(s[i * 2 + 1]); + if (!h || !l) return std::nullopt; + u.bytes[i] = static_cast((*h << 4) | *l); + } + return u; + } + return std::nullopt; +} + +// ── Well-known namespaces (RFC 4122) ───────────────────────────────────────── + +namespace Namespace +{ +// 6ba7b810-9dad-11d1-80b4-00c04fd430c8 +inline constexpr Uuid Dns{{ + 0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, + 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}}; +// 6ba7b811-9dad-11d1-80b4-00c04fd430c8 +inline constexpr Uuid Url{{ + 0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, + 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}}; +} // namespace Namespace + +} // namespace Void::Uuid diff --git a/src/Concurrency/module.cmake b/src/Concurrency/module.cmake new file mode 100644 index 0000000..5792ffa --- /dev/null +++ b/src/Concurrency/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Concurrency + INTERNAL_DEPS Log +) diff --git a/src/Configuration/module.cmake b/src/Configuration/module.cmake new file mode 100644 index 0000000..2924c26 --- /dev/null +++ b/src/Configuration/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Configuration + INTERNAL_DEPS Result FileSystem Log +) diff --git a/src/FileSystem/module.cmake b/src/FileSystem/module.cmake index 9d07866..87215ac 100644 --- a/src/FileSystem/module.cmake +++ b/src/FileSystem/module.cmake @@ -1,3 +1,3 @@ void_add_module(FileSystem - INTERNAL_DEPS Result + INTERNAL_DEPS Result Log ) diff --git a/src/Log/Log.cpp b/src/Log/Log.cpp new file mode 100644 index 0000000..d137402 --- /dev/null +++ b/src/Log/Log.cpp @@ -0,0 +1,28 @@ +#include +#include +#include + +namespace Void::Log +{ + + namespace + { + Sink g_sink; + std::shared_mutex g_mutex; + } // namespace + + void set_sink(Sink sink) + { + std::unique_lock lock{g_mutex}; + g_sink = std::move(sink); + } + + void log(Level level, std::string_view module, std::string_view message) + { + std::shared_lock lock{g_mutex}; + if (g_sink) { + g_sink(level, module, message); + } + } + +} // namespace Void::Log diff --git a/src/Log/module.cmake b/src/Log/module.cmake new file mode 100644 index 0000000..51b5cf1 --- /dev/null +++ b/src/Log/module.cmake @@ -0,0 +1 @@ +void_add_module(Log) diff --git a/src/Logging/ConsoleLogger.cpp b/src/Logging/ConsoleLogger.cpp index 972c9e2..d932005 100644 --- a/src/Logging/ConsoleLogger.cpp +++ b/src/Logging/ConsoleLogger.cpp @@ -1,3 +1,4 @@ +#include #include #ifdef VOID_HAS_STACKTRACE @@ -19,6 +20,28 @@ namespace Void::Logging std::string_view color_for(Level level) { using namespace Void::Stacktrace::Color; +#ifdef VOID_HAS_ENUM_REFLECTION + static constexpr auto enumerators = + std::define_static_array(std::meta::enumerators_of(^^Level)); + template for (constexpr auto e : enumerators) { + if (level == [:e:]) { + if constexpr (std::meta::identifier_of(e) == "Trace") + return dim; + if constexpr (std::meta::identifier_of(e) == "Debug") + return cyan; + if constexpr (std::meta::identifier_of(e) == "Info") + return bold_cyan; + if constexpr (std::meta::identifier_of(e) == "Warning") + return bold_yellow; + if constexpr (std::meta::identifier_of(e) == "Error") + return bold_red; + if constexpr (std::meta::identifier_of(e) == "Fatal") + return bold_magenta; + return reset; + } + } + return reset; +#else switch (level) { case Level::Trace: return dim; @@ -35,6 +58,7 @@ namespace Void::Logging default: return reset; } +#endif } #endif diff --git a/src/Logging/FileLogger.cpp b/src/Logging/FileLogger.cpp index 1c5d28a..396fb49 100644 --- a/src/Logging/FileLogger.cpp +++ b/src/Logging/FileLogger.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -9,12 +10,17 @@ namespace Void::Logging FileLogger::FileLogger(const std::filesystem::path& path, Mode mode, std::size_t capacity) - : Logger(mode, capacity), m_file(path, std::ios::app) + : Logger(mode, capacity), m_path(path), m_file(path, std::ios::app) { if (!m_file.is_open()) { + Void::Log::log( + Void::Log::Level::Warning, "Logging", + std::format("FileLogger: cannot open '{}'", path.string())); throw std::runtime_error( std::format("FileLogger: cannot open '{}'", path.string())); } + Void::Log::log(Void::Log::Level::Debug, "Logging", + std::format("FileLogger: opened '{}'", path.string())); } Void::Result::Result, Void::Result::Error> @@ -30,7 +36,13 @@ namespace Void::Logging } } - FileLogger::~FileLogger() noexcept { flush(); } + FileLogger::~FileLogger() noexcept + { + flush(); + Void::Log::log(Void::Log::Level::Debug, "Logging", + std::format("FileLogger: closed '{}'", + m_path.string())); + } void FileLogger::write(const Entry& entry) { diff --git a/src/Logging/module.cmake b/src/Logging/module.cmake index 66dfd2b..698066f 100644 --- a/src/Logging/module.cmake +++ b/src/Logging/module.cmake @@ -1,4 +1,4 @@ void_add_module(Logging - INTERNAL_DEPS Result + INTERNAL_DEPS Result Log OPTIONAL_DEPS Stacktrace ) diff --git a/src/Process/Process.cpp b/src/Process/Process.cpp new file mode 100644 index 0000000..9d60094 --- /dev/null +++ b/src/Process/Process.cpp @@ -0,0 +1,253 @@ +#include +#include + +#include + +#ifdef _WIN32 + +namespace Void::Process +{ + Void::Result::Result + run(const std::filesystem::path&, + std::vector, + std::string_view, + std::chrono::milliseconds) + { + return Void::Result::fail( + "Process::run: not implemented on Windows"); + } + + Void::Result::Result + shell(std::string_view, std::chrono::milliseconds) + { + return Void::Result::fail( + "Process::shell: not implemented on Windows"); + } +} // namespace Void::Process + +#else // POSIX + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::Process +{ + +namespace +{ + // Read into buf until EAGAIN (no more data right now) or EOF. + // Returns true on EOF, false on EAGAIN. + bool drain(int fd, std::string& buf) + { + char tmp[4096]; + for (;;) { + ssize_t n = ::read(fd, tmp, sizeof(tmp)); + if (n > 0) { + buf.append(tmp, static_cast(n)); + } else if (n == 0) { + return true; // EOF + } else { + if (errno == EINTR) { + continue; + } + // EAGAIN / EWOULDBLOCK: no data right now + return false; + } + } + } + + void set_nonblock(int fd) + { + int flags = ::fcntl(fd, F_GETFL, 0); + if (flags >= 0) { + ::fcntl(fd, F_SETFL, flags | O_NONBLOCK); + } + } + + // Close an fd if it is >= 0, then set it to -1. + void safe_close(int& fd) + { + if (fd >= 0) { + ::close(fd); + fd = -1; + } + } +} // namespace + +Void::Result::Result + run(const std::filesystem::path& executable, + std::vector args, + std::string_view stdin_data, + std::chrono::milliseconds timeout) +{ + // [0] = read end, [1] = write end + int stdin_pipe[2] = {-1, -1}; + int stdout_pipe[2] = {-1, -1}; + int stderr_pipe[2] = {-1, -1}; + + if (::pipe(stdin_pipe) != 0 || ::pipe(stdout_pipe) != 0 || + ::pipe(stderr_pipe) != 0) { + safe_close(stdin_pipe[0]); + safe_close(stdin_pipe[1]); + safe_close(stdout_pipe[0]); + safe_close(stdout_pipe[1]); + safe_close(stderr_pipe[0]); + safe_close(stderr_pipe[1]); + return Void::Result::fail(std::format("Process::run: pipe() failed: {}", + std::strerror(errno))); + } + + Void::Log::log(Void::Log::Level::Debug, "Process", + std::format("run: '{}'", executable.string())); + + std::vector argv; + argv.push_back(executable.c_str()); + for (const auto& a : args) { + argv.push_back(a.c_str()); + } + argv.push_back(nullptr); + + pid_t pid = ::fork(); + if (pid < 0) { + safe_close(stdin_pipe[0]); + safe_close(stdin_pipe[1]); + safe_close(stdout_pipe[0]); + safe_close(stdout_pipe[1]); + safe_close(stderr_pipe[0]); + safe_close(stderr_pipe[1]); + return Void::Result::fail(std::format("Process::run: fork() failed: {}", + std::strerror(errno))); + } + + if (pid == 0) { + // Child process + ::dup2(stdin_pipe[0], STDIN_FILENO); + ::dup2(stdout_pipe[1], STDOUT_FILENO); + ::dup2(stderr_pipe[1], STDERR_FILENO); + ::close(stdin_pipe[0]); + ::close(stdin_pipe[1]); + ::close(stdout_pipe[0]); + ::close(stdout_pipe[1]); + ::close(stderr_pipe[0]); + ::close(stderr_pipe[1]); + ::execvp(executable.c_str(), + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + const_cast(argv.data())); + // execvp only returns on error; 127 is the POSIX convention + ::_exit(127); + } + + // Parent: close child-side ends + safe_close(stdin_pipe[0]); + safe_close(stdout_pipe[1]); + safe_close(stderr_pipe[1]); + + // Write stdin and close immediately so the child sees EOF + if (!stdin_data.empty()) { + const char* p = stdin_data.data(); + std::size_t remaining = stdin_data.size(); + while (remaining > 0) { + ssize_t n = ::write(stdin_pipe[1], p, remaining); + if (n < 0) { + if (errno == EINTR) { + continue; + } + break; // child likely closed stdin; ignore + } + p += static_cast(n); + remaining -= static_cast(n); + } + } + safe_close(stdin_pipe[1]); + + set_nonblock(stdout_pipe[0]); + set_nonblock(stderr_pipe[0]); + + Output output; + bool out_done = false; + bool err_done = false; + + const bool has_timeout = timeout.count() > 0; + const auto deadline = + std::chrono::steady_clock::now() + + (has_timeout ? timeout : std::chrono::milliseconds{30'000}); + + while (!out_done || !err_done) { + struct pollfd pfds[2]; + int nfds = 0; + if (!out_done) { + pfds[nfds++] = {stdout_pipe[0], POLLIN, 0}; + } + if (!err_done) { + pfds[nfds++] = {stderr_pipe[0], POLLIN, 0}; + } + + auto left_ms = std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()) + .count(); + if (left_ms <= 0) { + ::kill(pid, SIGTERM); + break; + } + + int ret = ::poll(pfds, static_cast(nfds), + static_cast(left_ms)); + if (ret < 0) { + if (errno == EINTR) { + continue; + } + break; + } + if (ret == 0) { + // Wall-clock timeout expired + ::kill(pid, SIGTERM); + break; + } + + for (int i = 0; i < nfds; ++i) { + if ((pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) == 0) { + continue; + } + bool& done = + (pfds[i].fd == stdout_pipe[0]) ? out_done : err_done; + std::string& buf = + (pfds[i].fd == stdout_pipe[0]) ? output.out : output.err; + bool eof = drain(pfds[i].fd, buf); + // POLLHUP means the write end was closed; no more data will arrive + if (eof || (pfds[i].revents & (POLLHUP | POLLERR))) { + done = true; + } + } + } + + safe_close(stdout_pipe[0]); + safe_close(stderr_pipe[0]); + + int status = 0; + ::waitpid(pid, &status, 0); + output.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1; + + Void::Log::log( + Void::Log::Level::Debug, "Process", + std::format("run: '{}' exited {}", executable.string(), + output.exit_code)); + + return Void::Result::ok(std::move(output)); +} + +Void::Result::Result + shell(std::string_view command, std::chrono::milliseconds timeout) +{ + return run("/bin/sh", {"-c", std::string{command}}, {}, timeout); +} + +} // namespace Void::Process + +#endif // _WIN32 diff --git a/src/Process/module.cmake b/src/Process/module.cmake new file mode 100644 index 0000000..3b5c29c --- /dev/null +++ b/src/Process/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Process + INTERNAL_DEPS Result Log +) diff --git a/src/Stacktrace/Stacktrace.cpp b/src/Stacktrace/Stacktrace.cpp index cdcba28..ed197e8 100644 --- a/src/Stacktrace/Stacktrace.cpp +++ b/src/Stacktrace/Stacktrace.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -37,6 +38,8 @@ namespace Void::Stacktrace } } catch (...) { } + Void::Log::log(Void::Log::Level::Debug, "Stacktrace", + std::format("captured {} frames", result.size())); return result; } @@ -46,6 +49,9 @@ namespace Void::Stacktrace { std::ifstream ifs{file}; if (!ifs.is_open()) { + Void::Log::log( + Void::Log::Level::Warning, "Stacktrace", + std::format("read_source_snippet: cannot open '{}'", file)); return Void::Result::fail( std::format("read_source_snippet: cannot open '{}'", file)); } diff --git a/src/Stacktrace/module.cmake b/src/Stacktrace/module.cmake index 7f3e3a8..b13ca16 100644 --- a/src/Stacktrace/module.cmake +++ b/src/Stacktrace/module.cmake @@ -1,5 +1,5 @@ void_add_module(Stacktrace - INTERNAL_DEPS Result + INTERNAL_DEPS Result Log EXTERNAL_DEPS Boost::stacktrace_backtrace DEPS_WIN32 dbghelp DEPS_UNIX dl diff --git a/src/String/.keep b/src/String/.keep new file mode 100644 index 0000000..e69de29 diff --git a/src/Testing/ConsoleReporter.cpp b/src/Testing/ConsoleReporter.cpp index c4496cb..718071f 100644 --- a/src/Testing/ConsoleReporter.cpp +++ b/src/Testing/ConsoleReporter.cpp @@ -1,12 +1,11 @@ #include -#include #include #include #include #include namespace Void::Testing { -using namespace Void::Stacktrace::Color; +using namespace Void::Testing::Detail::Color; void ConsoleReporter::on_run_start(const RunConfig&, int total_tests) { os_ << "\n" << apply(bold_blue, "╭──────────────────────────────────────────────╮") << "\n" diff --git a/src/Testing/Runner.cpp b/src/Testing/Runner.cpp index f845445..47fe428 100644 --- a/src/Testing/Runner.cpp +++ b/src/Testing/Runner.cpp @@ -1,17 +1,43 @@ #include #include "Void/Testing/Config.hpp" -#include -#include +#include +#include +#include #include -#include -#include + +#ifdef VOID_HAS_STACKTRACE #include +#endif +#include #include #include #include +#include + +#ifdef VOID_HAS_CONCURRENCY +#include +#include +#endif + +#ifdef VOID_HAS_CONFIGURATION +#include +#else +#include +#endif + +#ifdef VOID_HAS_LOGGING +#include +#include +#include +#include +#endif + +#ifdef VOID_HAS_STRING +#include +#endif + #include #include -#include #include #include #include @@ -28,9 +54,10 @@ namespace Void::Testing RunConfig config; for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; - if ((arg == "--filter" || arg == "--suite" || arg == "--reporter" || - arg == "--output" || arg == "--tag" || arg == "--seed" || - arg == "--repeat" || arg == "--log-file") && + if ((arg == "--filter" || arg == "--suite" || + arg == "--reporter" || arg == "--output" || + arg == "--tag" || arg == "--seed" || arg == "--repeat" || + arg == "--log-file" || arg == "--parallel") && i + 1 < argc) { std::string val = argv[++i]; if (arg == "--filter") { @@ -47,11 +74,14 @@ namespace Void::Testing config.log_file = val; } else if (arg == "--seed") { config.shuffle = true; - config.random_seed = static_cast(std::stoul(val)); + config.random_seed = + static_cast(std::stoul(val)); } else if (arg == "--repeat") { config.repeat = static_cast(std::stoul(val)); + } else if (arg == "--parallel") { + config.parallel_threads = + static_cast(std::stoul(val)); } - } else if (arg == "--help") { config.show_help = true; } else if (arg == "--list") { @@ -138,10 +168,11 @@ namespace Void::Testing int crash_signal = 0; std::string crash_stacktrace; - Detail::install_signal_handlers([&](int sig, const std::string& trace) { - crash_signal = sig; - crash_stacktrace = trace; - }); + Detail::install_signal_handlers( + [&](int sig, const std::string& trace) { + crash_signal = sig; + crash_stacktrace = trace; + }); auto start = std::chrono::high_resolution_clock::now(); try { @@ -167,13 +198,17 @@ namespace Void::Testing result.state = TestState::Failed; result.crash_info = std::format("Unhandled exception: {}", e.what()); +#ifdef VOID_HAS_STACKTRACE result.stacktrace = Void::Stacktrace::format_stacktrace( Void::Stacktrace::capture_stacktrace(1, 8)); +#endif } catch (...) { result.state = TestState::Failed; result.crash_info = "Unhandled unknown exception"; +#ifdef VOID_HAS_STACKTRACE result.stacktrace = Void::Stacktrace::format_stacktrace( Void::Stacktrace::capture_stacktrace(1, 8)); +#endif } auto end = std::chrono::high_resolution_clock::now(); @@ -183,9 +218,56 @@ namespace Void::Testing if (result.state != TestState::Skipped && result.state != TestState::Crashed) { - bool any = - std::any_of(result.assertions.begin(), result.assertions.end(), - [](const auto& a) { return !a.passed; }); + bool any = std::any_of( + result.assertions.begin(), result.assertions.end(), + [](const auto& a) { return !a.passed; }); + result.state = any ? TestState::Failed : TestState::Passed; + } + return result; + } + + // Like execute_test() but without sigsetjmp/signal-handler installation, + // safe to call from multiple threads simultaneously. + TestResult Runner::execute_test_parallel(TestCase& test_case) + { + TestResult result; + result.name = test_case.name; + result.suite = test_case.suite; + result.tags = test_case.tags; + if (test_case.disabled) { + result.state = TestState::Skipped; + result.skip_reason = test_case.skip_reason.empty() + ? "disabled" + : test_case.skip_reason; + return result; + } + Detail::TestContext::current().current_result = &result; + Detail::TestContext::current().should_abort = false; + + auto start = std::chrono::high_resolution_clock::now(); + try { + run_test_body(test_case, result); + } catch (const Detail::RequireFailure&) { + if (result.state != TestState::Skipped) { + result.state = TestState::Failed; + } + } catch (const std::exception& e) { + result.state = TestState::Failed; + result.crash_info = + std::format("Unhandled exception: {}", e.what()); + } catch (...) { + result.state = TestState::Failed; + result.crash_info = "Unhandled unknown exception"; + } + auto end = std::chrono::high_resolution_clock::now(); + result.duration = end - start; + Detail::TestContext::current().current_result = nullptr; + + if (result.state != TestState::Skipped && + result.state != TestState::Crashed) { + bool any = std::any_of( + result.assertions.begin(), result.assertions.end(), + [](const auto& a) { return !a.passed; }); result.state = any ? TestState::Failed : TestState::Passed; } return result; @@ -215,56 +297,103 @@ namespace Void::Testing RunResult Runner::run(const RunConfig& config) { - Void::Stacktrace::Color::g_color_enabled = !config.no_color; + Void::Testing::Detail::Color::g_color_enabled = !config.no_color; if (config.show_help) { - using namespace Void::Stacktrace::Color; + using namespace Void::Testing::Detail::Color; std::cout << "\n" - << apply(bold_blue, "╭─────────────────────────────────────────" - "─────────────────────────╮") + << apply(bold_blue, + "\xe2\x95\xad\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x95\xae") << "\n" - << apply(bold_blue, "│") << apply(bold_white, " Void Testing") - << apply(dim, " — Command Line Interface") - << std::string(28, ' ') << apply(bold_blue, "│") << "\n" - << apply(bold_blue, "╰─────────────────────────────────────────" - "─────────────────────────╯") + << apply(bold_blue, "\xe2\x94\x82") + << apply(bold_white, " Void Testing") + << apply(dim, " \xe2\x80\x94 Command Line Interface") + << std::string(28, ' ') << apply(bold_blue, "\xe2\x94\x82") + << "\n" + << apply(bold_blue, + "\xe2\x95\xb0\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" + "\xe2\x94\x80\xe2\x94\x80\xe2\x95\xaf") << "\n" << "\n" << " " << apply(bold_white, "USAGE:") << "\n" << " " << apply(cyan, "") << " " << apply(dim, "[options]") << "\n" << "\n" - << " " << apply(bold_white, "OPTIONS:") << "\n" - << " " << apply(green, "--filter ") + << " " << apply(bold_white, "OPTIONS:") << "\n"; + + constexpr std::size_t OPT_WIDTH = 23; + auto opt = [&](std::string_view name) { +#ifdef VOID_HAS_STRING + return apply(green, Void::String::pad_right(name, OPT_WIDTH)); +#else + std::string s{name}; + if (s.size() < OPT_WIDTH) { + s.append(OPT_WIDTH - s.size(), ' '); + } + return apply(green, s); +#endif + }; + + std::cout + << " " << opt("--filter ") << apply(dim, "Run tests matching the regex pattern") << "\n" - << " " << apply(green, "--suite ") + << " " << opt("--suite ") << apply(dim, "Run only tests in the specified suite") << "\n" - << " " << apply(green, "--tag ") + << " " << opt("--tag ") << apply(dim, "Run only tests with the specified tag") << "\n" - << " " << apply(green, "--list ") + << " " << opt("--list") << apply(dim, "List discovered tests without running them") << "\n" - << " " << apply(green, "--shuffle ") + << " " << opt("--shuffle") << apply(dim, "Randomize the order of test execution") << "\n" - << " " << apply(green, "--seed ") + << " " << opt("--seed ") << apply(dim, "Set the random seed (implies --shuffle)") << "\n" - << " " << apply(green, "--repeat ") + << " " << opt("--repeat ") << apply(dim, "Repeat the test run n times") << "\n" - << " " << apply(green, "--reporter ") + << " " << opt("--reporter ") << apply(dim, "Choose the output reporter: console, junit") << "\n" - << " " << apply(green, "--output ") + << " " << opt("--output ") << apply(dim, "Write reporter output to a file") << "\n" - << " " << apply(green, "--log-file ") +#ifdef VOID_HAS_LOGGING + << " " << opt("--log-file ") << apply(dim, "Mirror test events to via Void::Logging") << "\n" - << " " << apply(green, "--verbose ") +#endif +#ifdef VOID_HAS_CONCURRENCY + << " " << opt("--parallel ") + << apply(dim, + "Run tests across n threads (no crash detection)") + << "\n" +#endif + << " " << opt("--verbose") << apply(dim, "Enable verbose output") << "\n" - << " " << apply(green, "--no-color ") + << " " << opt("--no-color") << apply(dim, "Disable colored console output") << "\n" - << " " << apply(green, "--help ") + << " " << opt("--help") << apply(dim, "Show this help message") << "\n" << "\n" << " " << apply(bold_white, "EXAMPLES:") << "\n" @@ -284,6 +413,8 @@ namespace Void::Testing auto tests = filter_tests(all_tests, config); auto reporter = create_reporter(config); +// ── Optional: file logger sink (requires Void::Logging) ────────────────── +#ifdef VOID_HAS_LOGGING std::unique_ptr log_sink; if (!config.log_file.empty()) { try { @@ -294,6 +425,45 @@ namespace Void::Testing << "\n"; } } +#else + if (!config.log_file.empty()) { + std::cerr + << "warning: --log-file requires Void::Logging (not linked)\n"; + } +#endif + +// ── Optional: VOID_LOG_LEVEL auto-sink ─────────────────────────────────── +#ifdef VOID_HAS_LOGGING + std::unique_ptr env_log; + { +#ifdef VOID_HAS_CONFIGURATION + const auto lvl_str = + Void::Configuration::get_env_or("VOID_LOG_LEVEL"); +#else + const char* raw_env = + std::getenv("VOID_LOG_LEVEL"); // NOLINT(concurrency-mt-unsafe) + const std::string lvl_str = raw_env ? raw_env : ""; +#endif + if (!lvl_str.empty()) { +#ifdef VOID_HAS_ENUM_REFLECTION + auto level = + Void::Detail::enum_parse(lvl_str) + .value_or(Void::Logging::Level::Info); +#else + Void::Logging::Level level = Void::Logging::Level::Info; + if (lvl_str == "Trace") level = Void::Logging::Level::Trace; + else if (lvl_str == "Debug") level = Void::Logging::Level::Debug; + else if (lvl_str == "Warning") level = Void::Logging::Level::Warning; + else if (lvl_str == "Error") level = Void::Logging::Level::Error; + else if (lvl_str == "Fatal") level = Void::Logging::Level::Fatal; +#endif + env_log = + std::make_unique(std::cerr); + env_log->set_level(level); + Void::Log::set_sink(Void::Log::make_sink(*env_log)); + } + } +#endif // VOID_HAS_LOGGING if (config.list_only) { for (const auto& t : tests) { @@ -304,19 +474,6 @@ namespace Void::Testing } RunResult run_result; - reporter->on_run_start(config, static_cast(tests.size())); - if (log_sink) { - log_sink->info(std::format("run start: {} test(s) discovered", - tests.size())); - } - if (config.shuffle) { - std::shuffle(tests.begin(), tests.end(), - std::mt19937{config.random_seed}); - if (log_sink) { - log_sink->info(std::format("shuffle enabled (seed = {})", - config.random_seed)); - } - } std::vector suite_results; std::unordered_map suite_index; @@ -326,58 +483,148 @@ namespace Void::Testing suite_results.push_back({.name = test.suite}); } } + + auto log_result = [&](const TestResult& r, const std::string& q) { +#ifdef VOID_HAS_LOGGING + if (!log_sink) { + return; + } + const auto ts = Void::Time::utc_now_iso8601_ms(); + const auto dur = Void::Time::format_duration(r.duration); + switch (r.state) { + case TestState::Passed: + log_sink->info(std::format("[{}] test pass: {} ({})", ts, + q, dur)); + break; + case TestState::Failed: + log_sink->error(std::format( + "[{}] test fail: {} ({}) \xe2\x80\x94 {}", ts, q, dur, + r.crash_info.empty() ? "assertion failed" + : r.crash_info)); + break; + case TestState::Skipped: + log_sink->warning(std::format( + "[{}] test skip: {} \xe2\x80\x94 {}", ts, q, + r.skip_reason.empty() ? "no reason" : r.skip_reason)); + break; + case TestState::Crashed: + log_sink->fatal(std::format( + "[{}] test crash: {} \xe2\x80\x94 {}", ts, q, + r.crash_info)); + break; + } +#else + (void)r; + (void)q; +#endif + }; + auto start_time = std::chrono::high_resolution_clock::now(); - for (unsigned rep = 0; rep < config.repeat; ++rep) { +// ── Optional: parallel execution (requires Void::Concurrency) ──────────── + bool run_parallel = config.parallel_threads > 0; +#ifndef VOID_HAS_CONCURRENCY + if (run_parallel) { + std::cerr << "warning: --parallel requires Void::Concurrency " + "(not linked); running sequentially\n"; + run_parallel = false; + } +#endif + + if (run_parallel) { +#ifdef VOID_HAS_CONCURRENCY + reporter->on_run_start(config, static_cast(tests.size())); +#ifdef VOID_HAS_LOGGING + if (log_sink) { + log_sink->info(std::format( + "run start (parallel, {} threads): {} test(s)", + config.parallel_threads, tests.size())); + } +#endif + Void::Concurrency::ThreadPool pool{config.parallel_threads}; + std::vector> futures; + futures.reserve(tests.size()); for (auto& test : tests) { - auto& suite = suite_results[suite_index[test.suite]]; - if (rep == 0) { + futures.push_back(pool.submit( + [this, &test] { return execute_test_parallel(test); })); + } + std::vector par_results; + par_results.reserve(tests.size()); + for (auto& fut : futures) { + par_results.push_back(fut.get()); + } + + std::unordered_map suite_started; + for (std::size_t i = 0; i < tests.size(); ++i) { + auto& test = tests[i]; + auto& result = par_results[i]; + if (!suite_started[test.suite]) { + suite_started[test.suite] = true; reporter->on_suite_start( - suite.name, std::count_if(tests.begin(), tests.end(), - [&](const auto& t) { - return t.suite == - suite.name; - })); - if (log_sink) { - log_sink->info( - std::format("suite start: {}", suite.name)); - } + test.suite, + static_cast( + std::count_if(tests.begin(), tests.end(), + [&](const auto& t) { + return t.suite == test.suite; + }))); } reporter->on_test_start(test); - auto result = execute_test(test); reporter->on_test_end(result); + log_result(result, std::format("{}.{}", result.suite, + result.name)); + suite_results[suite_index[test.suite]].tests.push_back( + std::move(result)); + } +#endif // VOID_HAS_CONCURRENCY + } else { + reporter->on_run_start(config, static_cast(tests.size())); +#ifdef VOID_HAS_LOGGING + if (log_sink) { + log_sink->info(std::format("run start: {} test(s) discovered", + tests.size())); + } +#endif + if (config.shuffle) { + std::shuffle(tests.begin(), tests.end(), + std::mt19937{config.random_seed}); +#ifdef VOID_HAS_LOGGING if (log_sink) { - const auto qualified = - std::format("{}.{}", result.suite, result.name); - switch (result.state) { - case TestState::Passed: - log_sink->info( - std::format("test pass: {}", qualified)); - break; - case TestState::Failed: - log_sink->error(std::format( - "test fail: {} — {}", qualified, - result.crash_info.empty() ? "assertion failed" - : result.crash_info)); - break; - case TestState::Skipped: - log_sink->warning(std::format( - "test skip: {} ({})", qualified, - result.skip_reason.empty() ? "no reason" - : result.skip_reason)); - break; - case TestState::Crashed: - log_sink->fatal(std::format( - "test crash: {} — {}", qualified, - result.crash_info)); - break; - } + log_sink->info(std::format("shuffle enabled (seed = {})", + config.random_seed)); } - if (rep == config.repeat - 1) { - suite.tests.push_back(std::move(result)); +#endif + } + + for (unsigned rep = 0; rep < config.repeat; ++rep) { + for (auto& test : tests) { + auto& suite = suite_results[suite_index[test.suite]]; + if (rep == 0) { + reporter->on_suite_start( + suite.name, + std::count_if( + tests.begin(), tests.end(), + [&](const auto& t) { + return t.suite == suite.name; + })); +#ifdef VOID_HAS_LOGGING + if (log_sink) { + log_sink->info(std::format("suite start: {}", + suite.name)); + } +#endif + } + reporter->on_test_start(test); + auto result = execute_test(test); + reporter->on_test_end(result); + log_result(result, std::format("{}.{}", result.suite, + result.name)); + if (rep == config.repeat - 1) { + suite.tests.push_back(std::move(result)); + } } } } + auto end_time = std::chrono::high_resolution_clock::now(); for (auto& suite : suite_results) { @@ -403,12 +650,19 @@ namespace Void::Testing } run_result.total_duration = end_time - start_time; reporter->on_run_end(run_result); +#ifdef VOID_HAS_LOGGING if (log_sink) { - log_sink->info(std::format( - "run end: {} total / {} passed / {} failed / {} skipped / {} crashed", - run_result.total, run_result.passed, run_result.failed, - run_result.skipped, run_result.crashed)); + log_sink->info( + std::format("run end: {} total / {} passed / {} failed / {} " + "skipped / {} crashed", + run_result.total, run_result.passed, + run_result.failed, run_result.skipped, + run_result.crashed)); } + if (env_log) { + Void::Log::set_sink({}); + } +#endif return run_result; } diff --git a/src/Testing/SignalHandler.cpp b/src/Testing/SignalHandler.cpp index 2a1bfdf..8b5e383 100644 --- a/src/Testing/SignalHandler.cpp +++ b/src/Testing/SignalHandler.cpp @@ -1,5 +1,7 @@ #include +#ifdef VOID_HAS_STACKTRACE #include +#endif #include #include #include @@ -30,8 +32,12 @@ const char* signal_name(int sig) { static void crash_handler(int sig) { g_last_signal = sig; +#ifdef VOID_HAS_STACKTRACE auto frames = Void::Stacktrace::capture_stacktrace(1, 16); auto trace = Void::Stacktrace::format_stacktrace(frames); +#else + std::string trace; +#endif if (g_crash_callback) g_crash_callback(sig, trace); #ifndef _WIN32 if (g_jump_ready) { g_jump_ready = false; siglongjmp(g_jump_buffer, sig); } diff --git a/src/Testing/module.cmake b/src/Testing/module.cmake index 6704ee6..3c57aa4 100644 --- a/src/Testing/module.cmake +++ b/src/Testing/module.cmake @@ -1 +1,3 @@ -void_add_module(Testing INTERNAL_DEPS Stacktrace Logging Result) +void_add_module(Testing + OPTIONAL_DEPS Stacktrace Logging Concurrency Configuration String +) diff --git a/tests/internal/CrossModule.cpp b/tests/internal/CrossModule.cpp index db5e12c..75a1283 100644 --- a/tests/internal/CrossModule.cpp +++ b/tests/internal/CrossModule.cpp @@ -1,10 +1,12 @@ // Cross-module integration tests for the kitchen-sink VoidInternalTests -// binary. Exercises Logging + Result + Stacktrace + FileSystem working +// binary. Exercises Logging + Result + Stacktrace + FileSystem + Log working // together — the kind of thing the standalone per-module tests can't // reach because they only link one module. #include #include +#include +#include #include #include #include @@ -113,3 +115,57 @@ Void::Testing::Test error_chain_logged_to_file_roundtrip() Void::Testing::expect(content.find("socket closed") != std::string::npos); Void::Testing::expect(content.find("caused by:") != std::string::npos); } + +// Void::Log + Void::Logging: make_sink() bridges the two modules so that +// internal library events routed through Void::Log::log() surface in a +// Void::Logging::ConsoleLogger captured via a stringstream. +Void::Testing::Test log_adapter_routes_to_void_logging() +{ + std::ostringstream out; + Void::Logging::ConsoleLogger logger{out}; + logger.set_level(Void::Logging::Level::Trace); + + Void::Log::set_sink(Void::Log::make_sink(logger)); + + Void::Log::log( + Void::Log::Level::Info, "TestModule", "hello from Void::Log"); + Void::Log::log(Void::Log::Level::Warning, "TestModule", "a warning"); + + Void::Log::set_sink({}); + + const auto text = out.str(); + Void::Testing::expect(text.find("hello from Void::Log") != + std::string::npos); + Void::Testing::expect(text.find("a warning") != std::string::npos); + Void::Testing::expect(text.find("[TestModule]") != std::string::npos); +} + +// FileSystem operations now emit Void::Log events; verify they reach a sink. +Void::Testing::Test filesystem_ops_emit_log_events() +{ + int debug_count = 0; + int warning_count = 0; + Void::Log::set_sink( + [&](Void::Log::Level l, std::string_view, std::string_view) { + if (l == Void::Log::Level::Debug) { + ++debug_count; + } + if (l == Void::Log::Level::Warning) { + ++warning_count; + } + }); + + Void::FileSystem::TempDir tmp; + auto p = tmp / "test.txt"; + (void)Void::FileSystem::write_file(p, "data"); + (void)Void::FileSystem::read_file(p); + (void)Void::FileSystem::read_file(tmp / "nonexistent.txt"); + + Void::Log::set_sink({}); + + // TempDir creation + read success + write (no debug from write_file) = at + // least 2 + Void::Testing::expect(debug_count >= 2); + // Missing file read = 1 warning + Void::Testing::expect(warning_count >= 1); +} diff --git a/tests/standalone/Bits/Bits.cpp b/tests/standalone/Bits/Bits.cpp new file mode 100644 index 0000000..ff14e79 --- /dev/null +++ b/tests/standalone/Bits/Bits.cpp @@ -0,0 +1,138 @@ +#include +#include +#include + +#include + +// ── popcount ────────────────────────────────────────────────────────────────── + +Void::Testing::Test popcount_zero() +{ + Void::Testing::expect_eq(Void::Bits::popcount(0u), 0); +} + +Void::Testing::Test popcount_all_ones_u8() +{ + Void::Testing::expect_eq(Void::Bits::popcount(std::uint8_t{0xFF}), 8); +} + +Void::Testing::Test popcount_u32() +{ + Void::Testing::expect_eq(Void::Bits::popcount(std::uint32_t{0x0F0F0F0F}), 16); +} + +// ── test/set/clear/toggle ──────────────────────────────────────────────────── + +Void::Testing::Test test_bit_set() +{ + Void::Testing::expect(Void::Bits::test_bit(std::uint8_t{0b00000100u}, 2)); +} + +Void::Testing::Test test_bit_clear() +{ + Void::Testing::expect(!Void::Bits::test_bit(std::uint8_t{0b00000100u}, 0)); +} + +Void::Testing::Test set_bit_works() +{ + Void::Testing::expect_eq(Void::Bits::set_bit(std::uint8_t{0u}, 3), + std::uint8_t{0b00001000u}); +} + +Void::Testing::Test clear_bit_works() +{ + Void::Testing::expect_eq(Void::Bits::clear_bit(std::uint8_t{0xFF}, 3), + std::uint8_t{0b11110111u}); +} + +Void::Testing::Test toggle_bit_works() +{ + Void::Testing::expect_eq(Void::Bits::toggle_bit(std::uint8_t{0u}, 5), + std::uint8_t{0b00100000u}); +} + +// ── extract / deposit ───────────────────────────────────────────────────────── + +Void::Testing::Test extract_bits_works() +{ + // bits 4-7 of 0b10110100 = 0b1011 + Void::Testing::expect_eq( + Void::Bits::extract_bits(std::uint8_t{0b10110100u}, 4, 4), + std::uint8_t{0b1011u}); +} + +Void::Testing::Test deposit_bits_works() +{ + // deposit 0b1010 into bits 4-7 of 0x00 + Void::Testing::expect_eq( + Void::Bits::deposit_bits(std::uint8_t{0u}, std::uint8_t{0b1010u}, 4, 4), + std::uint8_t{0b10100000u}); +} + +// ── rotation ───────────────────────────────────────────────────────────────── + +Void::Testing::Test rotl_8() +{ + Void::Testing::expect_eq(Void::Bits::rotl(std::uint8_t{0b10000001u}, 1), + std::uint8_t{0b00000011u}); +} + +Void::Testing::Test rotr_8() +{ + Void::Testing::expect_eq(Void::Bits::rotr(std::uint8_t{0b10000001u}, 1), + std::uint8_t{0b11000000u}); +} + +// ── pow2 helpers ────────────────────────────────────────────────────────────── + +Void::Testing::Test has_single_bit() +{ + Void::Testing::expect(Void::Bits::has_single_bit(64u)); + Void::Testing::expect(!Void::Bits::has_single_bit(63u)); +} + +Void::Testing::Test ceil_pow2_works() +{ + Void::Testing::expect_eq(Void::Bits::ceil_pow2(5u), 8u); + Void::Testing::expect_eq(Void::Bits::ceil_pow2(8u), 8u); +} + +Void::Testing::Test floor_pow2_works() +{ + Void::Testing::expect_eq(Void::Bits::floor_pow2(5u), 4u); +} + +// ── align ──────────────────────────────────────────────────────────────────── + +Void::Testing::Test align_up_works() +{ + Void::Testing::expect_eq(Void::Bits::align_up(13u, 8u), 16u); + Void::Testing::expect_eq(Void::Bits::align_up(8u, 8u), 8u); +} + +Void::Testing::Test align_down_works() +{ + Void::Testing::expect_eq(Void::Bits::align_down(13u, 8u), 8u); +} + +// ── masks ──────────────────────────────────────────────────────────────────── + +Void::Testing::Test low_mask_works() +{ + Void::Testing::expect_eq(Void::Bits::low_mask(4), + std::uint8_t{0x0F}); +} + +Void::Testing::Test range_mask_works() +{ + Void::Testing::expect_eq(Void::Bits::range_mask(2, 5), + std::uint8_t{0b00111100u}); +} + +// ── byteswap / endian ──────────────────────────────────────────────────────── + +Void::Testing::Test byteswap_u32() +{ + Void::Testing::expect_eq(Void::Bits::byteswap(std::uint32_t{0x12345678u}), + std::uint32_t{0x78563412u}); +} diff --git a/tests/standalone/Concurrency/Channel.cpp b/tests/standalone/Concurrency/Channel.cpp new file mode 100644 index 0000000..c53092f --- /dev/null +++ b/tests/standalone/Concurrency/Channel.cpp @@ -0,0 +1,84 @@ +#include +#include +#include + +#include +#include + +using Void::Concurrency::Channel; + +Void::Testing::Test capacity_is_preserved() +{ + Channel ch{8}; + Void::Testing::expect_eq(ch.capacity(), std::size_t{8}); +} + +Void::Testing::Test try_send_and_try_receive_roundtrip() +{ + Channel ch{4}; + Void::Testing::expect(ch.try_send(10)); + Void::Testing::expect(ch.try_send(20)); + Void::Testing::expect_eq(ch.size(), std::size_t{2}); + auto v1 = ch.try_receive(); + Void::Testing::expect(v1.has_value()); + Void::Testing::expect_eq(*v1, 10); + auto v2 = ch.try_receive(); + Void::Testing::expect(v2.has_value()); + Void::Testing::expect_eq(*v2, 20); + auto empty = ch.try_receive(); + Void::Testing::expect(!empty.has_value()); +} + +Void::Testing::Test try_send_fails_when_full() +{ + Channel ch{2}; + Void::Testing::expect(ch.try_send(1)); + Void::Testing::expect(ch.try_send(2)); + Void::Testing::expect(!ch.try_send(3)); +} + +Void::Testing::Test close_unblocks_receiver() +{ + Channel ch{4}; + std::thread producer{[&] { ch.close(); }}; + auto val = ch.receive(); + producer.join(); + Void::Testing::expect(!val.has_value()); + Void::Testing::expect(ch.is_closed()); +} + +Void::Testing::Test producer_consumer_ordering() +{ + Channel ch{16}; + constexpr int N = 10; + std::thread producer{[&] { + for (int i = 0; i < N; ++i) { + ch.send(i); + } + ch.close(); + }}; + std::vector received; + while (auto v = ch.receive()) { + received.push_back(*v); + } + producer.join(); + Void::Testing::expect_eq(static_cast(received.size()), N); + for (int i = 0; i < N; ++i) { + Void::Testing::expect_eq(received[i], i); + } +} + +Void::Testing::Test try_send_fails_after_close() +{ + Channel ch{4}; + ch.close(); + Void::Testing::expect(!ch.try_send(1)); +} + +Void::Testing::Test send_returns_false_when_closed() +{ + Channel ch{1}; + ch.close(); + bool ok = ch.send(42); + Void::Testing::expect(!ok); +} diff --git a/tests/standalone/Concurrency/ParallelFor.cpp b/tests/standalone/Concurrency/ParallelFor.cpp new file mode 100644 index 0000000..ac9b48f --- /dev/null +++ b/tests/standalone/Concurrency/ParallelFor.cpp @@ -0,0 +1,57 @@ +#include +#include +#include + +#include +#include + +using namespace Void::Concurrency; + +Void::Testing::Test parallel_sum_matches_sequential() +{ + constexpr int N = 1000; + std::atomic total{0}; + parallel_for(0, N, [&](int i) { total += i; }); + Void::Testing::expect_eq(total.load(), + static_cast(N) * (N - 1) / 2); +} + +Void::Testing::Test empty_range_does_nothing() +{ + std::atomic calls{0}; + parallel_for(5, 5, [&](int) { ++calls; }); + Void::Testing::expect_eq(calls.load(), 0); +} + +Void::Testing::Test with_explicit_pool() +{ + ThreadPool pool{2}; + std::atomic count{0}; + parallel_for(0, 10, [&](int) { ++count; }, pool); + Void::Testing::expect_eq(count.load(), 10); +} + +Void::Testing::Test results_written_to_indexed_array() +{ + constexpr int N = 64; + std::vector out(N, 0); + parallel_for(0, N, [&](int i) { out[i] = i * i; }); + for (int i = 0; i < N; ++i) { + Void::Testing::expect_eq(out[i], i * i); + } +} + +Void::Testing::Test exception_propagates() +{ + bool caught = false; + try { + parallel_for(0, 4, [](int i) { + if (i == 2) { + throw std::runtime_error("bad index"); + } + }); + } catch (const std::runtime_error&) { + caught = true; + } + Void::Testing::expect(caught); +} diff --git a/tests/standalone/Concurrency/ThreadPool.cpp b/tests/standalone/Concurrency/ThreadPool.cpp new file mode 100644 index 0000000..91841ac --- /dev/null +++ b/tests/standalone/Concurrency/ThreadPool.cpp @@ -0,0 +1,88 @@ +#include +#include +#include + +#include +#include +#include + +using Void::Concurrency::ThreadPool; + +Void::Testing::Test thread_count_matches_requested() +{ + ThreadPool pool{4}; + Void::Testing::expect_eq(pool.thread_count(), std::size_t{4}); +} + +Void::Testing::Test defaults_to_hardware_concurrency() +{ + ThreadPool pool; + Void::Testing::expect(pool.thread_count() >= 1); +} + +Void::Testing::Test submit_returns_correct_value() +{ + ThreadPool pool{2}; + auto fut = pool.submit([] { return 42; }); + Void::Testing::expect_eq(fut.get(), 42); +} + +Void::Testing::Test tasks_run_concurrently() +{ + constexpr int N = 8; + ThreadPool pool{N}; + std::atomic counter{0}; + std::vector> futs; + futs.reserve(N); + for (int i = 0; i < N; ++i) { + futs.push_back(pool.submit([&] { + ++counter; + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + })); + } + for (auto& f : futs) { + f.get(); + } + Void::Testing::expect_eq(counter.load(), N); +} + +Void::Testing::Test parallel_sum_is_correct() +{ + ThreadPool pool{4}; + constexpr int N = 100; + std::atomic total{0}; + std::vector> futs; + futs.reserve(N); + for (int i = 1; i <= N; ++i) { + futs.push_back(pool.submit([&, i] { total += i; })); + } + for (auto& f : futs) { + f.get(); + } + Void::Testing::expect_eq(total.load(), 5050LL); +} + +Void::Testing::Test exception_propagates_through_future() +{ + ThreadPool pool{1}; + auto fut = pool.submit([] -> int { throw std::runtime_error("boom"); }); + bool caught = false; + try { + fut.get(); + } catch (const std::runtime_error& e) { + caught = (std::string{e.what()} == "boom"); + } + Void::Testing::expect(caught); +} + +Void::Testing::Test submit_after_destruction_throws() +{ + std::optional> fut; + { + ThreadPool pool{1}; + fut = pool.submit([] { return 1; }); + fut->get(); + } + // pool is now destroyed; this just verifies destruction was clean + Void::Testing::expect(true); +} diff --git a/tests/standalone/Configuration/Config.cpp b/tests/standalone/Configuration/Config.cpp new file mode 100644 index 0000000..7211824 --- /dev/null +++ b/tests/standalone/Configuration/Config.cpp @@ -0,0 +1,121 @@ +#include +#include +#include +#include +#include +#include + +#include +#include + +Void::Testing::Test get_env_finds_set_variable() +{ + ::setenv("VOID_TEST_VAR_A", "hello", 1); + auto r = Void::Configuration::get_env("VOID_TEST_VAR_A"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"hello"}); + ::unsetenv("VOID_TEST_VAR_A"); +} + +Void::Testing::Test get_env_returns_error_for_missing() +{ + ::unsetenv("VOID_TEST_VAR_MISSING_XYZ"); + auto r = Void::Configuration::get_env("VOID_TEST_VAR_MISSING_XYZ"); + Void::Testing::expect(!r.has_value()); +} + +Void::Testing::Test get_env_or_returns_fallback_when_absent() +{ + ::unsetenv("VOID_TEST_VAR_MISSING_XYZ"); + auto val = Void::Configuration::get_env_or("VOID_TEST_VAR_MISSING_XYZ", "default"); + Void::Testing::expect_eq(val, std::string{"default"}); +} + +Void::Testing::Test get_env_or_returns_value_when_present() +{ + ::setenv("VOID_TEST_VAR_B", "world", 1); + auto val = Void::Configuration::get_env_or("VOID_TEST_VAR_B", "fallback"); + Void::Testing::expect_eq(val, std::string{"world"}); + ::unsetenv("VOID_TEST_VAR_B"); +} + +Void::Testing::Test config_set_and_get() +{ + Void::Configuration::Config cfg; + cfg.set("key", "value"); + auto r = cfg.get("key"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(std::string{*r}, std::string{"value"}); +} + +Void::Testing::Test config_get_missing_key_fails() +{ + Void::Configuration::Config cfg; + auto r = cfg.get("nonexistent"); + Void::Testing::expect(!r.has_value()); +} + +Void::Testing::Test config_get_or_returns_fallback() +{ + Void::Configuration::Config cfg; + auto val = cfg.get_or("missing", "fb"); + Void::Testing::expect_eq(std::string{val}, std::string{"fb"}); +} + +Void::Testing::Test config_from_env_reads_listed_keys() +{ + ::setenv("VOID_TEST_CFG_X", "42", 1); + ::unsetenv("VOID_TEST_CFG_Y"); + + auto cfg = Void::Configuration::Config::from_env({"VOID_TEST_CFG_X", "VOID_TEST_CFG_Y"}); + Void::Testing::expect_eq(cfg.size(), std::size_t{1}); + Void::Testing::expect_eq(std::string{cfg.get_or("VOID_TEST_CFG_X")}, std::string{"42"}); + ::unsetenv("VOID_TEST_CFG_X"); +} + +Void::Testing::Test config_from_file_parses_key_value() +{ + Void::FileSystem::TempDir tmp; + auto path = tmp / "cfg.env"; + (void)Void::FileSystem::write_file(path, "HOST=localhost\nPORT=5432\n"); + + auto r = Void::Configuration::Config::from_file(path); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(std::string{r->get_or("HOST")}, std::string{"localhost"}); + Void::Testing::expect_eq(std::string{r->get_or("PORT")}, std::string{"5432"}); +} + +Void::Testing::Test config_from_file_skips_comments_and_blank_lines() +{ + Void::FileSystem::TempDir tmp; + auto path = tmp / "cfg.env"; + (void)Void::FileSystem::write_file(path, "# this is a comment\n\nFOO=bar\n"); + + auto r = Void::Configuration::Config::from_file(path); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->size(), std::size_t{1}); + Void::Testing::expect_eq(std::string{r->get_or("FOO")}, std::string{"bar"}); +} + +Void::Testing::Test config_overlay_later_wins_on_conflict() +{ + Void::Configuration::Config base; + base.set("A", "from_base"); + base.set("B", "only_base"); + + Void::Configuration::Config top; + top.set("A", "from_top"); + top.set("C", "only_top"); + + base.overlay(top); + + Void::Testing::expect_eq(std::string{base.get_or("A")}, std::string{"from_top"}); + Void::Testing::expect_eq(std::string{base.get_or("B")}, std::string{"only_base"}); + Void::Testing::expect_eq(std::string{base.get_or("C")}, std::string{"only_top"}); +} + +Void::Testing::Test config_from_file_missing_path_fails() +{ + auto r = Void::Configuration::Config::from_file("/no/such/file.env"); + Void::Testing::expect(!r.has_value()); +} diff --git a/tests/standalone/Encoding/Encoding.cpp b/tests/standalone/Encoding/Encoding.cpp new file mode 100644 index 0000000..5af8b34 --- /dev/null +++ b/tests/standalone/Encoding/Encoding.cpp @@ -0,0 +1,159 @@ +#include +#include +#include +#include + +// ── Base64 encode ───────────────────────────────────────────────────────────── + +Void::Testing::Test base64_encode_empty() +{ + Void::Testing::expect(Void::Encoding::Base64::encode("").empty()); +} + +Void::Testing::Test base64_encode_man() +{ + Void::Testing::expect_eq(Void::Encoding::Base64::encode("Man"), + std::string{"TWFu"}); +} + +Void::Testing::Test base64_encode_ma() +{ + Void::Testing::expect_eq(Void::Encoding::Base64::encode("Ma"), + std::string{"TWE="}); +} + +Void::Testing::Test base64_encode_m() +{ + Void::Testing::expect_eq(Void::Encoding::Base64::encode("M"), + std::string{"TQ=="}); +} + +Void::Testing::Test base64_encode_hello_world() +{ + Void::Testing::expect_eq(Void::Encoding::Base64::encode("Hello, World!"), + std::string{"SGVsbG8sIFdvcmxkIQ=="}); +} + +// ── Base64 decode ───────────────────────────────────────────────────────────── + +Void::Testing::Test base64_decode_empty() +{ + const auto r = Void::Encoding::Base64::decode(""); + Void::Testing::expect(r.has_value()); + Void::Testing::expect(r->empty()); +} + +Void::Testing::Test base64_decode_man() +{ + const auto r = Void::Encoding::Base64::decode("TWFu"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"Man"}); +} + +Void::Testing::Test base64_decode_with_padding() +{ + const auto r = Void::Encoding::Base64::decode("SGVsbG8sIFdvcmxkIQ=="); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"Hello, World!"}); +} + +Void::Testing::Test base64_decode_invalid_returns_nullopt() +{ + const auto r = Void::Encoding::Base64::decode("!!"); + Void::Testing::expect(!r.has_value()); +} + +Void::Testing::Test base64_round_trip() +{ + const std::string original = "The quick brown fox jumps over the lazy dog"; + const auto encoded = Void::Encoding::Base64::encode(original); + const auto decoded = Void::Encoding::Base64::decode(encoded); + Void::Testing::expect(decoded.has_value()); + Void::Testing::expect_eq(*decoded, original); +} + +// ── Base64 URL ──────────────────────────────────────────────────────────────── + +Void::Testing::Test base64url_no_padding() +{ + const auto s = Void::Encoding::Base64::encode_url("Man"); + Void::Testing::expect_eq(s, std::string{"TWFu"}); + Void::Testing::expect(s.find('=') == std::string::npos); +} + +Void::Testing::Test base64url_no_plus_or_slash() +{ + // encode something that would produce + or / in standard base64 + const std::string tricky = "\xfb\xff\xfe"; + const auto s = Void::Encoding::Base64::encode_url(tricky); + Void::Testing::expect(s.find('+') == std::string::npos); + Void::Testing::expect(s.find('/') == std::string::npos); +} + +// ── Hex encode ─────────────────────────────────────────────────────────────── + +Void::Testing::Test hex_encode_empty() +{ + Void::Testing::expect(Void::Encoding::Hex::encode("").empty()); +} + +Void::Testing::Test hex_encode_hello() +{ + Void::Testing::expect_eq(Void::Encoding::Hex::encode("Hi"), + std::string{"4869"}); +} + +Void::Testing::Test hex_encode_binary() +{ + const std::string bin{'\x00', '\xff', '\xab'}; + Void::Testing::expect_eq(Void::Encoding::Hex::encode(bin), + std::string{"00ffab"}); +} + +Void::Testing::Test hex_encode_upper() +{ + Void::Testing::expect_eq(Void::Encoding::Hex::encode_upper("Hi"), + std::string{"4869"}); +} + +// ── Hex decode ─────────────────────────────────────────────────────────────── + +Void::Testing::Test hex_decode_empty() +{ + const auto r = Void::Encoding::Hex::decode(""); + Void::Testing::expect(r.has_value()); + Void::Testing::expect(r->empty()); +} + +Void::Testing::Test hex_decode_hello() +{ + const auto r = Void::Encoding::Hex::decode("4869"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"Hi"}); +} + +Void::Testing::Test hex_decode_uppercase() +{ + const auto r = Void::Encoding::Hex::decode("4869"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"Hi"}); +} + +Void::Testing::Test hex_decode_odd_length_fails() +{ + Void::Testing::expect(!Void::Encoding::Hex::decode("abc").has_value()); +} + +Void::Testing::Test hex_decode_invalid_char_fails() +{ + Void::Testing::expect(!Void::Encoding::Hex::decode("zz").has_value()); +} + +Void::Testing::Test hex_round_trip() +{ + const std::string original = "binary\x00\x01\x02\xff"; + const auto encoded = Void::Encoding::Hex::encode(original); + const auto decoded = Void::Encoding::Hex::decode(encoded); + Void::Testing::expect(decoded.has_value()); + Void::Testing::expect_eq(*decoded, original); +} diff --git a/tests/standalone/FileSystem/Query.cpp b/tests/standalone/FileSystem/Query.cpp new file mode 100644 index 0000000..2db9dc6 --- /dev/null +++ b/tests/standalone/FileSystem/Query.cpp @@ -0,0 +1,128 @@ +#include +#include +#include +#include +#include + +#include +#include + +Void::Testing::Test exists_returns_true_for_existing_file() +{ + Void::FileSystem::TempDir tmp; + auto p = tmp / "f.txt"; + (void)Void::FileSystem::write_file(p, "x"); + Void::Testing::expect(Void::FileSystem::exists(p)); +} + +Void::Testing::Test exists_returns_false_for_missing() +{ + Void::FileSystem::TempDir tmp; + Void::Testing::expect(!Void::FileSystem::exists(tmp / "no_such.txt")); +} + +Void::Testing::Test file_size_returns_correct_byte_count() +{ + Void::FileSystem::TempDir tmp; + auto p = tmp / "sized.txt"; + (void)Void::FileSystem::write_file(p, "hello"); + auto r = Void::FileSystem::file_size(p); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::uintmax_t{5}); +} + +Void::Testing::Test file_size_fails_for_missing_path() +{ + auto r = Void::FileSystem::file_size("/no/such/file.txt"); + Void::Testing::expect(!r.has_value()); +} + +Void::Testing::Test last_modified_returns_a_time() +{ + Void::FileSystem::TempDir tmp; + auto p = tmp / "ts.txt"; + (void)Void::FileSystem::write_file(p, "data"); + auto r = Void::FileSystem::last_modified(p); + Void::Testing::expect(r.has_value()); +} + +Void::Testing::Test last_modified_fails_for_missing_path() +{ + auto r = Void::FileSystem::last_modified("/no/such/file.txt"); + Void::Testing::expect(!r.has_value()); +} + +Void::Testing::Test list_directory_returns_created_entries() +{ + Void::FileSystem::TempDir tmp; + (void)Void::FileSystem::write_file(tmp / "a.txt", ""); + (void)Void::FileSystem::write_file(tmp / "b.txt", ""); + auto r = Void::FileSystem::list_directory(tmp.path()); + Void::Testing::expect(r.has_value()); + Void::Testing::expect(r->size() >= 2); + const auto has_a = std::any_of(r->begin(), r->end(), [&](const auto& p) { + return p.filename() == "a.txt"; + }); + const auto has_b = std::any_of(r->begin(), r->end(), [&](const auto& p) { + return p.filename() == "b.txt"; + }); + Void::Testing::expect(has_a); + Void::Testing::expect(has_b); +} + +Void::Testing::Test list_directory_fails_for_missing_path() +{ + auto r = Void::FileSystem::list_directory("/no/such/directory"); + Void::Testing::expect(!r.has_value()); +} + +Void::Testing::Test copy_file_creates_duplicate() +{ + Void::FileSystem::TempDir tmp; + auto src = tmp / "src.txt"; + auto dst = tmp / "dst.txt"; + (void)Void::FileSystem::write_file(src, "contents"); + auto r = Void::FileSystem::copy_file(src, dst); + Void::Testing::expect(r.has_value()); + auto back = Void::FileSystem::read_file(dst); + Void::Testing::expect(back.has_value()); + Void::Testing::expect_eq(*back, std::string{"contents"}); +} + +Void::Testing::Test copy_file_fails_without_overwrite_when_dst_exists() +{ + Void::FileSystem::TempDir tmp; + auto src = tmp / "src.txt"; + auto dst = tmp / "dst.txt"; + (void)Void::FileSystem::write_file(src, "new"); + (void)Void::FileSystem::write_file(dst, "old"); + auto r = Void::FileSystem::copy_file(src, dst, /*overwrite=*/false); + Void::Testing::expect(!r.has_value()); +} + +Void::Testing::Test copy_file_with_overwrite_replaces_dst() +{ + Void::FileSystem::TempDir tmp; + auto src = tmp / "src.txt"; + auto dst = tmp / "dst.txt"; + (void)Void::FileSystem::write_file(src, "new_content"); + (void)Void::FileSystem::write_file(dst, "old_content"); + auto r = Void::FileSystem::copy_file(src, dst, /*overwrite=*/true); + Void::Testing::expect(r.has_value()); + auto back = Void::FileSystem::read_file(dst); + Void::Testing::expect_eq(*back, std::string{"new_content"}); +} + +Void::Testing::Test copy_dir_duplicates_tree() +{ + Void::FileSystem::TempDir tmp; + auto src = tmp / "src"; + auto dst = tmp / "dst"; + (void)Void::FileSystem::ensure_directory(src); + (void)Void::FileSystem::write_file(src / "file.txt", "tree"); + auto r = Void::FileSystem::copy_dir(src, dst); + Void::Testing::expect(r.has_value()); + auto back = Void::FileSystem::read_file(dst / "file.txt"); + Void::Testing::expect(back.has_value()); + Void::Testing::expect_eq(*back, std::string{"tree"}); +} diff --git a/tests/standalone/Hash/Hash.cpp b/tests/standalone/Hash/Hash.cpp new file mode 100644 index 0000000..10f2cee --- /dev/null +++ b/tests/standalone/Hash/Hash.cpp @@ -0,0 +1,121 @@ +#include +#include +#include + +#include + +using namespace Void::Hash::Literals; + +// ── FNV-1a 32 ──────────────────────────────────────────────────────────────── + +Void::Testing::Test fnv1a32_empty_string() +{ + Void::Testing::expect_eq(Void::Hash::fnv1a32(""), 2166136261u); +} + +Void::Testing::Test fnv1a32_hello_world() +{ + const auto a = Void::Hash::fnv1a32("hello"); + const auto b = Void::Hash::fnv1a32("world"); + Void::Testing::expect(a != b); + Void::Testing::expect(a != 0u); +} + +Void::Testing::Test fnv1a32_deterministic() +{ + Void::Testing::expect_eq(Void::Hash::fnv1a32("test"), + Void::Hash::fnv1a32("test")); +} + +Void::Testing::Test fnv1a32_different_strings_differ() +{ + Void::Testing::expect(Void::Hash::fnv1a32("abc") != + Void::Hash::fnv1a32("abd")); +} + +// ── FNV-1a 64 ──────────────────────────────────────────────────────────────── + +Void::Testing::Test fnv1a64_empty_basis() +{ + Void::Testing::expect_eq(Void::Hash::fnv1a64(""), + 14695981039346656037ull); +} + +Void::Testing::Test fnv1a64_hello_is_stable() +{ + Void::Testing::expect_eq(Void::Hash::fnv1a64("hello"), + Void::Hash::fnv1a64("hello")); +} + +Void::Testing::Test fnv1a64_wider_than_32() +{ + // 64-bit should differ from 32-bit value for same input + Void::Testing::expect(Void::Hash::fnv1a64("test") != + static_cast(Void::Hash::fnv1a32("test"))); +} + +// ── CRC-32 ─────────────────────────────────────────────────────────────────── + +Void::Testing::Test crc32_known_value() +{ + // CRC-32 of "123456789" is a well-known check value: 0xCBF43926 + Void::Testing::expect_eq(Void::Hash::crc32("123456789"), std::uint32_t{0xCBF43926u}); +} + +Void::Testing::Test crc32_empty_is_zero() +{ + Void::Testing::expect_eq(Void::Hash::crc32(""), std::uint32_t{0u}); +} + +Void::Testing::Test crc32_deterministic() +{ + Void::Testing::expect_eq(Void::Hash::crc32("void"), Void::Hash::crc32("void")); +} + +// ── DJB2 ───────────────────────────────────────────────────────────────────── + +Void::Testing::Test djb2_non_zero_for_nonempty() +{ + Void::Testing::expect(Void::Hash::djb2("hello") != 0u); +} + +Void::Testing::Test djb2_differs_per_string() +{ + Void::Testing::expect(Void::Hash::djb2("foo") != Void::Hash::djb2("bar")); +} + +// ── MurmurHash3 ────────────────────────────────────────────────────────────── + +Void::Testing::Test murmur3_32_deterministic() +{ + Void::Testing::expect_eq(Void::Hash::murmur3_32("hello", 42u), + Void::Hash::murmur3_32("hello", 42u)); +} + +Void::Testing::Test murmur3_32_seed_affects_output() +{ + Void::Testing::expect(Void::Hash::murmur3_32("hello", 0u) != + Void::Hash::murmur3_32("hello", 1u)); +} + +Void::Testing::Test murmur3_32_empty_with_zero_seed() +{ + // MurmurHash3("", 0) = 0 + Void::Testing::expect_eq(Void::Hash::murmur3_32("", 0u), std::uint32_t{0u}); +} + +// ── UDL literals ───────────────────────────────────────────────────────────── + +Void::Testing::Test udl_fnv32_comptime() +{ + constexpr auto h = "hello"_fnv32; + static_assert(h != 0u); + Void::Testing::expect_eq(h, Void::Hash::fnv1a32("hello")); +} + +Void::Testing::Test udl_fnv64_comptime() +{ + constexpr auto h = "hello"_fnv64; + static_assert(h != 0u); + Void::Testing::expect_eq(h, Void::Hash::fnv1a64("hello")); +} diff --git a/tests/standalone/Log/Log.cpp b/tests/standalone/Log/Log.cpp new file mode 100644 index 0000000..ef3d1b1 --- /dev/null +++ b/tests/standalone/Log/Log.cpp @@ -0,0 +1,107 @@ +#include +#include +#include + +#include +#include +#include +#include + +// Reset the global sink between tests via a scoped RAII guard. +struct SinkGuard { + ~SinkGuard() { Void::Log::set_sink({}); } +}; + +Void::Testing::Test no_sink_is_silent() +{ + SinkGuard guard; + bool called = false; + // No sink installed — this must not crash or invoke anything. + Void::Log::log(Void::Log::Level::Info, "test", "silent message"); + Void::Testing::expect(!called); +} + +Void::Testing::Test sink_receives_all_fields() +{ + SinkGuard guard; + Void::Log::Level got_level{}; + std::string got_module; + std::string got_message; + + Void::Log::set_sink( + [&](Void::Log::Level l, std::string_view mod, std::string_view msg) { + got_level = l; + got_module = mod; + got_message = msg; + }); + + Void::Log::log(Void::Log::Level::Warning, "MyModule", "something happened"); + + Void::Testing::expect(got_level == Void::Log::Level::Warning); + Void::Testing::expect(got_module == "MyModule"); + Void::Testing::expect(got_message == "something happened"); +} + +Void::Testing::Test set_sink_replaces_previous() +{ + SinkGuard guard; + int first_calls = 0; + int second_calls = 0; + + Void::Log::set_sink([&](auto, auto, auto) { ++first_calls; }); + Void::Log::log(Void::Log::Level::Info, "m", "a"); + + Void::Log::set_sink([&](auto, auto, auto) { ++second_calls; }); + Void::Log::log(Void::Log::Level::Info, "m", "b"); + + Void::Testing::expect_eq(first_calls, 1); + Void::Testing::expect_eq(second_calls, 1); +} + +Void::Testing::Test clear_sink_silences_output() +{ + SinkGuard guard; + int calls = 0; + Void::Log::set_sink([&](auto, auto, auto) { ++calls; }); + Void::Log::log(Void::Log::Level::Info, "m", "before clear"); + Void::Log::set_sink({}); + Void::Log::log(Void::Log::Level::Info, "m", "after clear"); + Void::Testing::expect_eq(calls, 1); +} + +Void::Testing::Test concurrent_log_calls_are_safe() +{ + SinkGuard guard; + std::atomic count{0}; + Void::Log::set_sink([&](auto, auto, auto) { ++count; }); + + constexpr int N = 64; + std::vector threads; + threads.reserve(N); + for (int i = 0; i < N; ++i) { + threads.emplace_back([] { + Void::Log::log(Void::Log::Level::Debug, "test", "concurrent"); + }); + } + for (auto& t : threads) { + t.join(); + } + + Void::Testing::expect_eq(count.load(), N); +} + +Void::Testing::Test all_levels_are_forwarded() +{ + SinkGuard guard; + int calls = 0; + Void::Log::set_sink([&](auto, auto, auto) { ++calls; }); + + Void::Log::log(Void::Log::Level::Trace, "m", "t"); + Void::Log::log(Void::Log::Level::Debug, "m", "d"); + Void::Log::log(Void::Log::Level::Info, "m", "i"); + Void::Log::log(Void::Log::Level::Warning, "m", "w"); + Void::Log::log(Void::Log::Level::Error, "m", "e"); + Void::Log::log(Void::Log::Level::Fatal, "m", "f"); + + Void::Testing::expect_eq(calls, 6); +} diff --git a/tests/standalone/Logging/ConsoleLogger.cpp b/tests/standalone/Logging/ConsoleLogger.cpp index f5b0d17..1d1c020 100644 --- a/tests/standalone/Logging/ConsoleLogger.cpp +++ b/tests/standalone/Logging/ConsoleLogger.cpp @@ -21,7 +21,7 @@ class ConsoleLoggerTests : public Void::Testing::Fixture const auto content = out.str(); Void::Testing::expect(content.find("hello world") != std::string::npos); - Void::Testing::expect(content.find("INFO") != std::string::npos); + Void::Testing::expect(content.find("Info") != std::string::npos); } Void::Testing::Test level_filtering() diff --git a/tests/standalone/Math/VecMat.cpp b/tests/standalone/Math/VecMat.cpp new file mode 100644 index 0000000..86f825e --- /dev/null +++ b/tests/standalone/Math/VecMat.cpp @@ -0,0 +1,154 @@ +#include +#include +#include +#include + +#include + +static constexpr float EPS = 1e-5f; + +// ── Vec2 ────────────────────────────────────────────────────────────────────── + +Void::Testing::Test vec2_add() +{ + constexpr auto v = Void::Math::Vec2f{1, 2} + Void::Math::Vec2f{3, 4}; + static_assert(v.x == 4.f && v.y == 6.f); + Void::Testing::expect_eq(v.x, 4.f); +} + +Void::Testing::Test vec2_subtract() +{ + constexpr auto v = Void::Math::Vec2f{3, 4} - Void::Math::Vec2f{1, 1}; + Void::Testing::expect_eq(v.x, 2.f); + Void::Testing::expect_eq(v.y, 3.f); +} + +Void::Testing::Test vec2_scale() +{ + constexpr auto v = Void::Math::Vec2f{2, 3} * 2.f; + Void::Testing::expect_eq(v.x, 4.f); + Void::Testing::expect_eq(v.y, 6.f); +} + +Void::Testing::Test vec2_dot() +{ + constexpr auto d = Void::Math::Vec2f{1, 0}.dot({0, 1}); + static_assert(d == 0.f); + Void::Testing::expect_eq(d, 0.f); +} + +Void::Testing::Test vec2_length() +{ + const Void::Math::Vec2f v{3, 4}; + Void::Testing::expect(std::abs(v.length() - 5.f) < EPS); +} + +Void::Testing::Test vec2_normalized() +{ + const Void::Math::Vec2f v = Void::Math::Vec2f{3, 4}.normalized(); + Void::Testing::expect(std::abs(v.length() - 1.f) < EPS); +} + +Void::Testing::Test vec2_lerp() +{ + const auto v = Void::Math::lerp(Void::Math::Vec2f{0, 0}, + Void::Math::Vec2f{2, 4}, 0.5f); + Void::Testing::expect(std::abs(v.x - 1.f) < EPS); + Void::Testing::expect(std::abs(v.y - 2.f) < EPS); +} + +// ── Vec3 ────────────────────────────────────────────────────────────────────── + +Void::Testing::Test vec3_cross_unit_vectors() +{ + constexpr Void::Math::Vec3f x{1, 0, 0}; + constexpr Void::Math::Vec3f y{0, 1, 0}; + constexpr Void::Math::Vec3f z = x.cross(y); + static_assert(z.x == 0.f && z.y == 0.f && z.z == 1.f); + Void::Testing::expect_eq(z.z, 1.f); +} + +Void::Testing::Test vec3_length() +{ + const Void::Math::Vec3f v{1, 2, 2}; + Void::Testing::expect(std::abs(v.length() - 3.f) < EPS); +} + +Void::Testing::Test vec3_normalized_unit_length() +{ + const auto v = Void::Math::Vec3f{2, 3, 6}.normalized(); + Void::Testing::expect(std::abs(v.length() - 1.f) < EPS); +} + +// ── Vec4 ────────────────────────────────────────────────────────────────────── + +Void::Testing::Test vec4_from_vec3() +{ + constexpr Void::Math::Vec4f v{Void::Math::Vec3f{1, 2, 3}, 1.f}; + static_assert(v.w == 1.f); + Void::Testing::expect_eq(v.z, 3.f); +} + +Void::Testing::Test vec4_xyz() +{ + constexpr Void::Math::Vec4f v{1, 2, 3, 4}; + constexpr auto xyz = v.xyz(); + static_assert(xyz.x == 1.f && xyz.y == 2.f && xyz.z == 3.f); +} + +// ── Mat4 ────────────────────────────────────────────────────────────────────── + +Void::Testing::Test mat4_identity_times_vec() +{ + constexpr auto I = Void::Math::Mat4f::identity(); + constexpr Void::Math::Vec4f v{1, 2, 3, 1}; + constexpr auto r = I * v; + static_assert(r.x == 1.f && r.y == 2.f && r.z == 3.f && r.w == 1.f); +} + +Void::Testing::Test mat4_translation() +{ + const auto T = Void::Math::Mat4f::translation(1, 2, 3); + const Void::Math::Vec4f v{0, 0, 0, 1}; + const auto r = T * v; + Void::Testing::expect(std::abs(r.x - 1.f) < EPS); + Void::Testing::expect(std::abs(r.y - 2.f) < EPS); + Void::Testing::expect(std::abs(r.z - 3.f) < EPS); +} + +Void::Testing::Test mat4_scale() +{ + const auto S = Void::Math::Mat4f::scale(2, 3, 4); + const Void::Math::Vec4f v{1, 1, 1, 1}; + const auto r = S * v; + Void::Testing::expect(std::abs(r.x - 2.f) < EPS); + Void::Testing::expect(std::abs(r.y - 3.f) < EPS); + Void::Testing::expect(std::abs(r.z - 4.f) < EPS); +} + +Void::Testing::Test mat4_rotation_z_90_degrees() +{ + const auto R = Void::Math::Mat4f::rotation_z( + static_cast(M_PI) / 2.f); + const Void::Math::Vec4f v{1, 0, 0, 0}; + const auto r = R * v; + Void::Testing::expect(std::abs(r.x - 0.f) < EPS); + Void::Testing::expect(std::abs(r.y - 1.f) < EPS); +} + +Void::Testing::Test mat4_mul_identity_nop() +{ + const auto A = Void::Math::Mat4f::translation(1, 2, 3); + const auto I = Void::Math::Mat4f::identity(); + const auto R = A * I; + Void::Testing::expect_eq(R, A); +} + +Void::Testing::Test mat4_transpose() +{ + auto M = Void::Math::Mat4f::identity(); + M.at(0, 1) = 5.f; + const auto T = M.transposed(); + Void::Testing::expect_eq(T.at(1, 0), 5.f); + Void::Testing::expect_eq(T.at(0, 1), 0.f); +} diff --git a/tests/standalone/Process/Process.cpp b/tests/standalone/Process/Process.cpp new file mode 100644 index 0000000..05ae0de --- /dev/null +++ b/tests/standalone/Process/Process.cpp @@ -0,0 +1,74 @@ +#include +#include +#include + +#include + +Void::Testing::Test shell_echo_captures_stdout() +{ + auto r = Void::Process::shell("echo hello"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->exit_code, 0); + Void::Testing::expect(r->out.find("hello") != std::string::npos); +} + +Void::Testing::Test shell_exit_code_propagates() +{ + auto r = Void::Process::shell("exit 42"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->exit_code, 42); +} + +Void::Testing::Test shell_captures_stderr_separately() +{ + auto r = Void::Process::shell("echo err_output >&2"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect(r->err.find("err_output") != std::string::npos); + Void::Testing::expect(r->out.find("err_output") == std::string::npos); +} + +Void::Testing::Test run_with_args_builds_correct_argv() +{ + auto r = Void::Process::run("/bin/echo", {"hello", "world"}); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->exit_code, 0); + Void::Testing::expect(r->out.find("hello world") != std::string::npos); +} + +Void::Testing::Test run_stdin_forwarded_to_cat() +{ + auto r = Void::Process::run("/bin/cat", {}, "piped_input"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->exit_code, 0); + Void::Testing::expect(r->out.find("piped_input") != std::string::npos); +} + +Void::Testing::Test run_missing_executable_returns_code_127() +{ + auto r = Void::Process::run("/this/binary/does/not/exist"); + // fork succeeds, execvp fails, child _exits(127) + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->exit_code, 127); +} + +Void::Testing::Test run_stdout_and_stderr_independent() +{ + auto r = Void::Process::shell( + "echo to_stdout; echo to_stderr >&2"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect(r->out.find("to_stdout") != std::string::npos); + Void::Testing::expect(r->err.find("to_stderr") != std::string::npos); + Void::Testing::expect(r->out.find("to_stderr") == std::string::npos); + Void::Testing::expect(r->err.find("to_stdout") == std::string::npos); +} + +Void::Testing::Test run_large_output_is_captured_fully() +{ + // Generate 10 000 lines; poll-based reader must accumulate them all. + auto r = Void::Process::shell("seq 1 10000"); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->exit_code, 0); + // "10000\n" must be present, and total output must be substantial + Void::Testing::expect(r->out.find("10000") != std::string::npos); + Void::Testing::expect(r->out.size() > 40000); +} diff --git a/tests/standalone/Random/Random.cpp b/tests/standalone/Random/Random.cpp new file mode 100644 index 0000000..86db1b2 --- /dev/null +++ b/tests/standalone/Random/Random.cpp @@ -0,0 +1,120 @@ +#include +#include +#include + +#include +#include + +// ── Xoshiro256 ─────────────────────────────────────────────────────────────── + +Void::Testing::Test xoshiro_produces_output() +{ + Void::Random::Xoshiro256 rng{42}; + const auto a = rng(); + const auto b = rng(); + Void::Testing::expect(a != b); +} + +Void::Testing::Test xoshiro_same_seed_same_sequence() +{ + Void::Random::Xoshiro256 r1{12345}; + Void::Random::Xoshiro256 r2{12345}; + for (int i = 0; i < 10; ++i) { + Void::Testing::expect_eq(r1(), r2()); + } +} + +Void::Testing::Test xoshiro_different_seeds_differ() +{ + Void::Random::Xoshiro256 r1{1}; + Void::Random::Xoshiro256 r2{2}; + Void::Testing::expect(r1() != r2()); +} + +// ── uniform_int ────────────────────────────────────────────────────────────── + +Void::Testing::Test uniform_int_in_range() +{ + for (int i = 0; i < 100; ++i) { + const auto v = Void::Random::uniform_int(1, 6); + Void::Testing::expect(v >= 1); + Void::Testing::expect(v <= 6); + } +} + +Void::Testing::Test uniform_int_single_value() +{ + Void::Testing::expect_eq(Void::Random::uniform_int(7, 7), 7); +} + +// ── uniform_real ───────────────────────────────────────────────────────────── + +Void::Testing::Test uniform_real_in_range() +{ + for (int i = 0; i < 50; ++i) { + const double v = Void::Random::uniform_real(0.0, 1.0); + Void::Testing::expect(v >= 0.0); + Void::Testing::expect(v < 1.0); + } +} + +// ── coin_flip ──────────────────────────────────────────────────────────────── + +Void::Testing::Test coin_flip_always_true() +{ + Void::Testing::expect(Void::Random::coin_flip(1.0)); +} + +Void::Testing::Test coin_flip_always_false() +{ + Void::Testing::expect(!Void::Random::coin_flip(0.0)); +} + +// ── shuffle ────────────────────────────────────────────────────────────────── + +Void::Testing::Test shuffle_preserves_elements() +{ + std::vector v{1, 2, 3, 4, 5}; + const auto orig = v; + Void::Random::shuffle(v); + auto sorted = v; + std::sort(sorted.begin(), sorted.end()); + Void::Testing::expect_eq(sorted, orig); +} + +// ── random_string ──────────────────────────────────────────────────────────── + +Void::Testing::Test random_string_correct_length() +{ + Void::Testing::expect_eq(Void::Random::random_string(10).size(), + std::size_t{10}); +} + +Void::Testing::Test random_string_empty() +{ + Void::Testing::expect(Void::Random::random_string(0).empty()); +} + +Void::Testing::Test random_string_varies() +{ + // Extremely unlikely to produce identical 16-char strings twice + const auto a = Void::Random::random_string(16); + const auto b = Void::Random::random_string(16); + Void::Testing::expect(a != b); +} + +// ── sample_indices ─────────────────────────────────────────────────────────── + +Void::Testing::Test sample_indices_correct_count() +{ + const auto idxs = Void::Random::sample_indices(20, 5); + Void::Testing::expect_eq(idxs.size(), std::size_t{5}); +} + +Void::Testing::Test sample_indices_in_range() +{ + const auto idxs = Void::Random::sample_indices(10, 10); + for (auto i : idxs) { + Void::Testing::expect(i < std::size_t{10}); + } +} diff --git a/tests/standalone/String/String.cpp b/tests/standalone/String/String.cpp new file mode 100644 index 0000000..eeec164 --- /dev/null +++ b/tests/standalone/String/String.cpp @@ -0,0 +1,186 @@ +#include +#include +#include + +#include +#include +#include + +// ── trim ───────────────────────────────────────────────────────────────── + +Void::Testing::Test trim_removes_leading_and_trailing_spaces() +{ + Void::Testing::expect_eq( + std::string{Void::String::trim(" hello ")}, + std::string{"hello"}); +} + +Void::Testing::Test trim_leaves_interior_whitespace() +{ + Void::Testing::expect_eq( + std::string{Void::String::trim(" a b ")}, + std::string{"a b"}); +} + +Void::Testing::Test trim_empty_string_stays_empty() +{ + Void::Testing::expect(Void::String::trim("").empty()); +} + +Void::Testing::Test trim_only_whitespace_returns_empty() +{ + Void::Testing::expect(Void::String::trim(" \t\n ").empty()); +} + +Void::Testing::Test trim_left_only_removes_prefix() +{ + Void::Testing::expect_eq( + std::string{Void::String::trim_left(" hi ")}, + std::string{"hi "}); +} + +Void::Testing::Test trim_right_only_removes_suffix() +{ + Void::Testing::expect_eq( + std::string{Void::String::trim_right(" hi ")}, + std::string{" hi"}); +} + +// ── split ───────────────────────────────────────────────────────────────── + +Void::Testing::Test split_char_produces_correct_parts() +{ + const auto parts = Void::String::split("a,b,c", ','); + Void::Testing::expect_eq(parts.size(), std::size_t{3}); + Void::Testing::expect_eq(std::string{parts[0]}, std::string{"a"}); + Void::Testing::expect_eq(std::string{parts[1]}, std::string{"b"}); + Void::Testing::expect_eq(std::string{parts[2]}, std::string{"c"}); +} + +Void::Testing::Test split_char_preserves_empty_tokens() +{ + const auto parts = Void::String::split("a,,b", ','); + Void::Testing::expect_eq(parts.size(), std::size_t{3}); + Void::Testing::expect(parts[1].empty()); +} + +Void::Testing::Test split_char_no_delimiter_returns_whole_string() +{ + const auto parts = Void::String::split("hello", ','); + Void::Testing::expect_eq(parts.size(), std::size_t{1}); + Void::Testing::expect_eq(std::string{parts[0]}, std::string{"hello"}); +} + +Void::Testing::Test split_string_delimiter_works() +{ + const auto parts = Void::String::split("a::b::c", "::"); + Void::Testing::expect_eq(parts.size(), std::size_t{3}); + Void::Testing::expect_eq(std::string{parts[1]}, std::string{"b"}); +} + +Void::Testing::Test split_empty_delimiter_returns_whole() +{ + const auto parts = Void::String::split("abc", ""); + Void::Testing::expect_eq(parts.size(), std::size_t{1}); +} + +// ── join ────────────────────────────────────────────────────────────────── + +Void::Testing::Test join_vector_of_string_view() +{ + const std::vector parts{"a", "b", "c"}; + Void::Testing::expect_eq(Void::String::join(parts, ", "), + std::string{"a, b, c"}); +} + +Void::Testing::Test join_single_element_no_separator() +{ + const std::vector parts{"only"}; + Void::Testing::expect_eq(Void::String::join(parts, "-"), + std::string{"only"}); +} + +Void::Testing::Test join_empty_range_returns_empty() +{ + const std::vector parts; + Void::Testing::expect(Void::String::join(parts, ",").empty()); +} + +// ── case ────────────────────────────────────────────────────────────────── + +Void::Testing::Test to_lower_converts_ascii() +{ + Void::Testing::expect_eq(Void::String::to_lower("Hello World"), + std::string{"hello world"}); +} + +Void::Testing::Test to_upper_converts_ascii() +{ + Void::Testing::expect_eq(Void::String::to_upper("Hello World"), + std::string{"HELLO WORLD"}); +} + +// ── replace_all ─────────────────────────────────────────────────────────── + +Void::Testing::Test replace_all_replaces_all_occurrences() +{ + Void::Testing::expect_eq(Void::String::replace_all("aXbXc", "X", "--"), + std::string{"a--b--c"}); +} + +Void::Testing::Test replace_all_with_empty_from_returns_original() +{ + Void::Testing::expect_eq(Void::String::replace_all("abc", "", "x"), + std::string{"abc"}); +} + +Void::Testing::Test replace_all_no_match_returns_original() +{ + Void::Testing::expect_eq(Void::String::replace_all("abc", "z", "x"), + std::string{"abc"}); +} + +// ── pad ─────────────────────────────────────────────────────────────────── + +Void::Testing::Test pad_right_pads_to_width() +{ + Void::Testing::expect_eq(Void::String::pad_right("hi", 5), + std::string{"hi "}); +} + +Void::Testing::Test pad_right_no_op_when_already_wide() +{ + Void::Testing::expect_eq(Void::String::pad_right("hello", 3), + std::string{"hello"}); +} + +Void::Testing::Test pad_left_pads_to_width() +{ + Void::Testing::expect_eq(Void::String::pad_left("hi", 5), + std::string{" hi"}); +} + +// ── misc ────────────────────────────────────────────────────────────────── + +Void::Testing::Test repeat_produces_correct_output() +{ + Void::Testing::expect_eq(Void::String::repeat("ab", 3), + std::string{"ababab"}); +} + +Void::Testing::Test repeat_zero_returns_empty() +{ + Void::Testing::expect(Void::String::repeat("ab", 0).empty()); +} + +Void::Testing::Test count_occurrences_finds_all() +{ + Void::Testing::expect_eq(Void::String::count_occurrences("abab", "ab"), + std::size_t{2}); +} + +Void::Testing::Test count_occurrences_no_match_returns_zero() +{ + Void::Testing::expect_eq(Void::String::count_occurrences("abc", "x"), + std::size_t{0}); +} diff --git a/tests/standalone/Time/Time.cpp b/tests/standalone/Time/Time.cpp new file mode 100644 index 0000000..a95e3e1 --- /dev/null +++ b/tests/standalone/Time/Time.cpp @@ -0,0 +1,121 @@ +#include +#include +#include +#include + +#include +#include +#include + +// ── Stopwatch ───────────────────────────────────────────────────────────── + +Void::Testing::Test stopwatch_elapsed_is_non_negative() +{ + Void::Time::Stopwatch sw; + Void::Testing::expect(sw.elapsed().count() >= 0); +} + +Void::Testing::Test stopwatch_elapsed_as_milliseconds() +{ + Void::Time::Stopwatch sw; + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + const auto ms = sw.elapsed_as().count(); + Void::Testing::expect(ms >= 4); + Void::Testing::expect(ms < 500); +} + +Void::Testing::Test stopwatch_reset_restarts_from_zero() +{ + Void::Time::Stopwatch sw; + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + sw.reset(); + const auto ns = sw.elapsed().count(); + Void::Testing::expect(ns < 5'000'000); // < 5ms since reset +} + +Void::Testing::Test stopwatch_split_returns_elapsed_and_resets() +{ + Void::Time::Stopwatch sw; + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + const auto d = sw.split(); + const auto after = sw.elapsed().count(); + Void::Testing::expect(d.count() >= 0); + Void::Testing::expect(after < d.count()); // after reset < before reset +} + +// ── format_duration ─────────────────────────────────────────────────────── + +Void::Testing::Test format_duration_nanoseconds() +{ + using namespace std::chrono_literals; + Void::Testing::expect_eq(Void::Time::format_duration(500ns), + std::string{"500ns"}); +} + +Void::Testing::Test format_duration_microseconds() +{ + using namespace std::chrono_literals; + Void::Testing::expect( + Void::Time::format_duration(4500ns).find("\xc2\xb5s") != + std::string::npos); +} + +Void::Testing::Test format_duration_milliseconds() +{ + using namespace std::chrono_literals; + Void::Testing::expect( + Void::Time::format_duration(2'300'000ns).find("ms") != + std::string::npos); +} + +Void::Testing::Test format_duration_seconds() +{ + using namespace std::chrono_literals; + Void::Testing::expect( + Void::Time::format_duration(1'500'000'000ns).find('s') != + std::string::npos); +} + +Void::Testing::Test format_duration_minutes() +{ + Void::Testing::expect( + Void::Time::format_duration(std::chrono::seconds{90}).find('m') != + std::string::npos); +} + +Void::Testing::Test format_duration_hours() +{ + Void::Testing::expect( + Void::Time::format_duration(std::chrono::seconds{3700}).find('h') != + std::string::npos); +} + +Void::Testing::Test format_duration_works_with_chrono_milliseconds() +{ + using namespace std::chrono_literals; + const auto s = Void::Time::format_duration(15ms); + Void::Testing::expect(s.find("ms") != std::string::npos); +} + +// ── utc timestamps ──────────────────────────────────────────────────────── + +Void::Testing::Test utc_now_iso8601_has_correct_format() +{ + const auto s = Void::Time::utc_now_iso8601(); + // "2026-05-14T10:30:00Z" + Void::Testing::expect_eq(s.size(), std::size_t{20}); + Void::Testing::expect_eq(s[4], '-'); + Void::Testing::expect_eq(s[7], '-'); + Void::Testing::expect_eq(s[10], 'T'); + Void::Testing::expect_eq(s.back(), 'Z'); +} + +Void::Testing::Test utc_now_iso8601_ms_has_correct_format() +{ + const auto s = Void::Time::utc_now_iso8601_ms(); + // "2026-05-14T10:30:00.123Z" + Void::Testing::expect_eq(s.size(), std::size_t{24}); + Void::Testing::expect_eq(s[10], 'T'); + Void::Testing::expect_eq(s[19], '.'); + Void::Testing::expect_eq(s.back(), 'Z'); +} diff --git a/tests/standalone/Uuid/Uuid.cpp b/tests/standalone/Uuid/Uuid.cpp new file mode 100644 index 0000000..34327de --- /dev/null +++ b/tests/standalone/Uuid/Uuid.cpp @@ -0,0 +1,113 @@ +#include +#include +#include + +// ── v4 ─────────────────────────────────────────────────────────────────────── + +Void::Testing::Test v4_not_nil() +{ + Void::Testing::expect(!Void::Uuid::v4().is_nil()); +} + +Void::Testing::Test v4_version_nibble() +{ + const auto u = Void::Uuid::v4(); + Void::Testing::expect_eq(u.bytes[6] >> 4, std::uint8_t{4}); +} + +Void::Testing::Test v4_variant_bits() +{ + const auto u = Void::Uuid::v4(); + // top two bits of byte 8 must be 10 + Void::Testing::expect_eq(u.bytes[8] >> 6, std::uint8_t{2}); +} + +Void::Testing::Test v4_unique() +{ + Void::Testing::expect(Void::Uuid::v4() != Void::Uuid::v4()); +} + +Void::Testing::Test v4_string_length() +{ + Void::Testing::expect_eq(Void::Uuid::v4().to_string().size(), + std::size_t{36}); +} + +Void::Testing::Test v4_string_has_dashes() +{ + const auto s = Void::Uuid::v4().to_string(); + Void::Testing::expect_eq(s[8], '-'); + Void::Testing::expect_eq(s[13], '-'); + Void::Testing::expect_eq(s[18], '-'); + Void::Testing::expect_eq(s[23], '-'); +} + +// ── v5_lite ─────────────────────────────────────────────────────────────────── + +Void::Testing::Test v5_lite_deterministic() +{ + const auto a = Void::Uuid::v5_lite(Void::Uuid::Namespace::Dns, "example.com"); + const auto b = Void::Uuid::v5_lite(Void::Uuid::Namespace::Dns, "example.com"); + Void::Testing::expect_eq(a, b); +} + +Void::Testing::Test v5_lite_different_names() +{ + const auto a = Void::Uuid::v5_lite(Void::Uuid::Namespace::Dns, "foo.com"); + const auto b = Void::Uuid::v5_lite(Void::Uuid::Namespace::Dns, "bar.com"); + Void::Testing::expect(a != b); +} + +Void::Testing::Test v5_lite_different_namespaces() +{ + const auto a = Void::Uuid::v5_lite(Void::Uuid::Namespace::Dns, "example"); + const auto b = Void::Uuid::v5_lite(Void::Uuid::Namespace::Url, "example"); + Void::Testing::expect(a != b); +} + +Void::Testing::Test v5_lite_version_nibble() +{ + const auto u = Void::Uuid::v5_lite(Void::Uuid::Namespace::Dns, "test"); + Void::Testing::expect_eq(u.bytes[6] >> 4, std::uint8_t{5}); +} + +// ── parse ──────────────────────────────────────────────────────────────────── + +Void::Testing::Test parse_round_trip() +{ + const auto u = Void::Uuid::v4(); + const auto s = u.to_string(); + const auto parsed = Void::Uuid::parse(s); + Void::Testing::expect(parsed.has_value()); + Void::Testing::expect_eq(*parsed, u); +} + +Void::Testing::Test parse_uppercase() +{ + const auto opt = Void::Uuid::parse( + "550E8400-E29B-41D4-A716-446655440000"); + Void::Testing::expect(opt.has_value()); +} + +Void::Testing::Test parse_invalid_returns_nullopt() +{ + Void::Testing::expect(!Void::Uuid::parse("not-a-uuid").has_value()); +} + +Void::Testing::Test parse_32_char_hex() +{ + const auto opt = Void::Uuid::parse("550e8400e29b41d4a716446655440000"); + Void::Testing::expect(opt.has_value()); +} + +// ── nil ────────────────────────────────────────────────────────────────────── + +Void::Testing::Test nil_uuid_is_nil() +{ + Void::Testing::expect(Void::Uuid::Uuid::nil().is_nil()); +} + +Void::Testing::Test v4_not_nil_check() +{ + Void::Testing::expect(!Void::Uuid::v4().is_nil()); +}