Add 20+ new modules with tests: Pipeline, Matrix, Tokenizer, ScopeGuard, Bitset, Optional, Counted, Curry, TypeMap, Bench, DisjointSet, Histogram, StopWatch, and more

Also fixes Diff/Memo/PriorityQueue from previous session: LineDiff is now
an alias for Edit<string> so count_op/apply work on line diffs; Memoized
uses std::apply instead of type-based get to handle duplicate arg types.

874/877 tests pass (3 are platform-gated plugin tests).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 4.6 committed 2026-05-14 23:49:09 +03:00
1 parent cb4dd58500
commit 58ff7b38a0
65 files changed
+8987 -37

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
#pragma once
#include <expected>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Argparse
{
// ── Parser ────────────────────────────────────────────────────────────────────
// Fluent command-line argument parser.
//
// Supports:
// --flag, -f boolean flag (default false, set to true by presence)
// --key=value option with value (= or space separator)
// --key value option with value
// positional args collected in declaration order
// --help / -h auto-generated help text
class Parser
{
public:
explicit Parser(std::string program, std::string description = {});
// Add a boolean flag.
// long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name may be "")
Parser& flag(std::string_view long_name, std::string_view short_name,
std::string_view description, bool& out);
// Add an option that takes a value. If not provided, out stays nullopt.
Parser& option(std::string_view long_name, std::string_view short_name,
std::string_view description, std::optional<std::string>& out);
// Add an option with a default value. out is always set after parse().
Parser& option_default(std::string_view long_name, std::string_view short_name,
std::string_view description, std::string& out,
std::string_view default_value = "");
// Add a required positional argument.
Parser& positional(std::string_view name, std::string_view description, std::string& out);
// Parse argc/argv. Returns error message on failure.
[[nodiscard]] std::expected<void, std::string>
parse(int argc, const char* const* argv) const;
// Returns formatted help text.
[[nodiscard]] std::string help() const;
private:
struct FlagEntry { std::string lng, sht, desc; bool* out; };
struct OptionEntry{ std::string lng, sht, desc, def; std::optional<std::string>* out_opt; std::string* out_str; };
struct PosEntry { std::string name, desc; std::string* out; };
std::string program_, description_;
std::vector<FlagEntry> flags_;
std::vector<OptionEntry> options_;
std::vector<PosEntry> positionals_;
};
} // namespace Void::Argparse
+143
View File
@@ -0,0 +1,143 @@
#pragma once
#include <chrono>
#include <cstddef>
#include <functional>
#include <string>
#include <vector>
namespace Void::Bench
{
using Clock = std::chrono::steady_clock;
using Duration = std::chrono::nanoseconds;
// ── BenchResult ───────────────────────────────────────────────────────────────
struct BenchResult {
std::string name;
std::size_t iterations;
Duration total;
Duration min_ns;
Duration max_ns;
[[nodiscard]] double mean_ns() const noexcept
{
return iterations > 0
? static_cast<double>(total.count()) / static_cast<double>(iterations)
: 0.0;
}
[[nodiscard]] double ops_per_sec() const noexcept
{
const double total_s =
std::chrono::duration<double>(total).count();
return total_s > 0.0
? static_cast<double>(iterations) / total_s
: 0.0;
}
};
// ── run ───────────────────────────────────────────────────────────────────────
// Run fn for `iterations` iterations, discarding the first `warmup` runs.
// The body is not inlined / optimized away — use DoNotOptimize below.
[[nodiscard]] inline BenchResult
run(std::string name, std::size_t iterations, std::function<void()> fn,
std::size_t warmup = 3)
{
for (std::size_t i = 0; i < warmup; ++i) fn();
Duration total{0};
Duration mn = Duration::max();
Duration mx = Duration::min();
for (std::size_t i = 0; i < iterations; ++i) {
const auto t0 = Clock::now();
fn();
const auto dt = Clock::now() - t0;
const auto ns = std::chrono::duration_cast<Duration>(dt);
total += ns;
if (ns < mn) mn = ns;
if (ns > mx) mx = ns;
}
return {std::move(name), iterations, total, mn, mx};
}
// ── run_for ───────────────────────────────────────────────────────────────────
// Run fn as many times as possible within `budget`, return result.
template <typename Rep, typename Period>
[[nodiscard]] inline BenchResult
run_for(std::string name, std::chrono::duration<Rep, Period> budget,
std::function<void()> fn, std::size_t warmup = 3)
{
for (std::size_t i = 0; i < warmup; ++i) fn();
Duration total{0};
Duration mn = Duration::max();
Duration mx = Duration::min();
std::size_t count = 0;
const auto deadline = Clock::now() + budget;
while (Clock::now() < deadline) {
const auto t0 = Clock::now();
fn();
const auto ns = std::chrono::duration_cast<Duration>(Clock::now() - t0);
total += ns;
if (ns < mn) mn = ns;
if (ns > mx) mx = ns;
++count;
}
if (mn == Duration::max()) mn = Duration{0};
if (mx == Duration::min()) mx = Duration{0};
return {std::move(name), count, total, mn, mx};
}
// ── DoNotOptimize ─────────────────────────────────────────────────────────────
// Prevent the compiler from optimizing away a value.
template <typename T>
inline void do_not_optimize(T& val) noexcept
{
#if defined(__GNUC__) || defined(__clang__)
asm volatile("" : "+r,m"(val) : : "memory");
#else
volatile T* p = &val;
(void)*p;
#endif
}
template <typename T>
inline void do_not_optimize(const T& val) noexcept
{
#if defined(__GNUC__) || defined(__clang__)
asm volatile("" : : "r,m"(val) : "memory");
#else
volatile const T* p = &val;
(void)*p;
#endif
}
// ── Suite ─────────────────────────────────────────────────────────────────────
// Collect multiple benchmark results.
class Suite
{
public:
void add(BenchResult r) { results_.push_back(std::move(r)); }
[[nodiscard]] const std::vector<BenchResult>& results() const noexcept
{
return results_;
}
[[nodiscard]] std::size_t size() const noexcept { return results_.size(); }
private:
std::vector<BenchResult> results_;
};
} // namespace Void::Bench
+219
View File
@@ -0,0 +1,219 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <stdexcept>
#include <string>
namespace Void::Bitset
{
// ── Bitset<N> ─────────────────────────────────────────────────────────────────
// Fixed-size bitset stored as an array of uint64_t words.
// All operations are O(N/64).
template <std::size_t N>
class Bitset
{
static constexpr std::size_t Words = (N + 63) / 64;
public:
constexpr Bitset() noexcept { words_.fill(0); }
// Set bit at position (throws if out of range).
constexpr Bitset& set(std::size_t pos)
{
check(pos);
words_[pos / 64] |= mask(pos);
return *this;
}
// Clear bit at position.
constexpr Bitset& reset(std::size_t pos)
{
check(pos);
words_[pos / 64] &= ~mask(pos);
return *this;
}
// Flip bit at position.
constexpr Bitset& flip(std::size_t pos)
{
check(pos);
words_[pos / 64] ^= mask(pos);
return *this;
}
// Test bit at position.
[[nodiscard]] constexpr bool test(std::size_t pos) const
{
check(pos);
return (words_[pos / 64] & mask(pos)) != 0;
}
[[nodiscard]] constexpr bool operator[](std::size_t pos) const { return test(pos); }
// Set / clear / flip all bits.
constexpr Bitset& set_all() noexcept { for (auto& w : words_) w = ~uint64_t{0}; trim(); return *this; }
constexpr Bitset& reset_all() noexcept { words_.fill(0); return *this; }
constexpr Bitset& flip_all() noexcept { for (auto& w : words_) w = ~w; trim(); return *this; }
// Count of set bits.
[[nodiscard]] constexpr std::size_t count() const noexcept
{
std::size_t n = 0;
for (auto w : words_) n += popcount(w);
return n;
}
[[nodiscard]] constexpr bool none() const noexcept
{
for (auto w : words_) if (w) return false;
return true;
}
[[nodiscard]] constexpr bool any() const noexcept { return !none(); }
[[nodiscard]] constexpr bool all() const noexcept { return count() == N; }
static constexpr std::size_t size() noexcept { return N; }
// ── bitwise ops ───────────────────────────────────────────────────────────
[[nodiscard]] constexpr Bitset operator&(const Bitset& o) const noexcept
{
Bitset r;
for (std::size_t i = 0; i < Words; ++i) r.words_[i] = words_[i] & o.words_[i];
return r;
}
[[nodiscard]] constexpr Bitset operator|(const Bitset& o) const noexcept
{
Bitset r;
for (std::size_t i = 0; i < Words; ++i) r.words_[i] = words_[i] | o.words_[i];
return r;
}
[[nodiscard]] constexpr Bitset operator^(const Bitset& o) const noexcept
{
Bitset r;
for (std::size_t i = 0; i < Words; ++i) r.words_[i] = words_[i] ^ o.words_[i];
return r;
}
[[nodiscard]] constexpr Bitset operator~() const noexcept
{
Bitset r = *this;
r.flip_all();
return r;
}
constexpr Bitset& operator&=(const Bitset& o) noexcept
{
for (std::size_t i = 0; i < Words; ++i) words_[i] &= o.words_[i];
return *this;
}
constexpr Bitset& operator|=(const Bitset& o) noexcept
{
for (std::size_t i = 0; i < Words; ++i) words_[i] |= o.words_[i];
return *this;
}
constexpr Bitset& operator^=(const Bitset& o) noexcept
{
for (std::size_t i = 0; i < Words; ++i) words_[i] ^= o.words_[i];
return *this;
}
// ── shift ─────────────────────────────────────────────────────────────────
[[nodiscard]] constexpr Bitset operator<<(std::size_t shift) const noexcept
{
if (shift >= N) return Bitset{};
Bitset r;
const std::size_t word_shift = shift / 64;
const std::size_t bit_shift = shift % 64;
for (std::size_t i = Words; i-- > 0;) {
if (i >= word_shift)
r.words_[i] = words_[i - word_shift] << bit_shift;
if (bit_shift && i > word_shift)
r.words_[i] |= words_[i - word_shift - 1] >> (64 - bit_shift);
}
r.trim();
return r;
}
[[nodiscard]] constexpr Bitset operator>>(std::size_t shift) const noexcept
{
if (shift >= N) return Bitset{};
Bitset r;
const std::size_t word_shift = shift / 64;
const std::size_t bit_shift = shift % 64;
for (std::size_t i = 0; i < Words; ++i) {
if (i + word_shift < Words)
r.words_[i] = words_[i + word_shift] >> bit_shift;
if (bit_shift && i + word_shift + 1 < Words)
r.words_[i] |= words_[i + word_shift + 1] << (64 - bit_shift);
}
return r;
}
// ── comparison ────────────────────────────────────────────────────────────
[[nodiscard]] constexpr bool operator==(const Bitset& o) const noexcept
{
return words_ == o.words_;
}
[[nodiscard]] constexpr bool operator!=(const Bitset& o) const noexcept
{
return !(*this == o);
}
// ── string conversion ─────────────────────────────────────────────────────
[[nodiscard]] std::string to_string() const
{
std::string s(N, '0');
for (std::size_t i = 0; i < N; ++i)
if (test(N - 1 - i)) s[i] = '1';
return s;
}
// ── index of first set bit (-1 if none) ──────────────────────────────────
[[nodiscard]] constexpr std::size_t find_first() const noexcept
{
for (std::size_t w = 0; w < Words; ++w) {
if (words_[w] == 0) continue;
return w * 64 + ctz(words_[w]);
}
return N; // sentinel: no bit set
}
private:
std::array<std::uint64_t, Words> words_;
static constexpr std::uint64_t mask(std::size_t pos) noexcept
{
return std::uint64_t{1} << (pos % 64);
}
constexpr void check(std::size_t pos) const
{
if (pos >= N) throw std::out_of_range{"Bitset: position out of range"};
}
// Clear bits above N in the last word.
constexpr void trim() noexcept
{
if constexpr (N % 64 != 0)
words_[Words - 1] &= (std::uint64_t{1} << (N % 64)) - 1;
}
static constexpr std::size_t popcount(std::uint64_t w) noexcept
{
return static_cast<std::size_t>(__builtin_popcountll(w));
}
static constexpr std::size_t ctz(std::uint64_t w) noexcept
{
return static_cast<std::size_t>(__builtin_ctzll(w));
}
};
} // namespace Void::Bitset
+124
View File
@@ -0,0 +1,124 @@
#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
+176
View File
@@ -0,0 +1,176 @@
#pragma once
#include <coroutine>
#include <exception>
#include <iterator>
#include <optional>
#include <type_traits>
#include <utility>
namespace Void::Coro
{
// ── Generator<T> ──────────────────────────────────────────────────────────────
// Lazy pull-based sequence driven by co_yield. Supports range-for.
// The coroutine body is NOT resumed until the first iterator increment.
//
// Generator<int> iota(int start) {
// while (true) co_yield start++;
// }
// for (int v : iota(0) | take(5)) { ... }
template <typename T>
class Generator
{
public:
struct promise_type
{
T* current{nullptr};
std::exception_ptr exception;
Generator get_return_object()
{
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
template <std::convertible_to<T> U>
std::suspend_always yield_value(U&& v) noexcept(std::is_nothrow_constructible_v<T, U>)
{
current = std::addressof(value_);
value_ = std::forward<U>(v);
return {};
}
void return_void() noexcept {}
void unhandled_exception() { exception = std::current_exception(); }
private:
T value_{};
};
using handle_type = std::coroutine_handle<promise_type>;
// ── construction ──────────────────────────────────────────────────────────
explicit Generator(handle_type h) noexcept : handle_{h} {}
Generator(const Generator&) = delete;
Generator& operator=(const Generator&) = delete;
Generator(Generator&& o) noexcept : handle_{std::exchange(o.handle_, {})} {}
Generator& operator=(Generator&& o) noexcept
{
if (this != &o) {
if (handle_) handle_.destroy();
handle_ = std::exchange(o.handle_, {});
}
return *this;
}
~Generator() { if (handle_) handle_.destroy(); }
// ── range interface ───────────────────────────────────────────────────────
struct sentinel {};
struct iterator
{
using iterator_category = std::input_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
handle_type handle;
[[nodiscard]] bool operator==(sentinel) const noexcept { return handle.done(); }
iterator& operator++()
{
handle.resume();
if (handle.done() && handle.promise().exception)
std::rethrow_exception(handle.promise().exception);
return *this;
}
void operator++(int) { ++(*this); }
[[nodiscard]] T& operator*() const noexcept { return *handle.promise().current; }
[[nodiscard]] T* operator->() const noexcept { return handle.promise().current; }
};
[[nodiscard]] iterator begin()
{
handle_.resume(); // advance to the first yield
if (handle_.done() && handle_.promise().exception)
std::rethrow_exception(handle_.promise().exception);
return iterator{handle_};
}
[[nodiscard]] sentinel end() noexcept { return {}; }
// ── explicit pull interface ───────────────────────────────────────────────
[[nodiscard]] bool done() const noexcept { return handle_.done(); }
[[nodiscard]] bool valid() const noexcept { return handle_ && !handle_.done(); }
// Resume and return the next value, or nullopt when exhausted.
[[nodiscard]] std::optional<T> next()
{
if (!handle_ || handle_.done()) return std::nullopt;
handle_.resume();
if (handle_.done()) {
if (handle_.promise().exception)
std::rethrow_exception(handle_.promise().exception);
return std::nullopt;
}
return *handle_.promise().current;
}
private:
handle_type handle_;
};
// ── generator combinators ─────────────────────────────────────────────────────
// take(n) — yield at most n elements from g.
template <typename T>
Generator<T> take(Generator<T> g, std::size_t n)
{
std::size_t i = 0;
for (T& v : g) {
if (i++ >= n) break;
co_yield v;
}
}
// filter(g, pred) — yield only elements satisfying pred.
template <typename T, typename Pred>
requires std::predicate<Pred, const T&>
Generator<T> filter(Generator<T> g, Pred pred)
{
for (T& v : g)
if (pred(v)) co_yield v;
}
// map(g, fn) — transform each element.
template <typename T, typename F>
requires std::invocable<F, T&>
Generator<std::invoke_result_t<F, T&>> map(Generator<T> g, F fn)
{
for (T& v : g)
co_yield fn(v);
}
// from_range(begin, end) — wrap an existing iterator range as a generator.
template <typename Iter, typename Sentinel>
Generator<typename std::iterator_traits<Iter>::value_type>
from_range(Iter first, Sentinel last)
{
for (; first != last; ++first)
co_yield *first;
}
} // namespace Void::Coro
+195
View File
@@ -0,0 +1,195 @@
#pragma once
#include <coroutine>
#include <exception>
#include <optional>
#include <utility>
namespace Void::Coro
{
// ── Task<T> ───────────────────────────────────────────────────────────────────
// A lazy coroutine that produces a single value via co_return.
// The coroutine does NOT run until explicitly driven (run() or sync_wait()).
//
// Awaiting a Task<T> from inside another Task<T> is supported:
// Task<int> inner() { co_return 42; }
// Task<int> outer() { co_return co_await inner() + 1; }
//
// Task is NOT thread-safe and uses no scheduler. Everything runs on the
// caller's thread synchronously when sync_wait() is called.
template <typename T>
class Task
{
public:
struct promise_type
{
std::optional<T> result;
std::exception_ptr exception;
std::coroutine_handle<> continuation; // parent waiting on this task
Task get_return_object()
{
return Task{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
struct FinalAwaiter
{
bool await_ready() noexcept { return false; }
void await_resume() noexcept {}
std::coroutine_handle<> await_suspend(
std::coroutine_handle<promise_type> h) noexcept
{
// Resume parent if it was awaiting us; otherwise just stop.
auto cont = h.promise().continuation;
return cont ? cont : std::noop_coroutine();
}
};
FinalAwaiter final_suspend() noexcept { return {}; }
void return_value(T v) { result.emplace(std::move(v)); }
void unhandled_exception() { exception = std::current_exception(); }
};
using handle_type = std::coroutine_handle<promise_type>;
// ── construction ──────────────────────────────────────────────────────────
explicit Task(handle_type h) noexcept : handle_{h} {}
Task(const Task&) = delete;
Task& operator=(const Task&) = delete;
Task(Task&& o) noexcept : handle_{std::exchange(o.handle_, {})} {}
Task& operator=(Task&& o) noexcept
{
if (this != &o) {
if (handle_) handle_.destroy();
handle_ = std::exchange(o.handle_, {});
}
return *this;
}
~Task() { if (handle_) handle_.destroy(); }
[[nodiscard]] bool done() const noexcept { return !handle_ || handle_.done(); }
// ── co_await support (allows Task<T> to be awaited by another Task) ───────
[[nodiscard]] bool await_ready() const noexcept { return false; }
std::coroutine_handle<> await_suspend(std::coroutine_handle<> continuation) noexcept
{
handle_.promise().continuation = continuation;
return handle_; // resume this task's coroutine
}
T await_resume()
{
auto& p = handle_.promise();
if (p.exception) std::rethrow_exception(p.exception);
return std::move(*p.result);
}
// Synchronous execution — runs the coroutine to completion on the
// calling thread. Returns the result or rethrows any stored exception.
T run()
{
handle_.resume();
return await_resume();
}
private:
handle_type handle_;
};
// ── Task<void> ────────────────────────────────────────────────────────────────
template <>
class Task<void>
{
public:
struct promise_type
{
std::exception_ptr exception;
std::coroutine_handle<> continuation;
Task get_return_object()
{
return Task{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
struct FinalAwaiter
{
bool await_ready() noexcept { return false; }
void await_resume() noexcept {}
std::coroutine_handle<> await_suspend(
std::coroutine_handle<promise_type> h) noexcept
{
auto cont = h.promise().continuation;
return cont ? cont : std::noop_coroutine();
}
};
FinalAwaiter final_suspend() noexcept { return {}; }
void return_void() noexcept {}
void unhandled_exception() { exception = std::current_exception(); }
};
using handle_type = std::coroutine_handle<promise_type>;
explicit Task(handle_type h) noexcept : handle_{h} {}
Task(const Task&) = delete;
Task& operator=(const Task&) = delete;
Task(Task&& o) noexcept : handle_{std::exchange(o.handle_, {})} {}
Task& operator=(Task&& o) noexcept
{
if (this != &o) {
if (handle_) handle_.destroy();
handle_ = std::exchange(o.handle_, {});
}
return *this;
}
~Task() { if (handle_) handle_.destroy(); }
[[nodiscard]] bool done() const noexcept { return !handle_ || handle_.done(); }
[[nodiscard]] bool await_ready() const noexcept { return false; }
std::coroutine_handle<> await_suspend(std::coroutine_handle<> c) noexcept
{
handle_.promise().continuation = c;
return handle_;
}
void await_resume()
{
if (handle_.promise().exception)
std::rethrow_exception(handle_.promise().exception);
}
void run()
{
handle_.resume();
await_resume();
}
private:
handle_type handle_;
};
// ── sync_wait — drive a Task<T> to completion synchronously ──────────────────
template <typename T>
T sync_wait(Task<T> task) { return task.run(); }
inline void sync_wait(Task<void> task) { task.run(); }
} // namespace Void::Coro
+106
View File
@@ -0,0 +1,106 @@
#pragma once
#include <atomic>
#include <cstddef>
namespace Void::Counted
{
// ── InstanceCounter<Tag> ──────────────────────────────────────────────────────
// Mix-in that counts how many instances of a class exist.
// Use a unique Tag type per class to keep counters separate.
//
// struct MyClass : InstanceCounter<MyClass> { ... };
// std::size_t alive = MyClass::instance_count(); // thread-safe
template <typename Tag>
class InstanceCounter
{
public:
InstanceCounter() noexcept { count_.fetch_add(1, std::memory_order_relaxed); }
~InstanceCounter() noexcept { count_.fetch_sub(1, std::memory_order_relaxed); }
InstanceCounter(const InstanceCounter&) noexcept { count_.fetch_add(1, std::memory_order_relaxed); }
InstanceCounter(InstanceCounter&&) noexcept { count_.fetch_add(1, std::memory_order_relaxed); }
InstanceCounter& operator=(const InstanceCounter&) noexcept { return *this; }
InstanceCounter& operator=(InstanceCounter&&) noexcept { return *this; }
[[nodiscard]] static std::size_t instance_count() noexcept
{
return count_.load(std::memory_order_relaxed);
}
private:
static std::atomic<std::size_t> count_;
};
template <typename Tag>
std::atomic<std::size_t> InstanceCounter<Tag>::count_{0};
// ── AtomicCounter ─────────────────────────────────────────────────────────────
// Standalone thread-safe counter with increment/decrement/reset.
class AtomicCounter
{
public:
explicit AtomicCounter(std::size_t initial = 0) noexcept : value_{initial} {}
std::size_t increment(std::size_t by = 1) noexcept
{
return value_.fetch_add(by, std::memory_order_relaxed) + by;
}
std::size_t decrement(std::size_t by = 1) noexcept
{
return value_.fetch_sub(by, std::memory_order_relaxed) - by;
}
void reset(std::size_t v = 0) noexcept { value_.store(v, std::memory_order_relaxed); }
[[nodiscard]] std::size_t get() const noexcept
{
return value_.load(std::memory_order_relaxed);
}
[[nodiscard]] std::size_t operator++(int) noexcept
{
return value_.fetch_add(1, std::memory_order_relaxed);
}
[[nodiscard]] std::size_t operator--(int) noexcept
{
return value_.fetch_sub(1, std::memory_order_relaxed);
}
AtomicCounter& operator++() noexcept { increment(); return *this; }
AtomicCounter& operator--() noexcept { decrement(); return *this; }
private:
std::atomic<std::size_t> value_;
};
// ── SeqId ────────────────────────────────────────────────────────────────────
// Monotonically increasing sequence ID generator.
// Each SeqId<Tag> has its own counter, starting from 1.
template <typename Tag = void>
class SeqId
{
public:
SeqId() : id_{next_.fetch_add(1, std::memory_order_relaxed)} {}
[[nodiscard]] std::size_t id() const noexcept { return id_; }
[[nodiscard]] static std::size_t next_id() noexcept
{
return next_.load(std::memory_order_relaxed);
}
private:
static std::atomic<std::size_t> next_;
std::size_t id_;
};
template <typename Tag>
std::atomic<std::size_t> SeqId<Tag>::next_{1};
} // namespace Void::Counted
+88
View File
@@ -0,0 +1,88 @@
#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
+160
View File
@@ -0,0 +1,160 @@
#pragma once
#include <algorithm>
#include <cstddef>
#include <functional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Diff
{
// ── Edit operations ───────────────────────────────────────────────────────────
enum class Op { Equal, Insert, Delete };
template <typename T>
struct Edit {
Op op;
T value;
};
// ── Myers diff ────────────────────────────────────────────────────────────────
// Returns the shortest edit script (SES) to transform `a` into `b`.
// Uses Myers' O(ND) algorithm.
template <typename T, typename Eq = std::equal_to<T>>
[[nodiscard]] std::vector<Edit<T>>
diff(std::span<const T> a, std::span<const T> b, Eq eq = {})
{
const int n = static_cast<int>(a.size());
const int m = static_cast<int>(b.size());
const int max_d = n + m;
if (max_d == 0) return {};
// v[k + max_d] = furthest-reaching x in diagonal k
std::vector<int> v(2 * max_d + 1, -1);
// trace[d] = snapshot of v at step d (for backtracking)
std::vector<std::vector<int>> trace;
v[max_d + 1] = 0;
bool done = false;
int final_d = 0;
for (int d = 0; d <= max_d && !done; ++d) {
trace.push_back(v);
for (int k = -d; k <= d; k += 2) {
int x;
if (k == -d || (k != d && v[max_d + k - 1] < v[max_d + k + 1]))
x = v[max_d + k + 1];
else
x = v[max_d + k - 1] + 1;
int y = x - k;
while (x < n && y < m && eq(a[x], b[y])) { ++x; ++y; }
v[max_d + k] = x;
if (x == n && y == m) { final_d = d; done = true; break; }
}
}
// Backtrack to reconstruct the edit script
std::vector<Edit<T>> script;
int x = n, y = m;
for (int d = final_d; d > 0; --d) {
const auto& pv = trace[d];
const int k = x - y;
int prev_k;
if (k == -d || (k != d && pv[max_d + k - 1] < pv[max_d + k + 1]))
prev_k = k + 1;
else
prev_k = k - 1;
const int prev_x = pv[max_d + prev_k];
const int prev_y = prev_x - prev_k;
// snake (equal)
while (x > prev_x && y > prev_y) {
--x; --y;
script.push_back({Op::Equal, a[x]});
}
if (d > 0) {
if (x == prev_x) { --y; script.push_back({Op::Insert, b[y]}); }
else { --x; script.push_back({Op::Delete, a[x]}); }
}
x = prev_x; y = prev_y;
}
// Remaining snake at start
while (x > 0 && y > 0) { --x; --y; script.push_back({Op::Equal, a[x]}); }
std::reverse(script.begin(), script.end());
return script;
}
// Convenience overload for vectors
template <typename T, typename Eq = std::equal_to<T>>
[[nodiscard]] std::vector<Edit<T>>
diff(const std::vector<T>& a, const std::vector<T>& b, Eq eq = {})
{
return diff<T, Eq>(std::span<const T>{a}, std::span<const T>{b}, eq);
}
// ── string diff ───────────────────────────────────────────────────────────────
// Line-level diff on strings split by newline.
// LineDiff is Edit<string> — count_op and apply work on it directly.
using LineDiff = Edit<std::string>;
[[nodiscard]] inline std::vector<LineDiff>
line_diff(std::string_view a, std::string_view b)
{
auto split = [](std::string_view s) {
std::vector<std::string> lines;
std::size_t pos = 0;
while (pos <= s.size()) {
const auto nl = s.find('\n', pos);
lines.emplace_back(s.substr(pos, nl == std::string_view::npos ? nl : nl - pos));
if (nl == std::string_view::npos) break;
pos = nl + 1;
}
return lines;
};
return diff(split(a), split(b));
}
// ── helpers ───────────────────────────────────────────────────────────────────
// Count edits by type
template <typename T>
[[nodiscard]] std::size_t count_op(const std::vector<Edit<T>>& edits, Op op)
{
return static_cast<std::size_t>(std::count_if(edits.begin(), edits.end(),
[op](const Edit<T>& e) { return e.op == op; }));
}
// Reconstruct the "b" sequence from an edit script applied to "a"
template <typename T>
[[nodiscard]] std::vector<T> apply(const std::vector<Edit<T>>& edits)
{
std::vector<T> out;
for (const auto& e : edits)
if (e.op != Op::Delete) out.push_back(e.value);
return out;
}
// Format a unified-diff-style patch for string line diffs
[[nodiscard]] inline std::string format_patch(const std::vector<LineDiff>& edits)
{
std::string out;
for (const auto& e : edits) {
switch (e.op) {
case Op::Equal: out += ' '; break;
case Op::Insert: out += '+'; break;
case Op::Delete: out += '-'; break;
}
out += e.value + '\n';
}
return out;
}
} // namespace Void::Diff
+92
View File
@@ -0,0 +1,92 @@
#pragma once
#include <cstddef>
#include <numeric>
#include <stdexcept>
#include <vector>
namespace Void::DisjointSet
{
// ── DisjointSet ───────────────────────────────────────────────────────────────
// Union-Find with path compression and union by rank.
// Elements are integers in [0, n). O(α(n)) per operation (inverse Ackermann).
//
// DisjointSet ds{5};
// ds.unite(0, 1);
// ds.unite(1, 2);
// ds.connected(0, 2); // true
// ds.count(); // 3 components (0-1-2, 3, 4)
class DisjointSet
{
public:
explicit DisjointSet(std::size_t n)
: parent_(n), rank_(n, 0), component_count_{n}
{
std::iota(parent_.begin(), parent_.end(), std::size_t{0});
}
// Find root of element x (with path compression).
[[nodiscard]] std::size_t find(std::size_t x)
{
check(x);
if (parent_[x] != x)
parent_[x] = find(parent_[x]);
return parent_[x];
}
// Merge the components containing x and y.
// Returns true if they were in different components.
bool unite(std::size_t x, std::size_t y)
{
check(x); check(y);
const std::size_t rx = find(x);
const std::size_t ry = find(y);
if (rx == ry) return false;
if (rank_[rx] < rank_[ry]) {
parent_[rx] = ry;
} else if (rank_[rx] > rank_[ry]) {
parent_[ry] = rx;
} else {
parent_[ry] = rx;
++rank_[rx];
}
--component_count_;
return true;
}
[[nodiscard]] bool connected(std::size_t x, std::size_t y)
{
return find(x) == find(y);
}
// Number of disjoint components.
[[nodiscard]] std::size_t count() const noexcept { return component_count_; }
// Total number of elements.
[[nodiscard]] std::size_t size() const noexcept { return parent_.size(); }
// Component size of the component containing x.
[[nodiscard]] std::size_t component_size(std::size_t x)
{
const std::size_t root = find(x);
std::size_t n = 0;
for (std::size_t i = 0; i < parent_.size(); ++i)
if (find(i) == root) ++n;
return n;
}
private:
std::vector<std::size_t> parent_;
std::vector<std::size_t> rank_;
std::size_t component_count_;
void check(std::size_t x) const
{
if (x >= parent_.size())
throw std::out_of_range{"DisjointSet: index out of range"};
}
};
} // namespace Void::DisjointSet
+111
View File
@@ -0,0 +1,111 @@
#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". Use std::expected for simpler cases;
// Either is better when both sides are equally meaningful (e.g. sum types).
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:
// ── 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)}; }
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)}; }
// ── query ─────────────────────────────────────────────────────────────────
[[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_); }
// ── 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&>>
{
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()));
}
// 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>
{
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());
}
// 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&>
{
if (is_right()) return std::invoke(fn, right_value());
using Result = std::invoke_result_t<F, const R&>;
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&>,
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());
}
// ── comparison ────────────────────────────────────────────────────────────
[[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)} {}
};
// ── free helpers ──────────────────────────────────────────────────────────────
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
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <any>
#include <cstddef>
#include <functional>
#include <typeindex>
#include <unordered_map>
#include <vector>
namespace Void::EventBus
{
// ── EventBus ──────────────────────────────────────────────────────────────────
// Synchronous publish/subscribe bus keyed by event type.
// Handlers are invoked on the caller's thread inside publish().
// Not thread-safe; use external locking if shared across threads.
class EventBus
{
public:
using HandlerId = std::size_t;
// Subscribe to events of type Event. Returns a HandlerId for unsubscription.
template <typename Event>
HandlerId subscribe(std::function<void(const Event&)> handler)
{
const auto key = std::type_index{typeid(Event)};
const HandlerId id = next_id_++;
handlers_[key].push_back(Entry{id, [h = std::move(handler)](const std::any& ev) {
h(std::any_cast<const Event&>(ev));
}});
return id;
}
// Publish an event to all subscribers of its type.
template <typename Event>
void publish(const Event& event)
{
const auto key = std::type_index{typeid(Event)};
const auto it = handlers_.find(key);
if (it == handlers_.end()) return;
for (const auto& e : it->second) e.fn(event);
}
// Unsubscribe by id. O(n) per event type — acceptable for small handler counts.
void unsubscribe(HandlerId id)
{
for (auto& [key, list] : handlers_) {
const auto before = list.size();
std::erase_if(list, [id](const Entry& e) { return e.id == id; });
if (list.size() != before) return;
}
}
// Remove all handlers for a given event type.
template <typename Event>
void clear()
{
handlers_.erase(std::type_index{typeid(Event)});
}
void clear_all() { handlers_.clear(); }
template <typename Event>
[[nodiscard]] std::size_t subscriber_count() const
{
const auto it = handlers_.find(std::type_index{typeid(Event)});
return it == handlers_.end() ? 0 : it->second.size();
}
private:
struct Entry {
HandlerId id;
std::function<void(const std::any&)> fn;
};
std::unordered_map<std::type_index, std::vector<Entry>> handlers_;
HandlerId next_id_{1};
};
} // namespace Void::EventBus
+114
View File
@@ -0,0 +1,114 @@
#pragma once
#include <initializer_list>
#include <type_traits>
namespace Void::Flags
{
// ── Flags<E> ─────────────────────────────────────────────────────────────────
// Type-safe bitmask wrapper over a scoped enum class E.
// E's enumerators must be distinct single-bit values (1, 2, 4, 8, …).
template <typename E>
requires std::is_enum_v<E>
class Flags
{
public:
using underlying = std::underlying_type_t<E>;
constexpr Flags() noexcept = default;
constexpr Flags(E bit) noexcept : bits_{static_cast<underlying>(bit)} {}
constexpr explicit Flags(underlying raw) noexcept : bits_{raw} {}
constexpr Flags(std::initializer_list<E> list) noexcept
{
for (const E e : list) bits_ |= static_cast<underlying>(e);
}
// ── query ─────────────────────────────────────────────────────────────────
[[nodiscard]] constexpr bool test(E bit) const noexcept
{
return (bits_ & static_cast<underlying>(bit)) != 0;
}
[[nodiscard]] constexpr bool any() const noexcept { return bits_ != 0; }
[[nodiscard]] constexpr bool none() const noexcept { return bits_ == 0; }
[[nodiscard]] constexpr bool all(Flags mask) const noexcept
{
return (bits_ & mask.bits_) == mask.bits_;
}
[[nodiscard]] constexpr bool any_of(Flags mask) const noexcept
{
return (bits_ & mask.bits_) != 0;
}
[[nodiscard]] constexpr underlying raw() const noexcept { return bits_; }
// ── mutation ──────────────────────────────────────────────────────────────
constexpr Flags& set(E bit) noexcept
{
bits_ |= static_cast<underlying>(bit);
return *this;
}
constexpr Flags& unset(E bit) noexcept
{
bits_ &= ~static_cast<underlying>(bit);
return *this;
}
constexpr Flags& toggle(E bit) noexcept
{
bits_ ^= static_cast<underlying>(bit);
return *this;
}
constexpr void clear() noexcept { bits_ = 0; }
// ── operators ─────────────────────────────────────────────────────────────
[[nodiscard]] constexpr Flags operator|(Flags o) const noexcept { return Flags{static_cast<underlying>(bits_ | o.bits_)}; }
[[nodiscard]] constexpr Flags operator&(Flags o) const noexcept { return Flags{static_cast<underlying>(bits_ & o.bits_)}; }
[[nodiscard]] constexpr Flags operator^(Flags o) const noexcept { return Flags{static_cast<underlying>(bits_ ^ o.bits_)}; }
[[nodiscard]] constexpr Flags operator~() const noexcept { return Flags{static_cast<underlying>(~bits_)}; }
[[nodiscard]] constexpr Flags operator|(E bit) const noexcept { return *this | Flags{bit}; }
[[nodiscard]] constexpr Flags operator&(E bit) const noexcept { return *this & Flags{bit}; }
[[nodiscard]] constexpr Flags operator^(E bit) const noexcept { return *this ^ Flags{bit}; }
constexpr Flags& operator|=(Flags o) noexcept { bits_ |= o.bits_; return *this; }
constexpr Flags& operator&=(Flags o) noexcept { bits_ &= o.bits_; return *this; }
constexpr Flags& operator^=(Flags o) noexcept { bits_ ^= o.bits_; return *this; }
constexpr Flags& operator|=(E bit) noexcept { return set(bit); }
constexpr Flags& operator&=(E bit) noexcept { bits_ &= static_cast<underlying>(bit); return *this; }
constexpr Flags& operator^=(E bit) noexcept { return toggle(bit); }
[[nodiscard]] constexpr bool operator==(const Flags&) const noexcept = default;
[[nodiscard]] constexpr explicit operator bool() const noexcept { return any(); }
private:
underlying bits_{0};
};
// ── make_flags — convenience factory ─────────────────────────────────────────
template <typename E>
requires std::is_enum_v<E>
[[nodiscard]] constexpr Flags<E> make_flags(std::initializer_list<E> list) noexcept
{
return Flags<E>{list};
}
template <typename E>
requires std::is_enum_v<E>
[[nodiscard]] constexpr Flags<E> operator|(E a, E b) noexcept
{
return Flags<E>{a} | Flags<E>{b};
}
} // namespace Void::Flags
+160
View File
@@ -0,0 +1,160 @@
#pragma once
#include <algorithm>
#include <cstddef>
#include <optional>
#include <stdexcept>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::Histogram
{
// ── Histogram<K> ──────────────────────────────────────────────────────────────
// Frequency counter for discrete keys.
template <typename K>
class Histogram
{
public:
// Increment the count for key by n (default 1).
void add(const K& key, std::size_t n = 1)
{
counts_[key] += n;
total_ += n;
}
// Remove a key entirely.
bool erase(const K& key)
{
const auto it = counts_.find(key);
if (it == counts_.end()) return false;
total_ -= it->second;
counts_.erase(it);
return true;
}
// Get count for key (0 if not present).
[[nodiscard]] std::size_t count(const K& key) const
{
const auto it = counts_.find(key);
return it != counts_.end() ? it->second : 0;
}
// Frequency as a fraction of total (0 if total == 0).
[[nodiscard]] double frequency(const K& key) const
{
if (total_ == 0) return 0.0;
return static_cast<double>(count(key)) / static_cast<double>(total_);
}
// True if key has been observed.
[[nodiscard]] bool contains(const K& key) const { return counts_.count(key) > 0; }
// Most common key (nullopt if empty).
[[nodiscard]] std::optional<K> mode() const
{
if (counts_.empty()) return std::nullopt;
const auto it = std::max_element(counts_.begin(), counts_.end(),
[](const auto& a, const auto& b) { return a.second < b.second; });
return it->first;
}
// Least common key (nullopt if empty).
[[nodiscard]] std::optional<K> least_common() const
{
if (counts_.empty()) return std::nullopt;
const auto it = std::min_element(counts_.begin(), counts_.end(),
[](const auto& a, const auto& b) { return a.second < b.second; });
return it->first;
}
// All key-count pairs sorted by count descending.
[[nodiscard]] std::vector<std::pair<K, std::size_t>> top_k(std::size_t k) const
{
std::vector<std::pair<K, std::size_t>> v{counts_.begin(), counts_.end()};
const std::size_t n = std::min(k, v.size());
std::partial_sort(v.begin(), v.begin() + static_cast<std::ptrdiff_t>(n), v.end(),
[](const auto& a, const auto& b) { return a.second > b.second; });
v.resize(n);
return v;
}
// Total observations.
[[nodiscard]] std::size_t total() const noexcept { return total_; }
[[nodiscard]] std::size_t distinct() const noexcept { return counts_.size(); }
[[nodiscard]] bool empty() const noexcept { return counts_.empty(); }
void clear() noexcept { counts_.clear(); total_ = 0; }
// Merge another histogram into this one.
void merge(const Histogram& other)
{
for (const auto& [k, v] : other.counts_) { counts_[k] += v; }
total_ += other.total_;
}
[[nodiscard]] const std::unordered_map<K, std::size_t>& counts() const noexcept
{
return counts_;
}
private:
std::unordered_map<K, std::size_t> counts_;
std::size_t total_{0};
};
// ── FixedBinHistogram ─────────────────────────────────────────────────────────
// Numeric histogram with fixed-width equal-width bins over [min, max).
class FixedBinHistogram
{
public:
// n_bins bins covering [min_val, max_val).
FixedBinHistogram(double min_val, double max_val, std::size_t n_bins)
: min_{min_val}, max_{max_val}, bins_(n_bins, 0)
{
if (n_bins == 0) throw std::invalid_argument{"n_bins must be > 0"};
if (min_ >= max_) throw std::invalid_argument{"min must be < max"};
width_ = (max_ - min_) / static_cast<double>(n_bins);
}
// Record a value. Values outside [min, max) are clamped to edge bins.
void add(double v)
{
std::size_t idx;
if (v <= min_) {
idx = 0;
} else if (v >= max_) {
idx = bins_.size() - 1;
} else {
idx = static_cast<std::size_t>((v - min_) / width_);
if (idx >= bins_.size()) idx = bins_.size() - 1;
}
++bins_[idx];
++total_;
}
[[nodiscard]] std::size_t bin_count(std::size_t idx) const
{
if (idx >= bins_.size()) throw std::out_of_range{"bin index out of range"};
return bins_[idx];
}
[[nodiscard]] double bin_low(std::size_t idx) const noexcept { return min_ + width_ * static_cast<double>(idx); }
[[nodiscard]] double bin_high(std::size_t idx) const noexcept { return bin_low(idx) + width_; }
[[nodiscard]] std::size_t n_bins() const noexcept { return bins_.size(); }
[[nodiscard]] std::size_t total() const noexcept { return total_; }
[[nodiscard]] double width() const noexcept { return width_; }
void clear() noexcept { for (auto& b : bins_) b = 0; total_ = 0; }
private:
double min_, max_, width_;
std::vector<std::size_t> bins_;
std::size_t total_{0};
};
} // namespace Void::Histogram
+92
View File
@@ -0,0 +1,92 @@
#pragma once
#include <algorithm>
#include <concepts>
#include <stdexcept>
namespace Void::Interval
{
// ── Interval<T> ───────────────────────────────────────────────────────────────
// Half-open [lo, hi) interval. T must be totally ordered.
template <std::totally_ordered T>
struct Interval
{
T lo{};
T hi{};
// Construct [lo, hi). Throws if lo > hi.
constexpr Interval(T lo_, T hi_) : lo{std::move(lo_)}, hi{std::move(hi_)}
{
if (lo > hi) throw std::invalid_argument{"Interval: lo > hi"};
}
// ── query ─────────────────────────────────────────────────────────────────
[[nodiscard]] constexpr bool contains(const T& v) const noexcept
{
return v >= lo && v < hi;
}
[[nodiscard]] constexpr bool contains_closed(const T& v) const noexcept
{
return v >= lo && v <= hi;
}
[[nodiscard]] constexpr bool empty() const noexcept { return lo >= hi; }
[[nodiscard]] constexpr auto length() const { return hi - lo; }
[[nodiscard]] constexpr bool overlaps(const Interval& o) const noexcept
{
return lo < o.hi && o.lo < hi;
}
[[nodiscard]] constexpr bool adjacent(const Interval& o) const noexcept
{
return hi == o.lo || o.hi == lo;
}
// ── set operations ────────────────────────────────────────────────────────
[[nodiscard]] constexpr Interval hull(const Interval& o) const noexcept
{
return Interval{std::min(lo, o.lo), std::max(hi, o.hi)};
}
// Returns the intersection, or an empty [lo,lo) if disjoint.
[[nodiscard]] constexpr Interval intersection(const Interval& o) const noexcept
{
const T new_lo = std::max(lo, o.lo);
const T new_hi = std::min(hi, o.hi);
if (new_lo >= new_hi) return Interval{lo, lo};
return Interval{new_lo, new_hi};
}
[[nodiscard]] constexpr T clamp(const T& v) const noexcept
{
return std::clamp(v, lo, hi);
}
// ── comparison ────────────────────────────────────────────────────────────
[[nodiscard]] constexpr bool operator==(const Interval&) const noexcept = default;
};
// ── factory helpers ───────────────────────────────────────────────────────────
template <std::totally_ordered T>
[[nodiscard]] constexpr Interval<T> make_interval(T lo, T hi)
{
return Interval<T>{std::move(lo), std::move(hi)};
}
// Closed [lo, hi] interval as [lo, hi+1) — only safe for integer types.
template <std::integral T>
[[nodiscard]] constexpr Interval<T> closed(T lo, T hi)
{
return Interval<T>{lo, static_cast<T>(hi + 1)};
}
} // namespace Void::Interval
+444
View File
@@ -0,0 +1,444 @@
#pragma once
#include <charconv>
#include <cmath>
#include <cstdint>
#include <expected>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
namespace Void::Json
{
// ── Value ─────────────────────────────────────────────────────────────────────
class Value;
struct ParseError {
std::size_t line{1}, col{1};
std::string message;
};
class Value
{
public:
using Array_t = std::vector<Value>;
using Object_t = std::vector<std::pair<std::string, Value>>;
private:
using Data = std::variant<
std::monostate, // null
bool, // bool
double, // number
std::string, // string
std::unique_ptr<Array_t>, // array (boxed to avoid incomplete-type issues)
std::unique_ptr<Object_t> // object (same)
>;
Data data_{};
static Data clone(const Data& src)
{
return std::visit([](const auto& v) -> Data {
using T = std::decay_t<decltype(v)>;
if constexpr (std::is_same_v<T, std::unique_ptr<Array_t>>)
return std::make_unique<Array_t>(*v);
else if constexpr (std::is_same_v<T, std::unique_ptr<Object_t>>)
return std::make_unique<Object_t>(*v);
else
return v;
}, src);
}
public:
// ── construction ──────────────────────────────────────────────────────────
Value() noexcept = default;
Value(std::nullptr_t) noexcept {}
Value(bool b) noexcept : data_{b} {}
Value(double n) noexcept : data_{n} {}
Value(int n) noexcept : data_{static_cast<double>(n)} {}
Value(long long n) noexcept : data_{static_cast<double>(n)} {}
Value(std::string s) : data_{std::move(s)} {}
Value(std::string_view s) : data_{std::string{s}} {}
Value(const char* s) : data_{std::string{s}} {}
Value(Array_t a) : data_{std::make_unique<Array_t>(std::move(a))} {}
Value(Object_t o) : data_{std::make_unique<Object_t>(std::move(o))} {}
Value(const Value& o) : data_{clone(o.data_)} {}
Value& operator=(const Value& o) { if (this != &o) data_ = clone(o.data_); return *this; }
Value(Value&&) noexcept = default;
Value& operator=(Value&&) noexcept = default;
~Value() = default;
// ── type query ────────────────────────────────────────────────────────────
[[nodiscard]] bool is_null() const noexcept { return data_.index() == 0; }
[[nodiscard]] bool is_bool() const noexcept { return data_.index() == 1; }
[[nodiscard]] bool is_number() const noexcept { return data_.index() == 2; }
[[nodiscard]] bool is_string() const noexcept { return data_.index() == 3; }
[[nodiscard]] bool is_array() const noexcept { return data_.index() == 4; }
[[nodiscard]] bool is_object() const noexcept { return data_.index() == 5; }
// ── typed access (throws std::bad_variant_access on wrong type) ───────────
[[nodiscard]] bool as_bool() const { return std::get<bool>(data_); }
[[nodiscard]] double as_number() const { return std::get<double>(data_); }
[[nodiscard]] std::int64_t as_int() const { return static_cast<std::int64_t>(as_number()); }
[[nodiscard]] const std::string& as_string() const { return std::get<std::string>(data_); }
[[nodiscard]] const Array_t& as_array() const { return *std::get<std::unique_ptr<Array_t>>(data_); }
[[nodiscard]] const Object_t& as_object() const { return *std::get<std::unique_ptr<Object_t>>(data_); }
[[nodiscard]] Array_t& as_array() { return *std::get<std::unique_ptr<Array_t>>(data_); }
[[nodiscard]] Object_t& as_object() { return *std::get<std::unique_ptr<Object_t>>(data_); }
// ── optional access ───────────────────────────────────────────────────────
[[nodiscard]] std::optional<bool> get_bool() const noexcept { if (!is_bool()) return {}; return as_bool(); }
[[nodiscard]] std::optional<double> get_number() const noexcept { if (!is_number()) return {}; return as_number(); }
[[nodiscard]] std::optional<std::string_view> get_string() const noexcept { if (!is_string()) return {}; return as_string(); }
// ── subscript (array by index, object by key) ─────────────────────────────
[[nodiscard]] const Value& operator[](std::size_t i) const { return as_array().at(i); }
[[nodiscard]] Value& operator[](std::size_t i) { return as_array().at(i); }
[[nodiscard]] const Value* find(std::string_view key) const noexcept
{
if (!is_object()) return nullptr;
for (const auto& [k, v] : as_object())
if (k == key) return &v;
return nullptr;
}
[[nodiscard]] Value* find(std::string_view key) noexcept
{
if (!is_object()) return nullptr;
for (auto& [k, v] : as_object())
if (k == key) return &v;
return nullptr;
}
[[nodiscard]] const Value& operator[](std::string_view key) const
{
const auto* p = find(key);
if (!p) throw std::out_of_range{std::string{"key not found: "} + std::string{key}};
return *p;
}
[[nodiscard]] std::size_t size() const noexcept
{
if (is_array()) return as_array().size();
if (is_object()) return as_object().size();
if (is_string()) return as_string().size();
return 0;
}
[[nodiscard]] bool empty() const noexcept { return size() == 0; }
[[nodiscard]] bool operator==(const Value& o) const noexcept
{
if (data_.index() != o.data_.index()) return false;
if (is_array()) return as_array() == o.as_array();
if (is_object()) return as_object() == o.as_object();
// For monostate, bool, double, string — variant equality works
return std::visit([&](const auto& lhs) -> bool {
using T = std::decay_t<decltype(lhs)>;
if constexpr (std::is_same_v<T, std::unique_ptr<Array_t>> ||
std::is_same_v<T, std::unique_ptr<Object_t>>)
return false; // unreachable (handled above)
else
return lhs == std::get<T>(o.data_);
}, data_);
}
};
// ── static factories ──────────────────────────────────────────────────────────
[[nodiscard]] inline Value array(Value::Array_t a = {}) { return Value{std::move(a)}; }
[[nodiscard]] inline Value object(Value::Object_t o = {}) { return Value{std::move(o)}; }
// ── parse ─────────────────────────────────────────────────────────────────────
namespace Detail
{
struct Parser
{
std::string_view src;
std::size_t pos{0}, line{1}, col{1};
[[nodiscard]] char peek() const noexcept { return pos < src.size() ? src[pos] : '\0'; }
char advance() noexcept
{
const char c = src[pos++];
if (c == '\n') { ++line; col = 1; } else ++col;
return c;
}
bool at_end() const noexcept { return pos >= src.size(); }
void skip_ws() noexcept
{
while (!at_end() && (peek() == ' ' || peek() == '\t' || peek() == '\n' || peek() == '\r'))
advance();
}
ParseError err(std::string msg) const { return {line, col, std::move(msg)}; }
bool match(std::string_view lit) noexcept
{
if (pos + lit.size() > src.size()) return false;
if (src.substr(pos, lit.size()) != lit) return false;
for (std::size_t i = 0; i < lit.size(); ++i) advance();
return true;
}
std::expected<Value, ParseError> parse_value()
{
skip_ws();
if (at_end()) return std::unexpected{err("unexpected end of input")};
const char c = peek();
if (c == 'n') return parse_literal("null", Value{nullptr});
if (c == 't') return parse_literal("true", Value{true});
if (c == 'f') return parse_literal("false", Value{false});
if (c == '"') return parse_string();
if (c == '[') return parse_array();
if (c == '{') return parse_object();
if (c == '-' || (c >= '0' && c <= '9')) return parse_number();
return std::unexpected{err(std::string{"unexpected character '"} + c + "'")};
}
std::expected<Value, ParseError> parse_literal(std::string_view lit, Value v)
{
if (!match(lit))
return std::unexpected{err(std::string{"expected '"} + std::string{lit} + "'")};
return v;
}
std::expected<Value, ParseError> parse_number()
{
const std::size_t start = pos;
if (peek() == '-') advance();
if (peek() == '0') { advance(); }
else { while (peek() >= '1' && peek() <= '9') advance(); while (peek() >= '0' && peek() <= '9') advance(); }
bool is_float = false;
if (peek() == '.') { is_float = true; advance(); while (peek() >= '0' && peek() <= '9') advance(); }
if (peek() == 'e' || peek() == 'E') {
is_float = true; advance();
if (peek() == '+' || peek() == '-') advance();
while (peek() >= '0' && peek() <= '9') advance();
}
const std::string_view raw = src.substr(start, pos - start);
double val = 0.0;
const auto [ptr, ec] = std::from_chars(raw.data(), raw.data() + raw.size(), val);
if (ec != std::errc{})
return std::unexpected{err("invalid number: " + std::string{raw})};
return Value{val};
}
std::expected<std::string, ParseError> parse_string_raw()
{
if (peek() != '"') return std::unexpected{err("expected '\"'")};
advance(); // consume opening quote
std::string out;
while (!at_end() && peek() != '"') {
const char c = advance();
if (c != '\\') { out += c; continue; }
if (at_end()) return std::unexpected{err("unterminated escape")};
const char esc = advance();
switch (esc) {
case '"': out += '"'; break;
case '\\': out += '\\'; break;
case '/': out += '/'; break;
case 'b': out += '\b'; break;
case 'f': out += '\f'; break;
case 'n': out += '\n'; break;
case 'r': out += '\r'; break;
case 't': out += '\t'; break;
case 'u': {
if (pos + 4 > src.size()) return std::unexpected{err("incomplete \\uXXXX")};
const auto hex = src.substr(pos, 4);
unsigned cp = 0;
const auto [p, e] = std::from_chars(hex.data(), hex.data() + 4, cp, 16);
if (e != std::errc{} || p != hex.data() + 4)
return std::unexpected{err("invalid \\uXXXX escape")};
for (std::size_t i = 0; i < 4; ++i) advance();
// Encode as UTF-8
if (cp < 0x80) {
out += static_cast<char>(cp);
} else if (cp < 0x800) {
out += static_cast<char>(0xC0 | (cp >> 6));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else {
out += static_cast<char>(0xE0 | (cp >> 12));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(0x80 | (cp & 0x3F));
}
break;
}
default: return std::unexpected{err(std::string{"unknown escape '\\"} + esc + "'")};
}
}
if (at_end()) return std::unexpected{err("unterminated string")};
advance(); // consume closing quote
return out;
}
std::expected<Value, ParseError> parse_string()
{
auto r = parse_string_raw();
if (!r) return std::unexpected{r.error()};
return Value{std::move(*r)};
}
std::expected<Value, ParseError> parse_array()
{
advance(); // '['
Value::Array_t arr;
skip_ws();
if (peek() == ']') { advance(); return Value{std::move(arr)}; }
while (true) {
auto v = parse_value();
if (!v) return v;
arr.push_back(std::move(*v));
skip_ws();
if (peek() == ']') { advance(); break; }
if (peek() != ',') return std::unexpected{err("expected ',' or ']' in array")};
advance();
}
return Value{std::move(arr)};
}
std::expected<Value, ParseError> parse_object()
{
advance(); // '{'
Value::Object_t obj;
skip_ws();
if (peek() == '}') { advance(); return Value{std::move(obj)}; }
while (true) {
skip_ws();
auto key = parse_string_raw();
if (!key) return std::unexpected{key.error()};
skip_ws();
if (peek() != ':') return std::unexpected{err("expected ':' after object key")};
advance();
auto val = parse_value();
if (!val) return val;
obj.emplace_back(std::move(*key), std::move(*val));
skip_ws();
if (peek() == '}') { advance(); break; }
if (peek() != ',') return std::unexpected{err("expected ',' or '}' in object")};
advance();
}
return Value{std::move(obj)};
}
};
} // namespace Detail
[[nodiscard]] inline std::expected<Value, ParseError> parse(std::string_view json)
{
Detail::Parser p{json};
auto r = p.parse_value();
if (!r) return r;
p.skip_ws();
if (!p.at_end())
return std::unexpected{p.err("trailing characters after JSON value")};
return r;
}
// ── serialize ─────────────────────────────────────────────────────────────────
struct SerializeOptions {
bool pretty{false};
int indent_width{2};
};
namespace Detail
{
inline void escape_string(std::string& out, std::string_view s)
{
out += '"';
for (const unsigned char c : s) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
default:
if (c < 0x20) {
out += "\\u00";
const char hex[] = "0123456789abcdef";
out += hex[c >> 4];
out += hex[c & 0xF];
} else {
out += static_cast<char>(c);
}
}
}
out += '"';
}
inline void serialize_impl(std::string& out, const Value& v, const SerializeOptions& opts, int depth)
{
if (v.is_null()) { out += "null"; return; }
if (v.is_bool()) { out += v.as_bool() ? "true" : "false"; return; }
if (v.is_number()) {
const double n = v.as_number();
if (std::floor(n) == n && std::abs(n) < 1e15) {
out += std::to_string(static_cast<std::int64_t>(n));
} else {
char buf[32];
const auto [ptr, ec] = std::to_chars(buf, buf + sizeof(buf), n,
std::chars_format::general, 17);
if (ec == std::errc{}) out.append(buf, ptr);
}
return;
}
if (v.is_string()) { escape_string(out, v.as_string()); return; }
const std::string nl = opts.pretty ? "\n" : "";
const std::string sep = opts.pretty ? " " : "";
auto indent = [&](int d) {
if (opts.pretty) out.append(static_cast<std::size_t>(d * opts.indent_width), ' ');
};
if (v.is_array()) {
out += '[';
const auto& arr = v.as_array();
for (std::size_t i = 0; i < arr.size(); ++i) {
out += nl; indent(depth + 1);
serialize_impl(out, arr[i], opts, depth + 1);
if (i + 1 < arr.size()) out += ',';
}
if (!arr.empty()) { out += nl; indent(depth); }
out += ']';
return;
}
// object
out += '{';
const auto& obj = v.as_object();
for (std::size_t i = 0; i < obj.size(); ++i) {
out += nl; indent(depth + 1);
escape_string(out, obj[i].first);
out += ':'; out += sep;
serialize_impl(out, obj[i].second, opts, depth + 1);
if (i + 1 < obj.size()) out += ',';
}
if (!obj.empty()) { out += nl; indent(depth); }
out += '}';
}
} // namespace Detail
[[nodiscard]] inline std::string serialize(const Value& v, SerializeOptions opts = {})
{
std::string out;
Detail::serialize_impl(out, v, opts, 0);
return out;
}
} // namespace Void::Json
+113
View File
@@ -0,0 +1,113 @@
#pragma once
#include <functional>
#include <mutex>
#include <optional>
#include <utility>
namespace Void::Lazy
{
// ── Lazy<T> ───────────────────────────────────────────────────────────────────
// Lazily evaluates a factory callable on first access.
// Thread-safety: NOT thread-safe. Use LazySync<T> for multi-threaded contexts.
template <typename T>
class Lazy
{
public:
using factory_type = std::function<T()>;
explicit Lazy(factory_type factory) : factory_{std::move(factory)} {}
Lazy(const Lazy&) = delete;
Lazy& operator=(const Lazy&) = delete;
Lazy(Lazy&&) = default;
Lazy& operator=(Lazy&&) = default;
[[nodiscard]] T& get()
{
if (!value_) value_.emplace(factory_());
return *value_;
}
[[nodiscard]] const T& get() const
{
if (!value_) value_.emplace(factory_());
return *value_;
}
[[nodiscard]] T& operator*() { return get(); }
[[nodiscard]] const T& operator*() const { return get(); }
[[nodiscard]] T* operator->() { return &get(); }
[[nodiscard]] const T* operator->() const { return &get(); }
[[nodiscard]] bool evaluated() const noexcept { return value_.has_value(); }
void reset()
{
value_.reset();
}
private:
factory_type factory_;
mutable std::optional<T> value_;
};
// ── LazySync<T> ───────────────────────────────────────────────────────────────
// Thread-safe variant using std::call_once.
template <typename T>
class LazySync
{
public:
using factory_type = std::function<T()>;
explicit LazySync(factory_type factory) : factory_{std::move(factory)} {}
LazySync(const LazySync&) = delete;
LazySync& operator=(const LazySync&) = delete;
LazySync(LazySync&&) = delete;
LazySync& operator=(LazySync&&) = delete;
[[nodiscard]] T& get()
{
std::call_once(flag_, [&] { value_.emplace(factory_()); });
return *value_;
}
[[nodiscard]] const T& get() const
{
std::call_once(flag_, [&] { value_.emplace(factory_()); });
return *value_;
}
[[nodiscard]] T& operator*() { return get(); }
[[nodiscard]] const T& operator*() const { return get(); }
[[nodiscard]] T* operator->() { return &get(); }
[[nodiscard]] const T* operator->() const { return &get(); }
[[nodiscard]] bool evaluated() const noexcept { return value_.has_value(); }
private:
factory_type factory_;
mutable std::once_flag flag_;
mutable std::optional<T> value_;
};
// ── make_lazy — deduction helper ──────────────────────────────────────────────
template <typename F>
[[nodiscard]] auto make_lazy(F&& factory) -> Lazy<std::invoke_result_t<F>>
{
return Lazy<std::invoke_result_t<F>>{std::forward<F>(factory)};
}
template <typename F>
[[nodiscard]] auto make_lazy_sync(F&& factory) -> LazySync<std::invoke_result_t<F>>
{
return LazySync<std::invoke_result_t<F>>{std::forward<F>(factory)};
}
} // namespace Void::Lazy
+248
View File
@@ -0,0 +1,248 @@
#pragma once
#include <array>
#include <cstddef>
#include <numeric>
#include <optional>
#include <stdexcept>
namespace Void::Matrix
{
// ── Matrix<T, Rows, Cols> ─────────────────────────────────────────────────────
// Compile-time-sized matrix stored in row-major order.
template <typename T, std::size_t Rows, std::size_t Cols>
class Matrix
{
static_assert(Rows > 0 && Cols > 0, "Matrix dimensions must be positive");
public:
using value_type = T;
static constexpr std::size_t rows = Rows;
static constexpr std::size_t cols = Cols;
constexpr Matrix() { data_.fill(T{}); }
explicit constexpr Matrix(T fill_value) { data_.fill(fill_value); }
// Row-major initializer: Matrix<int,2,2>{{1,2,3,4}}
constexpr Matrix(std::array<T, Rows * Cols> d) : data_{d} {}
[[nodiscard]] constexpr T& at(std::size_t r, std::size_t c)
{
if (r >= Rows || c >= Cols) throw std::out_of_range{"Matrix::at"};
return data_[r * Cols + c];
}
[[nodiscard]] constexpr const T& at(std::size_t r, std::size_t c) const
{
if (r >= Rows || c >= Cols) throw std::out_of_range{"Matrix::at"};
return data_[r * Cols + c];
}
[[nodiscard]] constexpr T& operator()(std::size_t r, std::size_t c) noexcept
{
return data_[r * Cols + c];
}
[[nodiscard]] constexpr const T& operator()(std::size_t r, std::size_t c) const noexcept
{
return data_[r * Cols + c];
}
// ── arithmetic ────────────────────────────────────────────────────────────
[[nodiscard]] constexpr Matrix operator+(const Matrix& o) const noexcept
{
Matrix result;
for (std::size_t i = 0; i < Rows * Cols; ++i)
result.data_[i] = data_[i] + o.data_[i];
return result;
}
[[nodiscard]] constexpr Matrix operator-(const Matrix& o) const noexcept
{
Matrix result;
for (std::size_t i = 0; i < Rows * Cols; ++i)
result.data_[i] = data_[i] - o.data_[i];
return result;
}
[[nodiscard]] constexpr Matrix operator*(T scalar) const noexcept
{
Matrix result;
for (std::size_t i = 0; i < Rows * Cols; ++i)
result.data_[i] = data_[i] * scalar;
return result;
}
[[nodiscard]] constexpr Matrix operator-() const noexcept
{
Matrix result;
for (std::size_t i = 0; i < Rows * Cols; ++i)
result.data_[i] = -data_[i];
return result;
}
constexpr Matrix& operator+=(const Matrix& o) noexcept
{
for (std::size_t i = 0; i < Rows * Cols; ++i) data_[i] += o.data_[i];
return *this;
}
constexpr Matrix& operator-=(const Matrix& o) noexcept
{
for (std::size_t i = 0; i < Rows * Cols; ++i) data_[i] -= o.data_[i];
return *this;
}
constexpr Matrix& operator*=(T scalar) noexcept
{
for (std::size_t i = 0; i < Rows * Cols; ++i) data_[i] *= scalar;
return *this;
}
// ── matrix multiplication ─────────────────────────────────────────────────
template <std::size_t K>
[[nodiscard]] constexpr Matrix<T, Rows, K>
operator*(const Matrix<T, Cols, K>& rhs) const noexcept
{
Matrix<T, Rows, K> result;
for (std::size_t r = 0; r < Rows; ++r)
for (std::size_t k = 0; k < Cols; ++k)
for (std::size_t c = 0; c < K; ++c)
result(r, c) += (*this)(r, k) * rhs(k, c);
return result;
}
// ── transpose ─────────────────────────────────────────────────────────────
[[nodiscard]] constexpr Matrix<T, Cols, Rows> transposed() const noexcept
{
Matrix<T, Cols, Rows> result;
for (std::size_t r = 0; r < Rows; ++r)
for (std::size_t c = 0; c < Cols; ++c)
result(c, r) = (*this)(r, c);
return result;
}
// ── comparison ────────────────────────────────────────────────────────────
[[nodiscard]] constexpr bool operator==(const Matrix& o) const noexcept
{
return data_ == o.data_;
}
[[nodiscard]] constexpr bool operator!=(const Matrix& o) const noexcept
{
return !(*this == o);
}
// ── aggregates ────────────────────────────────────────────────────────────
[[nodiscard]] constexpr T sum() const noexcept
{
return std::accumulate(data_.begin(), data_.end(), T{});
}
[[nodiscard]] constexpr T trace() const noexcept
requires (Rows == Cols)
{
T t{};
for (std::size_t i = 0; i < Rows; ++i) t += (*this)(i, i);
return t;
}
[[nodiscard]] constexpr T frobenius_sq() const noexcept
{
T s{};
for (const auto& v : data_) s += v * v;
return s;
}
// ── factory ───────────────────────────────────────────────────────────────
[[nodiscard]] static constexpr Matrix identity() noexcept
requires (Rows == Cols)
{
Matrix m;
for (std::size_t i = 0; i < Rows; ++i) m(i, i) = T{1};
return m;
}
[[nodiscard]] static constexpr Matrix zeros() noexcept { return Matrix{}; }
[[nodiscard]] static constexpr Matrix ones() noexcept { return Matrix{T{1}}; }
// ── element access helpers ────────────────────────────────────────────────
[[nodiscard]] constexpr const std::array<T, Rows * Cols>& flat() const noexcept
{
return data_;
}
private:
std::array<T, Rows * Cols> data_;
};
// Scalar * Matrix
template <typename T, std::size_t R, std::size_t C>
[[nodiscard]] constexpr Matrix<T, R, C> operator*(T scalar, const Matrix<T, R, C>& m) noexcept
{
return m * scalar;
}
// ── Type aliases ──────────────────────────────────────────────────────────────
template <typename T> using Mat2 = Matrix<T, 2, 2>;
template <typename T> using Mat3 = Matrix<T, 3, 3>;
template <typename T> using Mat4 = Matrix<T, 4, 4>;
template <typename T> using Vec2 = Matrix<T, 2, 1>;
template <typename T> using Vec3 = Matrix<T, 3, 1>;
template <typename T> using Vec4 = Matrix<T, 4, 1>;
using Mat2f = Mat2<float>;
using Mat3f = Mat3<float>;
using Mat4f = Mat4<float>;
using Mat2d = Mat2<double>;
using Mat3d = Mat3<double>;
using Mat4d = Mat4<double>;
// ── dot product for column vectors ───────────────────────────────────────────
template <typename T, std::size_t N>
[[nodiscard]] constexpr T dot(const Matrix<T, N, 1>& a, const Matrix<T, N, 1>& b) noexcept
{
T s{};
for (std::size_t i = 0; i < N; ++i) s += a(i, 0) * b(i, 0);
return s;
}
// ── 2×2 determinant ───────────────────────────────────────────────────────────
template <typename T>
[[nodiscard]] constexpr T det(const Mat2<T>& m) noexcept
{
return m(0, 0) * m(1, 1) - m(0, 1) * m(1, 0);
}
// ── 2×2 inverse ───────────────────────────────────────────────────────────────
template <typename T>
[[nodiscard]] constexpr std::optional<Mat2<T>> inverse(const Mat2<T>& m) noexcept
{
const T d = det(m);
if (d == T{}) return std::nullopt;
return Mat2<T>{{m(1, 1) / d, -m(0, 1) / d,
-m(1, 0) / d, m(0, 0) / d}};
}
// ── 3×3 determinant ───────────────────────────────────────────────────────────
template <typename T>
[[nodiscard]] constexpr T det(const Mat3<T>& m) noexcept
{
return m(0,0) * (m(1,1)*m(2,2) - m(1,2)*m(2,1))
- m(0,1) * (m(1,0)*m(2,2) - m(1,2)*m(2,0))
+ m(0,2) * (m(1,0)*m(2,1) - m(1,1)*m(2,0));
}
} // namespace Void::Matrix
+139
View File
@@ -0,0 +1,139 @@
#pragma once
#include <functional>
#include <optional>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <utility>
namespace Void::Memo
{
// ── tuple_hash ────────────────────────────────────────────────────────────────
namespace Detail
{
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
// ── memoize ───────────────────────────────────────────────────────────────────
// Wraps a callable F(Args...) -> R and caches results by argument tuple.
// 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>...>>;
// 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.
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::Memo
+165
View File
@@ -0,0 +1,165 @@
#pragma once
#include <functional>
#include <optional>
#include <stdexcept>
#include <type_traits>
#include <utility>
namespace Void::Optional
{
// ── 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 ───────────────────────────────────────────────────
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));
}
[[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();
}
} // namespace Void::Optional
+137
View File
@@ -0,0 +1,137 @@
#pragma once
#include <functional>
#include <type_traits>
#include <utility>
namespace Void::Pipeline
{
// ── pipe ──────────────────────────────────────────────────────────────────────
// Wraps a value and lets you chain single-argument callables with operator|.
//
// int result = pipe(5)
// | [](int x) { return x * 2; }
// | [](int x) { return x + 1; }
// | [](int x) { return x; }; // → 11
//
// The terminal | extracts the value when chained to a non-returning call,
// or just forwards the result type each step.
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_;
};
// Entry point: wrap a value in a Pipe.
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 two or more unary 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 to a callable, returning a new callable.
// 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 ──────────────────────────────────────────────────────────────────────
// Swap the first two arguments of a binary callable.
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 ───────────────────────────────────────────────────────
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; };
}
} // namespace Void::Pipeline
+73
View File
@@ -0,0 +1,73 @@
#pragma once
#include <Void/Plugin/Plugin.hpp>
#include <expected>
#include <filesystem>
#include <string_view>
namespace Void::Plugin
{
enum class LoadError {
FileNotFound,
DlopenFailed,
SymbolMissing,
AbiMismatch,
CreateFailed,
NotSupported, // platform does not support dlopen
};
[[nodiscard]] std::string_view to_string(LoadError e) noexcept;
// ── PluginLoader ──────────────────────────────────────────────────────────────
// Owns one plugin instance loaded from a shared library.
//
// Hot-reload protocol:
// 1. The new .so (at the same canonical path) is copied to a temp file so
// dlopen gets a fresh inode even if the path was already cached.
// 2. New instance is created and optional transfer_state() called (both
// old and new instances are alive simultaneously at this point).
// 3. Old instance is destroyed and old handle is closed.
//
// Thread safety: not thread-safe. Protect with external locking if needed.
class PluginLoader {
public:
[[nodiscard]] static std::expected<PluginLoader, LoadError>
load(std::filesystem::path path);
~PluginLoader();
PluginLoader(PluginLoader&&) noexcept;
PluginLoader& operator=(PluginLoader&&) noexcept;
PluginLoader(const PluginLoader&) = delete;
PluginLoader& operator=(const PluginLoader&) = delete;
[[nodiscard]] IPlugin* plugin() noexcept { return plugin_; }
[[nodiscard]] const IPlugin* plugin() const noexcept { return plugin_; }
[[nodiscard]] const PluginInfo& info() const noexcept { return info_; }
[[nodiscard]] bool loaded() const noexcept { return handle_ != nullptr; }
IPlugin* operator->() noexcept { return plugin_; }
// Hot-reload: copies current .so to a temp file (fresh inode), loads it,
// transfers state, then destroys old instance and swaps handles.
[[nodiscard]] std::expected<void, LoadError> reload();
private:
PluginLoader() = default;
void* handle_ {};
IPlugin* plugin_ {};
destroy_fn destroy_ {};
transfer_fn transfer_{};
PluginInfo info_ {};
std::filesystem::path path_;
[[nodiscard]] std::expected<void, LoadError>
load_from(const std::filesystem::path& path);
void destroy_current() noexcept;
};
} // namespace Void::Plugin
+62
View File
@@ -0,0 +1,62 @@
#pragma once
#include <cstdint>
#include <string_view>
namespace Void::Plugin
{
// ── ABI version ───────────────────────────────────────────────────────────────
// Bump whenever IPlugin's vtable order changes. Loader rejects mismatches.
inline constexpr std::uint32_t ABI_VERSION = 1;
// ── PluginInfo ────────────────────────────────────────────────────────────────
// Plain-C struct returned by the info entry point. All fields are C strings so
// they cross the ABI boundary without C++ allocator involvement.
struct PluginInfo {
std::uint32_t abi_version {ABI_VERSION};
const char* name {""};
const char* plugin_version{"0.0.0"};
const char* description {""};
};
// ── IPlugin ───────────────────────────────────────────────────────────────────
// Abstract interface every plugin must implement.
// Vtable layout is FROZEN: new pure-virtual methods go only at the END.
class IPlugin {
public:
virtual ~IPlugin() = default;
[[nodiscard]] virtual std::string_view name() const noexcept = 0;
// Called once after the plugin is successfully created and verified.
virtual void on_load() {}
// Called once before the plugin is destroyed (including during hot-reload).
virtual void on_unload() {}
};
// ── C ABI entry-point typedefs ────────────────────────────────────────────────
// The .so MUST export these symbols via extern "C":
//
// void* void_plugin_create() — construct and return IPlugin*
// void void_plugin_destroy(void*) — destruct the IPlugin*
// PluginInfo void_plugin_info() — return metadata + ABI version
//
// Optional (enables hot-reload state transfer):
// void void_plugin_transfer_state(void* old, void* new)
using create_fn = void* (*)(void);
using destroy_fn = void (*)(void*);
using info_fn = PluginInfo (*)(void);
using transfer_fn = void (*)(void* old_instance, void* new_instance);
inline constexpr const char* kCreateSymbol = "void_plugin_create";
inline constexpr const char* kDestroySymbol = "void_plugin_destroy";
inline constexpr const char* kInfoSymbol = "void_plugin_info";
inline constexpr const char* kTransferSymbol = "void_plugin_transfer_state";
} // namespace Void::Plugin
@@ -0,0 +1,150 @@
#pragma once
#include <cassert>
#include <cstddef>
#include <functional>
#include <optional>
#include <stdexcept>
#include <unordered_map>
#include <vector>
namespace Void::PriorityQueue
{
// ── PriorityQueue<K, P> ───────────────────────────────────────────────────────
// Indexed min-heap (by priority P) with O(log n) push/pop/update.
// K is the key type (must be hashable). P is the priority type.
// Equal priorities maintain stable-ish order (not guaranteed).
template <typename K, typename P, typename Cmp = std::less<P>>
class PriorityQueue
{
public:
explicit PriorityQueue(Cmp cmp = {}) : cmp_{cmp} {}
// Push a key with priority. If key already exists, equivalent to update().
void push(K key, P priority)
{
const auto it = index_.find(key);
if (it != index_.end()) {
heap_[it->second].priority = priority;
bubble_up(it->second);
bubble_down(it->second);
return;
}
const std::size_t i = heap_.size();
heap_.push_back({std::move(key), std::move(priority)});
index_[heap_.back().key] = i;
bubble_up(i);
}
// Returns the top (min) element without removing it.
[[nodiscard]] const K& top_key() const
{
if (heap_.empty()) throw std::out_of_range{"PriorityQueue is empty"};
return heap_[0].key;
}
[[nodiscard]] const P& top_priority() const
{
if (heap_.empty()) throw std::out_of_range{"PriorityQueue is empty"};
return heap_[0].priority;
}
// Remove and return the top key.
K pop()
{
if (heap_.empty()) throw std::out_of_range{"PriorityQueue is empty"};
K result = std::move(heap_[0].key);
index_.erase(result);
if (heap_.size() > 1) {
heap_[0] = std::move(heap_.back());
index_[heap_[0].key] = 0;
}
heap_.pop_back();
if (!heap_.empty()) bubble_down(0);
return result;
}
// Update the priority of an existing key. No-op if key not found.
void update(const K& key, P priority)
{
const auto it = index_.find(key);
if (it == index_.end()) return;
heap_[it->second].priority = std::move(priority);
bubble_up(it->second);
bubble_down(it->second);
}
// Remove a specific key. No-op if not found.
void erase(const K& key)
{
const auto it = index_.find(key);
if (it == index_.end()) return;
const std::size_t i = it->second;
index_.erase(it);
if (i == heap_.size() - 1) { heap_.pop_back(); return; }
heap_[i] = std::move(heap_.back());
index_[heap_[i].key] = i;
heap_.pop_back();
bubble_up(i);
bubble_down(i);
}
[[nodiscard]] bool contains(const K& key) const { return index_.count(key) > 0; }
[[nodiscard]] std::optional<P> priority_of(const K& key) const
{
const auto it = index_.find(key);
if (it == index_.end()) return std::nullopt;
return heap_[it->second].priority;
}
[[nodiscard]] std::size_t size() const noexcept { return heap_.size(); }
[[nodiscard]] bool empty() const noexcept { return heap_.empty(); }
void clear() { heap_.clear(); index_.clear(); }
private:
struct Entry { K key; P priority; };
std::vector<Entry> heap_;
std::unordered_map<K, std::size_t> index_;
Cmp cmp_;
void swap_entries(std::size_t i, std::size_t j)
{
index_[heap_[i].key] = j;
index_[heap_[j].key] = i;
std::swap(heap_[i], heap_[j]);
}
void bubble_up(std::size_t i)
{
while (i > 0) {
const std::size_t parent = (i - 1) / 2;
if (!cmp_(heap_[i].priority, heap_[parent].priority)) break;
swap_entries(i, parent);
i = parent;
}
}
void bubble_down(std::size_t i)
{
const std::size_t n = heap_.size();
while (true) {
std::size_t smallest = i;
const std::size_t l = 2 * i + 1, r = 2 * i + 2;
if (l < n && cmp_(heap_[l].priority, heap_[smallest].priority)) smallest = l;
if (r < n && cmp_(heap_[r].priority, heap_[smallest].priority)) smallest = r;
if (smallest == i) break;
swap_entries(i, smallest);
i = smallest;
}
}
};
// ── MaxPriorityQueue — max-heap variant ───────────────────────────────────────
template <typename K, typename P>
using MaxPriorityQueue = PriorityQueue<K, P, std::greater<P>>;
} // namespace Void::PriorityQueue
+126
View File
@@ -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
+113
View File
@@ -0,0 +1,113 @@
#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
@@ -0,0 +1,112 @@
#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
+197
View File
@@ -0,0 +1,197 @@
#pragma once
#include <algorithm>
#include <cctype>
#include <charconv>
#include <string>
#include <string_view>
#include <system_error>
#include <vector>
namespace Void::Str
{
// ── trim ──────────────────────────────────────────────────────────────────────
[[nodiscard]] inline std::string_view trim_left(std::string_view s) noexcept
{
const auto it = std::find_if(s.begin(), s.end(),
[](unsigned char c) { return !std::isspace(c); });
s.remove_prefix(static_cast<std::size_t>(it - s.begin()));
return s;
}
[[nodiscard]] inline std::string_view trim_right(std::string_view s) noexcept
{
const auto it = std::find_if(s.rbegin(), s.rend(),
[](unsigned char c) { return !std::isspace(c); });
s.remove_suffix(static_cast<std::size_t>(it - s.rbegin()));
return s;
}
[[nodiscard]] inline std::string_view trim(std::string_view s) noexcept
{
return trim_right(trim_left(s));
}
// ── case ──────────────────────────────────────────────────────────────────────
[[nodiscard]] inline std::string to_lower(std::string_view s)
{
std::string out{s};
std::transform(out.begin(), out.end(), out.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return out;
}
[[nodiscard]] inline std::string to_upper(std::string_view s)
{
std::string out{s};
std::transform(out.begin(), out.end(), out.begin(),
[](unsigned char c) { return static_cast<char>(std::toupper(c)); });
return out;
}
// ── predicate ─────────────────────────────────────────────────────────────────
[[nodiscard]] inline bool starts_with(std::string_view s, std::string_view prefix) noexcept
{
return s.size() >= prefix.size() && s.substr(0, prefix.size()) == prefix;
}
[[nodiscard]] inline bool ends_with(std::string_view s, std::string_view suffix) noexcept
{
return s.size() >= suffix.size() && s.substr(s.size() - suffix.size()) == suffix;
}
[[nodiscard]] inline bool contains(std::string_view s, std::string_view needle) noexcept
{
return s.find(needle) != std::string_view::npos;
}
[[nodiscard]] inline bool is_alpha(std::string_view s) noexcept
{
return !s.empty() && std::all_of(s.begin(), s.end(),
[](unsigned char c) { return std::isalpha(c) != 0; });
}
[[nodiscard]] inline bool is_digit(std::string_view s) noexcept
{
return !s.empty() && std::all_of(s.begin(), s.end(),
[](unsigned char c) { return std::isdigit(c) != 0; });
}
[[nodiscard]] inline bool is_alnum(std::string_view s) noexcept
{
return !s.empty() && std::all_of(s.begin(), s.end(),
[](unsigned char c) { return std::isalnum(c) != 0; });
}
// ── split / join ──────────────────────────────────────────────────────────────
[[nodiscard]] inline std::vector<std::string_view>
split(std::string_view s, std::string_view 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 + delim.size();
}
return parts;
}
[[nodiscard]] inline std::vector<std::string_view>
split_once(std::string_view s, std::string_view delim)
{
const auto pos = s.find(delim);
if (pos == std::string_view::npos) return {s};
return {s.substr(0, pos), s.substr(pos + delim.size())};
}
template <typename Range>
[[nodiscard]] inline std::string join(const Range& parts, std::string_view sep)
{
std::string out;
bool first = true;
for (const auto& p : parts) {
if (!first) out += sep;
out += p;
first = false;
}
return out;
}
// ── replace ───────────────────────────────────────────────────────────────────
[[nodiscard]] inline std::string replace_all(
std::string_view s, std::string_view from, std::string_view to)
{
std::string out;
out.reserve(s.size());
std::size_t pos = 0;
while (true) {
const auto found = s.find(from, pos);
out += s.substr(pos, found - pos);
if (found == std::string_view::npos) break;
out += to;
pos = found + from.size();
}
return out;
}
// ── repeat ────────────────────────────────────────────────────────────────────
[[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_occurrences ─────────────────────────────────────────────────────────
[[nodiscard]] inline std::size_t count(std::string_view s, std::string_view needle) noexcept
{
if (needle.empty()) return 0;
std::size_t n = 0;
std::size_t pos = 0;
while ((pos = s.find(needle, pos)) != std::string_view::npos) {
++n;
pos += needle.size();
}
return n;
}
// ── pad ───────────────────────────────────────────────────────────────────────
[[nodiscard]] inline std::string pad_left(std::string_view s, std::size_t width, char fill = ' ')
{
if (s.size() >= width) return std::string{s};
return std::string(width - s.size(), fill) + std::string{s};
}
[[nodiscard]] inline std::string pad_right(std::string_view s, std::size_t width, char fill = ' ')
{
if (s.size() >= width) return std::string{s};
return std::string{s} + std::string(width - s.size(), fill);
}
// ── numeric conversion ────────────────────────────────────────────────────────
[[nodiscard]] inline bool to_int(std::string_view s, int& out) noexcept
{
const auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), out);
return ec == std::errc{} && ptr == s.data() + s.size();
}
[[nodiscard]] inline bool to_double(std::string_view s, double& out) noexcept
{
const auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), out);
return ec == std::errc{} && ptr == s.data() + s.size();
}
} // namespace Void::Str
+189
View File
@@ -0,0 +1,189 @@
#pragma once
#include <cctype>
#include <cstddef>
#include <functional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <variant>
#include <vector>
namespace Void::Tokenizer
{
// ── Token ─────────────────────────────────────────────────────────────────────
struct Token {
std::string kind; // rule name / category
std::string value; // raw matched text
std::size_t line; // 1-based
std::size_t col; // 1-based, column of first char
};
// ── Rule ──────────────────────────────────────────────────────────────────────
// A rule matches a prefix of the remaining input.
// Returns the number of characters consumed, or 0 on no match.
using MatchFn = std::function<std::size_t(std::string_view)>;
struct Rule {
std::string kind;
MatchFn match;
bool skip{false}; // if true, consume but do not emit a token
};
// ── Built-in match helpers ────────────────────────────────────────────────────
// Matches a fixed literal string.
[[nodiscard]] inline MatchFn literal(std::string_view s)
{
return [s = std::string{s}](std::string_view in) -> std::size_t {
if (in.starts_with(s)) return s.size();
return 0;
};
}
// Matches one or more characters satisfying a predicate.
[[nodiscard]] inline MatchFn chars(std::function<bool(char)> pred, std::size_t min = 1)
{
return [pred, min](std::string_view in) -> std::size_t {
std::size_t n = 0;
while (n < in.size() && pred(in[n])) ++n;
return n >= min ? n : 0;
};
}
// Common character classes.
[[nodiscard]] inline MatchFn alpha()
{
return chars([](char c) { return std::isalpha(static_cast<unsigned char>(c)) != 0; });
}
[[nodiscard]] inline MatchFn digit()
{
return chars([](char c) { return std::isdigit(static_cast<unsigned char>(c)) != 0; });
}
[[nodiscard]] inline MatchFn alnum_or_underscore()
{
return chars([](char c) {
return std::isalnum(static_cast<unsigned char>(c)) != 0 || c == '_';
});
}
[[nodiscard]] inline MatchFn whitespace()
{
return chars([](char c) { return std::isspace(static_cast<unsigned char>(c)) != 0; });
}
// Matches a C-style identifier: [a-zA-Z_][a-zA-Z0-9_]*
[[nodiscard]] inline MatchFn identifier()
{
return [](std::string_view in) -> std::size_t {
if (in.empty()) return 0;
const char first = in[0];
if (!std::isalpha(static_cast<unsigned char>(first)) && first != '_') return 0;
std::size_t n = 1;
while (n < in.size() &&
(std::isalnum(static_cast<unsigned char>(in[n])) || in[n] == '_'))
++n;
return n;
};
}
// Matches a decimal integer literal.
[[nodiscard]] inline MatchFn integer_literal()
{
return [](std::string_view in) -> std::size_t {
if (in.empty()) return 0;
std::size_t n = 0;
if (in[0] == '-' || in[0] == '+') ++n;
const std::size_t start = n;
while (n < in.size() && std::isdigit(static_cast<unsigned char>(in[n]))) ++n;
return n > start ? n : 0;
};
}
// Matches a double-quoted string (with simple backslash escape).
[[nodiscard]] inline MatchFn quoted_string()
{
return [](std::string_view in) -> std::size_t {
if (in.empty() || in[0] != '"') return 0;
std::size_t n = 1;
while (n < in.size()) {
if (in[n] == '\\') { n += 2; continue; }
if (in[n] == '"') { ++n; return n; }
++n;
}
return 0; // unterminated
};
}
// ── Tokenizer ─────────────────────────────────────────────────────────────────
// Greedy first-match: the first rule that matches at the current position wins.
class Tokenizer
{
public:
void add_rule(Rule rule) { rules_.push_back(std::move(rule)); }
void skip(std::string kind, MatchFn fn)
{
rules_.push_back({std::move(kind), std::move(fn), true});
}
struct Error {
std::size_t line;
std::size_t col;
char unexpected;
std::string message;
};
// Tokenize input, returning all tokens (skipped rules emit nothing).
// On unrecognized input returns an error.
[[nodiscard]] std::variant<std::vector<Token>, Error>
tokenize(std::string_view input) const
{
std::vector<Token> tokens;
std::size_t pos = 0;
std::size_t line = 1, col = 1;
while (pos < input.size()) {
bool matched = false;
for (const auto& rule : rules_) {
const std::size_t n = rule.match(input.substr(pos));
if (n == 0) continue;
if (!rule.skip) {
tokens.push_back({rule.kind,
std::string{input.substr(pos, n)},
line, col});
}
// Update position bookkeeping
for (std::size_t i = 0; i < n; ++i) {
if (input[pos + i] == '\n') { ++line; col = 1; }
else { ++col; }
}
pos += n;
matched = true;
break;
}
if (!matched) {
return Error{line, col, input[pos],
std::string{"unexpected character: '"} + input[pos] + "'"};
}
}
return tokens;
}
// Convenience: throws on error.
[[nodiscard]] std::vector<Token> tokenize_or_throw(std::string_view input) const
{
auto result = tokenize(input);
if (auto* err = std::get_if<Error>(&result))
throw std::runtime_error{err->message};
return std::get<std::vector<Token>>(std::move(result));
}
private:
std::vector<Rule> rules_;
};
} // namespace Void::Tokenizer
+94
View File
@@ -0,0 +1,94 @@
#pragma once
#include <any>
#include <cstddef>
#include <optional>
#include <stdexcept>
#include <typeindex>
#include <unordered_map>
namespace Void::TypeMap
{
// ── TypeMap ───────────────────────────────────────────────────────────────────
// Heterogeneous map indexed by C++ type. Each type can hold at most one value.
// Values are type-erased internally; full type safety at the API level.
//
// TypeMap m;
// m.put<int>(42);
// m.put<std::string>("hello");
// int v = *m.get<int>(); // 42
// bool ok = m.contains<int>(); // true
class TypeMap
{
public:
// Store value of type T. Overwrites any previous value of the same type.
template <typename T>
void put(T value)
{
map_.insert_or_assign(std::type_index{typeid(T)}, std::any{std::move(value)});
}
// Retrieve value of type T, or nullopt if not stored.
template <typename T>
[[nodiscard]] std::optional<T> get() const
{
const auto it = map_.find(std::type_index{typeid(T)});
if (it == map_.end()) return std::nullopt;
return std::any_cast<T>(it->second);
}
// Get reference to value of type T. Throws std::out_of_range if absent.
template <typename T>
[[nodiscard]] const T& get_or_throw() const
{
const auto it = map_.find(std::type_index{typeid(T)});
if (it == map_.end()) throw std::out_of_range{"TypeMap: type not found"};
return std::any_cast<const T&>(it->second);
}
// Get value or a default if absent.
template <typename T>
[[nodiscard]] T get_or(T def) const
{
const auto it = map_.find(std::type_index{typeid(T)});
if (it == map_.end()) return def;
return std::any_cast<T>(it->second);
}
// Returns true if a value of type T is stored.
template <typename T>
[[nodiscard]] bool contains() const
{
return map_.count(std::type_index{typeid(T)}) > 0;
}
// Remove the value of type T. Returns true if something was erased.
template <typename T>
bool erase()
{
return map_.erase(std::type_index{typeid(T)}) > 0;
}
// Get-or-insert: if T is absent, construct it with args and store it.
template <typename T, typename... Args>
T& get_or_insert(Args&&... args)
{
const auto key = std::type_index{typeid(T)};
const auto it = map_.find(key);
if (it != map_.end()) return std::any_cast<T&>(it->second);
auto [ins, _] = map_.emplace(key, std::any{T{std::forward<Args>(args)...}});
return std::any_cast<T&>(ins->second);
}
void clear() noexcept { map_.clear(); }
[[nodiscard]] std::size_t size() const noexcept { return map_.size(); }
[[nodiscard]] bool empty() const noexcept { return map_.empty(); }
private:
std::unordered_map<std::type_index, std::any> map_;
};
} // namespace Void::TypeMap
+101
View File
@@ -0,0 +1,101 @@
#pragma once
#include <functional>
#include <optional>
#include <type_traits>
#include <utility>
#include <variant>
namespace Void::Variant
{
// ── overload ──────────────────────────────────────────────────────────────────
// Aggregate multiple callables into one visitor. Usage:
// std::visit(overload{[](int i){...}, [](std::string s){...}}, v);
template <typename... Fs>
struct overload : Fs... { using Fs::operator()...; };
// ── match ─────────────────────────────────────────────────────────────────────
// Apply visitor lambdas to a std::variant inline. Usage:
// match(v, [](int i){ return i; }, [](double d){ return (int)d; });
template <typename V, typename... Fs>
[[nodiscard]] decltype(auto) match(V&& v, Fs&&... fs)
{
return std::visit(overload<std::decay_t<Fs>...>{std::forward<Fs>(fs)...},
std::forward<V>(v));
}
// ── holds<T> ──────────────────────────────────────────────────────────────────
// Compile-time-named alternative to std::holds_alternative.
template <typename T, typename V>
[[nodiscard]] bool holds(const V& v) noexcept
{
return std::holds_alternative<T>(v);
}
// ── get_or<T> ─────────────────────────────────────────────────────────────────
// Returns the value if the variant holds T, otherwise returns default_val.
template <typename T, typename V>
[[nodiscard]] T get_or(const V& v, T default_val) noexcept
{
if (const auto* p = std::get_if<T>(&v)) return *p;
return default_val;
}
// ── try_get<T> ────────────────────────────────────────────────────────────────
// Returns optional<T> — present iff the variant holds T.
template <typename T, typename V>
[[nodiscard]] std::optional<T> try_get(const V& v) noexcept
{
if (const auto* p = std::get_if<T>(&v)) return *p;
return std::nullopt;
}
// ── index_of<T, V> ────────────────────────────────────────────────────────────
// Compile-time index of T within a std::variant<...> type V.
namespace Detail
{
template <typename T, typename V, std::size_t I = 0>
constexpr std::size_t variant_index()
{
if constexpr (I >= std::variant_size_v<V>) return std::variant_npos;
else if constexpr (std::is_same_v<T, std::variant_alternative_t<I, V>>) return I;
else return variant_index<T, V, I + 1>();
}
} // namespace Detail
template <typename T, typename V>
inline constexpr std::size_t index_of = Detail::variant_index<T, V>();
// ── apply_to<T> ───────────────────────────────────────────────────────────────
// Call fn only if the variant holds T. Returns optional of the result.
template <typename T, typename V, typename F>
[[nodiscard]] auto apply_to(const V& v, F&& fn)
-> std::optional<std::invoke_result_t<F, const T&>>
{
if (const auto* p = std::get_if<T>(&v))
return std::invoke(std::forward<F>(fn), *p);
return std::nullopt;
}
// ── narrow<U, V> ─────────────────────────────────────────────────────────────
// Map variant: if the active type is convertible to U, return U; else nullopt.
template <typename U, typename... Ts>
[[nodiscard]] std::optional<U> narrow(const std::variant<Ts...>& v)
{
return std::visit([](const auto& alt) -> std::optional<U> {
using T = std::decay_t<decltype(alt)>;
if constexpr (std::is_convertible_v<T, U>) return static_cast<U>(alt);
else return std::nullopt;
}, v);
}
} // namespace Void::Variant