Restructure into umbrella modules (~55 -> 16 targets)
Headers move, CMake targets merge, C++ namespaces stay unchanged: - Core: Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant - Functional: Pipeline, Either, Result, Retry - Containers: Ring, Pool, PriorityQueue, LRU, Trie, Graph, DisjointSet, Bitset, Interval - Math: +Matrix, Numeric, Random, Histogram - Text: Str, Format, Tokenizer, Diff, Encoding, Semver - Data: Json, Csv, Ini - Async: Coro, Concurrency, EventBus, Observable - Time: +Bench - Log: Log facade + Logging framework (facade now header-only, breaking the Stacktrace<->Log link cycle the merge would have created) - System: FileSystem + Process - Configuration: +Argparse - Unchanged: Stacktrace, Plugin, StateMachine, Testing, TestingMock, Detail Module system fixes: - OPTIONAL_DEPS resolution deferred to void_finalize_modules() so it no longer depends on the alphabetical discovery order of src/ subdirs (Testing -> Text would have been silently dropped). - Every header-only module now has a tracked module.cmake; previously the empty src/<Name> marker dirs were untracked, so a fresh clone would have silently skipped those modules. - VOID_HAS_LOGGING/CONCURRENCY/STR consumers renamed to LOG/ASYNC/TEXT. Tests move to tests/standalone/<Umbrella>/<Feature>.cpp (Result suite files prefixed: ResultBasic etc.). Test count verified identical (831) before and after. README/CLAUDE.md module tables updated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
da2e93c405
commit
28b94883fd
156 files changed
+278
-220
No files matched your search
@@ -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
|
||||
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
|
||||
#include <concepts>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
#if __has_include(<meta>) && defined(__cpp_consteval)
|
||||
#include <meta>
|
||||
#define VOID_RESULT_HAS_REFLECTION 1
|
||||
#endif
|
||||
|
||||
namespace Void::Result::Detail
|
||||
{
|
||||
/// Render a value for diagnostic / log output.
|
||||
///
|
||||
/// Resolution order:
|
||||
/// 1. If a `std::formatter<T>` exists, use `std::format("{}", v)`.
|
||||
/// 2. Otherwise, if `T` exposes a `.format()` method returning
|
||||
/// something convertible to `std::string`, call it.
|
||||
/// 3. Otherwise, if C++26 reflection is available, walk the
|
||||
/// non-static data members of `T` and render
|
||||
/// `Type{field1: value1, field2: value2}`.
|
||||
/// 4. Otherwise, return `"<unrepresentable>"`.
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value);
|
||||
|
||||
template <typename T>
|
||||
concept Formattable = std::formattable<T, char>;
|
||||
|
||||
template <typename T>
|
||||
concept HasFormatMethod = requires(const T& v) {
|
||||
{ v.format() } -> std::convertible_to<std::string>;
|
||||
};
|
||||
|
||||
#ifdef VOID_RESULT_HAS_REFLECTION
|
||||
template <typename T> [[nodiscard]] std::string reflect_struct(const T& obj)
|
||||
{
|
||||
std::string out;
|
||||
if constexpr (std::meta::has_identifier(^^T)) {
|
||||
out += std::meta::identifier_of(^^T);
|
||||
} else {
|
||||
out += "?";
|
||||
}
|
||||
out += '{';
|
||||
static constexpr auto members =
|
||||
std::define_static_array(std::meta::nonstatic_data_members_of(
|
||||
^^T, std::meta::access_context::unchecked()));
|
||||
bool first = true;
|
||||
template for (constexpr auto member : members)
|
||||
{
|
||||
if (!first) {
|
||||
out += ", ";
|
||||
}
|
||||
out += std::meta::identifier_of(member);
|
||||
out += ": ";
|
||||
out += repr(obj.[:member:]);
|
||||
first = false;
|
||||
}
|
||||
out += '}';
|
||||
return out;
|
||||
}
|
||||
#endif
|
||||
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value)
|
||||
{
|
||||
if constexpr (Formattable<T>) {
|
||||
return std::format("{}", value);
|
||||
} else if constexpr (HasFormatMethod<T>) {
|
||||
return std::string{value.format()};
|
||||
}
|
||||
#ifdef VOID_RESULT_HAS_REFLECTION
|
||||
else if constexpr (std::is_class_v<T> || std::is_union_v<T>) {
|
||||
return reflect_struct(value);
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
return "<unrepresentable>";
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Void::Result::Detail
|
||||
@@ -0,0 +1,102 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
|
||||
namespace Void::Either
|
||||
{
|
||||
|
||||
// ── Either<L, R> ──────────────────────────────────────────────────────────────
|
||||
// Discriminated union: Left<L> for error/secondary value, Right<R> for success.
|
||||
// Convention: Right is the "happy path".
|
||||
|
||||
template <typename L, typename R>
|
||||
class Either
|
||||
{
|
||||
static_assert(!std::is_same_v<L, R>, "Either<L,R>: L and R must be distinct types");
|
||||
|
||||
public:
|
||||
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)}; }
|
||||
|
||||
template <typename T>
|
||||
requires std::is_constructible_v<R, T>
|
||||
static Either right(T&& v) { return Either{std::in_place_index<1>, std::forward<T>(v)}; }
|
||||
|
||||
[[nodiscard]] bool is_left() const noexcept { return var_.index() == 0; }
|
||||
[[nodiscard]] bool is_right() const noexcept { return var_.index() == 1; }
|
||||
|
||||
[[nodiscard]] L& left_value() { return std::get<0>(var_); }
|
||||
[[nodiscard]] const L& left_value() const { return std::get<0>(var_); }
|
||||
[[nodiscard]] R& right_value() { return std::get<1>(var_); }
|
||||
[[nodiscard]] const R& right_value() const { return std::get<1>(var_); }
|
||||
|
||||
template <typename F>
|
||||
[[nodiscard]] auto map(F&& fn) const & -> Either<L, std::invoke_result_t<F, const R&>>
|
||||
{
|
||||
using R2 = std::invoke_result_t<F, const R&>;
|
||||
if (is_right()) return Either<L, R2>::right(std::invoke(fn, right_value()));
|
||||
return Either<L, R2>::left(left_value());
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
[[nodiscard]] auto map(F&& fn) && -> Either<L, std::invoke_result_t<F, R&&>>
|
||||
{
|
||||
using R2 = std::invoke_result_t<F, R&&>;
|
||||
if (is_right()) return Either<L, R2>::right(std::invoke(fn, std::move(right_value())));
|
||||
return Either<L, R2>::left(std::move(left_value()));
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
[[nodiscard]] auto map_left(F&& fn) const & -> Either<std::invoke_result_t<F, const L&>, R>
|
||||
{
|
||||
using L2 = std::invoke_result_t<F, const L&>;
|
||||
if (is_left()) return Either<L2, R>::left(std::invoke(fn, left_value()));
|
||||
return Either<L2, R>::right(right_value());
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
requires std::invocable<F, const R&>
|
||||
[[nodiscard]] auto and_then(F&& fn) const & -> std::invoke_result_t<F, const R&>
|
||||
{
|
||||
if (is_right()) return std::invoke(fn, right_value());
|
||||
using Result = std::invoke_result_t<F, const R&>;
|
||||
return Result::left(left_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&>,
|
||||
std::invoke_result_t<FR, const R&>>
|
||||
[[nodiscard]] auto fold(FL&& on_left, FR&& on_right) const
|
||||
-> std::invoke_result_t<FL, const L&>
|
||||
{
|
||||
if (is_left()) return std::invoke(on_left, left_value());
|
||||
return std::invoke(on_right, right_value());
|
||||
}
|
||||
|
||||
[[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;
|
||||
|
||||
private:
|
||||
std::variant<L, R> var_;
|
||||
|
||||
template <std::size_t I, typename T>
|
||||
Either(std::in_place_index_t<I> tag, T&& v) : var_{tag, std::forward<T>(v)} {}
|
||||
};
|
||||
|
||||
template <typename L, typename R>
|
||||
[[nodiscard]] Either<L, R> make_left(L v) { return Either<L, R>::left(std::move(v)); }
|
||||
|
||||
template <typename L, typename R>
|
||||
[[nodiscard]] Either<L, R> make_right(R v) { return Either<L, R>::right(std::move(v)); }
|
||||
|
||||
} // namespace Void::Either
|
||||
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Result
|
||||
{
|
||||
/// Default error type for Void::Result::Result<T, E>.
|
||||
///
|
||||
/// An Error carries a free-form `message` and an optional chained
|
||||
/// `cause`. New context layers can be added with `with_context()`,
|
||||
/// which returns a new Error whose `cause` is the previous error —
|
||||
/// useful for "loading config: parsing line 42: invalid number".
|
||||
///
|
||||
/// Errors are cheap to copy (the cause chain is shared via
|
||||
/// shared_ptr).
|
||||
class Error
|
||||
{
|
||||
public:
|
||||
|
||||
Error() = default;
|
||||
|
||||
explicit Error(std::string message) noexcept
|
||||
: m_message(std::move(message))
|
||||
{
|
||||
}
|
||||
|
||||
Error(std::string message, Error cause)
|
||||
: m_message(std::move(message)),
|
||||
m_cause(std::make_shared<Error>(std::move(cause)))
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::string& message() const noexcept
|
||||
{
|
||||
return m_message;
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::shared_ptr<const Error>&
|
||||
cause() const noexcept
|
||||
{
|
||||
return m_cause;
|
||||
}
|
||||
|
||||
/// Returns a new Error whose message is `ctx` and whose cause
|
||||
/// is *this.
|
||||
[[nodiscard]] Error with_context(std::string ctx) const&
|
||||
{
|
||||
return Error{std::move(ctx), *this};
|
||||
}
|
||||
|
||||
[[nodiscard]] Error with_context(std::string ctx) &&
|
||||
{
|
||||
return Error{std::move(ctx), std::move(*this)};
|
||||
}
|
||||
|
||||
/// Render the full cause chain as
|
||||
/// "outer\n caused by: middle\n caused by: inner"
|
||||
[[nodiscard]] std::string format() const
|
||||
{
|
||||
std::string out = m_message;
|
||||
const Error* cur = m_cause.get();
|
||||
while (cur != nullptr) {
|
||||
out += "\n caused by: ";
|
||||
out += cur->m_message;
|
||||
cur = cur->m_cause.get();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::string m_message;
|
||||
std::shared_ptr<const Error> m_cause;
|
||||
};
|
||||
|
||||
} // namespace Void::Result
|
||||
@@ -0,0 +1,167 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Pipeline
|
||||
{
|
||||
|
||||
// ── 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)
|
||||
{
|
||||
seed ^= std::hash<T>{}(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
|
||||
}
|
||||
|
||||
template <typename Tuple, std::size_t... Is>
|
||||
std::size_t hash_tuple_impl(const Tuple& t, std::index_sequence<Is...>)
|
||||
{
|
||||
std::size_t seed = 0;
|
||||
(hash_combine(seed, std::get<Is>(t)), ...);
|
||||
return seed;
|
||||
}
|
||||
|
||||
template <typename... Ts>
|
||||
struct TupleHash {
|
||||
std::size_t operator()(const std::tuple<Ts...>& t) const {
|
||||
return hash_tuple_impl(t, std::index_sequence_for<Ts...>{});
|
||||
}
|
||||
};
|
||||
} // 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(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 {
|
||||
// if (n < 2) return n;
|
||||
// return self(n-1) + self(n-2);
|
||||
// });
|
||||
|
||||
template <typename F>
|
||||
class Memoized
|
||||
{
|
||||
using Fn = std::decay_t<F>;
|
||||
|
||||
public:
|
||||
explicit Memoized(F&& fn) : fn_{std::forward<F>(fn)} {}
|
||||
|
||||
template <typename... Args>
|
||||
auto operator()(Args&&... args)
|
||||
-> std::invoke_result_t<Fn, Memoized&, Args...>
|
||||
{
|
||||
using R = std::invoke_result_t<Fn, Memoized&, Args...>;
|
||||
using Key = std::tuple<std::decay_t<Args>...>;
|
||||
using Map = std::unordered_map<Key, R, Detail::TupleHash<std::decay_t<Args>...>>;
|
||||
|
||||
// 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);
|
||||
if (it != cache.end()) return it->second;
|
||||
R result = std::apply([this](const auto&... a) -> R {
|
||||
return std::invoke(fn_, *this, a...);
|
||||
}, key);
|
||||
auto [ins, _] = cache.emplace(key, std::move(result));
|
||||
return ins->second;
|
||||
}
|
||||
|
||||
// Clear the cache for a specific argument type signature.
|
||||
template <typename... Args>
|
||||
void clear()
|
||||
{
|
||||
using R = std::invoke_result_t<Fn, Memoized&, Args...>;
|
||||
using Key = std::tuple<std::decay_t<Args>...>;
|
||||
using Map = std::unordered_map<Key, R, Detail::TupleHash<std::decay_t<Args>...>>;
|
||||
get_cache<R, Key, Map>().clear();
|
||||
}
|
||||
|
||||
private:
|
||||
Fn fn_;
|
||||
|
||||
template <typename R, typename Key, typename Map>
|
||||
Map& get_cache()
|
||||
{
|
||||
static Map cache;
|
||||
return cache;
|
||||
}
|
||||
};
|
||||
|
||||
// Factory function: deduce F automatically.
|
||||
template <typename F>
|
||||
[[nodiscard]] Memoized<F> memoize(F&& fn)
|
||||
{
|
||||
return Memoized<F>{std::forward<F>(fn)};
|
||||
}
|
||||
|
||||
// ── SimpleCache<K, V> ────────────────────────────────────────────────────────
|
||||
// Straightforward key→value cache with optional miss function.
|
||||
|
||||
template <typename K, typename V>
|
||||
class SimpleCache
|
||||
{
|
||||
public:
|
||||
// get_or_insert: compute value if not cached.
|
||||
template <typename F>
|
||||
[[nodiscard]] const V& get_or(const K& key, F&& compute)
|
||||
{
|
||||
const auto it = map_.find(key);
|
||||
if (it != map_.end()) return it->second;
|
||||
return map_.emplace(key, std::invoke(std::forward<F>(compute), key)).first->second;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<V> get(const K& key) const
|
||||
{
|
||||
const auto it = map_.find(key);
|
||||
if (it == map_.end()) return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
|
||||
void put(K key, V value) { map_.insert_or_assign(std::move(key), std::move(value)); }
|
||||
bool erase(const K& key) { return map_.erase(key) > 0; }
|
||||
void clear() { map_.clear(); }
|
||||
[[nodiscard]] std::size_t size() const noexcept { return map_.size(); }
|
||||
[[nodiscard]] bool empty() const noexcept { return map_.empty(); }
|
||||
|
||||
private:
|
||||
std::unordered_map<K, V> map_;
|
||||
};
|
||||
|
||||
} // namespace Void::Pipeline
|
||||
@@ -0,0 +1,140 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Either.hpp>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Either
|
||||
{
|
||||
|
||||
// ── 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
|
||||
{
|
||||
public:
|
||||
constexpr Opt() = default;
|
||||
explicit constexpr Opt(std::optional<T> o) : inner_{std::move(o)} {}
|
||||
explicit constexpr Opt(T v) : inner_{std::move(v)} {}
|
||||
|
||||
[[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)); }
|
||||
|
||||
template <typename F>
|
||||
[[nodiscard]] constexpr auto map(F&& fn) const
|
||||
-> Opt<std::invoke_result_t<F, const T&>>
|
||||
{
|
||||
using U = std::invoke_result_t<F, const T&>;
|
||||
if (!inner_) return Opt<U>{};
|
||||
return Opt<U>{std::invoke(std::forward<F>(fn), *inner_)};
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
[[nodiscard]] constexpr auto flat_map(F&& fn) const
|
||||
{
|
||||
using Res = std::invoke_result_t<F, const T&>;
|
||||
if (!inner_) return Res{};
|
||||
return std::invoke(std::forward<F>(fn), *inner_);
|
||||
}
|
||||
|
||||
template <typename Pred>
|
||||
[[nodiscard]] constexpr Opt filter(Pred&& pred) const
|
||||
{
|
||||
if (inner_ && std::invoke(std::forward<Pred>(pred), *inner_)) return *this;
|
||||
return none();
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
[[nodiscard]] constexpr Opt or_else(F&& fn) const
|
||||
{
|
||||
if (inner_) return *this;
|
||||
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:
|
||||
std::optional<T> inner_;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
[[nodiscard]] constexpr Opt<std::decay_t<T>> some(T&& v)
|
||||
{
|
||||
return Opt<std::decay_t<T>>::some(std::forward<T>(v));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
[[nodiscard]] constexpr Opt<T> none()
|
||||
{
|
||||
return Opt<T>::none();
|
||||
}
|
||||
|
||||
// ── 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,136 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Pipeline
|
||||
{
|
||||
|
||||
// ── 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; }; // → 11
|
||||
|
||||
template <typename T>
|
||||
class Pipe
|
||||
{
|
||||
public:
|
||||
explicit constexpr Pipe(T&& v) : value_{std::forward<T>(v)} {}
|
||||
|
||||
[[nodiscard]] constexpr T& get() noexcept { return value_; }
|
||||
[[nodiscard]] constexpr const T& get() const noexcept { return value_; }
|
||||
|
||||
constexpr operator T() const noexcept(std::is_nothrow_copy_constructible_v<T>)
|
||||
{
|
||||
return value_;
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
[[nodiscard]] constexpr auto operator|(F&& fn) &&
|
||||
-> Pipe<std::invoke_result_t<F, T>>
|
||||
{
|
||||
return Pipe<std::invoke_result_t<F, T>>{
|
||||
std::invoke(std::forward<F>(fn), std::move(value_))};
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
[[nodiscard]] constexpr auto operator|(F&& fn) const &
|
||||
-> Pipe<std::invoke_result_t<F, const T&>>
|
||||
{
|
||||
return Pipe<std::invoke_result_t<F, const T&>>{
|
||||
std::invoke(std::forward<F>(fn), value_)};
|
||||
}
|
||||
|
||||
private:
|
||||
T value_;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
[[nodiscard]] constexpr Pipe<std::decay_t<T>> pipe(T&& v)
|
||||
{
|
||||
return Pipe<std::decay_t<T>>{std::forward<T>(v)};
|
||||
}
|
||||
|
||||
// ── compose ───────────────────────────────────────────────────────────────────
|
||||
// Compose callables left-to-right: compose(f, g)(x) = g(f(x)).
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
template <typename F, typename G>
|
||||
struct Composed
|
||||
{
|
||||
F f;
|
||||
G g;
|
||||
template <typename T>
|
||||
constexpr auto operator()(T&& x) const
|
||||
{
|
||||
return std::invoke(g, std::invoke(f, std::forward<T>(x)));
|
||||
}
|
||||
};
|
||||
} // namespace Detail
|
||||
|
||||
template <typename F, typename G>
|
||||
[[nodiscard]] constexpr auto compose(F&& f, G&& g)
|
||||
{
|
||||
return Detail::Composed<std::decay_t<F>, std::decay_t<G>>{
|
||||
std::forward<F>(f), std::forward<G>(g)};
|
||||
}
|
||||
|
||||
template <typename F, typename G, typename... Rest>
|
||||
[[nodiscard]] constexpr auto compose(F&& f, G&& g, Rest&&... rest)
|
||||
{
|
||||
return compose(compose(std::forward<F>(f), std::forward<G>(g)),
|
||||
std::forward<Rest>(rest)...);
|
||||
}
|
||||
|
||||
// ── partial ───────────────────────────────────────────────────────────────────
|
||||
// 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 std::invoke(f, bound..., std::forward<decltype(rest)>(rest)...);
|
||||
};
|
||||
}
|
||||
|
||||
// ── flip ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
template <typename F>
|
||||
[[nodiscard]] constexpr auto flip(F&& f)
|
||||
{
|
||||
return [f = std::forward<F>(f)](auto&& a, auto&& b, auto&&... rest) mutable {
|
||||
return std::invoke(f,
|
||||
std::forward<decltype(b)>(b),
|
||||
std::forward<decltype(a)>(a),
|
||||
std::forward<decltype(rest)>(rest)...);
|
||||
};
|
||||
}
|
||||
|
||||
// ── identity / constant / negate ─────────────────────────────────────────────
|
||||
|
||||
struct Identity {
|
||||
template <typename T>
|
||||
constexpr T&& operator()(T&& x) const noexcept { return std::forward<T>(x); }
|
||||
};
|
||||
|
||||
inline constexpr Identity identity{};
|
||||
|
||||
template <typename T>
|
||||
[[nodiscard]] constexpr auto constant(T&& v)
|
||||
{
|
||||
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
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
|
||||
#include <concepts>
|
||||
#include <expected>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Result
|
||||
{
|
||||
/// `Result<T, E>` is a thin alias over `std::expected<T, E>`.
|
||||
///
|
||||
/// std::expected already provides every monadic operation we need
|
||||
/// (`and_then`, `or_else`, `transform` (= map), `transform_error`
|
||||
/// (= map_err), `value_or`). The wrappers in this module add
|
||||
/// context-chain support (see `with_context` below) and a default
|
||||
/// error type (`Void::Result::Error`).
|
||||
template <typename T, typename E = Error>
|
||||
using Result = std::expected<T, E>;
|
||||
|
||||
/// Tag wrapper for failure construction. Shorthand for
|
||||
/// `std::unexpected<E>`.
|
||||
template <typename E = Error> using Failure = std::unexpected<E>;
|
||||
|
||||
/// Convenience factory for a successful Result.
|
||||
template <typename T>
|
||||
[[nodiscard]] constexpr Result<std::remove_cvref_t<T>> ok(T&& value)
|
||||
{
|
||||
return Result<std::remove_cvref_t<T>>{std::forward<T>(value)};
|
||||
}
|
||||
|
||||
/// Convenience factory for a failed Result with the default Error type.
|
||||
[[nodiscard]] inline Failure<Error> fail(std::string message)
|
||||
{
|
||||
return Failure<Error>{Error{std::move(message)}};
|
||||
}
|
||||
|
||||
/// Convenience factory for a failed Result with an arbitrary E.
|
||||
/// Constrained so string-like types resolve to the `std::string`
|
||||
/// overload above (otherwise a literal `"..."` deduces E to a char
|
||||
/// array).
|
||||
template <typename E>
|
||||
requires(!std::convertible_to<std::remove_cvref_t<E>, std::string>)
|
||||
[[nodiscard]] constexpr Failure<std::remove_cvref_t<E>> fail(E&& error)
|
||||
{
|
||||
return Failure<std::remove_cvref_t<E>>{std::forward<E>(error)};
|
||||
}
|
||||
|
||||
/// Add a context layer to a failed Result. On success, the result is
|
||||
/// returned unchanged. Requires that `E` exposes a
|
||||
/// `with_context(std::string) const&` method (the bundled `Error`
|
||||
/// type does).
|
||||
template <typename T, typename E>
|
||||
[[nodiscard]] Result<T, E> with_context(Result<T, E> r, std::string ctx)
|
||||
{
|
||||
if (r) {
|
||||
return r;
|
||||
}
|
||||
return Failure<E>{std::move(r).error().with_context(std::move(ctx))};
|
||||
}
|
||||
|
||||
} // namespace Void::Result
|
||||
@@ -0,0 +1,126 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <expected>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
namespace Void::Retry
|
||||
{
|
||||
|
||||
// ── Backoff policies ──────────────────────────────────────────────────────────
|
||||
|
||||
struct NoDelay
|
||||
{
|
||||
[[nodiscard]] std::chrono::milliseconds delay(std::size_t /*attempt*/) const noexcept
|
||||
{
|
||||
return std::chrono::milliseconds{0};
|
||||
}
|
||||
};
|
||||
|
||||
struct ConstantDelay
|
||||
{
|
||||
std::chrono::milliseconds interval{100};
|
||||
|
||||
[[nodiscard]] std::chrono::milliseconds delay(std::size_t) const noexcept
|
||||
{
|
||||
return interval;
|
||||
}
|
||||
};
|
||||
|
||||
struct LinearBackoff
|
||||
{
|
||||
std::chrono::milliseconds base{100};
|
||||
std::chrono::milliseconds max{10'000};
|
||||
|
||||
[[nodiscard]] std::chrono::milliseconds delay(std::size_t attempt) const noexcept
|
||||
{
|
||||
const auto raw = base.count() * static_cast<long long>(attempt + 1);
|
||||
const auto capped = std::min(raw, static_cast<long long>(max.count()));
|
||||
return std::chrono::milliseconds{capped};
|
||||
}
|
||||
};
|
||||
|
||||
struct ExponentialBackoff
|
||||
{
|
||||
std::chrono::milliseconds base{100};
|
||||
std::chrono::milliseconds max{30'000};
|
||||
double multiplier{2.0};
|
||||
|
||||
[[nodiscard]] std::chrono::milliseconds delay(std::size_t attempt) const noexcept
|
||||
{
|
||||
double ms = static_cast<double>(base.count());
|
||||
for (std::size_t i = 0; i < attempt; ++i) ms *= multiplier;
|
||||
const auto clamped = std::min(ms, static_cast<double>(max.count()));
|
||||
return std::chrono::milliseconds{static_cast<long long>(clamped)};
|
||||
}
|
||||
};
|
||||
|
||||
// ── Policy ────────────────────────────────────────────────────────────────────
|
||||
|
||||
template <typename Backoff = ExponentialBackoff>
|
||||
struct Policy
|
||||
{
|
||||
std::size_t max_attempts{3};
|
||||
Backoff backoff{};
|
||||
|
||||
using BackoffType = Backoff;
|
||||
};
|
||||
|
||||
// ── retry — retries a callable up to max_attempts times ──────────────────────
|
||||
// The callable must return std::expected<T, E>. Retries on unexpected values.
|
||||
// Returns the last result (success or final error) after all attempts.
|
||||
|
||||
template <typename Policy, typename F>
|
||||
requires std::invocable<F>
|
||||
auto retry(const Policy& policy, F&& fn)
|
||||
{
|
||||
using Result = std::invoke_result_t<F>;
|
||||
Result last_result;
|
||||
for (std::size_t attempt = 0; attempt < policy.max_attempts; ++attempt) {
|
||||
last_result = fn();
|
||||
if (last_result.has_value()) return last_result;
|
||||
if (attempt + 1 < policy.max_attempts) {
|
||||
const auto wait = policy.backoff.delay(attempt);
|
||||
if (wait.count() > 0) std::this_thread::sleep_for(wait);
|
||||
}
|
||||
}
|
||||
return last_result;
|
||||
}
|
||||
|
||||
// ── retry_or_throw — throws on final failure ──────────────────────────────────
|
||||
|
||||
template <typename Policy, typename F>
|
||||
requires std::invocable<F>
|
||||
auto retry_or_throw(const Policy& policy, F&& fn)
|
||||
{
|
||||
auto result = retry(policy, std::forward<F>(fn));
|
||||
if (!result.has_value()) {
|
||||
throw std::runtime_error{"all retry attempts failed"};
|
||||
}
|
||||
return *result;
|
||||
}
|
||||
|
||||
// ── retry_while — retries while a predicate on the result holds ───────────────
|
||||
// Useful for retrying on specific error codes without expected<T,E>.
|
||||
|
||||
template <typename Policy, typename F, typename Pred>
|
||||
requires std::invocable<F> && std::predicate<Pred, std::invoke_result_t<F>>
|
||||
std::invoke_result_t<F> retry_while(const Policy& policy, F&& fn, Pred&& should_retry)
|
||||
{
|
||||
std::invoke_result_t<F> last{};
|
||||
for (std::size_t attempt = 0; attempt < policy.max_attempts; ++attempt) {
|
||||
last = fn();
|
||||
if (!should_retry(last)) return last;
|
||||
if (attempt + 1 < policy.max_attempts) {
|
||||
const auto wait = policy.backoff.delay(attempt);
|
||||
if (wait.count() > 0) std::this_thread::sleep_for(wait);
|
||||
}
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
} // namespace Void::Retry
|
||||
Reference in new issue
Block a user