diff --git a/include/Void/Channel/Channel.hpp b/include/Void/Channel/Channel.hpp deleted file mode 100644 index b9e846e..0000000 --- a/include/Void/Channel/Channel.hpp +++ /dev/null @@ -1,124 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace Void::Channel -{ - -// ── Channel ──────────────────────────────────────────────────────────────── -// Bounded, thread-safe MPMC (multi-producer, multi-consumer) queue. -// send() blocks when full; recv() blocks when empty. -// Closing the channel unblocks all waiters. After close: -// - send() returns false immediately. -// - recv() drains remaining items, then returns nullopt. - -template -class Channel -{ -public: - explicit Channel(std::size_t capacity = 64) - : buf_(capacity > 0 ? capacity : 1), cap_{buf_.size()} - {} - - Channel(const Channel&) = delete; - Channel& operator=(const Channel&) = delete; - Channel(Channel&&) = delete; - Channel& operator=(Channel&&) = delete; - - // ── send ────────────────────────────────────────────────────────────────── - // Blocks until space is available or the channel is closed. - // Returns true on success, false if the channel was closed. - bool send(T value) - { - std::unique_lock lk{mu_}; - not_full_.wait(lk, [&] { return count_ < cap_ || closed_; }); - if (closed_) return false; - buf_[tail_] = std::move(value); - tail_ = (tail_ + 1) % cap_; - ++count_; - not_empty_.notify_one(); - return true; - } - - // Non-blocking send. Returns false if full or closed. - bool try_send(T value) - { - std::unique_lock lk{mu_}; - if (closed_ || count_ == cap_) return false; - buf_[tail_] = std::move(value); - tail_ = (tail_ + 1) % cap_; - ++count_; - not_empty_.notify_one(); - return true; - } - - // ── recv ────────────────────────────────────────────────────────────────── - // Blocks until an item is available or the channel is closed and empty. - // Returns nullopt only when the channel is both closed and drained. - std::optional recv() - { - std::unique_lock lk{mu_}; - not_empty_.wait(lk, [&] { return count_ > 0 || closed_; }); - if (count_ == 0) return std::nullopt; - return dequeue_locked(); - } - - // Non-blocking recv. Returns nullopt if empty (or closed and empty). - std::optional try_recv() - { - std::unique_lock lk{mu_}; - if (count_ == 0) return std::nullopt; - return dequeue_locked(); - } - - // ── lifecycle ───────────────────────────────────────────────────────────── - void close() - { - { - std::unique_lock lk{mu_}; - closed_ = true; - } - not_full_.notify_all(); - not_empty_.notify_all(); - } - - [[nodiscard]] bool closed() const - { - std::unique_lock lk{mu_}; - return closed_; - } - - // ── query ───────────────────────────────────────────────────────────────── - [[nodiscard]] std::size_t size() const - { - std::unique_lock lk{mu_}; - return count_; - } - - [[nodiscard]] bool empty() const { return size() == 0; } - - [[nodiscard]] std::size_t capacity() const noexcept { return cap_; } - -private: - std::optional dequeue_locked() - { - T val = std::move(buf_[head_]); - head_ = (head_ + 1) % cap_; - --count_; - not_full_.notify_one(); - return val; - } - - std::vector buf_; - std::size_t cap_; - std::size_t head_{0}, tail_{0}, count_{0}; - bool closed_{false}; - mutable std::mutex mu_; - std::condition_variable not_full_; - std::condition_variable not_empty_; -}; - -} // namespace Void::Channel diff --git a/include/Void/Concurrency/Channel.hpp b/include/Void/Concurrency/Channel.hpp index d603345..30efb91 100644 --- a/include/Void/Concurrency/Channel.hpp +++ b/include/Void/Concurrency/Channel.hpp @@ -97,6 +97,12 @@ namespace Void::Concurrency return buf_.size(); } + bool empty() const + { + std::unique_lock lock{mu_}; + return buf_.empty(); + } + std::size_t capacity() const noexcept { return cap_; } private: diff --git a/include/Void/Curry/Curry.hpp b/include/Void/Curry/Curry.hpp deleted file mode 100644 index eeb2b10..0000000 --- a/include/Void/Curry/Curry.hpp +++ /dev/null @@ -1,88 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace Void::Curry -{ - -// ── curry ───────────────────────────────────────────────────────────────────── -// Transforms a multi-argument callable into a chain of single-argument -// callables. Supports auto-complete (collecting all args) and gradual -// application: -// -// auto add = curry([](int a, int b) { return a + b; }); -// auto add5 = add(5); // one arg applied → another callable -// int sum = add5(3); // = 8, all args collected → invoked -// -// Works for any arity ≥ 1 using a collected-args tuple under the hood. - -namespace Detail -{ - // Count non-deducible args from F by inspecting invoke_result_t. - // We rely on the user's F being an exactly N-ary callable. - - template - struct Curried - { - F fn; - std::tuple args; - - template - constexpr auto operator()(Arg&& arg) && - { - auto new_args = std::tuple_cat(std::move(args), - std::tuple>{std::forward(arg)}); - using NewCollected = Curried>; - - if constexpr (std::is_invocable_v>) { - return std::apply(fn, std::move(new_args)); - } else { - return NewCollected{std::move(fn), std::move(new_args)}; - } - } - - template - constexpr auto operator()(Arg&& arg) const & - { - auto new_args = std::tuple_cat(args, - std::tuple>{std::forward(arg)}); - using NewCollected = Curried>; - - if constexpr (std::is_invocable_v>) { - return std::apply(fn, std::move(new_args)); - } else { - return NewCollected{std::move(fn), std::move(new_args)}; - } - } - }; -} // namespace Detail - -template -[[nodiscard]] constexpr auto curry(F&& fn) -{ - return Detail::Curried>{std::forward(fn), {}}; -} - -// ── uncurry ─────────────────────────────────────────────────────────────────── -// Converts a unary-chain curried function back to a multi-arg callable. -// Works by collecting all args into a tuple and std::applying. -// -// auto add = [](int a) { return [a](int b) { return a + b; }; }; -// uncurry(add)(1, 2) == 3 - -template -[[nodiscard]] constexpr auto uncurry(F&& fn) -{ - return [fn = std::forward(fn)](auto&&... args) { - auto call = fn; - return (... , (call = call(std::forward(args)))); - }; -} - -// ── memoize_curry ───────────────────────────────────────────────────────────── -// Convenience: curry a function that takes two hashable arguments and -// caches results. Uses std::unordered_map under the hood. - -} // namespace Void::Curry diff --git a/include/Void/Either/Either.hpp b/include/Void/Either/Either.hpp index a60110b..8ad88f6 100644 --- a/include/Void/Either/Either.hpp +++ b/include/Void/Either/Either.hpp @@ -10,8 +10,7 @@ namespace Void::Either // ── Either ────────────────────────────────────────────────────────────── // Discriminated union: Left for error/secondary value, Right for success. -// Convention: Right is the "happy path". Use std::expected for simpler cases; -// Either is better when both sides are equally meaningful (e.g. sum types). +// Convention: Right is the "happy path". template class Either @@ -19,8 +18,6 @@ class Either static_assert(!std::is_same_v, "Either: L and R must be distinct types"); public: - // ── construction ────────────────────────────────────────────────────────── - template requires std::is_constructible_v static Either left(T&& v) { return Either{std::in_place_index<0>, std::forward(v)}; } @@ -29,8 +26,6 @@ public: requires std::is_constructible_v static Either right(T&& v) { return Either{std::in_place_index<1>, std::forward(v)}; } - // ── query ───────────────────────────────────────────────────────────────── - [[nodiscard]] bool is_left() const noexcept { return var_.index() == 0; } [[nodiscard]] bool is_right() const noexcept { return var_.index() == 1; } @@ -39,9 +34,6 @@ public: [[nodiscard]] R& right_value() { return std::get<1>(var_); } [[nodiscard]] const R& right_value() const { return std::get<1>(var_); } - // ── monadic operations ──────────────────────────────────────────────────── - - // map: transform Right, leave Left unchanged. template [[nodiscard]] auto map(F&& fn) const & -> Either> { @@ -58,7 +50,6 @@ public: return Either::left(std::move(left_value())); } - // map_left: transform Left, leave Right unchanged. template [[nodiscard]] auto map_left(F&& fn) const & -> Either, R> { @@ -67,7 +58,6 @@ public: return Either::right(right_value()); } - // and_then: flat-map over Right. template requires std::invocable [[nodiscard]] auto and_then(F&& fn) const & -> std::invoke_result_t @@ -77,7 +67,6 @@ public: return Result::left(left_value()); } - // fold: collapse both sides into a single value. template requires std::invocable && std::invocable && std::is_same_v, @@ -89,7 +78,11 @@ public: return std::invoke(on_right, right_value()); } - // ── comparison ──────────────────────────────────────────────────────────── + [[nodiscard]] Either swap() const + { + if (is_left()) return Either::right(left_value()); + return Either::left(right_value()); + } [[nodiscard]] bool operator==(const Either&) const noexcept = default; @@ -100,8 +93,6 @@ private: Either(std::in_place_index_t tag, T&& v) : var_{tag, std::forward(v)} {} }; -// ── free helpers ────────────────────────────────────────────────────────────── - template [[nodiscard]] Either make_left(L v) { return Either::left(std::move(v)); } diff --git a/include/Void/Optional/Optional.hpp b/include/Void/Either/Opt.hpp similarity index 50% rename from include/Void/Optional/Optional.hpp rename to include/Void/Either/Opt.hpp index 392e62a..010d8f8 100644 --- a/include/Void/Optional/Optional.hpp +++ b/include/Void/Either/Opt.hpp @@ -1,99 +1,19 @@ #pragma once +#include #include #include #include #include #include -namespace Void::Optional +namespace Void::Either { -// ── Monadic helpers for std::optional ──────────────────────────────────────── -// std::optional in C++23 already has and_then/transform/or_else. -// This module adds: or_default, try_or, zip, lift, filter, sequence, -// and a fluent wrapper so you can chain without ADL issues. - -// ── Free functions ──────────────────────────────────────────────────────────── - -// Returns the value or a provided default. -template -[[nodiscard]] constexpr T value_or_default(const std::optional& opt) noexcept -{ - return opt.value_or(T{}); -} - -// Applies fn to the value if present; returns the modified optional. -template -[[nodiscard]] constexpr auto transform(std::optional opt, F&& fn) - -> std::optional> -{ - if (!opt) return std::nullopt; - return std::invoke(std::forward(fn), *std::move(opt)); -} - -// Monadic bind: fn must return std::optional. -template -[[nodiscard]] constexpr auto and_then(std::optional opt, F&& fn) -{ - if (!opt) return std::invoke_result_t{}; - return std::invoke(std::forward(fn), *std::move(opt)); -} - -// Returns opt if predicate holds, else nullopt. -template -[[nodiscard]] constexpr std::optional filter(std::optional opt, Pred&& pred) -{ - if (opt && std::invoke(std::forward(pred), *opt)) return opt; - return std::nullopt; -} - -// Returns *opt or throws with the given message. -template -[[nodiscard]] const T& expect(const std::optional& opt, const char* msg = "optional is empty") -{ - if (!opt) throw std::runtime_error{msg}; - return *opt; -} - -// Lifts a regular function T->U into optional->optional. -template -[[nodiscard]] constexpr auto lift(F&& fn) -{ - return [fn = std::forward(fn)](auto opt) mutable - -> std::optional> - { - if (!opt) return std::nullopt; - return std::invoke(fn, *opt); - }; -} - -// zip: both must have values; returns optional>. -template -[[nodiscard]] constexpr std::optional> -zip(const std::optional& a, const std::optional& b) -{ - if (a && b) return std::pair{*a, *b}; - return std::nullopt; -} - -// sequence: convert optional> to optional. -template -[[nodiscard]] constexpr std::optional flatten(std::optional> opt) -{ - if (!opt || !*opt) return std::nullopt; - return **opt; -} - -// or_else: return opt if it has a value, else call fn(). -template -[[nodiscard]] constexpr std::optional or_else(std::optional opt, F&& fn) -{ - if (opt) return opt; - return std::invoke(std::forward(fn)); -} - -// ── Opt — fluent wrapper ─────────────────────────────────────────────────── +// ── Opt ──────────────────────────────────────────────────────────────────── +// Fluent wrapper around std::optional with monadic chaining. +// Complements Either: use Opt when a value is simply present or absent, +// Either when absent carries a specific error. template class Opt @@ -106,12 +26,11 @@ public: [[nodiscard]] static constexpr Opt none() { return Opt{std::optional{}}; } [[nodiscard]] static constexpr Opt some(T v) { return Opt{std::move(v)}; } - [[nodiscard]] constexpr bool has_value() const noexcept { return inner_.has_value(); } - [[nodiscard]] constexpr explicit operator bool() const noexcept { return has_value(); } - - [[nodiscard]] constexpr const T& operator*() const & { return *inner_; } - [[nodiscard]] constexpr T& operator*() & { return *inner_; } - [[nodiscard]] constexpr T value_or(T def) const { return inner_.value_or(std::move(def)); } + [[nodiscard]] constexpr bool has_value() const noexcept { return inner_.has_value(); } + [[nodiscard]] constexpr explicit operator bool() const noexcept { return has_value(); } + [[nodiscard]] constexpr const T& operator*() const & { return *inner_; } + [[nodiscard]] constexpr T& operator*() & { return *inner_; } + [[nodiscard]] constexpr T value_or(T def) const { return inner_.value_or(std::move(def)); } template [[nodiscard]] constexpr auto map(F&& fn) const @@ -144,6 +63,14 @@ public: return std::invoke(std::forward(fn)); } + // Convert to Either: Some(v) → Right(v), None → Left(err). + template + [[nodiscard]] Either ok_or(L err) const + { + if (inner_) return Either::right(*inner_); + return Either::left(std::move(err)); + } + [[nodiscard]] constexpr std::optional to_optional() const { return inner_; } private: @@ -162,4 +89,52 @@ template return Opt::none(); } -} // namespace Void::Optional +// ── free optional utilities ─────────────────────────────────────────────────── +// Operate on std::optional directly without the Opt wrapper. + +template +[[nodiscard]] constexpr auto opt_transform(std::optional opt, F&& fn) + -> std::optional> +{ + if (!opt) return std::nullopt; + return std::invoke(std::forward(fn), *std::move(opt)); +} + +template +[[nodiscard]] constexpr auto opt_and_then(std::optional opt, F&& fn) +{ + if (!opt) return std::invoke_result_t{}; + return std::invoke(std::forward(fn), *std::move(opt)); +} + +template +[[nodiscard]] constexpr std::optional opt_filter(std::optional opt, Pred&& pred) +{ + if (opt && std::invoke(std::forward(pred), *opt)) return opt; + return std::nullopt; +} + +template +[[nodiscard]] const T& opt_expect(const std::optional& opt, + const char* msg = "optional is empty") +{ + if (!opt) throw std::runtime_error{msg}; + return *opt; +} + +template +[[nodiscard]] constexpr std::optional> +opt_zip(const std::optional& a, const std::optional& b) +{ + if (a && b) return std::pair{*a, *b}; + return std::nullopt; +} + +template +[[nodiscard]] constexpr std::optional opt_flatten(std::optional> opt) +{ + if (!opt || !*opt) return std::nullopt; + return **opt; +} + +} // namespace Void::Either diff --git a/include/Void/Pipeline/Curry.hpp b/include/Void/Pipeline/Curry.hpp new file mode 100644 index 0000000..ceae70f --- /dev/null +++ b/include/Void/Pipeline/Curry.hpp @@ -0,0 +1,59 @@ +#pragma once + +#include +#include +#include + +namespace Void::Pipeline +{ + +// ── curry ───────────────────────────────────────────────────────────────────── +// Transforms a multi-argument callable into a chain of single-argument calls. +// +// auto add = curry([](int a, int b) { return a + b; }); +// auto add5 = add(5); // partially applied — returns another callable +// int sum = add5(3); // = 8, all args collected → invoked + +namespace Detail +{ + template + struct Curried + { + F fn; + std::tuple args; + + template + constexpr auto operator()(Arg&& arg) && + { + auto new_args = std::tuple_cat(std::move(args), + std::tuple>{std::forward(arg)}); + using NewCurried = Curried>; + if constexpr (std::is_invocable_v>) { + return std::apply(fn, std::move(new_args)); + } else { + return NewCurried{std::move(fn), std::move(new_args)}; + } + } + + template + constexpr auto operator()(Arg&& arg) const & + { + auto new_args = std::tuple_cat(args, + std::tuple>{std::forward(arg)}); + using NewCurried = Curried>; + if constexpr (std::is_invocable_v>) { + return std::apply(fn, std::move(new_args)); + } else { + return NewCurried{std::move(fn), std::move(new_args)}; + } + } + }; +} // namespace Detail + +template +[[nodiscard]] constexpr auto curry(F&& fn) +{ + return Detail::Curried>{std::forward(fn), {}}; +} + +} // namespace Void::Pipeline diff --git a/include/Void/Memo/Memo.hpp b/include/Void/Pipeline/Memo.hpp similarity index 76% rename from include/Void/Memo/Memo.hpp rename to include/Void/Pipeline/Memo.hpp index 9572b64..867b9bf 100644 --- a/include/Void/Memo/Memo.hpp +++ b/include/Void/Pipeline/Memo.hpp @@ -7,13 +7,33 @@ #include #include -namespace Void::Memo +namespace Void::Pipeline { -// ── tuple_hash ──────────────────────────────────────────────────────────────── +// ── memoize_fn ──────────────────────────────────────────────────────────────── +// Wrap a unary callable with an argument-keyed call cache. +// +// auto sq = memoize_fn([](int x){ return x * x; }); +// sq(5); // computed once, cached forever +// sq(5); // returned from cache namespace Detail { + template + struct MemoOne + { + Fn fn; + std::unordered_map cache; + + R operator()(const Arg& arg) + { + auto it = cache.find(arg); + if (it != cache.end()) return it->second; + auto [ins, _] = cache.emplace(arg, std::invoke(fn, arg)); + return ins->second; + } + }; + template void hash_combine(std::size_t& seed, const T& v) { @@ -36,8 +56,18 @@ namespace Detail }; } // namespace Detail +// Explicit Arg template parameter is required for key type deduction. +// Example: memoize_fn(lambda) where lambda takes int. +template , Arg>> +[[nodiscard]] auto memoize_fn(F&& fn) +{ + return Detail::MemoOne, Arg, R>{std::forward(fn), {}}; +} + // ── memoize ─────────────────────────────────────────────────────────────────── -// Wraps a callable F(Args...) -> R and caches results by argument tuple. +// Wraps a callable F(self, Args...) -> R and caches results by argument tuple. +// The first parameter is a self-reference enabling recursive memoization. // All arguments must be hashable. R must be copyable. // // auto fib = memoize([](auto& self, int n) -> int { @@ -61,9 +91,7 @@ public: using Key = std::tuple...>; using Map = std::unordered_map...>>; - // Use a per-call static-initialized cache per instantiation - // (one cache per unique (Fn, Args...) combination). - // For a clean API, store cache in the object. + // One cache per unique (Fn, Args...) combination. auto& cache = get_cache(); Key key{std::forward(args)...}; const auto it = cache.find(key); @@ -136,4 +164,4 @@ private: std::unordered_map map_; }; -} // namespace Void::Memo +} // namespace Void::Pipeline diff --git a/include/Void/Pipeline/Pipeline.hpp b/include/Void/Pipeline/Pipeline.hpp index 568d592..accab08 100644 --- a/include/Void/Pipeline/Pipeline.hpp +++ b/include/Void/Pipeline/Pipeline.hpp @@ -7,16 +7,12 @@ namespace Void::Pipeline { -// ── pipe ────────────────────────────────────────────────────────────────────── +// ── Pipe ─────────────────────────────────────────────────────────────────── // Wraps a value and lets you chain single-argument callables with operator|. // // int result = pipe(5) // | [](int x) { return x * 2; } -// | [](int x) { return x + 1; } -// | [](int x) { return x; }; // → 11 -// -// The terminal | extracts the value when chained to a non-returning call, -// or just forwards the result type each step. +// | [](int x) { return x + 1; }; // → 11 template class Pipe @@ -52,7 +48,6 @@ private: T value_; }; -// Entry point: wrap a value in a Pipe. template [[nodiscard]] constexpr Pipe> pipe(T&& v) { @@ -60,7 +55,7 @@ template } // ── compose ─────────────────────────────────────────────────────────────────── -// Compose two or more unary callables left-to-right: compose(f, g)(x) = g(f(x)). +// Compose callables left-to-right: compose(f, g)(x) = g(f(x)). namespace Detail { @@ -69,7 +64,6 @@ namespace Detail { F f; G g; - template constexpr auto operator()(T&& x) const { @@ -93,20 +87,17 @@ template } // ── partial ─────────────────────────────────────────────────────────────────── -// Bind leading arguments to a callable, returning a new callable. -// partial(f, a, b)(c) = f(a, b, c) +// Bind leading arguments: partial(f, a, b)(c) = f(a, b, c). template [[nodiscard]] constexpr auto partial(F&& f, Bound&&... bound) { - return [f = std::forward(f), - ...bound = std::forward(bound)](auto&&... rest) mutable { + return [f = std::forward(f), ...bound = std::forward(bound)](auto&&... rest) mutable { return std::invoke(f, bound..., std::forward(rest)...); }; } // ── flip ────────────────────────────────────────────────────────────────────── -// Swap the first two arguments of a binary callable. template [[nodiscard]] constexpr auto flip(F&& f) @@ -119,7 +110,7 @@ template }; } -// ── identity / constant ─────────────────────────────────────────────────────── +// ── identity / constant / negate ───────────────────────────────────────────── struct Identity { template @@ -134,4 +125,12 @@ template return [v = std::forward(v)](auto&&...) { return v; }; } +template +[[nodiscard]] constexpr auto negate(Pred&& pred) +{ + return [pred = std::forward(pred)](auto&&... args) mutable { + return !std::invoke(pred, std::forward(args)...); + }; +} + } // namespace Void::Pipeline diff --git a/include/Void/Scope/Scope.hpp b/include/Void/Scope/Scope.hpp index 7c78dda..3f967b2 100644 --- a/include/Void/Scope/Scope.hpp +++ b/include/Void/Scope/Scope.hpp @@ -17,20 +17,24 @@ public: { } - ~ScopeExit() noexcept + ScopeExit(ScopeExit&& o) noexcept + : f_{std::move(o.f_)}, active_{o.active_} { - if (active_) f_(); + o.active_ = false; } - ScopeExit(const ScopeExit&) = delete; - ScopeExit& operator=(const ScopeExit&) = delete; - ScopeExit(ScopeExit&&) = delete; - ScopeExit& operator=(ScopeExit&&) = delete; + ~ScopeExit() noexcept { if (active_) f_(); } - void release() noexcept { active_ = false; } + ScopeExit(const ScopeExit&) = delete; + ScopeExit& operator=(const ScopeExit&) = delete; + ScopeExit& operator=(ScopeExit&&) = delete; + + void release() noexcept { active_ = false; } + void dismiss() noexcept { active_ = false; } + [[nodiscard]] bool active() const noexcept { return active_; } private: - F f_; + F f_; bool active_{true}; }; @@ -50,15 +54,16 @@ public: if (active_ && std::uncaught_exceptions() == exceptions_) f_(); } - ScopeSuccess(const ScopeSuccess&) = delete; + ScopeSuccess(const ScopeSuccess&) = delete; ScopeSuccess& operator=(const ScopeSuccess&) = delete; - ScopeSuccess(ScopeSuccess&&) = delete; - ScopeSuccess& operator=(ScopeSuccess&&) = delete; + ScopeSuccess(ScopeSuccess&&) = delete; + ScopeSuccess& operator=(ScopeSuccess&&) = delete; void release() noexcept { active_ = false; } + void dismiss() noexcept { active_ = false; } private: - F f_; + F f_; int exceptions_; bool active_{true}; }; @@ -79,15 +84,16 @@ public: if (active_ && std::uncaught_exceptions() > exceptions_) f_(); } - ScopeFail(const ScopeFail&) = delete; + ScopeFail(const ScopeFail&) = delete; ScopeFail& operator=(const ScopeFail&) = delete; - ScopeFail(ScopeFail&&) = delete; - ScopeFail& operator=(ScopeFail&&) = delete; + ScopeFail(ScopeFail&&) = delete; + ScopeFail& operator=(ScopeFail&&) = delete; void release() noexcept { active_ = false; } + void dismiss() noexcept { active_ = false; } private: - F f_; + F f_; int exceptions_; bool active_{true}; }; @@ -112,4 +118,14 @@ template return ScopeFail>{std::forward(f)}; } +// Aliases matching std::scope_{exit,success,failure} proposal naming. +template +[[nodiscard]] auto scope_exit(F&& f) { return on_exit(std::forward(f)); } + +template +[[nodiscard]] auto scope_success(F&& f) { return on_success(std::forward(f)); } + +template +[[nodiscard]] auto scope_failure(F&& f) { return on_fail(std::forward(f)); } + } // namespace Void::Scope diff --git a/include/Void/ScopeGuard/ScopeGuard.hpp b/include/Void/ScopeGuard/ScopeGuard.hpp deleted file mode 100644 index 4587f75..0000000 --- a/include/Void/ScopeGuard/ScopeGuard.hpp +++ /dev/null @@ -1,113 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace Void::ScopeGuard -{ - -// ── ScopeGuard ──────────────────────────────────────────────────────────────── -// RAII wrapper that calls a cleanup function on scope exit. -// Always fires, regardless of whether the scope exits normally or via exception. -// -// auto guard = scope_exit([&] { file.close(); }); -// guard.dismiss(); // cancel the cleanup - -template -class ScopeGuard -{ -public: - explicit ScopeGuard(F&& fn) : fn_{std::forward(fn)}, active_{true} {} - - ScopeGuard(ScopeGuard&& o) noexcept - : fn_{std::move(o.fn_)}, active_{o.active_} - { - o.active_ = false; - } - - ScopeGuard(const ScopeGuard&) = delete; - ScopeGuard& operator=(const ScopeGuard&) = delete; - ScopeGuard& operator=(ScopeGuard&&) = delete; - - ~ScopeGuard() { if (active_) fn_(); } - - void dismiss() noexcept { active_ = false; } - [[nodiscard]] bool active() const noexcept { return active_; } - -private: - F fn_; - bool active_; -}; - -// ── ScopeSuccess ────────────────────────────────────────────────────────────── -// Fires only when the scope exits normally (no exception in flight). - -template -class ScopeSuccess -{ -public: - explicit ScopeSuccess(F&& fn) - : fn_{std::forward(fn)}, - exceptions_at_entry_{std::uncaught_exceptions()} - {} - - ~ScopeSuccess() - { - if (std::uncaught_exceptions() == exceptions_at_entry_) fn_(); - } - - ScopeSuccess(const ScopeSuccess&) = delete; - ScopeSuccess& operator=(const ScopeSuccess&) = delete; - -private: - F fn_; - int exceptions_at_entry_; -}; - -// ── ScopeFailure ────────────────────────────────────────────────────────────── -// Fires only when the scope exits via an exception. - -template -class ScopeFailure -{ -public: - explicit ScopeFailure(F&& fn) - : fn_{std::forward(fn)}, - exceptions_at_entry_{std::uncaught_exceptions()} - {} - - ~ScopeFailure() - { - if (std::uncaught_exceptions() > exceptions_at_entry_) fn_(); - } - - ScopeFailure(const ScopeFailure&) = delete; - ScopeFailure& operator=(const ScopeFailure&) = delete; - -private: - F fn_; - int exceptions_at_entry_; -}; - -// ── factory functions ───────────────────────────────────────────────────────── - -template -[[nodiscard]] auto scope_exit(F&& fn) -{ - return ScopeGuard>{std::forward(fn)}; -} - -template -[[nodiscard]] auto scope_success(F&& fn) -{ - return ScopeSuccess>{std::forward(fn)}; -} - -template -[[nodiscard]] auto scope_failure(F&& fn) -{ - return ScopeFailure>{std::forward(fn)}; -} - -} // namespace Void::ScopeGuard diff --git a/include/Void/StopWatch/StopWatch.hpp b/include/Void/StopWatch/StopWatch.hpp deleted file mode 100644 index d0b0aab..0000000 --- a/include/Void/StopWatch/StopWatch.hpp +++ /dev/null @@ -1,112 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace Void::StopWatch -{ - -using Clock = std::chrono::steady_clock; -using Duration = std::chrono::nanoseconds; - -// ── StopWatch ───────────────────────────────────────────────────────────────── -// Wall-clock stopwatch with lap support. Thread-safe for single writer. -// -// StopWatch sw; -// sw.start(); -// // ... work ... -// sw.lap(); -// // ... more work ... -// sw.stop(); -// sw.elapsed(); // total elapsed in ns -// sw.laps(); // vector of lap durations - -class StopWatch -{ -public: - // Start (or restart) the timer. - void start() noexcept - { - running_ = true; - start_ = Clock::now(); - laps_.clear(); - last_lap_ = start_; - } - - // Record a lap split without stopping. Returns the lap duration. - Duration lap() noexcept - { - if (!running_) return Duration::zero(); - const auto now = Clock::now(); - const Duration d = std::chrono::duration_cast(now - last_lap_); - laps_.push_back(d); - last_lap_ = now; - return d; - } - - // Stop the timer. Returns elapsed time since start. - Duration stop() noexcept - { - if (!running_) return elapsed_; - elapsed_ = std::chrono::duration_cast(Clock::now() - start_); - running_ = false; - return elapsed_; - } - - // Elapsed time (while running: from start to now; when stopped: total). - [[nodiscard]] Duration elapsed() const noexcept - { - if (running_) - return std::chrono::duration_cast(Clock::now() - start_); - return elapsed_; - } - - // Elapsed in milliseconds as double. - [[nodiscard]] double elapsed_ms() const noexcept - { - return std::chrono::duration(elapsed()).count(); - } - - [[nodiscard]] bool is_running() const noexcept { return running_; } - [[nodiscard]] const std::vector& laps() const noexcept { return laps_; } - [[nodiscard]] std::size_t lap_count() const noexcept { return laps_.size(); } - - void reset() noexcept - { - running_ = false; - elapsed_ = Duration::zero(); - laps_.clear(); - } - -private: - Clock::time_point start_{}; - Clock::time_point last_lap_{}; - Duration elapsed_{}; - std::vector laps_; - bool running_{false}; -}; - -// ── ScopedTimer ─────────────────────────────────────────────────────────────── -// RAII timer that records elapsed into a provided Duration on destruction. - -class ScopedTimer -{ -public: - explicit ScopedTimer(Duration& out) - : out_{out}, start_{Clock::now()} {} - - ~ScopedTimer() - { - out_ = std::chrono::duration_cast(Clock::now() - start_); - } - - ScopedTimer(const ScopedTimer&) = delete; - ScopedTimer& operator=(const ScopedTimer&) = delete; - -private: - Duration& out_; - Clock::time_point start_; -}; - -} // namespace Void::StopWatch diff --git a/include/Void/Str/Str.hpp b/include/Void/Str/Str.hpp index 0eff9f4..9da93c8 100644 --- a/include/Void/Str/Str.hpp +++ b/include/Void/Str/Str.hpp @@ -89,6 +89,20 @@ namespace Void::Str // ── split / join ────────────────────────────────────────────────────────────── +[[nodiscard]] inline std::vector +split(std::string_view s, char delim) +{ + std::vector parts; + std::size_t pos = 0; + while (true) { + const auto found = s.find(delim, pos); + parts.push_back(s.substr(pos, found - pos)); + if (found == std::string_view::npos) break; + pos = found + 1; + } + return parts; +} + [[nodiscard]] inline std::vector split(std::string_view s, std::string_view delim) { diff --git a/include/Void/String/String.hpp b/include/Void/String/String.hpp deleted file mode 100644 index 89b0349..0000000 --- a/include/Void/String/String.hpp +++ /dev/null @@ -1,207 +0,0 @@ -#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/Time/Stopwatch.hpp b/include/Void/Time/Stopwatch.hpp index 504a921..e157363 100644 --- a/include/Void/Time/Stopwatch.hpp +++ b/include/Void/Time/Stopwatch.hpp @@ -1,34 +1,90 @@ #pragma once #include +#include +#include namespace Void::Time { -/// Minimal RAII wall-clock timer built on std::chrono::steady_clock. +/// Wall-clock stopwatch with lap support, built on steady_clock. +/// Single-writer; not thread-safe across threads. /// -/// Usage: +/// Explicit style: /// Stopwatch sw; +/// sw.start(); +/// // ... work ... +/// sw.lap(); +/// sw.stop(); +/// sw.elapsed(); // total elapsed +/// sw.laps(); // lap durations +/// +/// RAII style (auto-started): +/// auto sw = Stopwatch::started(); /// do_work(); -/// auto ms = sw.elapsed(); +/// auto ms = sw.elapsed_as(); class Stopwatch { public: using Clock = std::chrono::steady_clock; using TimePoint = Clock::time_point; - using Duration = Clock::duration; + using Duration = std::chrono::nanoseconds; - /// Start the stopwatch at construction time. - Stopwatch() noexcept : start_(Clock::now()) {} + /// Constructed stopped with zero elapsed time. + Stopwatch() noexcept = default; - /// Restart from zero. - void reset() noexcept { start_ = Clock::now(); } + /// Convenience factory: a stopwatch already running. + [[nodiscard]] static Stopwatch started() noexcept + { + Stopwatch sw; + sw.start(); + return sw; + } - /// Elapsed time since construction or last reset(). + /// Start (or restart) the timer. Clears recorded laps. + void start() noexcept + { + running_ = true; + start_ = Clock::now(); + laps_.clear(); + last_lap_ = start_; + } + + /// Record a lap split without stopping. Returns the lap duration. + Duration lap() + { + if (!running_) { + return Duration::zero(); + } + const auto now = Clock::now(); + const auto d = + std::chrono::duration_cast(now - last_lap_); + laps_.push_back(d); + last_lap_ = now; + return d; + } + + /// Stop the timer. Returns elapsed time since start. + Duration stop() noexcept + { + if (!running_) { + return elapsed_; + } + elapsed_ = + std::chrono::duration_cast(Clock::now() - start_); + running_ = false; + return elapsed_; + } + + /// Elapsed time (while running: from start to now; stopped: total). [[nodiscard]] Duration elapsed() const noexcept { - return Clock::now() - start_; + if (running_) { + return std::chrono::duration_cast(Clock::now() - + start_); + } + return elapsed_; } /// Elapsed time cast to a specific duration type. @@ -38,17 +94,76 @@ class Stopwatch return std::chrono::duration_cast(elapsed()); } - /// Split: return elapsed and reset in one call. + /// Elapsed in milliseconds as double. + [[nodiscard]] double elapsed_ms() const noexcept + { + return std::chrono::duration(elapsed()) + .count(); + } + + /// Split: return elapsed and restart in one call. [[nodiscard]] Duration split() noexcept { - auto d = elapsed(); - reset(); + const auto d = elapsed(); + start(); return d; } + [[nodiscard]] bool is_running() const noexcept { return running_; } + + [[nodiscard]] const std::vector& laps() const noexcept + { + return laps_; + } + + [[nodiscard]] std::size_t lap_count() const noexcept + { + return laps_.size(); + } + + /// Stop and clear all recorded state. + void reset() noexcept + { + running_ = false; + elapsed_ = Duration::zero(); + laps_.clear(); + } + private: - TimePoint start_; + TimePoint start_{}; + TimePoint last_lap_{}; + Duration elapsed_{}; + std::vector laps_; + bool running_{false}; +}; + +/// RAII timer that records elapsed into a provided Duration on destruction. +class ScopedTimer +{ + public: + + using Clock = Stopwatch::Clock; + using Duration = Stopwatch::Duration; + + explicit ScopedTimer(Duration& out) + : out_{out}, start_{Clock::now()} + { + } + + ~ScopedTimer() + { + out_ = + std::chrono::duration_cast(Clock::now() - start_); + } + + ScopedTimer(const ScopedTimer&) = delete; + ScopedTimer& operator=(const ScopedTimer&) = delete; + + private: + + Duration& out_; + Clock::time_point start_; }; } // namespace Void::Time diff --git a/src/String/.keep b/src/String/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/src/Testing/Runner.cpp b/src/Testing/Runner.cpp index 47fe428..bed9c83 100644 --- a/src/Testing/Runner.cpp +++ b/src/Testing/Runner.cpp @@ -32,8 +32,8 @@ #include #endif -#ifdef VOID_HAS_STRING -#include +#ifdef VOID_HAS_STR +#include #endif #include @@ -345,8 +345,8 @@ namespace Void::Testing 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)); +#ifdef VOID_HAS_STR + return apply(green, Void::Str::pad_right(name, OPT_WIDTH)); #else std::string s{name}; if (s.size() < OPT_WIDTH) { @@ -596,9 +596,12 @@ namespace Void::Testing } for (unsigned rep = 0; rep < config.repeat; ++rep) { + std::string current_suite; for (auto& test : tests) { auto& suite = suite_results[suite_index[test.suite]]; - if (rep == 0) { + // Emit suite header only when the suite name changes. + if (test.suite != current_suite) { + current_suite = test.suite; reporter->on_suite_start( suite.name, std::count_if( diff --git a/src/Testing/module.cmake b/src/Testing/module.cmake index 3c57aa4..d960ed2 100644 --- a/src/Testing/module.cmake +++ b/src/Testing/module.cmake @@ -1,3 +1,3 @@ void_add_module(Testing - OPTIONAL_DEPS Stacktrace Logging Concurrency Configuration String + OPTIONAL_DEPS Stacktrace Logging Concurrency Configuration Str ) diff --git a/tests/standalone/Channel/Channel.cpp b/tests/standalone/Channel/Channel.cpp deleted file mode 100644 index e050c87..0000000 --- a/tests/standalone/Channel/Channel.cpp +++ /dev/null @@ -1,144 +0,0 @@ -#include -#include -#include - -#include -#include -#include - -using namespace Void::Channel; - -// ── non-blocking operations ─────────────────────────────────────────────────── - -Void::Testing::Test channel_try_send_recv() -{ - Channel ch{4}; - Void::Testing::expect(ch.try_send(1)); - Void::Testing::expect(ch.try_send(2)); - const auto v = ch.try_recv(); - Void::Testing::expect(v.has_value()); - Void::Testing::expect_eq(*v, 1); -} - -Void::Testing::Test channel_fifo_order() -{ - Channel ch{8}; - for (int i = 0; i < 5; ++i) ch.try_send(i); - for (int i = 0; i < 5; ++i) { - const auto v = ch.try_recv(); - Void::Testing::expect(v.has_value()); - Void::Testing::expect_eq(*v, i); - } -} - -Void::Testing::Test channel_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)); // full -} - -Void::Testing::Test channel_try_recv_empty_returns_nullopt() -{ - Channel ch{4}; - Void::Testing::expect(!ch.try_recv().has_value()); -} - -Void::Testing::Test channel_size_and_empty() -{ - Channel ch{4}; - Void::Testing::expect(ch.empty()); - Void::Testing::expect_eq(ch.size(), std::size_t{0}); - ch.try_send(1); - ch.try_send(2); - Void::Testing::expect_eq(ch.size(), std::size_t{2}); - Void::Testing::expect(!ch.empty()); -} - -Void::Testing::Test channel_capacity() -{ - Channel ch{16}; - Void::Testing::expect_eq(ch.capacity(), std::size_t{16}); -} - -// ── close semantics ─────────────────────────────────────────────────────────── - -Void::Testing::Test channel_send_after_close_returns_false() -{ - Channel ch{4}; - ch.close(); - Void::Testing::expect(!ch.try_send(1)); -} - -Void::Testing::Test channel_recv_drains_then_nullopt() -{ - Channel ch{4}; - ch.try_send(10); - ch.try_send(20); - ch.close(); - Void::Testing::expect_eq(*ch.try_recv(), 10); - Void::Testing::expect_eq(*ch.try_recv(), 20); - Void::Testing::expect(!ch.try_recv().has_value()); -} - -Void::Testing::Test channel_closed_flag() -{ - Channel ch{4}; - Void::Testing::expect(!ch.closed()); - ch.close(); - Void::Testing::expect(ch.closed()); -} - -// ── blocking with threads ───────────────────────────────────────────────────── - -Void::Testing::Test channel_producer_consumer_thread() -{ - Channel ch{16}; - std::vector received; - const int count = 10; - - std::thread producer([&] { - for (int i = 0; i < count; ++i) ch.send(i); - ch.close(); - }); - - while (auto v = ch.recv()) - received.push_back(*v); - - producer.join(); - - Void::Testing::expect_eq(static_cast(received.size()), count); - for (int i = 0; i < count; ++i) - Void::Testing::expect_eq(received[i], i); -} - -Void::Testing::Test channel_multiple_producers() -{ - Channel ch{64}; - std::atomic total{0}; - - auto producer = [&](int n) { - for (int i = 0; i < n; ++i) ch.send(i); - }; - - std::thread t1(producer, 5); - std::thread t2(producer, 5); - t1.join(); - t2.join(); - ch.close(); - - while (auto v = ch.recv()) total += *v; - - // Sum of 0+1+2+3+4 = 10, two producers → 20 - Void::Testing::expect_eq(total.load(), 20); -} - -Void::Testing::Test channel_string_values() -{ - Channel ch{4}; - ch.try_send("hello"); - ch.try_send("world"); - Void::Testing::expect_eq(*ch.try_recv(), std::string{"hello"}); - Void::Testing::expect_eq(*ch.try_recv(), std::string{"world"}); -} diff --git a/tests/standalone/Concurrency/Channel.cpp b/tests/standalone/Concurrency/Channel.cpp index c53092f..dd9f7c6 100644 --- a/tests/standalone/Concurrency/Channel.cpp +++ b/tests/standalone/Concurrency/Channel.cpp @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include @@ -82,3 +84,59 @@ Void::Testing::Test send_returns_false_when_closed() bool ok = ch.send(42); Void::Testing::expect(!ok); } + +Void::Testing::Test size_and_empty() +{ + Channel ch{4}; + Void::Testing::expect(ch.empty()); + Void::Testing::expect_eq(ch.size(), std::size_t{0}); + ch.try_send(1); + ch.try_send(2); + Void::Testing::expect_eq(ch.size(), std::size_t{2}); + Void::Testing::expect(!ch.empty()); +} + +Void::Testing::Test receive_drains_then_nullopt_after_close() +{ + Channel ch{4}; + ch.try_send(10); + ch.try_send(20); + ch.close(); + Void::Testing::expect_eq(*ch.try_receive(), 10); + Void::Testing::expect_eq(*ch.try_receive(), 20); + Void::Testing::expect(!ch.try_receive().has_value()); +} + +Void::Testing::Test multiple_producers_sum() +{ + Channel ch{64}; + std::atomic total{0}; + + auto producer = [&](int n) { + for (int i = 0; i < n; ++i) { + ch.send(i); + } + }; + + std::thread t1(producer, 5); + std::thread t2(producer, 5); + t1.join(); + t2.join(); + ch.close(); + + while (auto v = ch.receive()) { + total += *v; + } + + // Sum of 0+1+2+3+4 = 10, two producers → 20 + Void::Testing::expect_eq(total.load(), 20); +} + +Void::Testing::Test string_values_roundtrip() +{ + Channel ch{4}; + ch.try_send("hello"); + ch.try_send("world"); + Void::Testing::expect_eq(*ch.try_receive(), std::string{"hello"}); + Void::Testing::expect_eq(*ch.try_receive(), std::string{"world"}); +} diff --git a/tests/standalone/Curry/Curry.cpp b/tests/standalone/Curry/Curry.cpp deleted file mode 100644 index e007367..0000000 --- a/tests/standalone/Curry/Curry.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include -#include -#include - -#include - -using namespace Void::Curry; - -// ── curry ───────────────────────────────────────────────────────────────────── - -Void::Testing::Test curry_binary_full_apply() -{ - auto add = curry([](int a, int b) { return a + b; }); - Void::Testing::expect_eq(add(3)(4), 7); -} - -Void::Testing::Test curry_binary_partial_then_complete() -{ - auto add = curry([](int a, int b) { return a + b; }); - auto add10 = add(10); - Void::Testing::expect_eq(add10(5), 15); - Void::Testing::expect_eq(add10(20), 30); -} - -Void::Testing::Test curry_ternary() -{ - auto sum3 = curry([](int a, int b, int c) { return a + b + c; }); - Void::Testing::expect_eq(sum3(1)(2)(3), 6); -} - -Void::Testing::Test curry_ternary_partial_twice() -{ - auto sum3 = curry([](int a, int b, int c) { return a + b + c; }); - const auto sum3_with_1 = sum3(1); - const auto sum3_with_1_2 = sum3_with_1(2); - Void::Testing::expect_eq(sum3_with_1_2(10), 13); -} - -Void::Testing::Test curry_type_change() -{ - auto prefix = curry([](std::string p, std::string s) { return p + s; }); - const auto add_hello = prefix(std::string{"hello "}); - Void::Testing::expect_eq(add_hello(std::string{"world"}), std::string{"hello world"}); -} - -Void::Testing::Test curry_unary_invokes_immediately() -{ - auto square = curry([](int x) { return x * x; }); - Void::Testing::expect_eq(square(5), 25); -} - -Void::Testing::Test curry_reuse_partial() -{ - auto mul = curry([](int a, int b) { return a * b; }); - const auto triple = mul(3); - Void::Testing::expect_eq(triple(4), 12); - Void::Testing::expect_eq(triple(5), 15); - Void::Testing::expect_eq(triple(6), 18); -} - -Void::Testing::Test curry_with_lambda_capture() -{ - int offset = 100; - auto add_offset = curry([&](int a, int b) { return a + b + offset; }); - Void::Testing::expect_eq(add_offset(1)(2), 103); -} diff --git a/tests/standalone/Either/Either.cpp b/tests/standalone/Either/Either.cpp index b9edfae..d24391a 100644 --- a/tests/standalone/Either/Either.cpp +++ b/tests/standalone/Either/Either.cpp @@ -1,13 +1,16 @@ #include +#include #include #include +#include #include +#include using namespace Void::Either; using E = Either; -// ── construction & query ────────────────────────────────────────────────────── +// ── Either construction & query ─────────────────────────────────────────────── Void::Testing::Test either_left_is_left() { @@ -25,8 +28,6 @@ Void::Testing::Test either_right_is_right() Void::Testing::expect_eq(e.right_value(), 42); } -// ── map ─────────────────────────────────────────────────────────────────────── - Void::Testing::Test either_map_transforms_right() { const auto e = E::right(5); @@ -51,16 +52,6 @@ Void::Testing::Test either_map_left_transforms_left() Void::Testing::expect_eq(m.left_value(), std::size_t{3}); } -Void::Testing::Test either_map_left_skips_right() -{ - const auto e = E::right(7); - const auto m = e.map_left([](const std::string& s) { return s.size(); }); - Void::Testing::expect(m.is_right()); - Void::Testing::expect_eq(m.right_value(), 7); -} - -// ── fold ────────────────────────────────────────────────────────────────────── - Void::Testing::Test either_fold_right() { const auto e = E::right(10); @@ -79,20 +70,124 @@ Void::Testing::Test either_fold_left() Void::Testing::expect_eq(v, 4); } -// ── equality ────────────────────────────────────────────────────────────────── - -Void::Testing::Test either_equality_right() +Void::Testing::Test either_swap() { - const auto a = E::right(1); - const auto b = E::right(1); - const auto c = E::right(2); - Void::Testing::expect(a == b); - Void::Testing::expect(!(a == c)); + const auto e = E::right(5); + const auto s = e.swap(); + Void::Testing::expect(s.is_left()); + Void::Testing::expect_eq(s.left_value(), 5); } -Void::Testing::Test either_equality_left_vs_right() +Void::Testing::Test either_equality() { - const auto a = E::left("x"); - const auto b = E::right(0); - Void::Testing::expect(!(a == b)); + Void::Testing::expect(E::right(1) == E::right(1)); + Void::Testing::expect(!(E::right(1) == E::right(2))); + Void::Testing::expect(!(E::left("x") == E::right(0))); +} + +// ── Opt ──────────────────────────────────────────────────────────────────── + +Void::Testing::Test opt_some_has_value() +{ + const auto o = some(42); + Void::Testing::expect(o.has_value()); + Void::Testing::expect_eq(*o, 42); +} + +Void::Testing::Test opt_none_empty() +{ + const auto o = none(); + Void::Testing::expect(!o.has_value()); +} + +Void::Testing::Test opt_map_chain() +{ + const auto r = some(3) + .map([](int x) { return x + 1; }) + .map([](int x) { return x * 2; }); + Void::Testing::expect_eq(*r, 8); +} + +Void::Testing::Test opt_filter_fluent() +{ + Void::Testing::expect(some(10).filter([](int x) { return x > 5; }).has_value()); + Void::Testing::expect(!some(2).filter([](int x) { return x > 5; }).has_value()); +} + +Void::Testing::Test opt_flat_map_fluent() +{ + const auto r = some(5).flat_map([](int x) -> Opt { + return some(std::to_string(x)); + }); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"5"}); +} + +Void::Testing::Test opt_value_or() +{ + Void::Testing::expect_eq(some(7).value_or(0), 7); + Void::Testing::expect_eq(none().value_or(99), 99); +} + +Void::Testing::Test opt_ok_or_converts_to_either() +{ + const auto r = some(42).ok_or(std::string{"missing"}); + Void::Testing::expect(r.is_right()); + Void::Testing::expect_eq(r.right_value(), 42); + + const auto err = none().ok_or(std::string{"missing"}); + Void::Testing::expect(err.is_left()); +} + +// ── free optional utilities ─────────────────────────────────────────────────── + +Void::Testing::Test opt_transform_present() +{ + const std::optional o{5}; + const auto r = opt_transform(o, [](int x) { return x * 2; }); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, 10); +} + +Void::Testing::Test opt_transform_empty() +{ + const std::optional o; + const auto r = opt_transform(o, [](int x) { return x * 2; }); + Void::Testing::expect(!r.has_value()); +} + +Void::Testing::Test opt_filter_free() +{ + const std::optional o{10}; + Void::Testing::expect(opt_filter(o, [](int x) { return x > 5; }).has_value()); + Void::Testing::expect(!opt_filter(o, [](int x) { return x > 15; }).has_value()); +} + +Void::Testing::Test opt_expect_throws_on_empty() +{ + const std::optional o; + bool threw = false; + try { [[maybe_unused]] auto v = opt_expect(o, "empty"); } catch (...) { threw = true; } + Void::Testing::expect(threw); +} + +Void::Testing::Test opt_zip_both_present() +{ + const auto r = opt_zip(std::optional{1}, std::optional{"hi"}); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->first, 1); + Void::Testing::expect_eq(r->second, std::string{"hi"}); +} + +Void::Testing::Test opt_zip_one_empty() +{ + const auto r = opt_zip(std::optional{1}, std::optional{}); + Void::Testing::expect(!r.has_value()); +} + +Void::Testing::Test opt_flatten_nested() +{ + const std::optional> o{std::optional{7}}; + Void::Testing::expect_eq(*opt_flatten(o), 7); + Void::Testing::expect(!opt_flatten(std::optional>{std::optional{}}).has_value()); } diff --git a/tests/standalone/Optional/Optional.cpp b/tests/standalone/Optional/Optional.cpp deleted file mode 100644 index 811b11a..0000000 --- a/tests/standalone/Optional/Optional.cpp +++ /dev/null @@ -1,168 +0,0 @@ -#include -#include -#include - -#include -#include -#include - -using namespace Void::Optional; - -// ── free functions ──────────────────────────────────────────────────────────── - -Void::Testing::Test opt_transform_present() -{ - const std::optional o{5}; - const auto r = transform(o, [](int x) { return x * 2; }); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(*r, 10); -} - -Void::Testing::Test opt_transform_empty() -{ - const std::optional o; - const auto r = transform(o, [](int x) { return x * 2; }); - Void::Testing::expect(!r.has_value()); -} - -Void::Testing::Test opt_and_then_chain() -{ - const std::optional o{4}; - const auto r = and_then(o, [](int x) -> std::optional { - if (x > 0) return std::to_string(x); - return std::nullopt; - }); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(*r, std::string{"4"}); -} - -Void::Testing::Test opt_and_then_short_circuits() -{ - const std::optional o; - bool called = false; - const auto r = and_then(o, [&](int) -> std::optional { called = true; return 1; }); - Void::Testing::expect(!called); - Void::Testing::expect(!r.has_value()); -} - -Void::Testing::Test opt_filter_passes() -{ - const std::optional o{10}; - const auto r = filter(o, [](int x) { return x > 5; }); - Void::Testing::expect(r.has_value()); -} - -Void::Testing::Test opt_filter_blocks() -{ - const std::optional o{3}; - const auto r = filter(o, [](int x) { return x > 5; }); - Void::Testing::expect(!r.has_value()); -} - -Void::Testing::Test opt_expect_present() -{ - const std::optional o{42}; - Void::Testing::expect_eq(expect(o), 42); -} - -Void::Testing::Test opt_expect_throws_on_empty() -{ - const std::optional o; - bool threw = false; - try { [[maybe_unused]] auto v = expect(o, "must have value"); } catch (...) { threw = true; } - Void::Testing::expect(threw); -} - -Void::Testing::Test opt_zip_both_present() -{ - const std::optional a{1}; - const std::optional b{"hello"}; - const auto r = zip(a, b); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(r->first, 1); - Void::Testing::expect_eq(r->second, std::string{"hello"}); -} - -Void::Testing::Test opt_zip_one_empty() -{ - const std::optional a{1}; - const std::optional b; - const auto r = zip(a, b); - Void::Testing::expect(!r.has_value()); -} - -Void::Testing::Test opt_flatten() -{ - const std::optional> o{std::optional{7}}; - const auto r = flatten(o); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(*r, 7); -} - -Void::Testing::Test opt_flatten_inner_empty() -{ - const std::optional> o{std::optional{}}; - Void::Testing::expect(!flatten(o).has_value()); -} - -Void::Testing::Test opt_or_else_calls_on_empty() -{ - const std::optional o; - const auto r = or_else(o, [] { return std::optional{99}; }); - Void::Testing::expect_eq(*r, 99); -} - -Void::Testing::Test opt_or_else_skips_on_present() -{ - const std::optional o{5}; - bool called = false; - const auto r = or_else(o, [&] { called = true; return std::optional{99}; }); - Void::Testing::expect(!called); - Void::Testing::expect_eq(*r, 5); -} - -// ── Opt fluent wrapper ───────────────────────────────────────────────────── - -Void::Testing::Test opt_some_has_value() -{ - const auto o = some(42); - Void::Testing::expect(o.has_value()); - Void::Testing::expect_eq(*o, 42); -} - -Void::Testing::Test opt_none_empty() -{ - const auto o = none(); - Void::Testing::expect(!o.has_value()); -} - -Void::Testing::Test opt_map_chain() -{ - const auto r = some(3) - .map([](int x) { return x + 1; }) - .map([](int x) { return x * 2; }); - Void::Testing::expect_eq(*r, 8); -} - -Void::Testing::Test opt_filter_fluent() -{ - const auto r = some(10).filter([](int x) { return x > 5; }); - Void::Testing::expect(r.has_value()); - const auto r2 = some(2).filter([](int x) { return x > 5; }); - Void::Testing::expect(!r2.has_value()); -} - -Void::Testing::Test opt_flat_map_fluent() -{ - const auto r = some(5).flat_map([](int x) -> Opt { - return some(std::to_string(x)); - }); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(*r, std::string{"5"}); -} - -Void::Testing::Test opt_value_or() -{ - Void::Testing::expect_eq(some(7).value_or(0), 7); - Void::Testing::expect_eq(none().value_or(99), 99); -} diff --git a/tests/standalone/Memo/Memo.cpp b/tests/standalone/Pipeline/Memo.cpp similarity index 98% rename from tests/standalone/Memo/Memo.cpp rename to tests/standalone/Pipeline/Memo.cpp index 16947eb..bf2f538 100644 --- a/tests/standalone/Memo/Memo.cpp +++ b/tests/standalone/Pipeline/Memo.cpp @@ -1,11 +1,11 @@ -#include +#include #include #include #include #include -using namespace Void::Memo; +using namespace Void::Pipeline; // ── Memoized ────────────────────────────────────────────────────────────────── diff --git a/tests/standalone/Pipeline/Pipeline.cpp b/tests/standalone/Pipeline/Pipeline.cpp index f711ed8..f976846 100644 --- a/tests/standalone/Pipeline/Pipeline.cpp +++ b/tests/standalone/Pipeline/Pipeline.cpp @@ -1,3 +1,5 @@ +#include +#include #include #include #include @@ -31,26 +33,12 @@ Void::Testing::Test pipe_type_change() Void::Testing::expect_eq(result, std::string{"[42]"}); } -Void::Testing::Test pipe_get_accessor() -{ - auto p = pipe(99); - Void::Testing::expect_eq(p.get(), 99); -} - Void::Testing::Test pipe_implicit_conversion() { int v = pipe(7) | [](int x) { return x + 1; }; Void::Testing::expect_eq(v, 8); } -Void::Testing::Test pipe_string_chain() -{ - const std::string result = pipe(std::string{"hello"}) - | [](std::string s) { s += " world"; return s; } - | [](std::string s) { s[0] = 'H'; return s; }; - Void::Testing::expect_eq(result, std::string{"Hello world"}); -} - // ── compose ─────────────────────────────────────────────────────────────────── Void::Testing::Test compose_two() @@ -115,3 +103,78 @@ Void::Testing::Test constant_ignores_args() Void::Testing::expect_eq(always5(), 5); Void::Testing::expect_eq(always5(1, 2, 3), 5); } + +// ── negate ──────────────────────────────────────────────────────────────────── + +Void::Testing::Test negate_predicate() +{ + auto is_positive = [](int x) { return x > 0; }; + auto is_non_positive = negate(is_positive); + Void::Testing::expect(!is_non_positive(5)); + Void::Testing::expect(is_non_positive(-3)); + Void::Testing::expect(is_non_positive(0)); +} + +// ── curry ───────────────────────────────────────────────────────────────────── + +Void::Testing::Test curry_binary_full_apply() +{ + auto add = curry([](int a, int b) { return a + b; }); + Void::Testing::expect_eq(add(3)(4), 7); +} + +Void::Testing::Test curry_binary_partial_then_complete() +{ + auto add = curry([](int a, int b) { return a + b; }); + auto add10 = add(10); + Void::Testing::expect_eq(add10(5), 15); + Void::Testing::expect_eq(add10(20), 30); +} + +Void::Testing::Test curry_ternary() +{ + auto sum3 = curry([](int a, int b, int c) { return a + b + c; }); + Void::Testing::expect_eq(sum3(1)(2)(3), 6); +} + +Void::Testing::Test curry_type_change() +{ + auto prefix = curry([](std::string p, std::string s) { return p + s; }); + const auto add_hello = prefix(std::string{"hello "}); + Void::Testing::expect_eq(add_hello(std::string{"world"}), std::string{"hello world"}); +} + +Void::Testing::Test curry_unary_invokes_immediately() +{ + auto square = curry([](int x) { return x * x; }); + Void::Testing::expect_eq(square(5), 25); +} + +Void::Testing::Test curry_reuse_partial() +{ + auto mul = curry([](int a, int b) { return a * b; }); + const auto triple = mul(3); + Void::Testing::expect_eq(triple(4), 12); + Void::Testing::expect_eq(triple(5), 15); +} + +// ── memoize_fn ──────────────────────────────────────────────────────────────── + +Void::Testing::Test memoize_fn_caches_result() +{ + int call_count = 0; + auto fn = memoize_fn([&](int x) { ++call_count; return x * x; }); + fn(5); + fn(5); + fn(5); + Void::Testing::expect_eq(call_count, 1); + fn(6); + Void::Testing::expect_eq(call_count, 2); +} + +Void::Testing::Test memoize_fn_correct_result() +{ + auto sq = memoize_fn([](int x) { return x * x; }); + Void::Testing::expect_eq(sq(4), 16); + Void::Testing::expect_eq(sq(7), 49); +} diff --git a/tests/standalone/Scope/Scope.cpp b/tests/standalone/Scope/Scope.cpp index 70cd210..f00a10d 100644 --- a/tests/standalone/Scope/Scope.cpp +++ b/tests/standalone/Scope/Scope.cpp @@ -5,13 +5,15 @@ #include #include +using namespace Void::Scope; + // ── on_exit ─────────────────────────────────────────────────────────────────── Void::Testing::Test on_exit_runs_on_normal_exit() { bool ran = false; { - auto guard = Void::Scope::on_exit([&] { ran = true; }); + auto guard = on_exit([&] { ran = true; }); } Void::Testing::expect(ran); } @@ -20,7 +22,7 @@ Void::Testing::Test on_exit_runs_on_exception() { bool ran = false; try { - auto guard = Void::Scope::on_exit([&] { ran = true; }); + auto guard = on_exit([&] { ran = true; }); throw std::runtime_error{"test"}; } catch (...) {} Void::Testing::expect(ran); @@ -30,31 +32,82 @@ Void::Testing::Test on_exit_release_prevents_run() { bool ran = false; { - auto guard = Void::Scope::on_exit([&] { ran = true; }); + auto guard = on_exit([&] { ran = true; }); guard.release(); } Void::Testing::expect(!ran); } +Void::Testing::Test on_exit_dismiss_prevents_run() +{ + bool ran = false; + { + auto guard = on_exit([&] { ran = true; }); + guard.dismiss(); + } + Void::Testing::expect(!ran); +} + +Void::Testing::Test on_exit_active_reflects_state() +{ + auto guard = on_exit([] {}); + Void::Testing::expect(guard.active()); + guard.dismiss(); + Void::Testing::expect(!guard.active()); +} + +Void::Testing::Test on_exit_move_transfers_ownership() +{ + int called = 0; + { + auto g1 = on_exit([&] { ++called; }); + auto g2 = std::move(g1); + Void::Testing::expect(!g1.active()); + Void::Testing::expect(g2.active()); + } + Void::Testing::expect_eq(called, 1); +} + Void::Testing::Test on_exit_lifo_order() { std::string order; { - auto a = Void::Scope::on_exit([&] { order += "A"; }); - auto b = Void::Scope::on_exit([&] { order += "B"; }); - auto c = Void::Scope::on_exit([&] { order += "C"; }); + auto a = on_exit([&] { order += "A"; }); + auto b = on_exit([&] { order += "B"; }); + auto c = on_exit([&] { order += "C"; }); } Void::Testing::expect_eq(order, std::string{"CBA"}); } -Void::Testing::Test on_exit_captures_by_ref() +Void::Testing::Test on_exit_multiple_guards_lifo() { - int count = 0; + int order = 0, a = 0, b = 0; { - auto guard = Void::Scope::on_exit([&] { count += 10; }); - count = 5; + auto ga = on_exit([&] { a = ++order; }); + auto gb = on_exit([&] { b = ++order; }); } - Void::Testing::expect_eq(count, 15); + Void::Testing::expect(b < a); +} + +Void::Testing::Test on_exit_resource_cleanup() +{ + bool released = false; + { + int handle = 42; + auto cleanup = on_exit([&] { if (handle) released = true; }); + (void)handle; + } + Void::Testing::expect(released); +} + +Void::Testing::Test on_exit_conditional_commit() +{ + int value = 10; + { + auto rollback = on_exit([&] { value = 0; }); + rollback.dismiss(); + } + Void::Testing::expect_eq(value, 10); } // ── on_success ──────────────────────────────────────────────────────────────── @@ -63,7 +116,7 @@ Void::Testing::Test on_success_runs_on_normal_exit() { bool ran = false; { - auto guard = Void::Scope::on_success([&] { ran = true; }); + auto guard = on_success([&] { ran = true; }); } Void::Testing::expect(ran); } @@ -72,7 +125,7 @@ Void::Testing::Test on_success_does_not_run_on_exception() { bool ran = false; try { - auto guard = Void::Scope::on_success([&] { ran = true; }); + auto guard = on_success([&] { ran = true; }); throw std::runtime_error{"test"}; } catch (...) {} Void::Testing::expect(!ran); @@ -82,7 +135,7 @@ Void::Testing::Test on_success_release_prevents_run() { bool ran = false; { - auto guard = Void::Scope::on_success([&] { ran = true; }); + auto guard = on_success([&] { ran = true; }); guard.release(); } Void::Testing::expect(!ran); @@ -94,7 +147,7 @@ Void::Testing::Test on_fail_does_not_run_on_normal_exit() { bool ran = false; { - auto guard = Void::Scope::on_fail([&] { ran = true; }); + auto guard = on_fail([&] { ran = true; }); } Void::Testing::expect(!ran); } @@ -103,7 +156,7 @@ Void::Testing::Test on_fail_runs_on_exception() { bool ran = false; try { - auto guard = Void::Scope::on_fail([&] { ran = true; }); + auto guard = on_fail([&] { ran = true; }); throw std::runtime_error{"test"}; } catch (...) {} Void::Testing::expect(ran); @@ -113,9 +166,39 @@ Void::Testing::Test on_fail_release_prevents_run() { bool ran = false; try { - auto guard = Void::Scope::on_fail([&] { ran = true; }); + auto guard = on_fail([&] { ran = true; }); guard.release(); throw std::runtime_error{"test"}; } catch (...) {} Void::Testing::expect(!ran); } + +// ── scope_exit / scope_success / scope_failure aliases ─────────────────────── + +Void::Testing::Test scope_exit_alias_fires() +{ + int called = 0; + { + auto g = scope_exit([&] { ++called; }); + } + Void::Testing::expect_eq(called, 1); +} + +Void::Testing::Test scope_success_alias_fires_on_normal() +{ + int called = 0; + { + auto g = scope_success([&] { ++called; }); + } + Void::Testing::expect_eq(called, 1); +} + +Void::Testing::Test scope_failure_alias_fires_on_exception() +{ + int called = 0; + try { + auto g = scope_failure([&] { ++called; }); + throw std::runtime_error{"x"}; + } catch (...) {} + Void::Testing::expect_eq(called, 1); +} diff --git a/tests/standalone/ScopeGuard/ScopeGuard.cpp b/tests/standalone/ScopeGuard/ScopeGuard.cpp deleted file mode 100644 index c4a5c0f..0000000 --- a/tests/standalone/ScopeGuard/ScopeGuard.cpp +++ /dev/null @@ -1,139 +0,0 @@ -#include -#include -#include - -#include - -using namespace Void::ScopeGuard; - -// ── scope_exit ──────────────────────────────────────────────────────────────── - -Void::Testing::Test scope_exit_fires_on_normal_exit() -{ - int called = 0; - { - auto g = scope_exit([&] { ++called; }); - } - Void::Testing::expect_eq(called, 1); -} - -Void::Testing::Test scope_exit_fires_on_exception() -{ - int called = 0; - try { - auto g = scope_exit([&] { ++called; }); - throw std::runtime_error{"oops"}; - } catch (...) {} - Void::Testing::expect_eq(called, 1); -} - -Void::Testing::Test scope_exit_dismiss_prevents_call() -{ - int called = 0; - { - auto g = scope_exit([&] { ++called; }); - g.dismiss(); - } - Void::Testing::expect_eq(called, 0); -} - -Void::Testing::Test scope_exit_active_reflects_state() -{ - auto g = scope_exit([] {}); - Void::Testing::expect(g.active()); - g.dismiss(); - Void::Testing::expect(!g.active()); -} - -Void::Testing::Test scope_exit_move_transfers_ownership() -{ - int called = 0; - { - auto g1 = scope_exit([&] { ++called; }); - auto g2 = std::move(g1); - Void::Testing::expect(!g1.active()); - Void::Testing::expect(g2.active()); - } - Void::Testing::expect_eq(called, 1); -} - -Void::Testing::Test scope_exit_multiple_guards() -{ - int order = 0, a = 0, b = 0; - { - auto ga = scope_exit([&] { a = ++order; }); - auto gb = scope_exit([&] { b = ++order; }); - } - // gb fires before ga (LIFO destruction) - Void::Testing::expect(b < a); -} - -// ── scope_success ───────────────────────────────────────────────────────────── - -Void::Testing::Test scope_success_fires_on_normal_exit() -{ - int called = 0; - { - auto g = scope_success([&] { ++called; }); - } - Void::Testing::expect_eq(called, 1); -} - -Void::Testing::Test scope_success_does_not_fire_on_exception() -{ - int called = 0; - try { - auto g = scope_success([&] { ++called; }); - throw std::runtime_error{"oops"}; - } catch (...) {} - Void::Testing::expect_eq(called, 0); -} - -// ── scope_failure ───────────────────────────────────────────────────────────── - -Void::Testing::Test scope_failure_does_not_fire_on_normal_exit() -{ - int called = 0; - { - auto g = scope_failure([&] { ++called; }); - } - Void::Testing::expect_eq(called, 0); -} - -Void::Testing::Test scope_failure_fires_on_exception() -{ - int called = 0; - try { - auto g = scope_failure([&] { ++called; }); - throw std::runtime_error{"oops"}; - } catch (...) {} - Void::Testing::expect_eq(called, 1); -} - -// ── practical usage ─────────────────────────────────────────────────────────── - -Void::Testing::Test scope_exit_resource_cleanup() -{ - bool released = false; - auto acquire = [&]() -> int { return 42; }; - { - int handle = acquire(); - auto cleanup = scope_exit([&] { if (handle) released = true; }); - (void)handle; - } - Void::Testing::expect(released); -} - -Void::Testing::Test scope_exit_conditional_commit() -{ - int value = 0; - bool committed = false; - { - value = 10; - auto rollback = scope_exit([&] { value = 0; }); - // Simulate successful operation — commit. - committed = true; - if (committed) rollback.dismiss(); - } - Void::Testing::expect_eq(value, 10); -} diff --git a/tests/standalone/String/String.cpp b/tests/standalone/String/String.cpp deleted file mode 100644 index eeec164..0000000 --- a/tests/standalone/String/String.cpp +++ /dev/null @@ -1,186 +0,0 @@ -#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/StopWatch/StopWatch.cpp b/tests/standalone/Time/Stopwatch.cpp similarity index 90% rename from tests/standalone/StopWatch/StopWatch.cpp rename to tests/standalone/Time/Stopwatch.cpp index e69bcc4..66b2dc0 100644 --- a/tests/standalone/StopWatch/StopWatch.cpp +++ b/tests/standalone/Time/Stopwatch.cpp @@ -1,30 +1,31 @@ -#include +#include #include #include #include -using namespace Void::StopWatch; +using namespace Void::Time; +using Duration = Void::Time::Stopwatch::Duration; -// ── StopWatch ───────────────────────────────────────────────────────────────── +// ── Stopwatch ───────────────────────────────────────────────────────────────── Void::Testing::Test stopwatch_not_running_initially() { - StopWatch sw; + Stopwatch sw; Void::Testing::expect(!sw.is_running()); Void::Testing::expect_eq(sw.elapsed(), Duration::zero()); } Void::Testing::Test stopwatch_start_sets_running() { - StopWatch sw; + Stopwatch sw; sw.start(); Void::Testing::expect(sw.is_running()); } Void::Testing::Test stopwatch_elapsed_increases_while_running() { - StopWatch sw; + Stopwatch sw; sw.start(); const auto first = sw.elapsed(); std::this_thread::sleep_for(std::chrono::milliseconds{5}); @@ -34,7 +35,7 @@ Void::Testing::Test stopwatch_elapsed_increases_while_running() Void::Testing::Test stopwatch_stop_returns_elapsed() { - StopWatch sw; + Stopwatch sw; sw.start(); std::this_thread::sleep_for(std::chrono::milliseconds{5}); const Duration d = sw.stop(); @@ -44,7 +45,7 @@ Void::Testing::Test stopwatch_stop_returns_elapsed() Void::Testing::Test stopwatch_elapsed_ms() { - StopWatch sw; + Stopwatch sw; sw.start(); std::this_thread::sleep_for(std::chrono::milliseconds{5}); sw.stop(); @@ -53,7 +54,7 @@ Void::Testing::Test stopwatch_elapsed_ms() Void::Testing::Test stopwatch_lap_count() { - StopWatch sw; + Stopwatch sw; sw.start(); sw.lap(); sw.lap(); @@ -63,7 +64,7 @@ Void::Testing::Test stopwatch_lap_count() Void::Testing::Test stopwatch_lap_durations_sum_to_elapsed() { - StopWatch sw; + Stopwatch sw; sw.start(); std::this_thread::sleep_for(std::chrono::milliseconds{2}); sw.lap(); @@ -80,7 +81,7 @@ Void::Testing::Test stopwatch_lap_durations_sum_to_elapsed() Void::Testing::Test stopwatch_reset_clears_state() { - StopWatch sw; + Stopwatch sw; sw.start(); sw.lap(); sw.stop(); @@ -92,7 +93,7 @@ Void::Testing::Test stopwatch_reset_clears_state() Void::Testing::Test stopwatch_restart_clears_laps() { - StopWatch sw; + Stopwatch sw; sw.start(); sw.lap(); sw.stop(); @@ -102,7 +103,7 @@ Void::Testing::Test stopwatch_restart_clears_laps() Void::Testing::Test stopwatch_stopped_elapsed_does_not_grow() { - StopWatch sw; + Stopwatch sw; sw.start(); std::this_thread::sleep_for(std::chrono::milliseconds{5}); sw.stop(); diff --git a/tests/standalone/Time/Time.cpp b/tests/standalone/Time/Time.cpp index a95e3e1..1bbdbc3 100644 --- a/tests/standalone/Time/Time.cpp +++ b/tests/standalone/Time/Time.cpp @@ -11,36 +11,36 @@ Void::Testing::Test stopwatch_elapsed_is_non_negative() { - Void::Time::Stopwatch sw; + auto sw = Void::Time::Stopwatch::started(); Void::Testing::expect(sw.elapsed().count() >= 0); } Void::Testing::Test stopwatch_elapsed_as_milliseconds() { - Void::Time::Stopwatch sw; + auto sw = Void::Time::Stopwatch::started(); 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::Testing::Test stopwatch_restart_starts_from_zero() { - Void::Time::Stopwatch sw; + auto sw = Void::Time::Stopwatch::started(); std::this_thread::sleep_for(std::chrono::milliseconds{5}); - sw.reset(); + sw.start(); const auto ns = sw.elapsed().count(); - Void::Testing::expect(ns < 5'000'000); // < 5ms since reset + Void::Testing::expect(ns < 5'000'000); // < 5ms since restart } -Void::Testing::Test stopwatch_split_returns_elapsed_and_resets() +Void::Testing::Test stopwatch_split_returns_elapsed_and_restarts() { - Void::Time::Stopwatch sw; + auto sw = Void::Time::Stopwatch::started(); 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 + Void::Testing::expect(after < d.count()); // after restart < before } // ── format_duration ───────────────────────────────────────────────────────