Finish module consolidation: fold Memo into Pipeline, dedupe Channel/Stopwatch

Completes the in-progress merges (Optional->Either/Opt, Curry+Memo->Pipeline,
ScopeGuard->Scope, String->Str):
- Pipeline/Memo.hpp now carries the full Memo API (memoize with recursion
  support, TupleHash, SimpleCache) alongside memoize_fn; old Memo module
  and its test dir removed.
- Duplicate Channel module removed; Concurrency::Channel gains empty() and
  the unique test cases (drain-after-close, multi-producer, string payloads).
- StopWatch module merged into Time::Stopwatch: one class with explicit
  start/stop/laps plus a started() factory for the auto-start RAII style;
  ScopedTimer moved along.
- Testing optional dep retargeted String->Str (pad_right lives in Str now).
- Stale empty dirs removed: src/{ScopeGuard,String,Core}, include/Void/{Core,
  Filesystem,Memo,Channel,StopWatch}.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-12 18:41:24 +03:00
1 parent 58ff7b38a0
commit da2e93c405
29 files changed
+752 -1593

No files matched your search

-124
View File
@@ -1,124 +0,0 @@
#pragma once
#include <condition_variable>
#include <mutex>
#include <optional>
#include <vector>
namespace Void::Channel
{
// ── Channel<T> ────────────────────────────────────────────────────────────────
// 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 <typename T>
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<T> 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<T> 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<T> dequeue_locked()
{
T val = std::move(buf_[head_]);
head_ = (head_ + 1) % cap_;
--count_;
not_full_.notify_one();
return val;
}
std::vector<T> 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
+6
View File
@@ -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:
-88
View File
@@ -1,88 +0,0 @@
#pragma once
#include <tuple>
#include <type_traits>
#include <utility>
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 <typename F, typename... Collected>
struct Curried
{
F fn;
std::tuple<Collected...> args;
template <typename Arg>
constexpr auto operator()(Arg&& arg) &&
{
auto new_args = std::tuple_cat(std::move(args),
std::tuple<std::decay_t<Arg>>{std::forward<Arg>(arg)});
using NewCollected = Curried<F, Collected..., std::decay_t<Arg>>;
if constexpr (std::is_invocable_v<F, Collected..., std::decay_t<Arg>>) {
return std::apply(fn, std::move(new_args));
} else {
return NewCollected{std::move(fn), std::move(new_args)};
}
}
template <typename Arg>
constexpr auto operator()(Arg&& arg) const &
{
auto new_args = std::tuple_cat(args,
std::tuple<std::decay_t<Arg>>{std::forward<Arg>(arg)});
using NewCollected = Curried<F, Collected..., std::decay_t<Arg>>;
if constexpr (std::is_invocable_v<F, Collected..., std::decay_t<Arg>>) {
return std::apply(fn, std::move(new_args));
} else {
return NewCollected{std::move(fn), std::move(new_args)};
}
}
};
} // namespace Detail
template <typename F>
[[nodiscard]] constexpr auto curry(F&& fn)
{
return Detail::Curried<std::decay_t<F>>{std::forward<F>(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 <typename F>
[[nodiscard]] constexpr auto uncurry(F&& fn)
{
return [fn = std::forward<F>(fn)](auto&&... args) {
auto call = fn;
return (... , (call = call(std::forward<decltype(args)>(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
+6 -15
View File
@@ -10,8 +10,7 @@ namespace Void::Either
// ── Either<L, R> ──────────────────────────────────────────────────────────────
// Discriminated union: Left<L> for error/secondary value, Right<R> 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 <typename L, typename R>
class Either
@@ -19,8 +18,6 @@ class Either
static_assert(!std::is_same_v<L, R>, "Either<L,R>: L and R must be distinct types");
public:
// ── construction ──────────────────────────────────────────────────────────
template <typename T>
requires std::is_constructible_v<L, T>
static Either left(T&& v) { return Either{std::in_place_index<0>, std::forward<T>(v)}; }
@@ -29,8 +26,6 @@ public:
requires std::is_constructible_v<R, T>
static Either right(T&& v) { return Either{std::in_place_index<1>, std::forward<T>(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 <typename F>
[[nodiscard]] auto map(F&& fn) const & -> Either<L, std::invoke_result_t<F, const R&>>
{
@@ -58,7 +50,6 @@ public:
return Either<L, R2>::left(std::move(left_value()));
}
// map_left: transform Left, leave Right unchanged.
template <typename F>
[[nodiscard]] auto map_left(F&& fn) const & -> Either<std::invoke_result_t<F, const L&>, R>
{
@@ -67,7 +58,6 @@ public:
return Either<L2, R>::right(right_value());
}
// and_then: flat-map over Right.
template <typename F>
requires std::invocable<F, const R&>
[[nodiscard]] auto and_then(F&& fn) const & -> std::invoke_result_t<F, const R&>
@@ -77,7 +67,6 @@ public:
return Result::left(left_value());
}
// fold: collapse both sides into a single value.
template <typename FL, typename FR>
requires std::invocable<FL, const L&> && std::invocable<FR, const R&>
&& std::is_same_v<std::invoke_result_t<FL, const L&>,
@@ -89,7 +78,11 @@ public:
return std::invoke(on_right, right_value());
}
// ── comparison ────────────────────────────────────────────────────────────
[[nodiscard]] Either<R, L> swap() const
{
if (is_left()) return Either<R, L>::right(left_value());
return Either<R, L>::left(right_value());
}
[[nodiscard]] bool operator==(const Either&) const noexcept = default;
@@ -100,8 +93,6 @@ private:
Either(std::in_place_index_t<I> tag, T&& v) : var_{tag, std::forward<T>(v)} {}
};
// ── free helpers ──────────────────────────────────────────────────────────────
template <typename L, typename R>
[[nodiscard]] Either<L, R> make_left(L v) { return Either<L, R>::left(std::move(v)); }
@@ -1,99 +1,19 @@
#pragma once
#include <Void/Either/Either.hpp>
#include <functional>
#include <optional>
#include <stdexcept>
#include <type_traits>
#include <utility>
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 <typename T>
[[nodiscard]] constexpr T value_or_default(const std::optional<T>& opt) noexcept
{
return opt.value_or(T{});
}
// Applies fn to the value if present; returns the modified optional.
template <typename T, typename F>
[[nodiscard]] constexpr auto transform(std::optional<T> opt, F&& fn)
-> std::optional<std::invoke_result_t<F, T>>
{
if (!opt) return std::nullopt;
return std::invoke(std::forward<F>(fn), *std::move(opt));
}
// Monadic bind: fn must return std::optional<U>.
template <typename T, typename F>
[[nodiscard]] constexpr auto and_then(std::optional<T> opt, F&& fn)
{
if (!opt) return std::invoke_result_t<F, T>{};
return std::invoke(std::forward<F>(fn), *std::move(opt));
}
// Returns opt if predicate holds, else nullopt.
template <typename T, typename Pred>
[[nodiscard]] constexpr std::optional<T> filter(std::optional<T> opt, Pred&& pred)
{
if (opt && std::invoke(std::forward<Pred>(pred), *opt)) return opt;
return std::nullopt;
}
// Returns *opt or throws with the given message.
template <typename T>
[[nodiscard]] const T& expect(const std::optional<T>& opt, const char* msg = "optional is empty")
{
if (!opt) throw std::runtime_error{msg};
return *opt;
}
// Lifts a regular function T->U into optional<T>->optional<U>.
template <typename F>
[[nodiscard]] constexpr auto lift(F&& fn)
{
return [fn = std::forward<F>(fn)](auto opt) mutable
-> std::optional<std::invoke_result_t<F, decltype(*opt)>>
{
if (!opt) return std::nullopt;
return std::invoke(fn, *opt);
};
}
// zip: both must have values; returns optional<pair<T,U>>.
template <typename T, typename U>
[[nodiscard]] constexpr std::optional<std::pair<T, U>>
zip(const std::optional<T>& a, const std::optional<U>& b)
{
if (a && b) return std::pair<T, U>{*a, *b};
return std::nullopt;
}
// sequence: convert optional<optional<T>> to optional<T>.
template <typename T>
[[nodiscard]] constexpr std::optional<T> flatten(std::optional<std::optional<T>> opt)
{
if (!opt || !*opt) return std::nullopt;
return **opt;
}
// or_else: return opt if it has a value, else call fn().
template <typename T, typename F>
[[nodiscard]] constexpr std::optional<T> or_else(std::optional<T> opt, F&& fn)
{
if (opt) return opt;
return std::invoke(std::forward<F>(fn));
}
// ── Opt<T> — fluent wrapper ───────────────────────────────────────────────────
// ── Opt<T> ────────────────────────────────────────────────────────────────────
// 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 <typename T>
class Opt
@@ -106,12 +26,11 @@ public:
[[nodiscard]] static constexpr Opt none() { return Opt{std::optional<T>{}}; }
[[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 <typename F>
[[nodiscard]] constexpr auto map(F&& fn) const
@@ -144,6 +63,14 @@ public:
return std::invoke(std::forward<F>(fn));
}
// Convert to Either: Some(v) → Right(v), None → Left(err).
template <typename L>
[[nodiscard]] Either<L, T> ok_or(L err) const
{
if (inner_) return Either<L, T>::right(*inner_);
return Either<L, T>::left(std::move(err));
}
[[nodiscard]] constexpr std::optional<T> to_optional() const { return inner_; }
private:
@@ -162,4 +89,52 @@ template <typename T>
return Opt<T>::none();
}
} // namespace Void::Optional
// ── free optional utilities ───────────────────────────────────────────────────
// Operate on std::optional directly without the Opt<T> wrapper.
template <typename T, typename F>
[[nodiscard]] constexpr auto opt_transform(std::optional<T> opt, F&& fn)
-> std::optional<std::invoke_result_t<F, T>>
{
if (!opt) return std::nullopt;
return std::invoke(std::forward<F>(fn), *std::move(opt));
}
template <typename T, typename F>
[[nodiscard]] constexpr auto opt_and_then(std::optional<T> opt, F&& fn)
{
if (!opt) return std::invoke_result_t<F, T>{};
return std::invoke(std::forward<F>(fn), *std::move(opt));
}
template <typename T, typename Pred>
[[nodiscard]] constexpr std::optional<T> opt_filter(std::optional<T> opt, Pred&& pred)
{
if (opt && std::invoke(std::forward<Pred>(pred), *opt)) return opt;
return std::nullopt;
}
template <typename T>
[[nodiscard]] const T& opt_expect(const std::optional<T>& opt,
const char* msg = "optional is empty")
{
if (!opt) throw std::runtime_error{msg};
return *opt;
}
template <typename T, typename U>
[[nodiscard]] constexpr std::optional<std::pair<T, U>>
opt_zip(const std::optional<T>& a, const std::optional<U>& b)
{
if (a && b) return std::pair<T, U>{*a, *b};
return std::nullopt;
}
template <typename T>
[[nodiscard]] constexpr std::optional<T> opt_flatten(std::optional<std::optional<T>> opt)
{
if (!opt || !*opt) return std::nullopt;
return **opt;
}
} // namespace Void::Either
+59
View File
@@ -0,0 +1,59 @@
#pragma once
#include <tuple>
#include <type_traits>
#include <utility>
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 <typename F, typename... Collected>
struct Curried
{
F fn;
std::tuple<Collected...> args;
template <typename Arg>
constexpr auto operator()(Arg&& arg) &&
{
auto new_args = std::tuple_cat(std::move(args),
std::tuple<std::decay_t<Arg>>{std::forward<Arg>(arg)});
using NewCurried = Curried<F, Collected..., std::decay_t<Arg>>;
if constexpr (std::is_invocable_v<F, Collected..., std::decay_t<Arg>>) {
return std::apply(fn, std::move(new_args));
} else {
return NewCurried{std::move(fn), std::move(new_args)};
}
}
template <typename Arg>
constexpr auto operator()(Arg&& arg) const &
{
auto new_args = std::tuple_cat(args,
std::tuple<std::decay_t<Arg>>{std::forward<Arg>(arg)});
using NewCurried = Curried<F, Collected..., std::decay_t<Arg>>;
if constexpr (std::is_invocable_v<F, Collected..., std::decay_t<Arg>>) {
return std::apply(fn, std::move(new_args));
} else {
return NewCurried{std::move(fn), std::move(new_args)};
}
}
};
} // namespace Detail
template <typename F>
[[nodiscard]] constexpr auto curry(F&& fn)
{
return Detail::Curried<std::decay_t<F>>{std::forward<F>(fn), {}};
}
} // namespace Void::Pipeline
@@ -7,13 +7,33 @@
#include <unordered_map>
#include <utility>
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>([](int x){ return x * x; });
// sq(5); // computed once, cached forever
// sq(5); // returned from cache
namespace Detail
{
template <typename Fn, typename Arg, typename R>
struct MemoOne
{
Fn fn;
std::unordered_map<Arg, R> 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 <typename T>
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<int>(lambda) where lambda takes int.
template <typename Arg, typename F,
typename R = std::invoke_result_t<std::decay_t<F>, Arg>>
[[nodiscard]] auto memoize_fn(F&& fn)
{
return Detail::MemoOne<std::decay_t<F>, Arg, R>{std::forward<F>(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<std::decay_t<Args>...>;
using Map = std::unordered_map<Key, R, Detail::TupleHash<std::decay_t<Args>...>>;
// 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<R, Key, Map>();
Key key{std::forward<Args>(args)...};
const auto it = cache.find(key);
@@ -136,4 +164,4 @@ private:
std::unordered_map<K, V> map_;
};
} // namespace Void::Memo
} // namespace Void::Pipeline
+14 -15
View File
@@ -7,16 +7,12 @@
namespace Void::Pipeline
{
// ── pipe ──────────────────────────────────────────────────────────────────────
// ── Pipe<T> ───────────────────────────────────────────────────────────────────
// 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 <typename T>
class Pipe
@@ -52,7 +48,6 @@ private:
T value_;
};
// Entry point: wrap a value in a Pipe.
template <typename T>
[[nodiscard]] constexpr Pipe<std::decay_t<T>> pipe(T&& v)
{
@@ -60,7 +55,7 @@ template <typename T>
}
// ── 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 <typename T>
constexpr auto operator()(T&& x) const
{
@@ -93,20 +87,17 @@ template <typename F, typename G, typename... Rest>
}
// ── 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 <typename F, typename... Bound>
[[nodiscard]] constexpr auto partial(F&& f, Bound&&... bound)
{
return [f = std::forward<F>(f),
...bound = std::forward<Bound>(bound)](auto&&... rest) mutable {
return [f = std::forward<F>(f), ...bound = std::forward<Bound>(bound)](auto&&... rest) mutable {
return std::invoke(f, bound..., std::forward<decltype(rest)>(rest)...);
};
}
// ── flip ──────────────────────────────────────────────────────────────────────
// Swap the first two arguments of a binary callable.
template <typename F>
[[nodiscard]] constexpr auto flip(F&& f)
@@ -119,7 +110,7 @@ template <typename F>
};
}
// ── identity / constant ───────────────────────────────────────────────────────
// ── identity / constant / negate ─────────────────────────────────────────────
struct Identity {
template <typename T>
@@ -134,4 +125,12 @@ template <typename T>
return [v = std::forward<T>(v)](auto&&...) { return v; };
}
template <typename Pred>
[[nodiscard]] constexpr auto negate(Pred&& pred)
{
return [pred = std::forward<Pred>(pred)](auto&&... args) mutable {
return !std::invoke(pred, std::forward<decltype(args)>(args)...);
};
}
} // namespace Void::Pipeline
+32 -16
View File
@@ -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 <std::invocable F>
return ScopeFail<std::decay_t<F>>{std::forward<F>(f)};
}
// Aliases matching std::scope_{exit,success,failure} proposal naming.
template <std::invocable F>
[[nodiscard]] auto scope_exit(F&& f) { return on_exit(std::forward<F>(f)); }
template <std::invocable F>
[[nodiscard]] auto scope_success(F&& f) { return on_success(std::forward<F>(f)); }
template <std::invocable F>
[[nodiscard]] auto scope_failure(F&& f) { return on_fail(std::forward<F>(f)); }
} // namespace Void::Scope
-113
View File
@@ -1,113 +0,0 @@
#pragma once
#include <exception>
#include <type_traits>
#include <utility>
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 <typename F>
class ScopeGuard
{
public:
explicit ScopeGuard(F&& fn) : fn_{std::forward<F>(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 <typename F>
class ScopeSuccess
{
public:
explicit ScopeSuccess(F&& fn)
: fn_{std::forward<F>(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 <typename F>
class ScopeFailure
{
public:
explicit ScopeFailure(F&& fn)
: fn_{std::forward<F>(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 <typename F>
[[nodiscard]] auto scope_exit(F&& fn)
{
return ScopeGuard<std::decay_t<F>>{std::forward<F>(fn)};
}
template <typename F>
[[nodiscard]] auto scope_success(F&& fn)
{
return ScopeSuccess<std::decay_t<F>>{std::forward<F>(fn)};
}
template <typename F>
[[nodiscard]] auto scope_failure(F&& fn)
{
return ScopeFailure<std::decay_t<F>>{std::forward<F>(fn)};
}
} // namespace Void::ScopeGuard
-112
View File
@@ -1,112 +0,0 @@
#pragma once
#include <chrono>
#include <cstddef>
#include <vector>
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<Duration>(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<Duration>(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<Duration>(Clock::now() - start_);
return elapsed_;
}
// Elapsed in milliseconds as double.
[[nodiscard]] double elapsed_ms() const noexcept
{
return std::chrono::duration<double, std::milli>(elapsed()).count();
}
[[nodiscard]] bool is_running() const noexcept { return running_; }
[[nodiscard]] const std::vector<Duration>& 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<Duration> 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<Duration>(Clock::now() - start_);
}
ScopedTimer(const ScopedTimer&) = delete;
ScopedTimer& operator=(const ScopedTimer&) = delete;
private:
Duration& out_;
Clock::time_point start_;
};
} // namespace Void::StopWatch
+14
View File
@@ -89,6 +89,20 @@ namespace Void::Str
// ── split / join ──────────────────────────────────────────────────────────────
[[nodiscard]] inline std::vector<std::string_view>
split(std::string_view s, char delim)
{
std::vector<std::string_view> 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<std::string_view>
split(std::string_view s, std::string_view delim)
{
-207
View File
@@ -1,207 +0,0 @@
#pragma once
#include <algorithm>
#include <cctype>
#include <concepts>
#include <ranges>
#include <string>
#include <string_view>
#include <vector>
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<std::size_t>(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<std::size_t>(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<std::string_view>
split(std::string_view s, char delimiter)
{
std::vector<std::string_view> 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<std::string_view>
split(std::string_view s, std::string_view delimiter)
{
std::vector<std::string_view> 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 <std::ranges::input_range R>
requires std::convertible_to<std::ranges::range_value_t<R>, 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<char>(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<char>(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
+129 -14
View File
@@ -1,34 +1,90 @@
#pragma once
#include <chrono>
#include <cstddef>
#include <vector>
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<std::chrono::milliseconds>();
/// auto ms = sw.elapsed_as<std::chrono::milliseconds>();
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<Duration>(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<Duration>(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<Duration>(Clock::now() -
start_);
}
return elapsed_;
}
/// Elapsed time cast to a specific duration type.
@@ -38,17 +94,76 @@ class Stopwatch
return std::chrono::duration_cast<D>(elapsed());
}
/// Split: return elapsed and reset in one call.
/// Elapsed in milliseconds as double.
[[nodiscard]] double elapsed_ms() const noexcept
{
return std::chrono::duration<double, std::milli>(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<Duration>& 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<Duration> 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<Duration>(Clock::now() - start_);
}
ScopedTimer(const ScopedTimer&) = delete;
ScopedTimer& operator=(const ScopedTimer&) = delete;
private:
Duration& out_;
Clock::time_point start_;
};
} // namespace Void::Time
View File
Whitespace-only changes.
+8 -5
View File
@@ -32,8 +32,8 @@
#include <Void/Logging/Level.hpp>
#endif
#ifdef VOID_HAS_STRING
#include <Void/String/String.hpp>
#ifdef VOID_HAS_STR
#include <Void/Str/Str.hpp>
#endif
#include <algorithm>
@@ -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(
+1 -1
View File
@@ -1,3 +1,3 @@
void_add_module(Testing
OPTIONAL_DEPS Stacktrace Logging Concurrency Configuration String
OPTIONAL_DEPS Stacktrace Logging Concurrency Configuration Str
)
-144
View File
@@ -1,144 +0,0 @@
#include <Void/Channel/Channel.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
#include <thread>
#include <vector>
using namespace Void::Channel;
// ── non-blocking operations ───────────────────────────────────────────────────
Void::Testing::Test channel_try_send_recv()
{
Channel<int> 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<int> 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<int> 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<int> ch{4};
Void::Testing::expect(!ch.try_recv().has_value());
}
Void::Testing::Test channel_size_and_empty()
{
Channel<int> 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<int> ch{16};
Void::Testing::expect_eq(ch.capacity(), std::size_t{16});
}
// ── close semantics ───────────────────────────────────────────────────────────
Void::Testing::Test channel_send_after_close_returns_false()
{
Channel<int> ch{4};
ch.close();
Void::Testing::expect(!ch.try_send(1));
}
Void::Testing::Test channel_recv_drains_then_nullopt()
{
Channel<int> 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<int> 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<int> ch{16};
std::vector<int> 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<int>(received.size()), count);
for (int i = 0; i < count; ++i)
Void::Testing::expect_eq(received[i], i);
}
Void::Testing::Test channel_multiple_producers()
{
Channel<int> ch{64};
std::atomic<int> 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<std::string> 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"});
}
+58
View File
@@ -2,6 +2,8 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <string>
#include <thread>
#include <vector>
@@ -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<int> 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<int> 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<int> ch{64};
std::atomic<int> 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<std::string> 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"});
}
-66
View File
@@ -1,66 +0,0 @@
#include <Void/Curry/Curry.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
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);
}
+120 -25
View File
@@ -1,13 +1,16 @@
#include <Void/Either/Either.hpp>
#include <Void/Either/Opt.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <optional>
#include <string>
#include <utility>
using namespace Void::Either;
using E = Either<std::string, int>;
// ── 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<T> ────────────────────────────────────────────────────────────────────
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<int>();
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<std::string> {
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<int>().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<int>().ok_or(std::string{"missing"});
Void::Testing::expect(err.is_left());
}
// ── free optional utilities ───────────────────────────────────────────────────
Void::Testing::Test opt_transform_present()
{
const std::optional<int> 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<int> 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<int> 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<int> 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<int>{1}, std::optional<std::string>{"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<int>{1}, std::optional<int>{});
Void::Testing::expect(!r.has_value());
}
Void::Testing::Test opt_flatten_nested()
{
const std::optional<std::optional<int>> o{std::optional<int>{7}};
Void::Testing::expect_eq(*opt_flatten(o), 7);
Void::Testing::expect(!opt_flatten(std::optional<std::optional<int>>{std::optional<int>{}}).has_value());
}
-168
View File
@@ -1,168 +0,0 @@
#include <Void/Optional/Optional.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <optional>
#include <string>
#include <utility>
using namespace Void::Optional;
// ── free functions ────────────────────────────────────────────────────────────
Void::Testing::Test opt_transform_present()
{
const std::optional<int> 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<int> 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<int> o{4};
const auto r = and_then(o, [](int x) -> std::optional<std::string> {
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<int> o;
bool called = false;
const auto r = and_then(o, [&](int) -> std::optional<int> { called = true; return 1; });
Void::Testing::expect(!called);
Void::Testing::expect(!r.has_value());
}
Void::Testing::Test opt_filter_passes()
{
const std::optional<int> 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<int> 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<int> o{42};
Void::Testing::expect_eq(expect(o), 42);
}
Void::Testing::Test opt_expect_throws_on_empty()
{
const std::optional<int> 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<int> a{1};
const std::optional<std::string> 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<int> a{1};
const std::optional<int> b;
const auto r = zip(a, b);
Void::Testing::expect(!r.has_value());
}
Void::Testing::Test opt_flatten()
{
const std::optional<std::optional<int>> o{std::optional<int>{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<std::optional<int>> o{std::optional<int>{}};
Void::Testing::expect(!flatten(o).has_value());
}
Void::Testing::Test opt_or_else_calls_on_empty()
{
const std::optional<int> o;
const auto r = or_else(o, [] { return std::optional<int>{99}; });
Void::Testing::expect_eq(*r, 99);
}
Void::Testing::Test opt_or_else_skips_on_present()
{
const std::optional<int> o{5};
bool called = false;
const auto r = or_else(o, [&] { called = true; return std::optional<int>{99}; });
Void::Testing::expect(!called);
Void::Testing::expect_eq(*r, 5);
}
// ── Opt<T> 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<int>();
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<std::string> {
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<int>().value_or(99), 99);
}
@@ -1,11 +1,11 @@
#include <Void/Memo/Memo.hpp>
#include <Void/Pipeline/Memo.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
#include <tuple>
using namespace Void::Memo;
using namespace Void::Pipeline;
// ── Memoized ──────────────────────────────────────────────────────────────────
+77 -14
View File
@@ -1,3 +1,5 @@
#include <Void/Pipeline/Curry.hpp>
#include <Void/Pipeline/Memo.hpp>
#include <Void/Pipeline/Pipeline.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
@@ -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>([&](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>([](int x) { return x * x; });
Void::Testing::expect_eq(sq(4), 16);
Void::Testing::expect_eq(sq(7), 49);
}
+100 -17
View File
@@ -5,13 +5,15 @@
#include <stdexcept>
#include <string>
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);
}
-139
View File
@@ -1,139 +0,0 @@
#include <Void/ScopeGuard/ScopeGuard.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <stdexcept>
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);
}
-186
View File
@@ -1,186 +0,0 @@
#include <Void/String/String.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
#include <string_view>
#include <vector>
// ── 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<std::string_view> 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<std::string_view> parts{"only"};
Void::Testing::expect_eq(Void::String::join(parts, "-"),
std::string{"only"});
}
Void::Testing::Test join_empty_range_returns_empty()
{
const std::vector<std::string_view> 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});
}
@@ -1,30 +1,31 @@
#include <Void/StopWatch/StopWatch.hpp>
#include <Void/Time/Stopwatch.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <thread>
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();
+9 -9
View File
@@ -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<std::chrono::milliseconds>().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 ───────────────────────────────────────────────────────