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:
1 parent
58ff7b38a0
commit
da2e93c405
29 files changed
+752
-1593
No files matched your search
@@ -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
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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
@@ -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
|
||||
Reference in new issue
Block a user