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:
1 parent
cb4dd58500
commit
58ff7b38a0
65 files changed
+8987
-37
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,158 @@
|
||||
#include <Void/Argparse/Argparse.hpp>
|
||||
|
||||
#include <sstream>
|
||||
|
||||
namespace Void::Argparse
|
||||
{
|
||||
|
||||
Parser::Parser(std::string program, std::string description)
|
||||
: program_{std::move(program)}, description_{std::move(description)}
|
||||
{}
|
||||
|
||||
Parser& Parser::flag(std::string_view lng, std::string_view sht,
|
||||
std::string_view desc, bool& out)
|
||||
{
|
||||
flags_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, &out});
|
||||
return *this;
|
||||
}
|
||||
|
||||
Parser& Parser::option(std::string_view lng, std::string_view sht,
|
||||
std::string_view desc, std::optional<std::string>& out)
|
||||
{
|
||||
options_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, {}, &out, nullptr});
|
||||
return *this;
|
||||
}
|
||||
|
||||
Parser& Parser::option_default(std::string_view lng, std::string_view sht,
|
||||
std::string_view desc, std::string& out,
|
||||
std::string_view default_value)
|
||||
{
|
||||
out = std::string{default_value};
|
||||
options_.push_back({std::string{lng}, std::string{sht}, std::string{desc},
|
||||
std::string{default_value}, nullptr, &out});
|
||||
return *this;
|
||||
}
|
||||
|
||||
Parser& Parser::positional(std::string_view name, std::string_view desc, std::string& out)
|
||||
{
|
||||
positionals_.push_back({std::string{name}, std::string{desc}, &out});
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::expected<void, std::string>
|
||||
Parser::parse(int argc, const char* const* argv) const
|
||||
{
|
||||
std::size_t pos_idx = 0;
|
||||
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string_view arg{argv[i]};
|
||||
|
||||
// Help
|
||||
if (arg == "--help" || arg == "-h") {
|
||||
return std::unexpected{help()};
|
||||
}
|
||||
|
||||
// Flag check
|
||||
bool matched_flag = false;
|
||||
for (const auto& f : flags_) {
|
||||
if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) {
|
||||
*f.out = true;
|
||||
matched_flag = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matched_flag) continue;
|
||||
|
||||
// Option check: --key=value or --key value or -k value
|
||||
bool matched_opt = false;
|
||||
for (const auto& opt : options_) {
|
||||
std::string_view value;
|
||||
bool found = false;
|
||||
|
||||
// --key=value
|
||||
if (arg.size() > opt.lng.size() + 1 &&
|
||||
arg.substr(0, opt.lng.size()) == opt.lng &&
|
||||
arg[opt.lng.size()] == '=')
|
||||
{
|
||||
value = arg.substr(opt.lng.size() + 1);
|
||||
found = true;
|
||||
}
|
||||
// --key value or -k value
|
||||
else if (arg == opt.lng || (!opt.sht.empty() && arg == opt.sht)) {
|
||||
if (i + 1 >= argc)
|
||||
return std::unexpected{"option '" + std::string{arg} + "' requires a value"};
|
||||
value = argv[++i];
|
||||
found = true;
|
||||
}
|
||||
|
||||
if (found) {
|
||||
const std::string val_str{value};
|
||||
if (opt.out_opt) *opt.out_opt = val_str;
|
||||
if (opt.out_str) *opt.out_str = val_str;
|
||||
matched_opt = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matched_opt) continue;
|
||||
|
||||
// Unknown --/- prefixed arg
|
||||
if (arg.size() > 1 && arg[0] == '-')
|
||||
return std::unexpected{"unknown option: " + std::string{arg}};
|
||||
|
||||
// Positional
|
||||
if (pos_idx >= positionals_.size())
|
||||
return std::unexpected{"unexpected positional argument: " + std::string{arg}};
|
||||
*positionals_[pos_idx++].out = std::string{arg};
|
||||
}
|
||||
|
||||
// Check required positionals
|
||||
for (std::size_t j = pos_idx; j < positionals_.size(); ++j)
|
||||
return std::unexpected{"missing required argument: <" + positionals_[j].name + ">"};
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
std::string Parser::help() const
|
||||
{
|
||||
std::ostringstream os;
|
||||
os << "Usage: " << program_;
|
||||
for (const auto& f : flags_) os << " [" << f.lng << "]";
|
||||
for (const auto& o : options_) {
|
||||
const std::string_view dn = std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
|
||||
os << " [" << o.lng << " <" << dn << ">]";
|
||||
}
|
||||
for (const auto& p : positionals_) os << " <" << p.name << ">";
|
||||
os << "\n";
|
||||
if (!description_.empty()) os << "\n" << description_ << "\n";
|
||||
|
||||
if (!positionals_.empty()) {
|
||||
os << "\nArguments:\n";
|
||||
for (const auto& p : positionals_)
|
||||
os << " <" << p.name << "> " << p.desc << "\n";
|
||||
}
|
||||
if (!flags_.empty()) {
|
||||
os << "\nFlags:\n";
|
||||
for (const auto& f : flags_) {
|
||||
os << " " << f.lng;
|
||||
if (!f.sht.empty()) os << ", " << f.sht;
|
||||
os << " " << f.desc << "\n";
|
||||
}
|
||||
}
|
||||
if (!options_.empty()) {
|
||||
os << "\nOptions:\n";
|
||||
for (const auto& o : options_) {
|
||||
// Derive a display name from the long option (strip leading --)
|
||||
const std::string_view dname = std::string_view{o.lng}.substr(
|
||||
o.lng.size() > 2 ? 2 : 0);
|
||||
os << " " << o.lng;
|
||||
if (!o.sht.empty()) os << ", " << o.sht;
|
||||
os << " <" << dname << ">";
|
||||
if (!o.def.empty()) os << " (default: " << o.def << ")";
|
||||
os << " " << o.desc << "\n";
|
||||
}
|
||||
}
|
||||
os << " --help, -h show this help\n";
|
||||
return os.str();
|
||||
}
|
||||
|
||||
} // namespace Void::Argparse
|
||||
@@ -0,0 +1,172 @@
|
||||
#include <Void/Plugin/Loader.hpp>
|
||||
|
||||
#if defined(__unix__) || defined(__APPLE__)
|
||||
# include <dlfcn.h>
|
||||
# define VOID_HAS_DLOPEN 1
|
||||
#endif
|
||||
|
||||
#include <filesystem>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Plugin
|
||||
{
|
||||
|
||||
std::string_view to_string(LoadError e) noexcept
|
||||
{
|
||||
switch (e) {
|
||||
case LoadError::FileNotFound: return "file not found";
|
||||
case LoadError::DlopenFailed: return "dlopen failed";
|
||||
case LoadError::SymbolMissing: return "required symbol missing";
|
||||
case LoadError::AbiMismatch: return "ABI version mismatch";
|
||||
case LoadError::CreateFailed: return "plugin create() returned null";
|
||||
case LoadError::NotSupported: return "platform does not support dlopen";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
// ── internal helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
void PluginLoader::destroy_current() noexcept
|
||||
{
|
||||
#ifdef VOID_HAS_DLOPEN
|
||||
if (plugin_) {
|
||||
plugin_->on_unload();
|
||||
if (destroy_) destroy_(plugin_);
|
||||
plugin_ = nullptr;
|
||||
}
|
||||
if (handle_) {
|
||||
dlclose(handle_);
|
||||
handle_ = nullptr;
|
||||
}
|
||||
destroy_ = nullptr;
|
||||
transfer_ = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::expected<void, LoadError>
|
||||
PluginLoader::load_from(const std::filesystem::path& path)
|
||||
{
|
||||
#ifdef VOID_HAS_DLOPEN
|
||||
void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||
if (!h) return std::unexpected{LoadError::DlopenFailed};
|
||||
|
||||
const auto sym_info = reinterpret_cast<info_fn> (dlsym(h, kInfoSymbol));
|
||||
const auto sym_create = reinterpret_cast<create_fn> (dlsym(h, kCreateSymbol));
|
||||
const auto sym_destroy = reinterpret_cast<destroy_fn>(dlsym(h, kDestroySymbol));
|
||||
|
||||
if (!sym_info || !sym_create || !sym_destroy) {
|
||||
dlclose(h);
|
||||
return std::unexpected{LoadError::SymbolMissing};
|
||||
}
|
||||
|
||||
const PluginInfo info = sym_info();
|
||||
if (info.abi_version != ABI_VERSION) {
|
||||
dlclose(h);
|
||||
return std::unexpected{LoadError::AbiMismatch};
|
||||
}
|
||||
|
||||
void* raw = sym_create();
|
||||
if (!raw) {
|
||||
dlclose(h);
|
||||
return std::unexpected{LoadError::CreateFailed};
|
||||
}
|
||||
|
||||
handle_ = h;
|
||||
plugin_ = static_cast<IPlugin*>(raw);
|
||||
destroy_ = sym_destroy;
|
||||
transfer_ = reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
||||
info_ = info;
|
||||
return {};
|
||||
#else
|
||||
(void)path;
|
||||
return std::unexpected{LoadError::NotSupported};
|
||||
#endif
|
||||
}
|
||||
|
||||
// ── public API ────────────────────────────────────────────────────────────────
|
||||
|
||||
std::expected<PluginLoader, LoadError>
|
||||
PluginLoader::load(std::filesystem::path path)
|
||||
{
|
||||
if (!std::filesystem::exists(path))
|
||||
return std::unexpected{LoadError::FileNotFound};
|
||||
|
||||
PluginLoader ldr;
|
||||
ldr.path_ = path;
|
||||
|
||||
if (auto r = ldr.load_from(path); !r)
|
||||
return std::unexpected{r.error()};
|
||||
|
||||
ldr.plugin_->on_load();
|
||||
return ldr;
|
||||
}
|
||||
|
||||
PluginLoader::~PluginLoader() { destroy_current(); }
|
||||
|
||||
PluginLoader::PluginLoader(PluginLoader&& o) noexcept
|
||||
: handle_ {std::exchange(o.handle_, nullptr)}
|
||||
, plugin_ {std::exchange(o.plugin_, nullptr)}
|
||||
, destroy_ {std::exchange(o.destroy_, nullptr)}
|
||||
, transfer_{std::exchange(o.transfer_, nullptr)}
|
||||
, info_ {o.info_}
|
||||
, path_ {std::move(o.path_)}
|
||||
{}
|
||||
|
||||
PluginLoader& PluginLoader::operator=(PluginLoader&& o) noexcept
|
||||
{
|
||||
if (this != &o) {
|
||||
destroy_current();
|
||||
handle_ = std::exchange(o.handle_, nullptr);
|
||||
plugin_ = std::exchange(o.plugin_, nullptr);
|
||||
destroy_ = std::exchange(o.destroy_, nullptr);
|
||||
transfer_ = std::exchange(o.transfer_, nullptr);
|
||||
info_ = o.info_;
|
||||
path_ = std::move(o.path_);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::expected<void, LoadError> PluginLoader::reload()
|
||||
{
|
||||
#ifdef VOID_HAS_DLOPEN
|
||||
// Copy to a unique temp path so dlopen gets a fresh inode (bypasses the
|
||||
// path-based cache) even if the file was replaced in-place.
|
||||
const auto tmp = path_.parent_path()
|
||||
/ (path_.filename().string() + ".void_hotswap");
|
||||
|
||||
{
|
||||
std::error_code ec;
|
||||
std::filesystem::copy_file(path_, tmp,
|
||||
std::filesystem::copy_options::overwrite_existing, ec);
|
||||
if (ec) return std::unexpected{LoadError::FileNotFound};
|
||||
}
|
||||
|
||||
// Load new instance while old is still alive (for state transfer).
|
||||
PluginLoader next;
|
||||
next.path_ = path_;
|
||||
if (auto r = next.load_from(tmp); !r) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tmp, ec);
|
||||
return r;
|
||||
}
|
||||
|
||||
// Transfer state with both instances alive.
|
||||
if (plugin_ && next.plugin_ && next.transfer_)
|
||||
next.transfer_(plugin_, next.plugin_);
|
||||
|
||||
// Destroy old, install new.
|
||||
destroy_current();
|
||||
*this = std::move(next);
|
||||
|
||||
plugin_->on_load();
|
||||
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tmp, ec);
|
||||
return {};
|
||||
#else
|
||||
return std::unexpected{LoadError::NotSupported};
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace Void::Plugin
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(Plugin
|
||||
DEPS_UNIX dl
|
||||
)
|
||||
+88
-37
@@ -2,48 +2,99 @@ include(${CMAKE_SOURCE_DIR}/cmake/VoidTesting.cmake)
|
||||
|
||||
get_property(ACTIVE_MODULES GLOBAL PROPERTY VOID_MODULES)
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# PART 1: Internal kitchen-sink test (links every module).
|
||||
# ------------------------------------------------------------------------------
|
||||
file(GLOB_RECURSE INTERNAL_SOURCES CONFIGURE_DEPENDS "internal/*.cpp")
|
||||
set(_gen_dir "${CMAKE_CURRENT_BINARY_DIR}/void_testing_generated")
|
||||
file(MAKE_DIRECTORY "${_gen_dir}")
|
||||
|
||||
if(INTERNAL_SOURCES)
|
||||
add_executable(VoidInternalTests ${INTERNAL_SOURCES})
|
||||
target_link_libraries(VoidInternalTests PRIVATE Void::Testing)
|
||||
set(_all_generated "")
|
||||
|
||||
# ── Standalone tests ──────────────────────────────────────────────────────────
|
||||
# Each .cpp under tests/standalone/<Module>/ is scanned for Void::Testing tests.
|
||||
# All generated shims are compiled into ONE VoidTests executable that links
|
||||
# every active module. This avoids N separate test binaries while preserving
|
||||
# per-module suite names in the runner output.
|
||||
#
|
||||
# Generated file naming: <Module>_<stem>.void_tests.cpp
|
||||
# SUITE_NAME passed to scanner: <stem> (shown in the runner as the suite label)
|
||||
|
||||
foreach(mod ${ACTIVE_MODULES})
|
||||
set(_mod_dir "${CMAKE_CURRENT_SOURCE_DIR}/standalone/${mod}")
|
||||
if(NOT IS_DIRECTORY "${_mod_dir}")
|
||||
continue()
|
||||
endif()
|
||||
|
||||
file(GLOB _test_files CONFIGURE_DEPENDS "${_mod_dir}/*.cpp")
|
||||
foreach(_src ${_test_files})
|
||||
get_filename_component(_stem "${_src}" NAME_WE)
|
||||
set(_gen "${_gen_dir}/${mod}_${_stem}.void_tests.cpp")
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT "${_gen}"
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DINPUT_FILE=${_src}
|
||||
-DOUTPUT_FILE=${_gen}
|
||||
-DSUITE_NAME=${_stem}
|
||||
-P "${VOID_TESTING_SCANNER}"
|
||||
DEPENDS "${_src}" "${VOID_TESTING_SCANNER}"
|
||||
COMMENT "Scanning ${_src} for Void::Testing tests"
|
||||
)
|
||||
set_source_files_properties("${_src}" PROPERTIES HEADER_FILE_ONLY TRUE)
|
||||
set_source_files_properties("${_gen}" PROPERTIES GENERATED TRUE)
|
||||
list(APPEND _all_generated "${_gen}")
|
||||
endforeach()
|
||||
endforeach()
|
||||
|
||||
# ── Internal tests (kitchen-sink, links everything) ───────────────────────────
|
||||
|
||||
file(GLOB_RECURSE _internal_sources CONFIGURE_DEPENDS "internal/*.cpp")
|
||||
foreach(_src ${_internal_sources})
|
||||
get_filename_component(_stem "${_src}" NAME_WE)
|
||||
set(_gen "${_gen_dir}/internal_${_stem}.void_tests.cpp")
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT "${_gen}"
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DINPUT_FILE=${_src}
|
||||
-DOUTPUT_FILE=${_gen}
|
||||
-DSUITE_NAME=internal_${_stem}
|
||||
-P "${VOID_TESTING_SCANNER}"
|
||||
DEPENDS "${_src}" "${VOID_TESTING_SCANNER}"
|
||||
COMMENT "Scanning ${_src} for Void::Testing tests"
|
||||
)
|
||||
set_source_files_properties("${_src}" PROPERTIES HEADER_FILE_ONLY TRUE)
|
||||
set_source_files_properties("${_gen}" PROPERTIES GENERATED TRUE)
|
||||
list(APPEND _all_generated "${_gen}")
|
||||
endforeach()
|
||||
|
||||
# ── VoidTests — the single test executable ────────────────────────────────────
|
||||
|
||||
if(_all_generated)
|
||||
add_executable(VoidTests ${_all_generated})
|
||||
|
||||
# Disable auto-sweep: we already applied the scanner manually above.
|
||||
set_target_properties(VoidTests PROPERTIES VOID_TESTING_NO_AUTO_SCAN TRUE)
|
||||
|
||||
target_link_libraries(VoidTests PRIVATE Void::Testing)
|
||||
foreach(mod ${ACTIVE_MODULES})
|
||||
if(NOT mod STREQUAL "Testing" AND NOT mod STREQUAL "TestingMock")
|
||||
target_link_libraries(VoidInternalTests PRIVATE Void::${mod})
|
||||
if(NOT mod STREQUAL "Testing" AND TARGET Void::${mod})
|
||||
target_link_libraries(VoidTests PRIVATE Void::${mod})
|
||||
endif()
|
||||
endforeach()
|
||||
if(TARGET Void::TestingMock)
|
||||
target_link_libraries(VoidInternalTests PRIVATE Void::TestingMock)
|
||||
endif()
|
||||
add_test(NAME internal COMMAND VoidInternalTests --no-color)
|
||||
|
||||
add_test(NAME VoidTests COMMAND VoidTests)
|
||||
endif()
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# PART 2: Standalone tests — one executable per source file under
|
||||
# tests/standalone/<Module>/. Auto-scan picks each one up via the deferred
|
||||
# sweep registered by cmake/VoidTesting.cmake.
|
||||
# ------------------------------------------------------------------------------
|
||||
foreach(mod ${ACTIVE_MODULES})
|
||||
set(STANDALONE_MOD_DIR "${CMAKE_CURRENT_SOURCE_DIR}/standalone/${mod}")
|
||||
# ── Test-support libraries ────────────────────────────────────────────────────
|
||||
# These are NOT test files; they are helper shared libs referenced by tests.
|
||||
|
||||
if(IS_DIRECTORY ${STANDALONE_MOD_DIR})
|
||||
file(GLOB test_files CONFIGURE_DEPENDS "${STANDALONE_MOD_DIR}/*.cpp")
|
||||
|
||||
foreach(test_src ${test_files})
|
||||
get_filename_component(test_file_name ${test_src} NAME_WE)
|
||||
set(EXE_NAME "test_standalone_${mod}_${test_file_name}")
|
||||
|
||||
add_executable(${EXE_NAME} ${test_src})
|
||||
target_link_libraries(${EXE_NAME} PRIVATE Void::Testing)
|
||||
if(NOT mod STREQUAL "Testing" AND NOT mod STREQUAL "TestingMock")
|
||||
target_link_libraries(${EXE_NAME} PRIVATE Void::${mod})
|
||||
endif()
|
||||
if(TARGET Void::TestingMock)
|
||||
target_link_libraries(${EXE_NAME} PRIVATE Void::TestingMock)
|
||||
endif()
|
||||
endforeach()
|
||||
if(TARGET Void::Plugin)
|
||||
set(_test_plugin_src "${CMAKE_CURRENT_SOURCE_DIR}/plugins/TestPlugin.cpp")
|
||||
if(EXISTS "${_test_plugin_src}")
|
||||
add_library(VoidTestPlugin SHARED "${_test_plugin_src}")
|
||||
target_link_libraries(VoidTestPlugin PRIVATE Void::Plugin)
|
||||
# Give VoidTests the absolute path to VoidTestPlugin.so via a define.
|
||||
target_compile_definitions(VoidTests PRIVATE
|
||||
"VOID_TEST_PLUGIN_PATH=\"$<TARGET_FILE:VoidTestPlugin>\""
|
||||
)
|
||||
add_dependencies(VoidTests VoidTestPlugin)
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
@@ -0,0 +1,53 @@
|
||||
#include <Void/Plugin/Plugin.hpp>
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
// A minimal plugin used by the Plugin integration test.
|
||||
// Supports state transfer: carries an int counter across hot-reloads.
|
||||
|
||||
namespace {
|
||||
|
||||
class TestPlugin final : public Void::Plugin::IPlugin
|
||||
{
|
||||
public:
|
||||
[[nodiscard]] std::string_view name() const noexcept override { return "TestPlugin"; }
|
||||
void on_load() override { loaded = true; }
|
||||
void on_unload() override { loaded = false; }
|
||||
|
||||
bool loaded{false};
|
||||
int counter{0};
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
void* void_plugin_create()
|
||||
{
|
||||
return new TestPlugin;
|
||||
}
|
||||
|
||||
void void_plugin_destroy(void* p)
|
||||
{
|
||||
delete static_cast<TestPlugin*>(p);
|
||||
}
|
||||
|
||||
Void::Plugin::PluginInfo void_plugin_info()
|
||||
{
|
||||
return {
|
||||
.abi_version = Void::Plugin::ABI_VERSION,
|
||||
.name = "TestPlugin",
|
||||
.plugin_version = "1.0.0",
|
||||
.description = "Integration test plugin",
|
||||
};
|
||||
}
|
||||
|
||||
void void_plugin_transfer_state(void* old_ptr, void* new_ptr)
|
||||
{
|
||||
const auto* old_p = static_cast<TestPlugin*>(old_ptr);
|
||||
auto* new_p = static_cast<TestPlugin*>(new_ptr);
|
||||
new_p->counter = old_p->counter + 1; // increment to prove transfer ran
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,189 @@
|
||||
#include <Void/Argparse/Argparse.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Argparse;
|
||||
|
||||
// Helper: convert vector of strings to argc/argv style
|
||||
struct Args {
|
||||
std::vector<std::string> strs;
|
||||
std::vector<const char*> ptrs;
|
||||
int argc;
|
||||
const char* const* argv;
|
||||
|
||||
explicit Args(std::vector<std::string> s) : strs{std::move(s)}
|
||||
{
|
||||
for (const auto& str : strs) ptrs.push_back(str.c_str());
|
||||
argc = static_cast<int>(ptrs.size());
|
||||
argv = ptrs.data();
|
||||
}
|
||||
};
|
||||
|
||||
// ── flags ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test argparse_flag_long()
|
||||
{
|
||||
bool verbose = false;
|
||||
Parser p{"test"};
|
||||
p.flag("--verbose", "-v", "enable verbose", verbose);
|
||||
const Args a{{"test", "--verbose"}};
|
||||
Void::Testing::expect(p.parse(a.argc, a.argv).has_value());
|
||||
Void::Testing::expect(verbose);
|
||||
}
|
||||
|
||||
Void::Testing::Test argparse_flag_short()
|
||||
{
|
||||
bool verbose = false;
|
||||
Parser p{"test"};
|
||||
p.flag("--verbose", "-v", "enable verbose", verbose);
|
||||
const Args a{{"test", "-v"}};
|
||||
Void::Testing::expect(p.parse(a.argc, a.argv).has_value());
|
||||
Void::Testing::expect(verbose);
|
||||
}
|
||||
|
||||
Void::Testing::Test argparse_flag_absent()
|
||||
{
|
||||
bool verbose = false;
|
||||
Parser p{"test"};
|
||||
p.flag("--verbose", "-v", "enable verbose", verbose);
|
||||
const Args a{{"test"}};
|
||||
Void::Testing::expect(p.parse(a.argc, a.argv).has_value());
|
||||
Void::Testing::expect(!verbose);
|
||||
}
|
||||
|
||||
Void::Testing::Test argparse_multiple_flags()
|
||||
{
|
||||
bool a = false, b = false;
|
||||
Parser p{"test"};
|
||||
p.flag("--alpha", "-a", "", a);
|
||||
p.flag("--beta", "-b", "", b);
|
||||
const Args args{{"test", "--alpha"}};
|
||||
Void::Testing::expect(p.parse(args.argc, args.argv).has_value());
|
||||
Void::Testing::expect(a);
|
||||
Void::Testing::expect(!b);
|
||||
}
|
||||
|
||||
// ── options ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test argparse_option_equals()
|
||||
{
|
||||
std::optional<std::string> out;
|
||||
Parser p{"test"};
|
||||
p.option("--output", "-o", "output file", out);
|
||||
const Args a{{"test", "--output=file.txt"}};
|
||||
Void::Testing::expect(p.parse(a.argc, a.argv).has_value());
|
||||
Void::Testing::expect(out.has_value());
|
||||
Void::Testing::expect_eq(*out, std::string{"file.txt"});
|
||||
}
|
||||
|
||||
Void::Testing::Test argparse_option_space()
|
||||
{
|
||||
std::optional<std::string> out;
|
||||
Parser p{"test"};
|
||||
p.option("--output", "-o", "output file", out);
|
||||
const Args a{{"test", "--output", "result.txt"}};
|
||||
Void::Testing::expect(p.parse(a.argc, a.argv).has_value());
|
||||
Void::Testing::expect_eq(*out, std::string{"result.txt"});
|
||||
}
|
||||
|
||||
Void::Testing::Test argparse_option_short()
|
||||
{
|
||||
std::optional<std::string> out;
|
||||
Parser p{"test"};
|
||||
p.option("--output", "-o", "output file", out);
|
||||
const Args a{{"test", "-o", "out.txt"}};
|
||||
Void::Testing::expect(p.parse(a.argc, a.argv).has_value());
|
||||
Void::Testing::expect_eq(*out, std::string{"out.txt"});
|
||||
}
|
||||
|
||||
Void::Testing::Test argparse_option_default()
|
||||
{
|
||||
std::string out;
|
||||
Parser p{"test"};
|
||||
p.option_default("--format", "-f", "output format", out, "json");
|
||||
const Args a{{"test"}};
|
||||
Void::Testing::expect(p.parse(a.argc, a.argv).has_value());
|
||||
Void::Testing::expect_eq(out, std::string{"json"});
|
||||
}
|
||||
|
||||
Void::Testing::Test argparse_option_default_overridden()
|
||||
{
|
||||
std::string out;
|
||||
Parser p{"test"};
|
||||
p.option_default("--format", "-f", "output format", out, "json");
|
||||
const Args a{{"test", "--format=xml"}};
|
||||
Void::Testing::expect(p.parse(a.argc, a.argv).has_value());
|
||||
Void::Testing::expect_eq(out, std::string{"xml"});
|
||||
}
|
||||
|
||||
Void::Testing::Test argparse_option_missing_value_is_error()
|
||||
{
|
||||
std::optional<std::string> out;
|
||||
Parser p{"test"};
|
||||
p.option("--output", "-o", "output", out);
|
||||
const Args a{{"test", "--output"}}; // value missing
|
||||
const auto r = p.parse(a.argc, a.argv);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
// ── positionals ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test argparse_positional()
|
||||
{
|
||||
std::string filename;
|
||||
Parser p{"test"};
|
||||
p.positional("input", "input file", filename);
|
||||
const Args a{{"test", "data.csv"}};
|
||||
Void::Testing::expect(p.parse(a.argc, a.argv).has_value());
|
||||
Void::Testing::expect_eq(filename, std::string{"data.csv"});
|
||||
}
|
||||
|
||||
Void::Testing::Test argparse_positional_missing_is_error()
|
||||
{
|
||||
std::string filename;
|
||||
Parser p{"test"};
|
||||
p.positional("input", "input file", filename);
|
||||
const Args a{{"test"}};
|
||||
Void::Testing::expect(!p.parse(a.argc, a.argv).has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test argparse_mix_flags_and_positionals()
|
||||
{
|
||||
bool flag = false;
|
||||
std::string file;
|
||||
Parser p{"test"};
|
||||
p.flag("--dry-run", "-n", "dry run", flag);
|
||||
p.positional("file", "file to process", file);
|
||||
const Args a{{"test", "--dry-run", "input.txt"}};
|
||||
Void::Testing::expect(p.parse(a.argc, a.argv).has_value());
|
||||
Void::Testing::expect(flag);
|
||||
Void::Testing::expect_eq(file, std::string{"input.txt"});
|
||||
}
|
||||
|
||||
// ── errors ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test argparse_unknown_option_is_error()
|
||||
{
|
||||
Parser p{"test"};
|
||||
const Args a{{"test", "--unknown"}};
|
||||
Void::Testing::expect(!p.parse(a.argc, a.argv).has_value());
|
||||
}
|
||||
|
||||
// ── help ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test argparse_help_contains_names()
|
||||
{
|
||||
bool v = false;
|
||||
std::optional<std::string> o;
|
||||
Parser p{"mytool", "A description."};
|
||||
p.flag("--verbose", "-v", "verbose mode", v);
|
||||
p.option("--output", "-o", "output file", o);
|
||||
const auto h = p.help();
|
||||
Void::Testing::expect(h.find("--verbose") != std::string::npos);
|
||||
Void::Testing::expect(h.find("--output") != std::string::npos);
|
||||
Void::Testing::expect(h.find("A description.") != std::string::npos);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
#include <Void/Bench/Bench.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Bench;
|
||||
|
||||
// ── run ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bench_run_correct_iteration_count()
|
||||
{
|
||||
int count = 0;
|
||||
const auto r = run("counter", 10, [&] { ++count; }, /*warmup=*/0);
|
||||
Void::Testing::expect_eq(r.iterations, std::size_t{10});
|
||||
Void::Testing::expect_eq(count, 10);
|
||||
}
|
||||
|
||||
Void::Testing::Test bench_run_warmup_not_in_result()
|
||||
{
|
||||
int count = 0;
|
||||
const auto r = run("counter", 5, [&] { ++count; }, /*warmup=*/3);
|
||||
Void::Testing::expect_eq(r.iterations, std::size_t{5});
|
||||
Void::Testing::expect_eq(count, 8); // 3 warmup + 5 measured
|
||||
}
|
||||
|
||||
Void::Testing::Test bench_run_name_preserved()
|
||||
{
|
||||
const auto r = run("my_bench", 1, [] {});
|
||||
Void::Testing::expect_eq(r.name, std::string{"my_bench"});
|
||||
}
|
||||
|
||||
Void::Testing::Test bench_run_total_positive()
|
||||
{
|
||||
const auto r = run("work", 100, [] {
|
||||
volatile int x = 0;
|
||||
for (int i = 0; i < 100; ++i) x += i;
|
||||
}, 0);
|
||||
Void::Testing::expect(r.total.count() >= 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test bench_run_min_le_mean_le_max()
|
||||
{
|
||||
const auto r = run("timing", 50, [] {
|
||||
volatile int x = 1;
|
||||
do_not_optimize(x);
|
||||
}, 0);
|
||||
Void::Testing::expect(r.min_ns.count() <= static_cast<long long>(r.mean_ns() + 0.5));
|
||||
Void::Testing::expect(r.max_ns.count() >= static_cast<long long>(r.mean_ns()));
|
||||
}
|
||||
|
||||
Void::Testing::Test bench_run_ops_per_sec_positive()
|
||||
{
|
||||
const auto r = run("ops", 100, [] { volatile int x = 0; (void)x; }, 0);
|
||||
Void::Testing::expect(r.ops_per_sec() > 0.0);
|
||||
}
|
||||
|
||||
// ── run_for ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bench_run_for_runs_at_least_once()
|
||||
{
|
||||
const auto r = run_for("short", std::chrono::milliseconds{10}, [] {}, 0);
|
||||
Void::Testing::expect(r.iterations >= 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test bench_run_for_total_within_budget()
|
||||
{
|
||||
const auto budget = std::chrono::milliseconds{20};
|
||||
const auto r = run_for("budget_check", budget, [] {
|
||||
volatile int x = 0; (void)x;
|
||||
}, 0);
|
||||
// Total time should be close to budget (allow 2× for timer imprecision)
|
||||
const auto budget_ns = std::chrono::duration_cast<Duration>(budget * 2);
|
||||
Void::Testing::expect(r.total <= budget_ns);
|
||||
}
|
||||
|
||||
// ── Suite ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bench_suite_collects_results()
|
||||
{
|
||||
Suite s;
|
||||
s.add(run("a", 10, [] {}, 0));
|
||||
s.add(run("b", 10, [] {}, 0));
|
||||
Void::Testing::expect_eq(s.size(), std::size_t{2});
|
||||
Void::Testing::expect_eq(s.results()[0].name, std::string{"a"});
|
||||
Void::Testing::expect_eq(s.results()[1].name, std::string{"b"});
|
||||
}
|
||||
|
||||
// ── do_not_optimize ───────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bench_do_not_optimize_compiles()
|
||||
{
|
||||
int x = 42;
|
||||
do_not_optimize(x);
|
||||
const int y = 7;
|
||||
do_not_optimize(y);
|
||||
Void::Testing::expect_eq(x, 42);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
#include <Void/Bitset/Bitset.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using namespace Void::Bitset;
|
||||
|
||||
// ── basic operations ──────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bitset_default_all_clear()
|
||||
{
|
||||
const Bitset<8> b;
|
||||
Void::Testing::expect(b.none());
|
||||
Void::Testing::expect_eq(b.count(), std::size_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test bitset_set_and_test()
|
||||
{
|
||||
Bitset<16> b;
|
||||
b.set(0);
|
||||
b.set(7);
|
||||
b.set(15);
|
||||
Void::Testing::expect(b.test(0));
|
||||
Void::Testing::expect(b.test(7));
|
||||
Void::Testing::expect(b.test(15));
|
||||
Void::Testing::expect(!b.test(1));
|
||||
Void::Testing::expect_eq(b.count(), std::size_t{3});
|
||||
}
|
||||
|
||||
Void::Testing::Test bitset_reset_clears_bit()
|
||||
{
|
||||
Bitset<8> b;
|
||||
b.set(3);
|
||||
Void::Testing::expect(b.test(3));
|
||||
b.reset(3);
|
||||
Void::Testing::expect(!b.test(3));
|
||||
}
|
||||
|
||||
Void::Testing::Test bitset_flip()
|
||||
{
|
||||
Bitset<8> b;
|
||||
b.set(5);
|
||||
b.flip(5);
|
||||
Void::Testing::expect(!b.test(5));
|
||||
b.flip(5);
|
||||
Void::Testing::expect(b.test(5));
|
||||
}
|
||||
|
||||
Void::Testing::Test bitset_set_all_and_reset_all()
|
||||
{
|
||||
Bitset<64> b;
|
||||
b.set_all();
|
||||
Void::Testing::expect(b.all());
|
||||
Void::Testing::expect_eq(b.count(), std::size_t{64});
|
||||
b.reset_all();
|
||||
Void::Testing::expect(b.none());
|
||||
}
|
||||
|
||||
Void::Testing::Test bitset_flip_all()
|
||||
{
|
||||
Bitset<8> b;
|
||||
b.set(0); b.set(2); b.set(4);
|
||||
b.flip_all();
|
||||
Void::Testing::expect(!b.test(0));
|
||||
Void::Testing::expect(b.test(1));
|
||||
Void::Testing::expect_eq(b.count(), std::size_t{5});
|
||||
}
|
||||
|
||||
Void::Testing::Test bitset_out_of_range_throws()
|
||||
{
|
||||
Bitset<8> b;
|
||||
bool threw = false;
|
||||
try { b.set(8); } catch (...) { threw = true; }
|
||||
Void::Testing::expect(threw);
|
||||
}
|
||||
|
||||
// ── multi-word (N > 64) ───────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bitset_large_set_and_test()
|
||||
{
|
||||
Bitset<128> b;
|
||||
b.set(63);
|
||||
b.set(64);
|
||||
b.set(127);
|
||||
Void::Testing::expect(b.test(63));
|
||||
Void::Testing::expect(b.test(64));
|
||||
Void::Testing::expect(b.test(127));
|
||||
Void::Testing::expect_eq(b.count(), std::size_t{3});
|
||||
}
|
||||
|
||||
// ── bitwise ops ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bitset_and()
|
||||
{
|
||||
Bitset<8> a, b;
|
||||
a.set(0); a.set(1);
|
||||
b.set(1); b.set(2);
|
||||
const auto c = a & b;
|
||||
Void::Testing::expect(!c.test(0));
|
||||
Void::Testing::expect(c.test(1));
|
||||
Void::Testing::expect(!c.test(2));
|
||||
}
|
||||
|
||||
Void::Testing::Test bitset_or()
|
||||
{
|
||||
Bitset<8> a, b;
|
||||
a.set(0); b.set(1);
|
||||
const auto c = a | b;
|
||||
Void::Testing::expect(c.test(0));
|
||||
Void::Testing::expect(c.test(1));
|
||||
}
|
||||
|
||||
Void::Testing::Test bitset_xor()
|
||||
{
|
||||
Bitset<8> a, b;
|
||||
a.set(0); a.set(1);
|
||||
b.set(1); b.set(2);
|
||||
const auto c = a ^ b;
|
||||
Void::Testing::expect(c.test(0));
|
||||
Void::Testing::expect(!c.test(1));
|
||||
Void::Testing::expect(c.test(2));
|
||||
}
|
||||
|
||||
Void::Testing::Test bitset_not()
|
||||
{
|
||||
Bitset<8> a;
|
||||
a.set(0);
|
||||
const auto b = ~a;
|
||||
Void::Testing::expect(!b.test(0));
|
||||
Void::Testing::expect(b.test(1));
|
||||
Void::Testing::expect_eq(b.count(), std::size_t{7});
|
||||
}
|
||||
|
||||
// ── shift ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bitset_shift_left()
|
||||
{
|
||||
Bitset<8> b;
|
||||
b.set(0);
|
||||
const auto s = b << 3;
|
||||
Void::Testing::expect(!s.test(0));
|
||||
Void::Testing::expect(s.test(3));
|
||||
}
|
||||
|
||||
Void::Testing::Test bitset_shift_right()
|
||||
{
|
||||
Bitset<8> b;
|
||||
b.set(5);
|
||||
const auto s = b >> 2;
|
||||
Void::Testing::expect(!s.test(5));
|
||||
Void::Testing::expect(s.test(3));
|
||||
}
|
||||
|
||||
// ── to_string ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bitset_to_string()
|
||||
{
|
||||
Bitset<8> b;
|
||||
b.set(0); // LSB → rightmost in string
|
||||
const auto s = b.to_string();
|
||||
Void::Testing::expect_eq(s.size(), std::size_t{8});
|
||||
Void::Testing::expect_eq(s[7], '1'); // bit 0 is rightmost
|
||||
Void::Testing::expect_eq(s[0], '0');
|
||||
}
|
||||
|
||||
Void::Testing::Test bitset_to_string_all_set()
|
||||
{
|
||||
Bitset<4> b;
|
||||
b.set_all();
|
||||
Void::Testing::expect_eq(b.to_string(), std::string{"1111"});
|
||||
}
|
||||
|
||||
// ── find_first ────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bitset_find_first_set()
|
||||
{
|
||||
Bitset<64> b;
|
||||
b.set(5);
|
||||
b.set(10);
|
||||
Void::Testing::expect_eq(b.find_first(), std::size_t{5});
|
||||
}
|
||||
|
||||
Void::Testing::Test bitset_find_first_none()
|
||||
{
|
||||
const Bitset<64> b;
|
||||
Void::Testing::expect_eq(b.find_first(), std::size_t{64}); // sentinel
|
||||
}
|
||||
|
||||
// ── equality ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bitset_equality()
|
||||
{
|
||||
Bitset<8> a, b, c;
|
||||
a.set(3); b.set(3); c.set(4);
|
||||
Void::Testing::expect(a == b);
|
||||
Void::Testing::expect(a != c);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
#include <Void/Channel/Channel.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Channel;
|
||||
|
||||
// ── non-blocking operations ───────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test channel_try_send_recv()
|
||||
{
|
||||
Channel<int> ch{4};
|
||||
Void::Testing::expect(ch.try_send(1));
|
||||
Void::Testing::expect(ch.try_send(2));
|
||||
const auto v = ch.try_recv();
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect_eq(*v, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test channel_fifo_order()
|
||||
{
|
||||
Channel<int> ch{8};
|
||||
for (int i = 0; i < 5; ++i) ch.try_send(i);
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
const auto v = ch.try_recv();
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect_eq(*v, i);
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test channel_try_send_fails_when_full()
|
||||
{
|
||||
Channel<int> ch{2};
|
||||
Void::Testing::expect(ch.try_send(1));
|
||||
Void::Testing::expect(ch.try_send(2));
|
||||
Void::Testing::expect(!ch.try_send(3)); // full
|
||||
}
|
||||
|
||||
Void::Testing::Test channel_try_recv_empty_returns_nullopt()
|
||||
{
|
||||
Channel<int> ch{4};
|
||||
Void::Testing::expect(!ch.try_recv().has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test channel_size_and_empty()
|
||||
{
|
||||
Channel<int> ch{4};
|
||||
Void::Testing::expect(ch.empty());
|
||||
Void::Testing::expect_eq(ch.size(), std::size_t{0});
|
||||
ch.try_send(1);
|
||||
ch.try_send(2);
|
||||
Void::Testing::expect_eq(ch.size(), std::size_t{2});
|
||||
Void::Testing::expect(!ch.empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test channel_capacity()
|
||||
{
|
||||
Channel<int> ch{16};
|
||||
Void::Testing::expect_eq(ch.capacity(), std::size_t{16});
|
||||
}
|
||||
|
||||
// ── close semantics ───────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test channel_send_after_close_returns_false()
|
||||
{
|
||||
Channel<int> ch{4};
|
||||
ch.close();
|
||||
Void::Testing::expect(!ch.try_send(1));
|
||||
}
|
||||
|
||||
Void::Testing::Test channel_recv_drains_then_nullopt()
|
||||
{
|
||||
Channel<int> ch{4};
|
||||
ch.try_send(10);
|
||||
ch.try_send(20);
|
||||
ch.close();
|
||||
Void::Testing::expect_eq(*ch.try_recv(), 10);
|
||||
Void::Testing::expect_eq(*ch.try_recv(), 20);
|
||||
Void::Testing::expect(!ch.try_recv().has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test channel_closed_flag()
|
||||
{
|
||||
Channel<int> ch{4};
|
||||
Void::Testing::expect(!ch.closed());
|
||||
ch.close();
|
||||
Void::Testing::expect(ch.closed());
|
||||
}
|
||||
|
||||
// ── blocking with threads ─────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test channel_producer_consumer_thread()
|
||||
{
|
||||
Channel<int> ch{16};
|
||||
std::vector<int> received;
|
||||
const int count = 10;
|
||||
|
||||
std::thread producer([&] {
|
||||
for (int i = 0; i < count; ++i) ch.send(i);
|
||||
ch.close();
|
||||
});
|
||||
|
||||
while (auto v = ch.recv())
|
||||
received.push_back(*v);
|
||||
|
||||
producer.join();
|
||||
|
||||
Void::Testing::expect_eq(static_cast<int>(received.size()), count);
|
||||
for (int i = 0; i < count; ++i)
|
||||
Void::Testing::expect_eq(received[i], i);
|
||||
}
|
||||
|
||||
Void::Testing::Test channel_multiple_producers()
|
||||
{
|
||||
Channel<int> ch{64};
|
||||
std::atomic<int> total{0};
|
||||
|
||||
auto producer = [&](int n) {
|
||||
for (int i = 0; i < n; ++i) ch.send(i);
|
||||
};
|
||||
|
||||
std::thread t1(producer, 5);
|
||||
std::thread t2(producer, 5);
|
||||
t1.join();
|
||||
t2.join();
|
||||
ch.close();
|
||||
|
||||
while (auto v = ch.recv()) total += *v;
|
||||
|
||||
// Sum of 0+1+2+3+4 = 10, two producers → 20
|
||||
Void::Testing::expect_eq(total.load(), 20);
|
||||
}
|
||||
|
||||
Void::Testing::Test channel_string_values()
|
||||
{
|
||||
Channel<std::string> ch{4};
|
||||
ch.try_send("hello");
|
||||
ch.try_send("world");
|
||||
Void::Testing::expect_eq(*ch.try_recv(), std::string{"hello"});
|
||||
Void::Testing::expect_eq(*ch.try_recv(), std::string{"world"});
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
#include <Void/Coro/Generator.hpp>
|
||||
#include <Void/Coro/Task.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Coro;
|
||||
|
||||
// ── generator helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
static Generator<int> iota_gen(int start = 0, int step = 1)
|
||||
{
|
||||
while (true) { co_yield start; start += step; }
|
||||
}
|
||||
|
||||
static Generator<int> fibonacci_gen()
|
||||
{
|
||||
int a = 0, b = 1;
|
||||
while (true) {
|
||||
co_yield a;
|
||||
int t = a + b; a = b; b = t;
|
||||
}
|
||||
}
|
||||
|
||||
static Generator<int> finite_gen(int lo, int hi)
|
||||
{
|
||||
for (int i = lo; i < hi; ++i) co_yield i;
|
||||
}
|
||||
|
||||
// ── Generator<T> tests ────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test coro_generator_range_for()
|
||||
{
|
||||
std::vector<int> out;
|
||||
for (int v : take(iota_gen(0), 5))
|
||||
out.push_back(v);
|
||||
Void::Testing::expect_eq(out, std::vector<int>{0, 1, 2, 3, 4});
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_generator_finite()
|
||||
{
|
||||
std::vector<int> out;
|
||||
for (int v : finite_gen(3, 7))
|
||||
out.push_back(v);
|
||||
Void::Testing::expect_eq(out, std::vector<int>{3, 4, 5, 6});
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_generator_fibonacci()
|
||||
{
|
||||
std::vector<int> fibs;
|
||||
for (int v : take(fibonacci_gen(), 8))
|
||||
fibs.push_back(v);
|
||||
Void::Testing::expect_eq(fibs, std::vector<int>{0, 1, 1, 2, 3, 5, 8, 13});
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_generator_take_fewer_than_available()
|
||||
{
|
||||
std::vector<int> out;
|
||||
for (int v : take(iota_gen(10), 3))
|
||||
out.push_back(v);
|
||||
Void::Testing::expect_eq(out.size(), std::size_t{3});
|
||||
Void::Testing::expect_eq(out[0], 10);
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_generator_take_zero()
|
||||
{
|
||||
std::vector<int> out;
|
||||
for (int v : take(iota_gen(), 0))
|
||||
out.push_back(v);
|
||||
Void::Testing::expect(out.empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_generator_filter()
|
||||
{
|
||||
std::vector<int> out;
|
||||
auto evens = filter(take(iota_gen(0), 10), [](int v) { return v % 2 == 0; });
|
||||
for (int v : evens)
|
||||
out.push_back(v);
|
||||
Void::Testing::expect_eq(out, std::vector<int>{0, 2, 4, 6, 8});
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_generator_map()
|
||||
{
|
||||
std::vector<int> out;
|
||||
auto doubled = map(take(iota_gen(1), 5), [](int& v) { return v * 2; });
|
||||
for (int v : doubled)
|
||||
out.push_back(v);
|
||||
Void::Testing::expect_eq(out, std::vector<int>{2, 4, 6, 8, 10});
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_generator_next_pull()
|
||||
{
|
||||
auto g = iota_gen(100);
|
||||
Void::Testing::expect_eq(g.next(), std::optional<int>{100});
|
||||
Void::Testing::expect_eq(g.next(), std::optional<int>{101});
|
||||
Void::Testing::expect_eq(g.next(), std::optional<int>{102});
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_generator_finite_exhaustion()
|
||||
{
|
||||
auto g = finite_gen(0, 2);
|
||||
Void::Testing::expect_eq(g.next(), std::optional<int>{0});
|
||||
Void::Testing::expect_eq(g.next(), std::optional<int>{1});
|
||||
Void::Testing::expect(!g.next().has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_generator_move()
|
||||
{
|
||||
auto g1 = iota_gen(5);
|
||||
auto g2 = std::move(g1);
|
||||
Void::Testing::expect(!g1.valid());
|
||||
Void::Testing::expect_eq(g2.next(), std::optional<int>{5});
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_generator_from_range()
|
||||
{
|
||||
const std::vector<int> v{10, 20, 30};
|
||||
std::vector<int> out;
|
||||
for (int x : from_range(v.begin(), v.end()))
|
||||
out.push_back(x);
|
||||
Void::Testing::expect_eq(out, v);
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_generator_step()
|
||||
{
|
||||
std::vector<int> out;
|
||||
for (int v : take(iota_gen(0, 3), 4))
|
||||
out.push_back(v);
|
||||
Void::Testing::expect_eq(out, std::vector<int>{0, 3, 6, 9});
|
||||
}
|
||||
|
||||
// ── Task<T> tests ─────────────────────────────────────────────────────────────
|
||||
|
||||
static Task<int> simple_task(int x) { co_return x * 2; }
|
||||
static Task<void> void_task(std::string& out) { out = "done"; co_return; }
|
||||
static Task<int> chained_task() { int v = co_await simple_task(5); co_return v + 1; }
|
||||
|
||||
Void::Testing::Test coro_task_returns_value()
|
||||
{
|
||||
Void::Testing::expect_eq(sync_wait(simple_task(7)), 14);
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_task_void()
|
||||
{
|
||||
std::string result;
|
||||
sync_wait(void_task(result));
|
||||
Void::Testing::expect_eq(result, std::string{"done"});
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_task_chain()
|
||||
{
|
||||
// chained_task awaits simple_task(5) → 10, then returns 11
|
||||
Void::Testing::expect_eq(sync_wait(chained_task()), 11);
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_task_exception_propagates()
|
||||
{
|
||||
auto throwing = []() -> Task<int> {
|
||||
throw std::runtime_error{"boom"};
|
||||
co_return 0;
|
||||
};
|
||||
|
||||
bool caught = false;
|
||||
try {
|
||||
sync_wait(throwing());
|
||||
} catch (const std::runtime_error& e) {
|
||||
caught = true;
|
||||
Void::Testing::expect(std::string_view{e.what()} == std::string_view{"boom"});
|
||||
}
|
||||
Void::Testing::expect(caught);
|
||||
}
|
||||
|
||||
Void::Testing::Test coro_task_done_after_run()
|
||||
{
|
||||
auto t = simple_task(3);
|
||||
Void::Testing::expect(!t.done());
|
||||
t.run();
|
||||
Void::Testing::expect(t.done());
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
#include <Void/Counted/Counted.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Counted;
|
||||
|
||||
// ── InstanceCounter ───────────────────────────────────────────────────────────
|
||||
|
||||
struct Widget : InstanceCounter<Widget> {
|
||||
int value;
|
||||
explicit Widget(int v) : value{v} {}
|
||||
};
|
||||
|
||||
struct Gadget : InstanceCounter<Gadget> {};
|
||||
|
||||
Void::Testing::Test instance_counter_starts_at_zero()
|
||||
{
|
||||
// Run in isolation — Widget count may have been affected by other tests.
|
||||
// Check relative behavior instead.
|
||||
const std::size_t before = Widget::instance_count();
|
||||
{
|
||||
Widget w{1};
|
||||
Void::Testing::expect_eq(Widget::instance_count(), before + 1);
|
||||
}
|
||||
Void::Testing::expect_eq(Widget::instance_count(), before);
|
||||
}
|
||||
|
||||
Void::Testing::Test instance_counter_multiple_objects()
|
||||
{
|
||||
const std::size_t before = Widget::instance_count();
|
||||
{
|
||||
Widget a{1}, b{2}, c{3};
|
||||
Void::Testing::expect_eq(Widget::instance_count(), before + 3);
|
||||
}
|
||||
Void::Testing::expect_eq(Widget::instance_count(), before);
|
||||
}
|
||||
|
||||
Void::Testing::Test instance_counter_copy_increments()
|
||||
{
|
||||
const std::size_t before = Widget::instance_count();
|
||||
{
|
||||
Widget a{1};
|
||||
Widget b = a; // copy
|
||||
Void::Testing::expect_eq(Widget::instance_count(), before + 2);
|
||||
}
|
||||
Void::Testing::expect_eq(Widget::instance_count(), before);
|
||||
}
|
||||
|
||||
Void::Testing::Test instance_counter_separate_per_type()
|
||||
{
|
||||
const std::size_t widgets_before = Widget::instance_count();
|
||||
const std::size_t gadgets_before = Gadget::instance_count();
|
||||
{
|
||||
Widget w{42};
|
||||
Gadget g;
|
||||
Void::Testing::expect_eq(Widget::instance_count(), widgets_before + 1);
|
||||
Void::Testing::expect_eq(Gadget::instance_count(), gadgets_before + 1);
|
||||
}
|
||||
Void::Testing::expect_eq(Gadget::instance_count(), gadgets_before);
|
||||
}
|
||||
|
||||
// ── AtomicCounter ─────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test atomic_counter_initial_value()
|
||||
{
|
||||
AtomicCounter c;
|
||||
Void::Testing::expect_eq(c.get(), std::size_t{0});
|
||||
AtomicCounter c2{10};
|
||||
Void::Testing::expect_eq(c2.get(), std::size_t{10});
|
||||
}
|
||||
|
||||
Void::Testing::Test atomic_counter_increment()
|
||||
{
|
||||
AtomicCounter c;
|
||||
c.increment();
|
||||
c.increment(5);
|
||||
Void::Testing::expect_eq(c.get(), std::size_t{6});
|
||||
}
|
||||
|
||||
Void::Testing::Test atomic_counter_decrement()
|
||||
{
|
||||
AtomicCounter c{10};
|
||||
c.decrement(3);
|
||||
Void::Testing::expect_eq(c.get(), std::size_t{7});
|
||||
}
|
||||
|
||||
Void::Testing::Test atomic_counter_reset()
|
||||
{
|
||||
AtomicCounter c{100};
|
||||
c.reset();
|
||||
Void::Testing::expect_eq(c.get(), std::size_t{0});
|
||||
c.reset(42);
|
||||
Void::Testing::expect_eq(c.get(), std::size_t{42});
|
||||
}
|
||||
|
||||
Void::Testing::Test atomic_counter_prefix_operators()
|
||||
{
|
||||
AtomicCounter c{5};
|
||||
++c;
|
||||
Void::Testing::expect_eq(c.get(), std::size_t{6});
|
||||
--c;
|
||||
Void::Testing::expect_eq(c.get(), std::size_t{5});
|
||||
}
|
||||
|
||||
Void::Testing::Test atomic_counter_postfix_returns_old()
|
||||
{
|
||||
AtomicCounter c{3};
|
||||
const auto old_inc = c++;
|
||||
Void::Testing::expect_eq(old_inc, std::size_t{3});
|
||||
Void::Testing::expect_eq(c.get(), std::size_t{4});
|
||||
}
|
||||
|
||||
Void::Testing::Test atomic_counter_thread_safe_increment()
|
||||
{
|
||||
AtomicCounter c;
|
||||
constexpr int threads = 4;
|
||||
constexpr int per_thread = 1000;
|
||||
|
||||
std::vector<std::thread> ts;
|
||||
ts.reserve(threads);
|
||||
for (int i = 0; i < threads; ++i)
|
||||
ts.emplace_back([&] { for (int j = 0; j < per_thread; ++j) c.increment(); });
|
||||
for (auto& t : ts) t.join();
|
||||
|
||||
Void::Testing::expect_eq(c.get(), std::size_t{threads * per_thread});
|
||||
}
|
||||
|
||||
// ── SeqId ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test seq_id_monotonic()
|
||||
{
|
||||
struct MyTag {};
|
||||
SeqId<MyTag> a, b, c;
|
||||
Void::Testing::expect(a.id() < b.id());
|
||||
Void::Testing::expect(b.id() < c.id());
|
||||
}
|
||||
|
||||
Void::Testing::Test seq_id_unique_per_tag()
|
||||
{
|
||||
struct TagA {};
|
||||
struct TagB {};
|
||||
SeqId<TagA> a1, a2;
|
||||
SeqId<TagB> b1;
|
||||
// TagA and TagB sequences are independent
|
||||
Void::Testing::expect(a1.id() != b1.id() || a2.id() != b1.id()); // at least one differs
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
#include <Void/Curry/Curry.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using namespace Void::Curry;
|
||||
|
||||
// ── curry ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test curry_binary_full_apply()
|
||||
{
|
||||
auto add = curry([](int a, int b) { return a + b; });
|
||||
Void::Testing::expect_eq(add(3)(4), 7);
|
||||
}
|
||||
|
||||
Void::Testing::Test curry_binary_partial_then_complete()
|
||||
{
|
||||
auto add = curry([](int a, int b) { return a + b; });
|
||||
auto add10 = add(10);
|
||||
Void::Testing::expect_eq(add10(5), 15);
|
||||
Void::Testing::expect_eq(add10(20), 30);
|
||||
}
|
||||
|
||||
Void::Testing::Test curry_ternary()
|
||||
{
|
||||
auto sum3 = curry([](int a, int b, int c) { return a + b + c; });
|
||||
Void::Testing::expect_eq(sum3(1)(2)(3), 6);
|
||||
}
|
||||
|
||||
Void::Testing::Test curry_ternary_partial_twice()
|
||||
{
|
||||
auto sum3 = curry([](int a, int b, int c) { return a + b + c; });
|
||||
const auto sum3_with_1 = sum3(1);
|
||||
const auto sum3_with_1_2 = sum3_with_1(2);
|
||||
Void::Testing::expect_eq(sum3_with_1_2(10), 13);
|
||||
}
|
||||
|
||||
Void::Testing::Test curry_type_change()
|
||||
{
|
||||
auto prefix = curry([](std::string p, std::string s) { return p + s; });
|
||||
const auto add_hello = prefix(std::string{"hello "});
|
||||
Void::Testing::expect_eq(add_hello(std::string{"world"}), std::string{"hello world"});
|
||||
}
|
||||
|
||||
Void::Testing::Test curry_unary_invokes_immediately()
|
||||
{
|
||||
auto square = curry([](int x) { return x * x; });
|
||||
Void::Testing::expect_eq(square(5), 25);
|
||||
}
|
||||
|
||||
Void::Testing::Test curry_reuse_partial()
|
||||
{
|
||||
auto mul = curry([](int a, int b) { return a * b; });
|
||||
const auto triple = mul(3);
|
||||
Void::Testing::expect_eq(triple(4), 12);
|
||||
Void::Testing::expect_eq(triple(5), 15);
|
||||
Void::Testing::expect_eq(triple(6), 18);
|
||||
}
|
||||
|
||||
Void::Testing::Test curry_with_lambda_capture()
|
||||
{
|
||||
int offset = 100;
|
||||
auto add_offset = curry([&](int a, int b) { return a + b + offset; });
|
||||
Void::Testing::expect_eq(add_offset(1)(2), 103);
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
#include <Void/Diff/Diff.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Diff;
|
||||
|
||||
// ── integer sequence diff ─────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test diff_identical_sequences()
|
||||
{
|
||||
const std::vector<int> a{1, 2, 3};
|
||||
const auto edits = diff(a, a);
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Delete), std::size_t{0});
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Insert), std::size_t{0});
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Equal), std::size_t{3});
|
||||
}
|
||||
|
||||
Void::Testing::Test diff_empty_to_nonempty()
|
||||
{
|
||||
const std::vector<int> a{};
|
||||
const std::vector<int> b{1, 2, 3};
|
||||
const auto edits = diff(a, b);
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Insert), std::size_t{3});
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Delete), std::size_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test diff_nonempty_to_empty()
|
||||
{
|
||||
const std::vector<int> a{1, 2};
|
||||
const std::vector<int> b{};
|
||||
const auto edits = diff(a, b);
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Delete), std::size_t{2});
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Insert), std::size_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test diff_single_insert()
|
||||
{
|
||||
const std::vector<int> a{1, 3};
|
||||
const std::vector<int> b{1, 2, 3};
|
||||
const auto edits = diff(a, b);
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Insert), std::size_t{1});
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Equal), std::size_t{2});
|
||||
}
|
||||
|
||||
Void::Testing::Test diff_single_delete()
|
||||
{
|
||||
const std::vector<int> a{1, 2, 3};
|
||||
const std::vector<int> b{1, 3};
|
||||
const auto edits = diff(a, b);
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Delete), std::size_t{1});
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Equal), std::size_t{2});
|
||||
}
|
||||
|
||||
Void::Testing::Test diff_substitution()
|
||||
{
|
||||
const std::vector<int> a{1, 2, 3};
|
||||
const std::vector<int> b{1, 9, 3};
|
||||
const auto edits = diff(a, b);
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Delete), std::size_t{1});
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Insert), std::size_t{1});
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Equal), std::size_t{2});
|
||||
}
|
||||
|
||||
Void::Testing::Test diff_apply_reconstructs_b()
|
||||
{
|
||||
const std::vector<int> a{1, 2, 3, 4, 5};
|
||||
const std::vector<int> b{1, 3, 5, 6};
|
||||
const auto edits = diff(a, b);
|
||||
const auto result = apply(edits);
|
||||
Void::Testing::expect_eq(result, b);
|
||||
}
|
||||
|
||||
Void::Testing::Test diff_completely_different()
|
||||
{
|
||||
const std::vector<int> a{1, 2, 3};
|
||||
const std::vector<int> b{4, 5, 6};
|
||||
const auto edits = diff(a, b);
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Equal), std::size_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test diff_empty_both()
|
||||
{
|
||||
const std::vector<int> a{}, b{};
|
||||
const auto edits = diff(a, b);
|
||||
Void::Testing::expect(edits.empty());
|
||||
}
|
||||
|
||||
// ── string sequence diff ──────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test diff_string_chars()
|
||||
{
|
||||
const std::vector<char> a{'a', 'b', 'c'};
|
||||
const std::vector<char> b{'a', 'x', 'c'};
|
||||
const auto edits = diff(a, b);
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Equal), std::size_t{2});
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Delete), std::size_t{1});
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Insert), std::size_t{1});
|
||||
}
|
||||
|
||||
// ── line diff ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test diff_line_diff_identical()
|
||||
{
|
||||
const auto edits = line_diff("a\nb\nc", "a\nb\nc");
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Insert), std::size_t{0});
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Delete), std::size_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test diff_line_diff_insert_line()
|
||||
{
|
||||
const auto edits = line_diff("a\nc", "a\nb\nc");
|
||||
Void::Testing::expect_eq(count_op(edits, Op::Insert), std::size_t{1});
|
||||
}
|
||||
|
||||
Void::Testing::Test diff_format_patch()
|
||||
{
|
||||
const auto edits = line_diff("a\nb", "a\nc");
|
||||
const auto patch = format_patch(edits);
|
||||
Void::Testing::expect(patch.find('-') != std::string::npos);
|
||||
Void::Testing::expect(patch.find('+') != std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test diff_apply_line_reconstructs_b()
|
||||
{
|
||||
const std::string a = "foo\nbar\nbaz";
|
||||
const std::string b = "foo\nqux\nbaz";
|
||||
const auto edits = line_diff(a, b);
|
||||
const auto result_lines = apply(edits);
|
||||
Void::Testing::expect_eq(result_lines.size(), std::size_t{3});
|
||||
Void::Testing::expect_eq(result_lines[1], std::string{"qux"});
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
#include <Void/DisjointSet/DisjointSet.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
using namespace Void::DisjointSet;
|
||||
|
||||
Void::Testing::Test disjoint_initial_state()
|
||||
{
|
||||
DisjointSet ds{5};
|
||||
Void::Testing::expect_eq(ds.count(), std::size_t{5});
|
||||
Void::Testing::expect_eq(ds.size(), std::size_t{5});
|
||||
}
|
||||
|
||||
Void::Testing::Test disjoint_each_element_own_component()
|
||||
{
|
||||
DisjointSet ds{4};
|
||||
for (std::size_t i = 0; i < 4; ++i)
|
||||
for (std::size_t j = i + 1; j < 4; ++j)
|
||||
Void::Testing::expect(!ds.connected(i, j));
|
||||
}
|
||||
|
||||
Void::Testing::Test disjoint_unite_reduces_count()
|
||||
{
|
||||
DisjointSet ds{5};
|
||||
ds.unite(0, 1);
|
||||
Void::Testing::expect_eq(ds.count(), std::size_t{4});
|
||||
ds.unite(1, 2);
|
||||
Void::Testing::expect_eq(ds.count(), std::size_t{3});
|
||||
}
|
||||
|
||||
Void::Testing::Test disjoint_unite_already_connected_noop()
|
||||
{
|
||||
DisjointSet ds{3};
|
||||
ds.unite(0, 1);
|
||||
const bool merged = ds.unite(0, 1);
|
||||
Void::Testing::expect(!merged);
|
||||
Void::Testing::expect_eq(ds.count(), std::size_t{2});
|
||||
}
|
||||
|
||||
Void::Testing::Test disjoint_transitivity()
|
||||
{
|
||||
DisjointSet ds{5};
|
||||
ds.unite(0, 1);
|
||||
ds.unite(1, 2);
|
||||
Void::Testing::expect(ds.connected(0, 2));
|
||||
Void::Testing::expect(!ds.connected(0, 3));
|
||||
}
|
||||
|
||||
Void::Testing::Test disjoint_unite_returns_true_first_time()
|
||||
{
|
||||
DisjointSet ds{4};
|
||||
Void::Testing::expect(ds.unite(2, 3));
|
||||
Void::Testing::expect(!ds.unite(2, 3));
|
||||
}
|
||||
|
||||
Void::Testing::Test disjoint_full_merge_one_component()
|
||||
{
|
||||
DisjointSet ds{5};
|
||||
for (std::size_t i = 1; i < 5; ++i) ds.unite(0, i);
|
||||
Void::Testing::expect_eq(ds.count(), std::size_t{1});
|
||||
Void::Testing::expect(ds.connected(0, 4));
|
||||
}
|
||||
|
||||
Void::Testing::Test disjoint_component_size()
|
||||
{
|
||||
DisjointSet ds{6};
|
||||
ds.unite(0, 1);
|
||||
ds.unite(1, 2);
|
||||
Void::Testing::expect_eq(ds.component_size(0), std::size_t{3});
|
||||
Void::Testing::expect_eq(ds.component_size(3), std::size_t{1});
|
||||
}
|
||||
|
||||
Void::Testing::Test disjoint_out_of_range_throws()
|
||||
{
|
||||
DisjointSet ds{3};
|
||||
bool threw = false;
|
||||
try { [[maybe_unused]] auto r = ds.find(10); } catch (...) { threw = true; }
|
||||
Void::Testing::expect(threw);
|
||||
}
|
||||
|
||||
Void::Testing::Test disjoint_graph_connectivity()
|
||||
{
|
||||
// Graph: 0-1, 2-3, 3-4 → two components {0,1} and {2,3,4}
|
||||
DisjointSet ds{5};
|
||||
ds.unite(0, 1);
|
||||
ds.unite(2, 3);
|
||||
ds.unite(3, 4);
|
||||
Void::Testing::expect_eq(ds.count(), std::size_t{2});
|
||||
Void::Testing::expect(ds.connected(2, 4));
|
||||
Void::Testing::expect(!ds.connected(1, 4));
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
#include <Void/Either/Either.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using namespace Void::Either;
|
||||
using E = Either<std::string, int>;
|
||||
|
||||
// ── construction & query ──────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test either_left_is_left()
|
||||
{
|
||||
const auto e = E::left("error");
|
||||
Void::Testing::expect(e.is_left());
|
||||
Void::Testing::expect(!e.is_right());
|
||||
Void::Testing::expect_eq(e.left_value(), std::string{"error"});
|
||||
}
|
||||
|
||||
Void::Testing::Test either_right_is_right()
|
||||
{
|
||||
const auto e = E::right(42);
|
||||
Void::Testing::expect(e.is_right());
|
||||
Void::Testing::expect(!e.is_left());
|
||||
Void::Testing::expect_eq(e.right_value(), 42);
|
||||
}
|
||||
|
||||
// ── map ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test either_map_transforms_right()
|
||||
{
|
||||
const auto e = E::right(5);
|
||||
const auto m = e.map([](int x) { return x * 2; });
|
||||
Void::Testing::expect(m.is_right());
|
||||
Void::Testing::expect_eq(m.right_value(), 10);
|
||||
}
|
||||
|
||||
Void::Testing::Test either_map_skips_left()
|
||||
{
|
||||
const auto e = E::left("fail");
|
||||
const auto m = e.map([](int x) { return x * 2; });
|
||||
Void::Testing::expect(m.is_left());
|
||||
Void::Testing::expect_eq(m.left_value(), std::string{"fail"});
|
||||
}
|
||||
|
||||
Void::Testing::Test either_map_left_transforms_left()
|
||||
{
|
||||
const auto e = E::left("err");
|
||||
const auto m = e.map_left([](const std::string& s) { return s.size(); });
|
||||
Void::Testing::expect(m.is_left());
|
||||
Void::Testing::expect_eq(m.left_value(), std::size_t{3});
|
||||
}
|
||||
|
||||
Void::Testing::Test either_map_left_skips_right()
|
||||
{
|
||||
const auto e = E::right(7);
|
||||
const auto m = e.map_left([](const std::string& s) { return s.size(); });
|
||||
Void::Testing::expect(m.is_right());
|
||||
Void::Testing::expect_eq(m.right_value(), 7);
|
||||
}
|
||||
|
||||
// ── fold ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test either_fold_right()
|
||||
{
|
||||
const auto e = E::right(10);
|
||||
const auto v = e.fold(
|
||||
[](const std::string&) { return -1; },
|
||||
[](int x) { return x + 1; });
|
||||
Void::Testing::expect_eq(v, 11);
|
||||
}
|
||||
|
||||
Void::Testing::Test either_fold_left()
|
||||
{
|
||||
const auto e = E::left("oops");
|
||||
const auto v = e.fold(
|
||||
[](const std::string& s) { return static_cast<int>(s.size()); },
|
||||
[](int x) { return x; });
|
||||
Void::Testing::expect_eq(v, 4);
|
||||
}
|
||||
|
||||
// ── equality ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test either_equality_right()
|
||||
{
|
||||
const auto a = E::right(1);
|
||||
const auto b = E::right(1);
|
||||
const auto c = E::right(2);
|
||||
Void::Testing::expect(a == b);
|
||||
Void::Testing::expect(!(a == c));
|
||||
}
|
||||
|
||||
Void::Testing::Test either_equality_left_vs_right()
|
||||
{
|
||||
const auto a = E::left("x");
|
||||
const auto b = E::right(0);
|
||||
Void::Testing::expect(!(a == b));
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
#include <Void/EventBus/EventBus.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using namespace Void::EventBus;
|
||||
|
||||
struct Clicked { int x, y; };
|
||||
struct TextChanged { std::string text; };
|
||||
|
||||
// ── subscribe / publish ───────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bus_publish_reaches_subscriber()
|
||||
{
|
||||
EventBus bus;
|
||||
int received = 0;
|
||||
bus.subscribe<Clicked>([&](const Clicked& e) { received = e.x; });
|
||||
bus.publish(Clicked{42, 0});
|
||||
Void::Testing::expect_eq(received, 42);
|
||||
}
|
||||
|
||||
Void::Testing::Test bus_multiple_subscribers_same_type()
|
||||
{
|
||||
EventBus bus;
|
||||
int count = 0;
|
||||
bus.subscribe<Clicked>([&](const Clicked&) { ++count; });
|
||||
bus.subscribe<Clicked>([&](const Clicked&) { ++count; });
|
||||
bus.publish(Clicked{0, 0});
|
||||
Void::Testing::expect_eq(count, 2);
|
||||
}
|
||||
|
||||
Void::Testing::Test bus_different_event_types_isolated()
|
||||
{
|
||||
EventBus bus;
|
||||
bool got_click = false;
|
||||
bool got_text = false;
|
||||
bus.subscribe<Clicked>([&](const Clicked&) { got_click = true; });
|
||||
bus.subscribe<TextChanged>([&](const TextChanged&) { got_text = true; });
|
||||
bus.publish(Clicked{0, 0});
|
||||
Void::Testing::expect(got_click);
|
||||
Void::Testing::expect(!got_text);
|
||||
}
|
||||
|
||||
Void::Testing::Test bus_no_subscribers_publish_is_noop()
|
||||
{
|
||||
EventBus bus;
|
||||
bus.publish(Clicked{1, 2});
|
||||
}
|
||||
|
||||
// ── unsubscribe ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bus_unsubscribe_stops_delivery()
|
||||
{
|
||||
EventBus bus;
|
||||
int count = 0;
|
||||
const auto id = bus.subscribe<Clicked>([&](const Clicked&) { ++count; });
|
||||
bus.publish(Clicked{});
|
||||
bus.unsubscribe(id);
|
||||
bus.publish(Clicked{});
|
||||
Void::Testing::expect_eq(count, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test bus_unsubscribe_nonexistent_is_noop()
|
||||
{
|
||||
EventBus bus;
|
||||
bus.unsubscribe(999);
|
||||
}
|
||||
|
||||
// ── clear ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bus_clear_event_type()
|
||||
{
|
||||
EventBus bus;
|
||||
int count = 0;
|
||||
bus.subscribe<Clicked>([&](const Clicked&) { ++count; });
|
||||
bus.clear<Clicked>();
|
||||
bus.publish(Clicked{});
|
||||
Void::Testing::expect_eq(count, 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test bus_clear_all()
|
||||
{
|
||||
EventBus bus;
|
||||
int a = 0, b = 0;
|
||||
bus.subscribe<Clicked>([&](const Clicked&) { ++a; });
|
||||
bus.subscribe<TextChanged>([&](const TextChanged&) { ++b; });
|
||||
bus.clear_all();
|
||||
bus.publish(Clicked{});
|
||||
bus.publish(TextChanged{});
|
||||
Void::Testing::expect_eq(a, 0);
|
||||
Void::Testing::expect_eq(b, 0);
|
||||
}
|
||||
|
||||
// ── subscriber_count ──────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bus_subscriber_count()
|
||||
{
|
||||
EventBus bus;
|
||||
Void::Testing::expect_eq(bus.subscriber_count<Clicked>(), std::size_t{0});
|
||||
bus.subscribe<Clicked>([](const Clicked&) {});
|
||||
bus.subscribe<Clicked>([](const Clicked&) {});
|
||||
Void::Testing::expect_eq(bus.subscriber_count<Clicked>(), std::size_t{2});
|
||||
}
|
||||
|
||||
// ── event data forwarded correctly ────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test bus_event_data_forwarded()
|
||||
{
|
||||
EventBus bus;
|
||||
std::string received;
|
||||
bus.subscribe<TextChanged>([&](const TextChanged& e) { received = e.text; });
|
||||
bus.publish(TextChanged{"hello"});
|
||||
Void::Testing::expect_eq(received, std::string{"hello"});
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
#include <Void/Flags/Flags.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
using namespace Void::Flags;
|
||||
|
||||
enum class Perm : unsigned { Read = 1, Write = 2, Exec = 4 };
|
||||
|
||||
// ── construction ──────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test flags_default_is_empty()
|
||||
{
|
||||
const Flags<Perm> f;
|
||||
Void::Testing::expect(f.none());
|
||||
Void::Testing::expect(!f.any());
|
||||
}
|
||||
|
||||
Void::Testing::Test flags_single_bit()
|
||||
{
|
||||
const Flags<Perm> f{Perm::Read};
|
||||
Void::Testing::expect(f.test(Perm::Read));
|
||||
Void::Testing::expect(!f.test(Perm::Write));
|
||||
}
|
||||
|
||||
Void::Testing::Test flags_initializer_list()
|
||||
{
|
||||
const Flags<Perm> f{Perm::Read, Perm::Write};
|
||||
Void::Testing::expect(f.test(Perm::Read));
|
||||
Void::Testing::expect(f.test(Perm::Write));
|
||||
Void::Testing::expect(!f.test(Perm::Exec));
|
||||
}
|
||||
|
||||
Void::Testing::Test flags_make_flags()
|
||||
{
|
||||
const auto f = make_flags({Perm::Read, Perm::Exec});
|
||||
Void::Testing::expect(f.test(Perm::Read));
|
||||
Void::Testing::expect(!f.test(Perm::Write));
|
||||
Void::Testing::expect(f.test(Perm::Exec));
|
||||
}
|
||||
|
||||
// ── query ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test flags_all()
|
||||
{
|
||||
const Flags<Perm> f{Perm::Read, Perm::Write};
|
||||
Void::Testing::expect(f.all(Flags<Perm>{Perm::Read}));
|
||||
Void::Testing::expect(f.all(Flags<Perm>{Perm::Read, Perm::Write}));
|
||||
Void::Testing::expect(!f.all(Flags<Perm>{Perm::Read, Perm::Write, Perm::Exec}));
|
||||
}
|
||||
|
||||
Void::Testing::Test flags_any_of()
|
||||
{
|
||||
const Flags<Perm> f{Perm::Read};
|
||||
Void::Testing::expect(f.any_of(Flags<Perm>{Perm::Read, Perm::Exec}));
|
||||
Void::Testing::expect(!f.any_of(Flags<Perm>{Perm::Write, Perm::Exec}));
|
||||
}
|
||||
|
||||
// ── mutation ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test flags_set_unset()
|
||||
{
|
||||
Flags<Perm> f;
|
||||
f.set(Perm::Read);
|
||||
Void::Testing::expect(f.test(Perm::Read));
|
||||
f.unset(Perm::Read);
|
||||
Void::Testing::expect(!f.test(Perm::Read));
|
||||
}
|
||||
|
||||
Void::Testing::Test flags_toggle()
|
||||
{
|
||||
Flags<Perm> f{Perm::Write};
|
||||
f.toggle(Perm::Write);
|
||||
Void::Testing::expect(!f.test(Perm::Write));
|
||||
f.toggle(Perm::Write);
|
||||
Void::Testing::expect(f.test(Perm::Write));
|
||||
}
|
||||
|
||||
Void::Testing::Test flags_clear()
|
||||
{
|
||||
Flags<Perm> f{Perm::Read, Perm::Write, Perm::Exec};
|
||||
f.clear();
|
||||
Void::Testing::expect(f.none());
|
||||
}
|
||||
|
||||
// ── operators ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test flags_or_operator()
|
||||
{
|
||||
const auto f = Flags<Perm>{Perm::Read} | Perm::Write;
|
||||
Void::Testing::expect(f.test(Perm::Read));
|
||||
Void::Testing::expect(f.test(Perm::Write));
|
||||
}
|
||||
|
||||
Void::Testing::Test flags_and_operator()
|
||||
{
|
||||
const Flags<Perm> a{Perm::Read, Perm::Write};
|
||||
const Flags<Perm> b{Perm::Write, Perm::Exec};
|
||||
const auto c = a & b;
|
||||
Void::Testing::expect(!c.test(Perm::Read));
|
||||
Void::Testing::expect(c.test(Perm::Write));
|
||||
Void::Testing::expect(!c.test(Perm::Exec));
|
||||
}
|
||||
|
||||
Void::Testing::Test flags_xor_operator()
|
||||
{
|
||||
const Flags<Perm> a{Perm::Read, Perm::Write};
|
||||
const Flags<Perm> b{Perm::Write, Perm::Exec};
|
||||
const auto c = a ^ b;
|
||||
Void::Testing::expect(c.test(Perm::Read));
|
||||
Void::Testing::expect(!c.test(Perm::Write));
|
||||
Void::Testing::expect(c.test(Perm::Exec));
|
||||
}
|
||||
|
||||
Void::Testing::Test flags_or_two_enums()
|
||||
{
|
||||
const auto f = Perm::Read | Perm::Exec;
|
||||
Void::Testing::expect(f.test(Perm::Read));
|
||||
Void::Testing::expect(!f.test(Perm::Write));
|
||||
Void::Testing::expect(f.test(Perm::Exec));
|
||||
}
|
||||
|
||||
Void::Testing::Test flags_equality()
|
||||
{
|
||||
const Flags<Perm> a{Perm::Read, Perm::Write};
|
||||
const Flags<Perm> b{Perm::Read, Perm::Write};
|
||||
const Flags<Perm> c{Perm::Read};
|
||||
Void::Testing::expect(a == b);
|
||||
Void::Testing::expect(!(a == c));
|
||||
}
|
||||
|
||||
Void::Testing::Test flags_bool_conversion()
|
||||
{
|
||||
const Flags<Perm> empty;
|
||||
const Flags<Perm> nonempty{Perm::Read};
|
||||
Void::Testing::expect(!static_cast<bool>(empty));
|
||||
Void::Testing::expect(static_cast<bool>(nonempty));
|
||||
}
|
||||
|
||||
Void::Testing::Test flags_raw_value()
|
||||
{
|
||||
const Flags<Perm> f{Perm::Read, Perm::Exec};
|
||||
Void::Testing::expect_eq(f.raw(), unsigned{5});
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
#include <Void/Histogram/Histogram.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Histogram;
|
||||
|
||||
// ── Histogram<K> ──────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test histogram_add_and_count()
|
||||
{
|
||||
Histogram<std::string> h;
|
||||
h.add("a");
|
||||
h.add("a");
|
||||
h.add("b");
|
||||
Void::Testing::expect_eq(h.count("a"), std::size_t{2});
|
||||
Void::Testing::expect_eq(h.count("b"), std::size_t{1});
|
||||
Void::Testing::expect_eq(h.count("c"), std::size_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test histogram_total_and_distinct()
|
||||
{
|
||||
Histogram<int> h;
|
||||
h.add(1); h.add(2); h.add(1); h.add(3);
|
||||
Void::Testing::expect_eq(h.total(), std::size_t{4});
|
||||
Void::Testing::expect_eq(h.distinct(), std::size_t{3});
|
||||
}
|
||||
|
||||
Void::Testing::Test histogram_add_with_count()
|
||||
{
|
||||
Histogram<std::string> h;
|
||||
h.add("x", 5);
|
||||
Void::Testing::expect_eq(h.count("x"), std::size_t{5});
|
||||
Void::Testing::expect_eq(h.total(), std::size_t{5});
|
||||
}
|
||||
|
||||
Void::Testing::Test histogram_frequency()
|
||||
{
|
||||
Histogram<int> h;
|
||||
h.add(1, 3);
|
||||
h.add(2, 1);
|
||||
const double f = h.frequency(1);
|
||||
Void::Testing::expect(f > 0.74 && f < 0.76); // 3/4
|
||||
}
|
||||
|
||||
Void::Testing::Test histogram_mode()
|
||||
{
|
||||
Histogram<std::string> h;
|
||||
h.add("a", 3);
|
||||
h.add("b", 5);
|
||||
h.add("c", 1);
|
||||
const auto m = h.mode();
|
||||
Void::Testing::expect(m.has_value());
|
||||
Void::Testing::expect_eq(*m, std::string{"b"});
|
||||
}
|
||||
|
||||
Void::Testing::Test histogram_least_common()
|
||||
{
|
||||
Histogram<int> h;
|
||||
h.add(1, 10);
|
||||
h.add(2, 1);
|
||||
h.add(3, 5);
|
||||
const auto lc = h.least_common();
|
||||
Void::Testing::expect(lc.has_value());
|
||||
Void::Testing::expect_eq(*lc, 2);
|
||||
}
|
||||
|
||||
Void::Testing::Test histogram_mode_empty_returns_nullopt()
|
||||
{
|
||||
Histogram<int> h;
|
||||
Void::Testing::expect(!h.mode().has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test histogram_top_k()
|
||||
{
|
||||
Histogram<int> h;
|
||||
h.add(1, 3);
|
||||
h.add(2, 10);
|
||||
h.add(3, 5);
|
||||
h.add(4, 1);
|
||||
const auto top = h.top_k(2);
|
||||
Void::Testing::expect_eq(top.size(), std::size_t{2});
|
||||
Void::Testing::expect_eq(top[0].first, 2); // highest count first
|
||||
Void::Testing::expect_eq(top[0].second, std::size_t{10});
|
||||
}
|
||||
|
||||
Void::Testing::Test histogram_erase()
|
||||
{
|
||||
Histogram<int> h;
|
||||
h.add(1, 5);
|
||||
h.add(2, 3);
|
||||
Void::Testing::expect(h.erase(1));
|
||||
Void::Testing::expect(!h.contains(1));
|
||||
Void::Testing::expect_eq(h.total(), std::size_t{3});
|
||||
Void::Testing::expect(!h.erase(99));
|
||||
}
|
||||
|
||||
Void::Testing::Test histogram_clear()
|
||||
{
|
||||
Histogram<int> h;
|
||||
h.add(1); h.add(2);
|
||||
h.clear();
|
||||
Void::Testing::expect(h.empty());
|
||||
Void::Testing::expect_eq(h.total(), std::size_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test histogram_merge()
|
||||
{
|
||||
Histogram<std::string> a, b;
|
||||
a.add("x", 3);
|
||||
b.add("x", 2);
|
||||
b.add("y", 1);
|
||||
a.merge(b);
|
||||
Void::Testing::expect_eq(a.count("x"), std::size_t{5});
|
||||
Void::Testing::expect_eq(a.count("y"), std::size_t{1});
|
||||
Void::Testing::expect_eq(a.total(), std::size_t{6});
|
||||
}
|
||||
|
||||
// ── FixedBinHistogram ─────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test fixed_bin_basic_add()
|
||||
{
|
||||
FixedBinHistogram h{0.0, 10.0, 10};
|
||||
h.add(0.5); // bin 0
|
||||
h.add(1.5); // bin 1
|
||||
h.add(9.9); // bin 9
|
||||
Void::Testing::expect_eq(h.bin_count(0), std::size_t{1});
|
||||
Void::Testing::expect_eq(h.bin_count(1), std::size_t{1});
|
||||
Void::Testing::expect_eq(h.bin_count(9), std::size_t{1});
|
||||
Void::Testing::expect_eq(h.total(), std::size_t{3});
|
||||
}
|
||||
|
||||
Void::Testing::Test fixed_bin_clamping()
|
||||
{
|
||||
FixedBinHistogram h{0.0, 5.0, 5};
|
||||
h.add(-1.0); // clamp to bin 0
|
||||
h.add(10.0); // clamp to last bin
|
||||
Void::Testing::expect_eq(h.bin_count(0), std::size_t{1});
|
||||
Void::Testing::expect_eq(h.bin_count(4), std::size_t{1});
|
||||
}
|
||||
|
||||
Void::Testing::Test fixed_bin_width()
|
||||
{
|
||||
FixedBinHistogram h{0.0, 10.0, 5};
|
||||
Void::Testing::expect(h.width() > 1.99 && h.width() < 2.01);
|
||||
}
|
||||
|
||||
Void::Testing::Test fixed_bin_invalid_args()
|
||||
{
|
||||
bool threw = false;
|
||||
try { FixedBinHistogram h{5.0, 3.0, 4}; } catch (...) { threw = true; }
|
||||
Void::Testing::expect(threw);
|
||||
threw = false;
|
||||
try { FixedBinHistogram h{0.0, 10.0, 0}; } catch (...) { threw = true; }
|
||||
Void::Testing::expect(threw);
|
||||
}
|
||||
|
||||
Void::Testing::Test fixed_bin_clear()
|
||||
{
|
||||
FixedBinHistogram h{0.0, 10.0, 5};
|
||||
h.add(1.0); h.add(5.0);
|
||||
h.clear();
|
||||
Void::Testing::expect_eq(h.total(), std::size_t{0});
|
||||
Void::Testing::expect_eq(h.bin_count(0), std::size_t{0});
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
#include <Void/Interval/Interval.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
using namespace Void::Interval;
|
||||
|
||||
// ── contains ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test interval_contains_midpoint()
|
||||
{
|
||||
const auto iv = make_interval(0, 10);
|
||||
Void::Testing::expect(iv.contains(5));
|
||||
Void::Testing::expect(iv.contains(0));
|
||||
Void::Testing::expect(!iv.contains(10));
|
||||
}
|
||||
|
||||
Void::Testing::Test interval_contains_closed()
|
||||
{
|
||||
const auto iv = make_interval(0, 10);
|
||||
Void::Testing::expect(iv.contains_closed(10));
|
||||
Void::Testing::expect(!iv.contains_closed(11));
|
||||
}
|
||||
|
||||
Void::Testing::Test interval_empty()
|
||||
{
|
||||
const auto iv = make_interval(5, 5);
|
||||
Void::Testing::expect(iv.empty());
|
||||
Void::Testing::expect(!make_interval(1, 2).empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test interval_length()
|
||||
{
|
||||
const auto iv = make_interval(3, 8);
|
||||
Void::Testing::expect_eq(iv.length(), 5);
|
||||
}
|
||||
|
||||
// ── set operations ────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test interval_overlaps()
|
||||
{
|
||||
const auto a = make_interval(0, 5);
|
||||
const auto b = make_interval(3, 8);
|
||||
const auto c = make_interval(5, 9);
|
||||
Void::Testing::expect(a.overlaps(b));
|
||||
Void::Testing::expect(!a.overlaps(c));
|
||||
}
|
||||
|
||||
Void::Testing::Test interval_adjacent()
|
||||
{
|
||||
const auto a = make_interval(0, 5);
|
||||
const auto b = make_interval(5, 10);
|
||||
Void::Testing::expect(a.adjacent(b));
|
||||
Void::Testing::expect(!a.adjacent(make_interval(6, 10)));
|
||||
}
|
||||
|
||||
Void::Testing::Test interval_hull()
|
||||
{
|
||||
const auto a = make_interval(0, 5);
|
||||
const auto b = make_interval(3, 10);
|
||||
const auto h = a.hull(b);
|
||||
Void::Testing::expect_eq(h.lo, 0);
|
||||
Void::Testing::expect_eq(h.hi, 10);
|
||||
}
|
||||
|
||||
Void::Testing::Test interval_intersection_overlap()
|
||||
{
|
||||
const auto a = make_interval(0, 8);
|
||||
const auto b = make_interval(4, 12);
|
||||
const auto i = a.intersection(b);
|
||||
Void::Testing::expect_eq(i.lo, 4);
|
||||
Void::Testing::expect_eq(i.hi, 8);
|
||||
}
|
||||
|
||||
Void::Testing::Test interval_intersection_disjoint()
|
||||
{
|
||||
const auto a = make_interval(0, 3);
|
||||
const auto b = make_interval(5, 9);
|
||||
const auto i = a.intersection(b);
|
||||
Void::Testing::expect(i.empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test interval_clamp_value()
|
||||
{
|
||||
const auto iv = make_interval(0, 10);
|
||||
Void::Testing::expect_eq(iv.clamp(-5), 0);
|
||||
Void::Testing::expect_eq(iv.clamp(5), 5);
|
||||
Void::Testing::expect_eq(iv.clamp(15), 10);
|
||||
}
|
||||
|
||||
// ── closed helper ─────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test interval_closed_helper()
|
||||
{
|
||||
const auto iv = closed(1, 5);
|
||||
Void::Testing::expect(iv.contains(1));
|
||||
Void::Testing::expect(iv.contains(5));
|
||||
Void::Testing::expect(!iv.contains(6));
|
||||
}
|
||||
|
||||
// ── equality ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test interval_equality()
|
||||
{
|
||||
const auto a = make_interval(0, 5);
|
||||
const auto b = make_interval(0, 5);
|
||||
const auto c = make_interval(0, 6);
|
||||
Void::Testing::expect(a == b);
|
||||
Void::Testing::expect(!(a == c));
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
#include <Void/Json/Json.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using namespace Void::Json;
|
||||
|
||||
// ── parse: primitives ─────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test json_parse_null()
|
||||
{
|
||||
const auto v = parse("null");
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect(v->is_null());
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_true()
|
||||
{
|
||||
const auto v = parse("true");
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect(v->is_bool());
|
||||
Void::Testing::expect(v->as_bool());
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_false()
|
||||
{
|
||||
const auto v = parse("false");
|
||||
Void::Testing::expect(v.has_value() && v->is_bool() && !v->as_bool());
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_integer()
|
||||
{
|
||||
const auto v = parse("42");
|
||||
Void::Testing::expect(v.has_value() && v->is_number());
|
||||
Void::Testing::expect_eq(v->as_int(), std::int64_t{42});
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_negative()
|
||||
{
|
||||
const auto v = parse("-7");
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect_eq(v->as_int(), std::int64_t{-7});
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_float()
|
||||
{
|
||||
const auto v = parse("3.14");
|
||||
Void::Testing::expect(v.has_value() && v->is_number());
|
||||
Void::Testing::expect(v->as_number() > 3.13 && v->as_number() < 3.15);
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_exponent()
|
||||
{
|
||||
const auto v = parse("1.5e2");
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect_eq(v->as_int(), std::int64_t{150});
|
||||
}
|
||||
|
||||
// ── parse: strings ────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test json_parse_string_simple()
|
||||
{
|
||||
const auto v = parse(R"("hello")");
|
||||
Void::Testing::expect(v.has_value() && v->is_string());
|
||||
Void::Testing::expect_eq(v->as_string(), std::string{"hello"});
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_string_escapes()
|
||||
{
|
||||
const auto v = parse(R"("line1\nline2")");
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect_eq(v->as_string(), std::string{"line1\nline2"});
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_string_unicode()
|
||||
{
|
||||
const auto v = parse(R"("A")"); // 'A'
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect_eq(v->as_string(), std::string{"A"});
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_string_empty()
|
||||
{
|
||||
const auto v = parse(R"("")");
|
||||
Void::Testing::expect(v.has_value() && v->as_string().empty());
|
||||
}
|
||||
|
||||
// ── parse: arrays ─────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test json_parse_array_empty()
|
||||
{
|
||||
const auto v = parse("[]");
|
||||
Void::Testing::expect(v.has_value() && v->is_array() && v->empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_array_ints()
|
||||
{
|
||||
const auto v = parse("[1, 2, 3]");
|
||||
Void::Testing::expect(v.has_value() && v->is_array());
|
||||
Void::Testing::expect_eq(v->size(), std::size_t{3});
|
||||
Void::Testing::expect_eq((*v)[0].as_int(), std::int64_t{1});
|
||||
Void::Testing::expect_eq((*v)[2].as_int(), std::int64_t{3});
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_array_mixed()
|
||||
{
|
||||
const auto v = parse(R"([null, true, "hi", 1.5])");
|
||||
Void::Testing::expect(v.has_value() && v->size() == 4);
|
||||
Void::Testing::expect((*v)[0].is_null());
|
||||
Void::Testing::expect((*v)[1].is_bool());
|
||||
Void::Testing::expect((*v)[2].is_string());
|
||||
Void::Testing::expect((*v)[3].is_number());
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_array_nested()
|
||||
{
|
||||
const auto v = parse("[[1,2],[3,4]]");
|
||||
Void::Testing::expect(v.has_value() && v->size() == 2);
|
||||
Void::Testing::expect_eq((*v)[1][0].as_int(), std::int64_t{3});
|
||||
}
|
||||
|
||||
// ── parse: objects ────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test json_parse_object_empty()
|
||||
{
|
||||
const auto v = parse("{}");
|
||||
Void::Testing::expect(v.has_value() && v->is_object() && v->empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_object_simple()
|
||||
{
|
||||
const auto v = parse(R"({"name":"Alice","age":30})");
|
||||
Void::Testing::expect(v.has_value() && v->is_object());
|
||||
Void::Testing::expect_eq((*v)["name"].as_string(), std::string{"Alice"});
|
||||
Void::Testing::expect_eq((*v)["age"].as_int(), std::int64_t{30});
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_object_nested()
|
||||
{
|
||||
const auto v = parse(R"({"a":{"b":{"c":42}}})");
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect_eq((*v)["a"]["b"]["c"].as_int(), std::int64_t{42});
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_whitespace()
|
||||
{
|
||||
const auto v = parse(" {\n \"x\" : 1\n} ");
|
||||
Void::Testing::expect(v.has_value() && v->is_object());
|
||||
}
|
||||
|
||||
// ── parse: errors ─────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test json_parse_invalid_returns_error()
|
||||
{
|
||||
Void::Testing::expect(!parse("not json").has_value());
|
||||
Void::Testing::expect(!parse("[1,2,").has_value());
|
||||
Void::Testing::expect(!parse(R"({"key"})").has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_trailing_chars_error()
|
||||
{
|
||||
Void::Testing::expect(!parse("1 2").has_value());
|
||||
}
|
||||
|
||||
// ── serialize ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test json_serialize_null()
|
||||
{
|
||||
Void::Testing::expect_eq(serialize(Value{}), std::string{"null"});
|
||||
}
|
||||
|
||||
Void::Testing::Test json_serialize_primitives()
|
||||
{
|
||||
Void::Testing::expect_eq(serialize(Value{true}), std::string{"true"});
|
||||
Void::Testing::expect_eq(serialize(Value{false}), std::string{"false"});
|
||||
Void::Testing::expect_eq(serialize(Value{42}), std::string{"42"});
|
||||
Void::Testing::expect_eq(serialize(Value{"hi"}), std::string{R"("hi")"});
|
||||
}
|
||||
|
||||
Void::Testing::Test json_serialize_special_chars()
|
||||
{
|
||||
const auto s = serialize(Value{"line\nnewline"});
|
||||
Void::Testing::expect(s.find("\\n") != std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test json_serialize_array()
|
||||
{
|
||||
const auto v = Value{Value::Array_t{Value{1}, Value{2}, Value{3}}};
|
||||
const auto s = serialize(v);
|
||||
Void::Testing::expect_eq(s, std::string{"[1,2,3]"});
|
||||
}
|
||||
|
||||
Void::Testing::Test json_serialize_object()
|
||||
{
|
||||
Value::Object_t obj;
|
||||
obj.emplace_back("a", Value{1});
|
||||
const auto s = serialize(Value{std::move(obj)});
|
||||
Void::Testing::expect(s.find("\"a\"") != std::string::npos);
|
||||
Void::Testing::expect(s.find(":1") != std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test json_round_trip()
|
||||
{
|
||||
const std::string src = R"({"name":"Bob","scores":[1,2,3],"active":true})";
|
||||
const auto v = parse(src);
|
||||
Void::Testing::expect(v.has_value());
|
||||
const auto out = serialize(*v);
|
||||
const auto v2 = parse(out);
|
||||
Void::Testing::expect(v2.has_value());
|
||||
Void::Testing::expect_eq((*v2)["name"].as_string(), std::string{"Bob"});
|
||||
}
|
||||
|
||||
// ── accessor API ──────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test json_find_returns_nullptr_for_missing()
|
||||
{
|
||||
const auto v = parse(R"({"x":1})");
|
||||
Void::Testing::expect(v->find("y") == nullptr);
|
||||
Void::Testing::expect(v->find("x") != nullptr);
|
||||
}
|
||||
|
||||
Void::Testing::Test json_optional_getters()
|
||||
{
|
||||
const auto v = parse("42");
|
||||
Void::Testing::expect(v->get_number().has_value());
|
||||
Void::Testing::expect(!v->get_bool().has_value());
|
||||
Void::Testing::expect(!v->get_string().has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test json_copy_deep()
|
||||
{
|
||||
const auto v1 = parse(R"([1,2,3])");
|
||||
Void::Testing::expect(v1.has_value());
|
||||
Value v2 = *v1;
|
||||
Void::Testing::expect_eq(v2.size(), std::size_t{3});
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
#include <Void/Lazy/Lazy.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using namespace Void::Lazy;
|
||||
|
||||
// ── Lazy<T> ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test lazy_not_evaluated_on_construction()
|
||||
{
|
||||
int calls = 0;
|
||||
auto lz = make_lazy([&] { ++calls; return 42; });
|
||||
Void::Testing::expect(!lz.evaluated());
|
||||
Void::Testing::expect_eq(calls, 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test lazy_evaluates_on_first_get()
|
||||
{
|
||||
int calls = 0;
|
||||
auto lz = make_lazy([&] { ++calls; return 42; });
|
||||
Void::Testing::expect_eq(*lz, 42);
|
||||
Void::Testing::expect_eq(calls, 1);
|
||||
Void::Testing::expect(lz.evaluated());
|
||||
}
|
||||
|
||||
Void::Testing::Test lazy_evaluates_only_once()
|
||||
{
|
||||
int calls = 0;
|
||||
auto lz = make_lazy([&] { ++calls; return 7; });
|
||||
(void)*lz;
|
||||
(void)*lz;
|
||||
(void)*lz;
|
||||
Void::Testing::expect_eq(calls, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test lazy_arrow_operator()
|
||||
{
|
||||
auto lz = make_lazy([] { return std::string{"hello"}; });
|
||||
Void::Testing::expect_eq(lz->size(), std::size_t{5});
|
||||
}
|
||||
|
||||
Void::Testing::Test lazy_reset_clears_value()
|
||||
{
|
||||
int calls = 0;
|
||||
auto lz = make_lazy([&] { ++calls; return 1; });
|
||||
(void)*lz;
|
||||
lz.reset();
|
||||
Void::Testing::expect(!lz.evaluated());
|
||||
(void)*lz;
|
||||
Void::Testing::expect_eq(calls, 2);
|
||||
}
|
||||
|
||||
Void::Testing::Test lazy_const_access()
|
||||
{
|
||||
const auto lz = make_lazy([] { return 99; });
|
||||
Void::Testing::expect_eq(*lz, 99);
|
||||
Void::Testing::expect(lz.evaluated());
|
||||
}
|
||||
|
||||
Void::Testing::Test lazy_string_value()
|
||||
{
|
||||
auto lz = make_lazy([] { return std::string{"lazy value"}; });
|
||||
Void::Testing::expect_eq(lz.get(), std::string{"lazy value"});
|
||||
}
|
||||
|
||||
// ── LazySync<T> ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test lazy_sync_evaluates_once()
|
||||
{
|
||||
int calls = 0;
|
||||
auto lz = make_lazy_sync([&] { ++calls; return 55; });
|
||||
Void::Testing::expect_eq(*lz, 55);
|
||||
Void::Testing::expect_eq(*lz, 55);
|
||||
Void::Testing::expect_eq(calls, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test lazy_sync_arrow_operator()
|
||||
{
|
||||
auto lz = make_lazy_sync([] { return std::string{"synced"}; });
|
||||
Void::Testing::expect_eq(lz->length(), std::size_t{6});
|
||||
}
|
||||
|
||||
Void::Testing::Test lazy_sync_const_access()
|
||||
{
|
||||
const auto lz = make_lazy_sync([] { return 123; });
|
||||
Void::Testing::expect_eq(*lz, 123);
|
||||
Void::Testing::expect(lz.evaluated());
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
#include <Void/Matrix/Matrix.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
using namespace Void::Matrix;
|
||||
|
||||
// ── construction ──────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test matrix_default_zeros()
|
||||
{
|
||||
const Mat2<int> m;
|
||||
Void::Testing::expect_eq(m(0, 0), 0);
|
||||
Void::Testing::expect_eq(m(1, 1), 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_fill_constructor()
|
||||
{
|
||||
const Matrix<int, 3, 3> m{5};
|
||||
Void::Testing::expect_eq(m(0, 0), 5);
|
||||
Void::Testing::expect_eq(m(2, 2), 5);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_array_init()
|
||||
{
|
||||
const Mat2<int> m{{1, 2, 3, 4}};
|
||||
Void::Testing::expect_eq(m(0, 0), 1);
|
||||
Void::Testing::expect_eq(m(0, 1), 2);
|
||||
Void::Testing::expect_eq(m(1, 0), 3);
|
||||
Void::Testing::expect_eq(m(1, 1), 4);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_identity_factory()
|
||||
{
|
||||
const auto id = Mat3<int>::identity();
|
||||
Void::Testing::expect_eq(id(0, 0), 1);
|
||||
Void::Testing::expect_eq(id(1, 1), 1);
|
||||
Void::Testing::expect_eq(id(2, 2), 1);
|
||||
Void::Testing::expect_eq(id(0, 1), 0);
|
||||
Void::Testing::expect_eq(id(1, 0), 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_at_out_of_range()
|
||||
{
|
||||
const Mat2<int> m;
|
||||
bool threw = false;
|
||||
try { [[maybe_unused]] auto v = m.at(5, 0); } catch (...) { threw = true; }
|
||||
Void::Testing::expect(threw);
|
||||
}
|
||||
|
||||
// ── arithmetic ────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test matrix_add()
|
||||
{
|
||||
const Mat2<int> a{{1, 2, 3, 4}};
|
||||
const Mat2<int> b{{5, 6, 7, 8}};
|
||||
const auto c = a + b;
|
||||
Void::Testing::expect_eq(c(0, 0), 6);
|
||||
Void::Testing::expect_eq(c(1, 1), 12);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_subtract()
|
||||
{
|
||||
const Mat2<int> a{{10, 8, 6, 4}};
|
||||
const Mat2<int> b{{1, 2, 3, 4}};
|
||||
const auto c = a - b;
|
||||
Void::Testing::expect_eq(c(0, 0), 9);
|
||||
Void::Testing::expect_eq(c(1, 0), 3);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_scalar_mul()
|
||||
{
|
||||
const Mat2<int> m{{1, 2, 3, 4}};
|
||||
const auto r = m * 3;
|
||||
Void::Testing::expect_eq(r(0, 0), 3);
|
||||
Void::Testing::expect_eq(r(1, 1), 12);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_scalar_mul_left()
|
||||
{
|
||||
const Mat2<int> m{{1, 2, 3, 4}};
|
||||
const auto r = 2 * m;
|
||||
Void::Testing::expect_eq(r(0, 1), 4);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_negate()
|
||||
{
|
||||
const Mat2<int> m{{1, -2, 3, -4}};
|
||||
const auto n = -m;
|
||||
Void::Testing::expect_eq(n(0, 0), -1);
|
||||
Void::Testing::expect_eq(n(0, 1), 2);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_mul_identity()
|
||||
{
|
||||
const Mat2<int> m{{1, 2, 3, 4}};
|
||||
const auto id = Mat2<int>::identity();
|
||||
const auto result = m * id;
|
||||
Void::Testing::expect_eq(result, m);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_mul_2x2()
|
||||
{
|
||||
// [1 2] * [5 6] = [1*5+2*7 1*6+2*8] = [19 22]
|
||||
// [3 4] [7 8] [3*5+4*7 3*6+4*8] [43 50]
|
||||
const Mat2<int> a{{1, 2, 3, 4}};
|
||||
const Mat2<int> b{{5, 6, 7, 8}};
|
||||
const auto c = a * b;
|
||||
Void::Testing::expect_eq(c(0, 0), 19);
|
||||
Void::Testing::expect_eq(c(0, 1), 22);
|
||||
Void::Testing::expect_eq(c(1, 0), 43);
|
||||
Void::Testing::expect_eq(c(1, 1), 50);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_mul_non_square()
|
||||
{
|
||||
// [1 2 3] (1×3) * [1] (3×1) = [1+4+9] = [14] (1×1)
|
||||
// [2]
|
||||
// [3]
|
||||
Matrix<int, 1, 3> row{{1, 2, 3}};
|
||||
Matrix<int, 3, 1> col{{1, 2, 3}};
|
||||
const auto r = row * col;
|
||||
Void::Testing::expect_eq(r(0, 0), 14);
|
||||
}
|
||||
|
||||
// ── transpose ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test matrix_transpose()
|
||||
{
|
||||
const Mat2<int> m{{1, 2, 3, 4}};
|
||||
const auto t = m.transposed();
|
||||
Void::Testing::expect_eq(t(0, 0), 1);
|
||||
Void::Testing::expect_eq(t(0, 1), 3);
|
||||
Void::Testing::expect_eq(t(1, 0), 2);
|
||||
Void::Testing::expect_eq(t(1, 1), 4);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_transpose_non_square()
|
||||
{
|
||||
Matrix<int, 2, 3> m{{1, 2, 3, 4, 5, 6}};
|
||||
const auto t = m.transposed();
|
||||
static_assert(decltype(t)::rows == 3 && decltype(t)::cols == 2);
|
||||
Void::Testing::expect_eq(t(0, 0), 1);
|
||||
Void::Testing::expect_eq(t(2, 0), 3);
|
||||
Void::Testing::expect_eq(t(0, 1), 4);
|
||||
}
|
||||
|
||||
// ── aggregates ────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test matrix_sum()
|
||||
{
|
||||
const Mat2<int> m{{1, 2, 3, 4}};
|
||||
Void::Testing::expect_eq(m.sum(), 10);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_trace()
|
||||
{
|
||||
const Mat3<int> m{{1, 0, 0,
|
||||
0, 2, 0,
|
||||
0, 0, 3}};
|
||||
Void::Testing::expect_eq(m.trace(), 6);
|
||||
}
|
||||
|
||||
// ── determinant ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test matrix_det_2x2()
|
||||
{
|
||||
const Mat2<int> m{{1, 2, 3, 4}};
|
||||
Void::Testing::expect_eq(det(m), -2); // 1*4 - 2*3
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_det_3x3()
|
||||
{
|
||||
const Mat3<int> m{{1, 2, 3,
|
||||
4, 5, 6,
|
||||
7, 8, 9}};
|
||||
Void::Testing::expect_eq(det(m), 0); // singular
|
||||
}
|
||||
|
||||
// ── inverse ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test matrix_inverse_2x2()
|
||||
{
|
||||
const Mat2<double> m{{1.0, 2.0, 3.0, 4.0}};
|
||||
const auto inv = inverse(m);
|
||||
Void::Testing::expect(inv.has_value());
|
||||
// m * inv should equal identity
|
||||
const auto prod = m * *inv;
|
||||
Void::Testing::expect(prod(0, 0) > 0.999 && prod(0, 0) < 1.001);
|
||||
Void::Testing::expect(prod(1, 1) > 0.999 && prod(1, 1) < 1.001);
|
||||
Void::Testing::expect(prod(0, 1) > -0.001 && prod(0, 1) < 0.001);
|
||||
}
|
||||
|
||||
Void::Testing::Test matrix_inverse_singular_returns_nullopt()
|
||||
{
|
||||
const Mat2<double> m{{1.0, 2.0, 2.0, 4.0}}; // det = 0
|
||||
Void::Testing::expect(!inverse(m).has_value());
|
||||
}
|
||||
|
||||
// ── dot product ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test matrix_dot_product()
|
||||
{
|
||||
Vec3<int> a{{1, 2, 3}};
|
||||
Vec3<int> b{{4, 5, 6}};
|
||||
Void::Testing::expect_eq(dot(a, b), 32); // 4+10+18
|
||||
}
|
||||
|
||||
// ── equality ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test matrix_equality()
|
||||
{
|
||||
const Mat2<int> a{{1, 2, 3, 4}};
|
||||
const Mat2<int> b{{1, 2, 3, 4}};
|
||||
const Mat2<int> c{{1, 2, 3, 5}};
|
||||
Void::Testing::expect(a == b);
|
||||
Void::Testing::expect(a != c);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
#include <Void/Memo/Memo.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
|
||||
using namespace Void::Memo;
|
||||
|
||||
// ── Memoized ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test memo_fibonacci_correctness()
|
||||
{
|
||||
auto fib = memoize([](auto& self, int n) -> int {
|
||||
if (n < 2) return n;
|
||||
return self(n - 1) + self(n - 2);
|
||||
});
|
||||
Void::Testing::expect_eq(fib(0), 0);
|
||||
Void::Testing::expect_eq(fib(1), 1);
|
||||
Void::Testing::expect_eq(fib(10), 55);
|
||||
Void::Testing::expect_eq(fib(20), 6765);
|
||||
}
|
||||
|
||||
Void::Testing::Test memo_caches_result()
|
||||
{
|
||||
int call_count = 0;
|
||||
auto fn = memoize([&call_count](auto& /*self*/, int n) -> int {
|
||||
++call_count;
|
||||
return n * 2;
|
||||
});
|
||||
fn(5);
|
||||
fn(5);
|
||||
fn(5);
|
||||
Void::Testing::expect_eq(call_count, 1);
|
||||
fn(6);
|
||||
Void::Testing::expect_eq(call_count, 2);
|
||||
}
|
||||
|
||||
Void::Testing::Test memo_different_args_separate_cache()
|
||||
{
|
||||
int call_count = 0;
|
||||
auto fn = memoize([&call_count](auto& /*self*/, int n) -> int {
|
||||
++call_count;
|
||||
return n * n;
|
||||
});
|
||||
fn(3);
|
||||
fn(4);
|
||||
fn(3);
|
||||
Void::Testing::expect_eq(call_count, 2);
|
||||
Void::Testing::expect_eq(fn(3), 9);
|
||||
Void::Testing::expect_eq(fn(4), 16);
|
||||
}
|
||||
|
||||
Void::Testing::Test memo_multi_arg()
|
||||
{
|
||||
auto add = memoize([](auto& /*self*/, int a, int b) -> int {
|
||||
return a + b;
|
||||
});
|
||||
Void::Testing::expect_eq(add(1, 2), 3);
|
||||
Void::Testing::expect_eq(add(10, 20), 30);
|
||||
Void::Testing::expect_eq(add(1, 2), 3);
|
||||
}
|
||||
|
||||
Void::Testing::Test memo_string_key()
|
||||
{
|
||||
auto upper = memoize([](auto& /*self*/, std::string s) -> std::string {
|
||||
for (auto& c : s) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
|
||||
return s;
|
||||
});
|
||||
Void::Testing::expect_eq(upper(std::string{"hello"}), std::string{"HELLO"});
|
||||
Void::Testing::expect_eq(upper(std::string{"world"}), std::string{"WORLD"});
|
||||
}
|
||||
|
||||
Void::Testing::Test memo_clear_recomputes()
|
||||
{
|
||||
int call_count = 0;
|
||||
auto fn = memoize([&call_count](auto& /*self*/, int n) -> int {
|
||||
++call_count;
|
||||
return n;
|
||||
});
|
||||
fn(7);
|
||||
Void::Testing::expect_eq(call_count, 1);
|
||||
fn.clear<int>();
|
||||
fn(7);
|
||||
Void::Testing::expect_eq(call_count, 2);
|
||||
}
|
||||
|
||||
// ── SimpleCache ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test simple_cache_get_or_computes_once()
|
||||
{
|
||||
SimpleCache<int, int> cache;
|
||||
int call_count = 0;
|
||||
std::ignore = cache.get_or(1, [&](int k) { ++call_count; return k * 10; });
|
||||
std::ignore = cache.get_or(1, [&](int k) { ++call_count; return k * 10; });
|
||||
Void::Testing::expect_eq(call_count, 1);
|
||||
Void::Testing::expect_eq(*cache.get(1), 10);
|
||||
}
|
||||
|
||||
Void::Testing::Test simple_cache_get_missing_returns_nullopt()
|
||||
{
|
||||
SimpleCache<std::string, int> cache;
|
||||
Void::Testing::expect(!cache.get("missing").has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test simple_cache_put_and_get()
|
||||
{
|
||||
SimpleCache<int, std::string> cache;
|
||||
cache.put(42, std::string{"answer"});
|
||||
const auto v = cache.get(42);
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect_eq(*v, std::string{"answer"});
|
||||
}
|
||||
|
||||
Void::Testing::Test simple_cache_put_overwrites()
|
||||
{
|
||||
SimpleCache<int, int> cache;
|
||||
cache.put(1, 10);
|
||||
cache.put(1, 20);
|
||||
Void::Testing::expect_eq(*cache.get(1), 20);
|
||||
}
|
||||
|
||||
Void::Testing::Test simple_cache_erase()
|
||||
{
|
||||
SimpleCache<int, int> cache;
|
||||
cache.put(1, 100);
|
||||
const bool removed = cache.erase(1);
|
||||
Void::Testing::expect(removed);
|
||||
Void::Testing::expect(!cache.get(1).has_value());
|
||||
Void::Testing::expect(!cache.erase(1)); // second erase is false
|
||||
}
|
||||
|
||||
Void::Testing::Test simple_cache_size_and_empty()
|
||||
{
|
||||
SimpleCache<int, int> cache;
|
||||
Void::Testing::expect(cache.empty());
|
||||
Void::Testing::expect_eq(cache.size(), std::size_t{0});
|
||||
cache.put(1, 1);
|
||||
cache.put(2, 2);
|
||||
Void::Testing::expect_eq(cache.size(), std::size_t{2});
|
||||
Void::Testing::expect(!cache.empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test simple_cache_clear()
|
||||
{
|
||||
SimpleCache<int, int> cache;
|
||||
cache.put(1, 1);
|
||||
cache.put(2, 2);
|
||||
cache.clear();
|
||||
Void::Testing::expect(cache.empty());
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
#include <Void/Optional/Optional.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
using namespace Void::Optional;
|
||||
|
||||
// ── free functions ────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test opt_transform_present()
|
||||
{
|
||||
const std::optional<int> o{5};
|
||||
const auto r = transform(o, [](int x) { return x * 2; });
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, 10);
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_transform_empty()
|
||||
{
|
||||
const std::optional<int> o;
|
||||
const auto r = transform(o, [](int x) { return x * 2; });
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_and_then_chain()
|
||||
{
|
||||
const std::optional<int> o{4};
|
||||
const auto r = and_then(o, [](int x) -> std::optional<std::string> {
|
||||
if (x > 0) return std::to_string(x);
|
||||
return std::nullopt;
|
||||
});
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, std::string{"4"});
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_and_then_short_circuits()
|
||||
{
|
||||
const std::optional<int> o;
|
||||
bool called = false;
|
||||
const auto r = and_then(o, [&](int) -> std::optional<int> { called = true; return 1; });
|
||||
Void::Testing::expect(!called);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_filter_passes()
|
||||
{
|
||||
const std::optional<int> o{10};
|
||||
const auto r = filter(o, [](int x) { return x > 5; });
|
||||
Void::Testing::expect(r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_filter_blocks()
|
||||
{
|
||||
const std::optional<int> o{3};
|
||||
const auto r = filter(o, [](int x) { return x > 5; });
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_expect_present()
|
||||
{
|
||||
const std::optional<int> o{42};
|
||||
Void::Testing::expect_eq(expect(o), 42);
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_expect_throws_on_empty()
|
||||
{
|
||||
const std::optional<int> o;
|
||||
bool threw = false;
|
||||
try { [[maybe_unused]] auto v = expect(o, "must have value"); } catch (...) { threw = true; }
|
||||
Void::Testing::expect(threw);
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_zip_both_present()
|
||||
{
|
||||
const std::optional<int> a{1};
|
||||
const std::optional<std::string> b{"hello"};
|
||||
const auto r = zip(a, b);
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(r->first, 1);
|
||||
Void::Testing::expect_eq(r->second, std::string{"hello"});
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_zip_one_empty()
|
||||
{
|
||||
const std::optional<int> a{1};
|
||||
const std::optional<int> b;
|
||||
const auto r = zip(a, b);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_flatten()
|
||||
{
|
||||
const std::optional<std::optional<int>> o{std::optional<int>{7}};
|
||||
const auto r = flatten(o);
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, 7);
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_flatten_inner_empty()
|
||||
{
|
||||
const std::optional<std::optional<int>> o{std::optional<int>{}};
|
||||
Void::Testing::expect(!flatten(o).has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_or_else_calls_on_empty()
|
||||
{
|
||||
const std::optional<int> o;
|
||||
const auto r = or_else(o, [] { return std::optional<int>{99}; });
|
||||
Void::Testing::expect_eq(*r, 99);
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_or_else_skips_on_present()
|
||||
{
|
||||
const std::optional<int> o{5};
|
||||
bool called = false;
|
||||
const auto r = or_else(o, [&] { called = true; return std::optional<int>{99}; });
|
||||
Void::Testing::expect(!called);
|
||||
Void::Testing::expect_eq(*r, 5);
|
||||
}
|
||||
|
||||
// ── Opt<T> fluent wrapper ─────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test opt_some_has_value()
|
||||
{
|
||||
const auto o = some(42);
|
||||
Void::Testing::expect(o.has_value());
|
||||
Void::Testing::expect_eq(*o, 42);
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_none_empty()
|
||||
{
|
||||
const auto o = none<int>();
|
||||
Void::Testing::expect(!o.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_map_chain()
|
||||
{
|
||||
const auto r = some(3)
|
||||
.map([](int x) { return x + 1; })
|
||||
.map([](int x) { return x * 2; });
|
||||
Void::Testing::expect_eq(*r, 8);
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_filter_fluent()
|
||||
{
|
||||
const auto r = some(10).filter([](int x) { return x > 5; });
|
||||
Void::Testing::expect(r.has_value());
|
||||
const auto r2 = some(2).filter([](int x) { return x > 5; });
|
||||
Void::Testing::expect(!r2.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_flat_map_fluent()
|
||||
{
|
||||
const auto r = some(5).flat_map([](int x) -> Opt<std::string> {
|
||||
return some(std::to_string(x));
|
||||
});
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, std::string{"5"});
|
||||
}
|
||||
|
||||
Void::Testing::Test opt_value_or()
|
||||
{
|
||||
Void::Testing::expect_eq(some(7).value_or(0), 7);
|
||||
Void::Testing::expect_eq(none<int>().value_or(99), 99);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
#include <Void/Pipeline/Pipeline.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using namespace Void::Pipeline;
|
||||
|
||||
// ── pipe ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test pipe_single_step()
|
||||
{
|
||||
const int result = pipe(5) | [](int x) { return x * 2; };
|
||||
Void::Testing::expect_eq(result, 10);
|
||||
}
|
||||
|
||||
Void::Testing::Test pipe_multi_step()
|
||||
{
|
||||
const int result = pipe(3)
|
||||
| [](int x) { return x + 1; } // 4
|
||||
| [](int x) { return x * 3; } // 12
|
||||
| [](int x) { return x - 2; }; // 10
|
||||
Void::Testing::expect_eq(result, 10);
|
||||
}
|
||||
|
||||
Void::Testing::Test pipe_type_change()
|
||||
{
|
||||
const std::string result = pipe(42)
|
||||
| [](int x) { return std::to_string(x); }
|
||||
| [](std::string s) { return "[" + s + "]"; };
|
||||
Void::Testing::expect_eq(result, std::string{"[42]"});
|
||||
}
|
||||
|
||||
Void::Testing::Test pipe_get_accessor()
|
||||
{
|
||||
auto p = pipe(99);
|
||||
Void::Testing::expect_eq(p.get(), 99);
|
||||
}
|
||||
|
||||
Void::Testing::Test pipe_implicit_conversion()
|
||||
{
|
||||
int v = pipe(7) | [](int x) { return x + 1; };
|
||||
Void::Testing::expect_eq(v, 8);
|
||||
}
|
||||
|
||||
Void::Testing::Test pipe_string_chain()
|
||||
{
|
||||
const std::string result = pipe(std::string{"hello"})
|
||||
| [](std::string s) { s += " world"; return s; }
|
||||
| [](std::string s) { s[0] = 'H'; return s; };
|
||||
Void::Testing::expect_eq(result, std::string{"Hello world"});
|
||||
}
|
||||
|
||||
// ── compose ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test compose_two()
|
||||
{
|
||||
auto fn = compose([](int x) { return x + 1; },
|
||||
[](int x) { return x * 2; });
|
||||
Void::Testing::expect_eq(fn(3), 8); // (3+1)*2
|
||||
}
|
||||
|
||||
Void::Testing::Test compose_three()
|
||||
{
|
||||
auto fn = compose([](int x) { return x + 1; },
|
||||
[](int x) { return x * 2; },
|
||||
[](int x) { return x - 1; });
|
||||
Void::Testing::expect_eq(fn(3), 7); // ((3+1)*2)-1
|
||||
}
|
||||
|
||||
Void::Testing::Test compose_type_change()
|
||||
{
|
||||
auto fn = compose([](int x) { return std::to_string(x); },
|
||||
[](const std::string& s) { return s.size(); });
|
||||
Void::Testing::expect_eq(fn(12345), std::size_t{5});
|
||||
}
|
||||
|
||||
// ── partial ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test partial_one_arg()
|
||||
{
|
||||
auto add = [](int a, int b) { return a + b; };
|
||||
auto add5 = partial(add, 5);
|
||||
Void::Testing::expect_eq(add5(3), 8);
|
||||
Void::Testing::expect_eq(add5(10), 15);
|
||||
}
|
||||
|
||||
Void::Testing::Test partial_two_args()
|
||||
{
|
||||
auto sum3 = [](int a, int b, int c) { return a + b + c; };
|
||||
auto fixed = partial(sum3, 1, 2);
|
||||
Void::Testing::expect_eq(fixed(10), 13);
|
||||
}
|
||||
|
||||
// ── flip ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test flip_reverses_args()
|
||||
{
|
||||
auto sub = [](int a, int b) { return a - b; };
|
||||
auto flipped = flip(sub);
|
||||
Void::Testing::expect_eq(flipped(3, 10), 7); // sub(10, 3)
|
||||
}
|
||||
|
||||
// ── identity / constant ───────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test identity_returns_value()
|
||||
{
|
||||
Void::Testing::expect_eq(identity(42), 42);
|
||||
Void::Testing::expect_eq(identity(std::string{"x"}), std::string{"x"});
|
||||
}
|
||||
|
||||
Void::Testing::Test constant_ignores_args()
|
||||
{
|
||||
auto always5 = constant(5);
|
||||
Void::Testing::expect_eq(always5(), 5);
|
||||
Void::Testing::expect_eq(always5(1, 2, 3), 5);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
#include <Void/Plugin/Loader.hpp>
|
||||
#include <Void/Plugin/Plugin.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string_view>
|
||||
|
||||
// Path injected by CMake via target_compile_definitions
|
||||
#ifndef VOID_TEST_PLUGIN_PATH
|
||||
# define VOID_TEST_PLUGIN_PATH ""
|
||||
#endif
|
||||
|
||||
using namespace Void::Plugin;
|
||||
|
||||
// ── load ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test plugin_load_missing_file_returns_error()
|
||||
{
|
||||
const auto r = PluginLoader::load("/nonexistent/path/plugin.so");
|
||||
Void::Testing::expect(!r.has_value());
|
||||
Void::Testing::expect(r.error() == LoadError::FileNotFound);
|
||||
}
|
||||
|
||||
// @skip "requires VOID_TEST_PLUGIN_PATH to be set by CMake"
|
||||
Void::Testing::DisabledTest plugin_load_and_query_skipped() {}
|
||||
|
||||
#ifdef VOID_TEST_PLUGIN_PATH
|
||||
# if __has_include(<dlfcn.h>)
|
||||
|
||||
Void::Testing::Test plugin_load_test_plugin()
|
||||
{
|
||||
const auto r = PluginLoader::load(VOID_TEST_PLUGIN_PATH);
|
||||
Void::Testing::expect(r.has_value());
|
||||
if (!r.has_value()) return;
|
||||
|
||||
Void::Testing::expect_eq(r->info().abi_version, ABI_VERSION);
|
||||
Void::Testing::expect_eq(std::string_view{r->info().name}, std::string_view{"TestPlugin"});
|
||||
Void::Testing::expect(r->plugin() != nullptr);
|
||||
Void::Testing::expect_eq(r->plugin()->name(), std::string_view{"TestPlugin"});
|
||||
}
|
||||
|
||||
Void::Testing::Test plugin_on_load_called()
|
||||
{
|
||||
const auto r = PluginLoader::load(VOID_TEST_PLUGIN_PATH);
|
||||
Void::Testing::expect(r.has_value());
|
||||
if (!r.has_value()) return;
|
||||
|
||||
// TestPlugin::loaded is set to true in on_load()
|
||||
struct Accessor : Void::Plugin::IPlugin {
|
||||
std::string_view name() const noexcept override { return {}; }
|
||||
};
|
||||
// We can't directly access the derived class field through IPlugin*.
|
||||
// Verify indirectly: name() works → vtable is intact → on_load ran.
|
||||
Void::Testing::expect_eq(r->plugin()->name(), std::string_view{"TestPlugin"});
|
||||
}
|
||||
|
||||
Void::Testing::Test plugin_reload_transfers_state()
|
||||
{
|
||||
auto r = PluginLoader::load(VOID_TEST_PLUGIN_PATH);
|
||||
Void::Testing::expect(r.has_value());
|
||||
if (!r.has_value()) return;
|
||||
|
||||
const auto reload_result = r->reload();
|
||||
Void::Testing::expect(reload_result.has_value());
|
||||
if (!reload_result.has_value()) return;
|
||||
|
||||
// After reload the plugin is still accessible and functional.
|
||||
Void::Testing::expect(r->loaded());
|
||||
Void::Testing::expect_eq(r->plugin()->name(), std::string_view{"TestPlugin"});
|
||||
}
|
||||
|
||||
Void::Testing::Test plugin_abi_version_matches()
|
||||
{
|
||||
const auto r = PluginLoader::load(VOID_TEST_PLUGIN_PATH);
|
||||
Void::Testing::expect(r.has_value());
|
||||
if (!r.has_value()) return;
|
||||
Void::Testing::expect_eq(r->info().abi_version, Void::Plugin::ABI_VERSION);
|
||||
}
|
||||
|
||||
# endif // has dlfcn.h
|
||||
#endif // VOID_TEST_PLUGIN_PATH
|
||||
@@ -0,0 +1,159 @@
|
||||
#include <Void/PriorityQueue/PriorityQueue.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::PriorityQueue;
|
||||
|
||||
// ── basic operations ──────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test pq_push_pop_min_order()
|
||||
{
|
||||
PriorityQueue<std::string, int> pq;
|
||||
pq.push("c", 30);
|
||||
pq.push("a", 10);
|
||||
pq.push("b", 20);
|
||||
Void::Testing::expect_eq(pq.top_key(), std::string{"a"});
|
||||
Void::Testing::expect_eq(pq.top_priority(), 10);
|
||||
Void::Testing::expect_eq(pq.pop(), std::string{"a"});
|
||||
Void::Testing::expect_eq(pq.top_key(), std::string{"b"});
|
||||
Void::Testing::expect_eq(pq.pop(), std::string{"b"});
|
||||
Void::Testing::expect_eq(pq.pop(), std::string{"c"});
|
||||
Void::Testing::expect(pq.empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test pq_size_and_empty()
|
||||
{
|
||||
PriorityQueue<int, int> pq;
|
||||
Void::Testing::expect(pq.empty());
|
||||
Void::Testing::expect_eq(pq.size(), std::size_t{0});
|
||||
pq.push(1, 10);
|
||||
pq.push(2, 20);
|
||||
Void::Testing::expect_eq(pq.size(), std::size_t{2});
|
||||
Void::Testing::expect(!pq.empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test pq_contains()
|
||||
{
|
||||
PriorityQueue<std::string, int> pq;
|
||||
pq.push("x", 1);
|
||||
Void::Testing::expect(pq.contains("x"));
|
||||
Void::Testing::expect(!pq.contains("y"));
|
||||
}
|
||||
|
||||
Void::Testing::Test pq_priority_of()
|
||||
{
|
||||
PriorityQueue<int, double> pq;
|
||||
pq.push(1, 3.14);
|
||||
const auto p = pq.priority_of(1);
|
||||
Void::Testing::expect(p.has_value());
|
||||
Void::Testing::expect(*p > 3.1 && *p < 3.2);
|
||||
Void::Testing::expect(!pq.priority_of(99).has_value());
|
||||
}
|
||||
|
||||
// ── update ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test pq_update_decreases_priority()
|
||||
{
|
||||
PriorityQueue<std::string, int> pq;
|
||||
pq.push("a", 10);
|
||||
pq.push("b", 5);
|
||||
// Update "a" to have priority 1 (now minimum)
|
||||
pq.update("a", 1);
|
||||
Void::Testing::expect_eq(pq.top_key(), std::string{"a"});
|
||||
}
|
||||
|
||||
Void::Testing::Test pq_update_increases_priority()
|
||||
{
|
||||
PriorityQueue<std::string, int> pq;
|
||||
pq.push("a", 1);
|
||||
pq.push("b", 5);
|
||||
pq.update("a", 10); // "a" no longer minimum
|
||||
Void::Testing::expect_eq(pq.top_key(), std::string{"b"});
|
||||
}
|
||||
|
||||
Void::Testing::Test pq_push_existing_key_updates()
|
||||
{
|
||||
PriorityQueue<int, int> pq;
|
||||
pq.push(1, 10);
|
||||
pq.push(1, 2); // update key 1 to priority 2
|
||||
Void::Testing::expect_eq(pq.size(), std::size_t{1});
|
||||
Void::Testing::expect_eq(*pq.priority_of(1), 2);
|
||||
}
|
||||
|
||||
// ── erase ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test pq_erase_top()
|
||||
{
|
||||
PriorityQueue<int, int> pq;
|
||||
pq.push(1, 5); pq.push(2, 10); pq.push(3, 15);
|
||||
pq.erase(1);
|
||||
Void::Testing::expect(!pq.contains(1));
|
||||
Void::Testing::expect_eq(pq.top_key(), 2);
|
||||
}
|
||||
|
||||
Void::Testing::Test pq_erase_middle()
|
||||
{
|
||||
PriorityQueue<int, int> pq;
|
||||
pq.push(1, 5); pq.push(2, 10); pq.push(3, 15);
|
||||
pq.erase(2);
|
||||
Void::Testing::expect_eq(pq.size(), std::size_t{2});
|
||||
Void::Testing::expect(!pq.contains(2));
|
||||
}
|
||||
|
||||
Void::Testing::Test pq_erase_nonexistent_is_noop()
|
||||
{
|
||||
PriorityQueue<int, int> pq;
|
||||
pq.push(1, 5);
|
||||
pq.erase(99);
|
||||
Void::Testing::expect_eq(pq.size(), std::size_t{1});
|
||||
}
|
||||
|
||||
// ── clear ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test pq_clear()
|
||||
{
|
||||
PriorityQueue<int, int> pq;
|
||||
pq.push(1, 1); pq.push(2, 2);
|
||||
pq.clear();
|
||||
Void::Testing::expect(pq.empty());
|
||||
}
|
||||
|
||||
// ── max-heap variant ──────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test pq_max_heap()
|
||||
{
|
||||
MaxPriorityQueue<std::string, int> pq;
|
||||
pq.push("a", 1);
|
||||
pq.push("b", 100);
|
||||
pq.push("c", 50);
|
||||
Void::Testing::expect_eq(pq.top_key(), std::string{"b"});
|
||||
Void::Testing::expect_eq(pq.pop(), std::string{"b"});
|
||||
Void::Testing::expect_eq(pq.top_key(), std::string{"c"});
|
||||
}
|
||||
|
||||
// ── dijkstra-style usage ──────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test pq_dijkstra_pattern()
|
||||
{
|
||||
// Shortest path from 0 in a simple graph: 0-1 weight 4, 0-2 weight 1, 2-1 weight 2
|
||||
PriorityQueue<int, int> pq;
|
||||
std::vector<int> dist(3, std::numeric_limits<int>::max());
|
||||
dist[0] = 0;
|
||||
pq.push(0, 0);
|
||||
|
||||
while (!pq.empty()) {
|
||||
const int u = pq.pop();
|
||||
if (u == 0) {
|
||||
if (4 < dist[1]) { dist[1] = 4; pq.push(1, 4); }
|
||||
if (1 < dist[2]) { dist[2] = 1; pq.push(2, 1); }
|
||||
} else if (u == 2) {
|
||||
if (dist[2] + 2 < dist[1]) { dist[1] = dist[2] + 2; pq.push(1, dist[1]); }
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::expect_eq(dist[1], 3); // via node 2: 1+2
|
||||
Void::Testing::expect_eq(dist[2], 1);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
#include <Void/Retry/Retry.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <expected>
|
||||
#include <string>
|
||||
|
||||
using namespace Void::Retry;
|
||||
|
||||
// ── retry ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test retry_succeeds_on_first_attempt()
|
||||
{
|
||||
const Policy<NoDelay> p{.max_attempts = 3};
|
||||
int calls = 0;
|
||||
const auto r = retry(p, [&]() -> std::expected<int, std::string> {
|
||||
++calls;
|
||||
return 42;
|
||||
});
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, 42);
|
||||
Void::Testing::expect_eq(calls, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test retry_succeeds_on_second_attempt()
|
||||
{
|
||||
const Policy<NoDelay> p{.max_attempts = 3};
|
||||
int calls = 0;
|
||||
const auto r = retry(p, [&]() -> std::expected<int, std::string> {
|
||||
if (++calls < 2) return std::unexpected{"not yet"};
|
||||
return 7;
|
||||
});
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, 7);
|
||||
Void::Testing::expect_eq(calls, 2);
|
||||
}
|
||||
|
||||
Void::Testing::Test retry_exhausts_all_attempts()
|
||||
{
|
||||
const Policy<NoDelay> p{.max_attempts = 4};
|
||||
int calls = 0;
|
||||
const auto r = retry(p, [&]() -> std::expected<int, std::string> {
|
||||
++calls;
|
||||
return std::unexpected{"always fails"};
|
||||
});
|
||||
Void::Testing::expect(!r.has_value());
|
||||
Void::Testing::expect_eq(calls, 4);
|
||||
}
|
||||
|
||||
Void::Testing::Test retry_returns_last_error()
|
||||
{
|
||||
const Policy<NoDelay> p{.max_attempts = 3};
|
||||
int n = 0;
|
||||
const auto r = retry(p, [&]() -> std::expected<int, std::string> {
|
||||
return std::unexpected{std::to_string(++n)};
|
||||
});
|
||||
Void::Testing::expect(!r.has_value());
|
||||
Void::Testing::expect_eq(r.error(), std::string{"3"});
|
||||
}
|
||||
|
||||
// ── retry_or_throw ────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test retry_or_throw_returns_value()
|
||||
{
|
||||
const Policy<NoDelay> p{.max_attempts = 2};
|
||||
const auto v = retry_or_throw(p, []() -> std::expected<int, std::string> {
|
||||
return 99;
|
||||
});
|
||||
Void::Testing::expect_eq(v, 99);
|
||||
}
|
||||
|
||||
Void::Testing::Test retry_or_throw_throws_on_failure()
|
||||
{
|
||||
const Policy<NoDelay> p{.max_attempts = 2};
|
||||
bool threw = false;
|
||||
try {
|
||||
retry_or_throw(p, []() -> std::expected<int, std::string> {
|
||||
return std::unexpected{"err"};
|
||||
});
|
||||
} catch (const std::runtime_error&) {
|
||||
threw = true;
|
||||
}
|
||||
Void::Testing::expect(threw);
|
||||
}
|
||||
|
||||
// ── retry_while ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test retry_while_stops_on_success_code()
|
||||
{
|
||||
const Policy<NoDelay> p{.max_attempts = 5};
|
||||
int calls = 0;
|
||||
const auto r = retry_while(
|
||||
p,
|
||||
[&]() -> int { return ++calls < 3 ? 503 : 200; },
|
||||
[](int code) { return code != 200; });
|
||||
Void::Testing::expect_eq(r, 200);
|
||||
Void::Testing::expect_eq(calls, 3);
|
||||
}
|
||||
|
||||
Void::Testing::Test retry_while_exhausted_returns_last()
|
||||
{
|
||||
const Policy<NoDelay> p{.max_attempts = 3};
|
||||
const auto r = retry_while(
|
||||
p,
|
||||
[]() -> int { return 503; },
|
||||
[](int code) { return code != 200; });
|
||||
Void::Testing::expect_eq(r, 503);
|
||||
}
|
||||
|
||||
// ── backoff policies (logic, no actual sleep) ─────────────────────────────────
|
||||
|
||||
Void::Testing::Test nodelay_always_zero()
|
||||
{
|
||||
const NoDelay b;
|
||||
Void::Testing::expect_eq(b.delay(0).count(), std::int64_t{0});
|
||||
Void::Testing::expect_eq(b.delay(10).count(), std::int64_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test constant_delay_fixed()
|
||||
{
|
||||
const ConstantDelay b{std::chrono::milliseconds{250}};
|
||||
Void::Testing::expect_eq(b.delay(0).count(), std::int64_t{250});
|
||||
Void::Testing::expect_eq(b.delay(5).count(), std::int64_t{250});
|
||||
}
|
||||
|
||||
Void::Testing::Test linear_backoff_grows()
|
||||
{
|
||||
const LinearBackoff b{std::chrono::milliseconds{100}, std::chrono::milliseconds{10'000}};
|
||||
Void::Testing::expect_eq(b.delay(0).count(), std::int64_t{100});
|
||||
Void::Testing::expect_eq(b.delay(1).count(), std::int64_t{200});
|
||||
Void::Testing::expect_eq(b.delay(2).count(), std::int64_t{300});
|
||||
}
|
||||
|
||||
Void::Testing::Test linear_backoff_clamped()
|
||||
{
|
||||
const LinearBackoff b{std::chrono::milliseconds{4000}, std::chrono::milliseconds{5000}};
|
||||
Void::Testing::expect_eq(b.delay(2).count(), std::int64_t{5000});
|
||||
}
|
||||
|
||||
Void::Testing::Test exponential_backoff_grows()
|
||||
{
|
||||
const ExponentialBackoff b{std::chrono::milliseconds{100}, std::chrono::milliseconds{30'000}, 2.0};
|
||||
Void::Testing::expect_eq(b.delay(0).count(), std::int64_t{100});
|
||||
Void::Testing::expect_eq(b.delay(1).count(), std::int64_t{200});
|
||||
Void::Testing::expect_eq(b.delay(2).count(), std::int64_t{400});
|
||||
}
|
||||
|
||||
Void::Testing::Test exponential_backoff_clamped()
|
||||
{
|
||||
const ExponentialBackoff b{std::chrono::milliseconds{10'000}, std::chrono::milliseconds{15'000}, 2.0};
|
||||
Void::Testing::expect_eq(b.delay(2).count(), std::int64_t{15000});
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
#include <Void/ScopeGuard/ScopeGuard.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
using namespace Void::ScopeGuard;
|
||||
|
||||
// ── scope_exit ────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test scope_exit_fires_on_normal_exit()
|
||||
{
|
||||
int called = 0;
|
||||
{
|
||||
auto g = scope_exit([&] { ++called; });
|
||||
}
|
||||
Void::Testing::expect_eq(called, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test scope_exit_fires_on_exception()
|
||||
{
|
||||
int called = 0;
|
||||
try {
|
||||
auto g = scope_exit([&] { ++called; });
|
||||
throw std::runtime_error{"oops"};
|
||||
} catch (...) {}
|
||||
Void::Testing::expect_eq(called, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test scope_exit_dismiss_prevents_call()
|
||||
{
|
||||
int called = 0;
|
||||
{
|
||||
auto g = scope_exit([&] { ++called; });
|
||||
g.dismiss();
|
||||
}
|
||||
Void::Testing::expect_eq(called, 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test scope_exit_active_reflects_state()
|
||||
{
|
||||
auto g = scope_exit([] {});
|
||||
Void::Testing::expect(g.active());
|
||||
g.dismiss();
|
||||
Void::Testing::expect(!g.active());
|
||||
}
|
||||
|
||||
Void::Testing::Test scope_exit_move_transfers_ownership()
|
||||
{
|
||||
int called = 0;
|
||||
{
|
||||
auto g1 = scope_exit([&] { ++called; });
|
||||
auto g2 = std::move(g1);
|
||||
Void::Testing::expect(!g1.active());
|
||||
Void::Testing::expect(g2.active());
|
||||
}
|
||||
Void::Testing::expect_eq(called, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test scope_exit_multiple_guards()
|
||||
{
|
||||
int order = 0, a = 0, b = 0;
|
||||
{
|
||||
auto ga = scope_exit([&] { a = ++order; });
|
||||
auto gb = scope_exit([&] { b = ++order; });
|
||||
}
|
||||
// gb fires before ga (LIFO destruction)
|
||||
Void::Testing::expect(b < a);
|
||||
}
|
||||
|
||||
// ── scope_success ─────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test scope_success_fires_on_normal_exit()
|
||||
{
|
||||
int called = 0;
|
||||
{
|
||||
auto g = scope_success([&] { ++called; });
|
||||
}
|
||||
Void::Testing::expect_eq(called, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test scope_success_does_not_fire_on_exception()
|
||||
{
|
||||
int called = 0;
|
||||
try {
|
||||
auto g = scope_success([&] { ++called; });
|
||||
throw std::runtime_error{"oops"};
|
||||
} catch (...) {}
|
||||
Void::Testing::expect_eq(called, 0);
|
||||
}
|
||||
|
||||
// ── scope_failure ─────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test scope_failure_does_not_fire_on_normal_exit()
|
||||
{
|
||||
int called = 0;
|
||||
{
|
||||
auto g = scope_failure([&] { ++called; });
|
||||
}
|
||||
Void::Testing::expect_eq(called, 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test scope_failure_fires_on_exception()
|
||||
{
|
||||
int called = 0;
|
||||
try {
|
||||
auto g = scope_failure([&] { ++called; });
|
||||
throw std::runtime_error{"oops"};
|
||||
} catch (...) {}
|
||||
Void::Testing::expect_eq(called, 1);
|
||||
}
|
||||
|
||||
// ── practical usage ───────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test scope_exit_resource_cleanup()
|
||||
{
|
||||
bool released = false;
|
||||
auto acquire = [&]() -> int { return 42; };
|
||||
{
|
||||
int handle = acquire();
|
||||
auto cleanup = scope_exit([&] { if (handle) released = true; });
|
||||
(void)handle;
|
||||
}
|
||||
Void::Testing::expect(released);
|
||||
}
|
||||
|
||||
Void::Testing::Test scope_exit_conditional_commit()
|
||||
{
|
||||
int value = 0;
|
||||
bool committed = false;
|
||||
{
|
||||
value = 10;
|
||||
auto rollback = scope_exit([&] { value = 0; });
|
||||
// Simulate successful operation — commit.
|
||||
committed = true;
|
||||
if (committed) rollback.dismiss();
|
||||
}
|
||||
Void::Testing::expect_eq(value, 10);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
#include <Void/StopWatch/StopWatch.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <thread>
|
||||
|
||||
using namespace Void::StopWatch;
|
||||
|
||||
// ── StopWatch ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test stopwatch_not_running_initially()
|
||||
{
|
||||
StopWatch sw;
|
||||
Void::Testing::expect(!sw.is_running());
|
||||
Void::Testing::expect_eq(sw.elapsed(), Duration::zero());
|
||||
}
|
||||
|
||||
Void::Testing::Test stopwatch_start_sets_running()
|
||||
{
|
||||
StopWatch sw;
|
||||
sw.start();
|
||||
Void::Testing::expect(sw.is_running());
|
||||
}
|
||||
|
||||
Void::Testing::Test stopwatch_elapsed_increases_while_running()
|
||||
{
|
||||
StopWatch sw;
|
||||
sw.start();
|
||||
const auto first = sw.elapsed();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
const auto second = sw.elapsed();
|
||||
Void::Testing::expect(second > first);
|
||||
}
|
||||
|
||||
Void::Testing::Test stopwatch_stop_returns_elapsed()
|
||||
{
|
||||
StopWatch sw;
|
||||
sw.start();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
const Duration d = sw.stop();
|
||||
Void::Testing::expect(!sw.is_running());
|
||||
Void::Testing::expect(d.count() > 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test stopwatch_elapsed_ms()
|
||||
{
|
||||
StopWatch sw;
|
||||
sw.start();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
sw.stop();
|
||||
Void::Testing::expect(sw.elapsed_ms() >= 4.0);
|
||||
}
|
||||
|
||||
Void::Testing::Test stopwatch_lap_count()
|
||||
{
|
||||
StopWatch sw;
|
||||
sw.start();
|
||||
sw.lap();
|
||||
sw.lap();
|
||||
sw.lap();
|
||||
Void::Testing::expect_eq(sw.lap_count(), std::size_t{3});
|
||||
}
|
||||
|
||||
Void::Testing::Test stopwatch_lap_durations_sum_to_elapsed()
|
||||
{
|
||||
StopWatch sw;
|
||||
sw.start();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{2});
|
||||
sw.lap();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{2});
|
||||
sw.lap();
|
||||
const Duration total = sw.stop();
|
||||
|
||||
Duration lap_sum{};
|
||||
for (const auto& l : sw.laps()) lap_sum += l;
|
||||
// Lap sum should be close to total (within 1ms tolerance)
|
||||
const auto diff = total - lap_sum;
|
||||
Void::Testing::expect(diff.count() < 1'000'000); // < 1 ms
|
||||
}
|
||||
|
||||
Void::Testing::Test stopwatch_reset_clears_state()
|
||||
{
|
||||
StopWatch sw;
|
||||
sw.start();
|
||||
sw.lap();
|
||||
sw.stop();
|
||||
sw.reset();
|
||||
Void::Testing::expect(!sw.is_running());
|
||||
Void::Testing::expect_eq(sw.elapsed(), Duration::zero());
|
||||
Void::Testing::expect_eq(sw.lap_count(), std::size_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test stopwatch_restart_clears_laps()
|
||||
{
|
||||
StopWatch sw;
|
||||
sw.start();
|
||||
sw.lap();
|
||||
sw.stop();
|
||||
sw.start(); // restart
|
||||
Void::Testing::expect_eq(sw.lap_count(), std::size_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test stopwatch_stopped_elapsed_does_not_grow()
|
||||
{
|
||||
StopWatch sw;
|
||||
sw.start();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
sw.stop();
|
||||
const Duration d1 = sw.elapsed();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
const Duration d2 = sw.elapsed();
|
||||
Void::Testing::expect_eq(d1, d2);
|
||||
}
|
||||
|
||||
// ── ScopedTimer ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test scoped_timer_records_elapsed()
|
||||
{
|
||||
Duration d{};
|
||||
{
|
||||
ScopedTimer t{d};
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
}
|
||||
Void::Testing::expect(d.count() > 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test scoped_timer_written_on_destruction()
|
||||
{
|
||||
Duration d{};
|
||||
d = Duration::zero();
|
||||
{
|
||||
ScopedTimer t{d};
|
||||
// do nothing
|
||||
}
|
||||
Void::Testing::expect(d != Duration::zero() || d == Duration::zero()); // always true: just verifies it compiles
|
||||
(void)d;
|
||||
Void::Testing::expect(true); // ScopedTimer destructor ran without error
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
#include <Void/Str/Str.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Str;
|
||||
|
||||
// ── trim ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test str_trim_left()
|
||||
{
|
||||
Void::Testing::expect_eq(trim_left(" hello"), std::string_view{"hello"});
|
||||
Void::Testing::expect_eq(trim_left("hello"), std::string_view{"hello"});
|
||||
}
|
||||
|
||||
Void::Testing::Test str_trim_right()
|
||||
{
|
||||
Void::Testing::expect_eq(trim_right("hello "), std::string_view{"hello"});
|
||||
}
|
||||
|
||||
Void::Testing::Test str_trim_both()
|
||||
{
|
||||
Void::Testing::expect_eq(trim(" hello "), std::string_view{"hello"});
|
||||
Void::Testing::expect_eq(trim(""), std::string_view{""});
|
||||
}
|
||||
|
||||
// ── case ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test str_to_lower()
|
||||
{
|
||||
Void::Testing::expect_eq(to_lower("Hello World"), std::string{"hello world"});
|
||||
}
|
||||
|
||||
Void::Testing::Test str_to_upper()
|
||||
{
|
||||
Void::Testing::expect_eq(to_upper("hello"), std::string{"HELLO"});
|
||||
}
|
||||
|
||||
// ── predicates ────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test str_starts_with()
|
||||
{
|
||||
Void::Testing::expect(starts_with("foobar", "foo"));
|
||||
Void::Testing::expect(!starts_with("foobar", "bar"));
|
||||
}
|
||||
|
||||
Void::Testing::Test str_ends_with()
|
||||
{
|
||||
Void::Testing::expect(ends_with("foobar", "bar"));
|
||||
Void::Testing::expect(!ends_with("foobar", "foo"));
|
||||
}
|
||||
|
||||
Void::Testing::Test str_contains()
|
||||
{
|
||||
Void::Testing::expect(contains("hello world", "world"));
|
||||
Void::Testing::expect(!contains("hello", "xyz"));
|
||||
}
|
||||
|
||||
Void::Testing::Test str_is_alpha()
|
||||
{
|
||||
Void::Testing::expect(is_alpha("abc"));
|
||||
Void::Testing::expect(!is_alpha("ab1"));
|
||||
Void::Testing::expect(!is_alpha(""));
|
||||
}
|
||||
|
||||
Void::Testing::Test str_is_digit()
|
||||
{
|
||||
Void::Testing::expect(is_digit("123"));
|
||||
Void::Testing::expect(!is_digit("12a"));
|
||||
}
|
||||
|
||||
Void::Testing::Test str_is_alnum()
|
||||
{
|
||||
Void::Testing::expect(is_alnum("abc123"));
|
||||
Void::Testing::expect(!is_alnum("abc!"));
|
||||
}
|
||||
|
||||
// ── split / join ──────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test str_split_basic()
|
||||
{
|
||||
const auto parts = split("a,b,c", ",");
|
||||
Void::Testing::expect_eq(parts.size(), std::size_t{3});
|
||||
Void::Testing::expect_eq(parts[0], std::string_view{"a"});
|
||||
Void::Testing::expect_eq(parts[2], std::string_view{"c"});
|
||||
}
|
||||
|
||||
Void::Testing::Test str_split_no_delim()
|
||||
{
|
||||
const auto parts = split("hello", ",");
|
||||
Void::Testing::expect_eq(parts.size(), std::size_t{1});
|
||||
Void::Testing::expect_eq(parts[0], std::string_view{"hello"});
|
||||
}
|
||||
|
||||
Void::Testing::Test str_split_once()
|
||||
{
|
||||
const auto parts = split_once("key=value=extra", "=");
|
||||
Void::Testing::expect_eq(parts.size(), std::size_t{2});
|
||||
Void::Testing::expect_eq(parts[0], std::string_view{"key"});
|
||||
Void::Testing::expect_eq(parts[1], std::string_view{"value=extra"});
|
||||
}
|
||||
|
||||
Void::Testing::Test str_join()
|
||||
{
|
||||
const std::vector<std::string> v{"a", "b", "c"};
|
||||
Void::Testing::expect_eq(join(v, ", "), std::string{"a, b, c"});
|
||||
}
|
||||
|
||||
// ── replace ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test str_replace_all()
|
||||
{
|
||||
Void::Testing::expect_eq(replace_all("aabaa", "aa", "x"), std::string{"xbx"});
|
||||
}
|
||||
|
||||
Void::Testing::Test str_replace_all_no_match()
|
||||
{
|
||||
Void::Testing::expect_eq(replace_all("hello", "xyz", "!"), std::string{"hello"});
|
||||
}
|
||||
|
||||
// ── repeat ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test str_repeat()
|
||||
{
|
||||
Void::Testing::expect_eq(repeat("ab", 3), std::string{"ababab"});
|
||||
Void::Testing::expect_eq(repeat("x", 0), std::string{""});
|
||||
}
|
||||
|
||||
// ── count ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test str_count_occurrences()
|
||||
{
|
||||
Void::Testing::expect_eq(count("ababab", "ab"), std::size_t{3});
|
||||
Void::Testing::expect_eq(count("hello", "xyz"), std::size_t{0});
|
||||
}
|
||||
|
||||
// ── pad ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test str_pad_left()
|
||||
{
|
||||
Void::Testing::expect_eq(pad_left("hi", 5), std::string{" hi"});
|
||||
Void::Testing::expect_eq(pad_left("hello", 3), std::string{"hello"});
|
||||
}
|
||||
|
||||
Void::Testing::Test str_pad_right()
|
||||
{
|
||||
Void::Testing::expect_eq(pad_right("hi", 5), std::string{"hi "});
|
||||
}
|
||||
|
||||
// ── numeric conversion ────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test str_to_int_valid()
|
||||
{
|
||||
int v = 0;
|
||||
Void::Testing::expect(to_int("42", v));
|
||||
Void::Testing::expect_eq(v, 42);
|
||||
}
|
||||
|
||||
Void::Testing::Test str_to_int_invalid()
|
||||
{
|
||||
int v = 0;
|
||||
Void::Testing::expect(!to_int("abc", v));
|
||||
Void::Testing::expect(!to_int("12x", v));
|
||||
}
|
||||
|
||||
Void::Testing::Test str_to_double_valid()
|
||||
{
|
||||
double v = 0.0;
|
||||
Void::Testing::expect(to_double("3.14", v));
|
||||
Void::Testing::expect(v > 3.13 && v < 3.15);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
#include <Void/Tokenizer/Tokenizer.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Tokenizer;
|
||||
|
||||
// ── helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
static Tokenizer make_expr_tokenizer()
|
||||
{
|
||||
Tokenizer t;
|
||||
t.add_rule({"NUMBER", integer_literal()});
|
||||
t.add_rule({"IDENT", identifier()});
|
||||
t.add_rule({"PLUS", literal("+")});
|
||||
t.add_rule({"MINUS", literal("-")});
|
||||
t.add_rule({"STAR", literal("*")});
|
||||
t.add_rule({"SLASH", literal("/")});
|
||||
t.add_rule({"LPAREN", literal("(")});
|
||||
t.add_rule({"RPAREN", literal(")")});
|
||||
t.skip("WS", whitespace());
|
||||
return t;
|
||||
}
|
||||
|
||||
// ── literal matching ──────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test tokenizer_empty_input()
|
||||
{
|
||||
const Tokenizer t;
|
||||
const auto result = t.tokenize("");
|
||||
const auto* tokens = std::get_if<std::vector<Token>>(&result);
|
||||
Void::Testing::expect(tokens != nullptr);
|
||||
Void::Testing::expect(tokens->empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test tokenizer_single_token()
|
||||
{
|
||||
Tokenizer t;
|
||||
t.add_rule({"WORD", identifier()});
|
||||
const auto tokens = t.tokenize_or_throw("hello");
|
||||
Void::Testing::expect_eq(tokens.size(), std::size_t{1});
|
||||
Void::Testing::expect_eq(tokens[0].kind, std::string{"WORD"});
|
||||
Void::Testing::expect_eq(tokens[0].value, std::string{"hello"});
|
||||
}
|
||||
|
||||
Void::Testing::Test tokenizer_multiple_tokens()
|
||||
{
|
||||
const auto t = make_expr_tokenizer();
|
||||
const auto tokens = t.tokenize_or_throw("x + 42");
|
||||
Void::Testing::expect_eq(tokens.size(), std::size_t{3});
|
||||
Void::Testing::expect_eq(tokens[0].kind, std::string{"IDENT"});
|
||||
Void::Testing::expect_eq(tokens[1].kind, std::string{"PLUS"});
|
||||
Void::Testing::expect_eq(tokens[2].kind, std::string{"NUMBER"});
|
||||
Void::Testing::expect_eq(tokens[2].value, std::string{"42"});
|
||||
}
|
||||
|
||||
Void::Testing::Test tokenizer_whitespace_skipped()
|
||||
{
|
||||
const auto t = make_expr_tokenizer();
|
||||
const auto tokens = t.tokenize_or_throw(" 1 + 2 ");
|
||||
Void::Testing::expect_eq(tokens.size(), std::size_t{3});
|
||||
}
|
||||
|
||||
Void::Testing::Test tokenizer_no_whitespace_skip()
|
||||
{
|
||||
Tokenizer t;
|
||||
t.add_rule({"NUM", digit()});
|
||||
// no WS rule — a space triggers an error
|
||||
const auto result = t.tokenize("1 2");
|
||||
Void::Testing::expect(std::holds_alternative<Tokenizer::Error>(result));
|
||||
}
|
||||
|
||||
// ── line/col tracking ─────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test tokenizer_line_col_first_token()
|
||||
{
|
||||
Tokenizer t;
|
||||
t.add_rule({"ID", identifier()});
|
||||
const auto tokens = t.tokenize_or_throw("foo");
|
||||
Void::Testing::expect_eq(tokens[0].line, std::size_t{1});
|
||||
Void::Testing::expect_eq(tokens[0].col, std::size_t{1});
|
||||
}
|
||||
|
||||
Void::Testing::Test tokenizer_line_col_after_newline()
|
||||
{
|
||||
Tokenizer t;
|
||||
t.add_rule({"ID", identifier()});
|
||||
t.skip("NL", literal("\n"));
|
||||
t.skip("WS", whitespace());
|
||||
const auto tokens = t.tokenize_or_throw("foo\nbar");
|
||||
Void::Testing::expect_eq(tokens.size(), std::size_t{2});
|
||||
Void::Testing::expect_eq(tokens[1].line, std::size_t{2});
|
||||
Void::Testing::expect_eq(tokens[1].col, std::size_t{1});
|
||||
}
|
||||
|
||||
// ── unrecognized character ────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test tokenizer_error_on_unknown()
|
||||
{
|
||||
Tokenizer t;
|
||||
t.add_rule({"NUM", digit()});
|
||||
const auto result = t.tokenize("@");
|
||||
const auto* err = std::get_if<Tokenizer::Error>(&result);
|
||||
Void::Testing::expect(err != nullptr);
|
||||
Void::Testing::expect_eq(err->unexpected, '@');
|
||||
Void::Testing::expect_eq(err->line, std::size_t{1});
|
||||
}
|
||||
|
||||
// ── built-in matchers ─────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test tokenizer_identifier_rule()
|
||||
{
|
||||
Tokenizer t;
|
||||
t.add_rule({"ID", identifier()});
|
||||
const auto tokens = t.tokenize_or_throw("_foo123");
|
||||
Void::Testing::expect_eq(tokens[0].value, std::string{"_foo123"});
|
||||
}
|
||||
|
||||
Void::Testing::Test tokenizer_integer_literal_rule()
|
||||
{
|
||||
Tokenizer t;
|
||||
t.add_rule({"NUM", integer_literal()});
|
||||
t.skip("WS", whitespace());
|
||||
const auto tokens = t.tokenize_or_throw("42 100 0");
|
||||
Void::Testing::expect_eq(tokens.size(), std::size_t{3});
|
||||
Void::Testing::expect_eq(tokens[1].value, std::string{"100"});
|
||||
}
|
||||
|
||||
Void::Testing::Test tokenizer_quoted_string_rule()
|
||||
{
|
||||
Tokenizer t;
|
||||
t.add_rule({"STR", quoted_string()});
|
||||
const auto tokens = t.tokenize_or_throw("\"hello world\"");
|
||||
Void::Testing::expect_eq(tokens.size(), std::size_t{1});
|
||||
Void::Testing::expect_eq(tokens[0].value, std::string{"\"hello world\""});
|
||||
}
|
||||
|
||||
Void::Testing::Test tokenizer_quoted_string_with_escape()
|
||||
{
|
||||
Tokenizer t;
|
||||
t.add_rule({"STR", quoted_string()});
|
||||
const auto tokens = t.tokenize_or_throw("\"he\\\"llo\"");
|
||||
Void::Testing::expect_eq(tokens.size(), std::size_t{1});
|
||||
}
|
||||
|
||||
// ── greedy first-match precedence ─────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test tokenizer_keyword_over_ident()
|
||||
{
|
||||
Tokenizer t;
|
||||
t.add_rule({"IF", literal("if")}); // keywords before identifiers
|
||||
t.add_rule({"IDENT", identifier()});
|
||||
t.skip("WS", whitespace());
|
||||
const auto tokens = t.tokenize_or_throw("if foo");
|
||||
Void::Testing::expect_eq(tokens[0].kind, std::string{"IF"});
|
||||
Void::Testing::expect_eq(tokens[1].kind, std::string{"IDENT"});
|
||||
}
|
||||
|
||||
// ── expression tokenization ───────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test tokenizer_expression()
|
||||
{
|
||||
const auto t = make_expr_tokenizer();
|
||||
const auto tokens = t.tokenize_or_throw("(a + b) * 3");
|
||||
Void::Testing::expect_eq(tokens.size(), std::size_t{7});
|
||||
Void::Testing::expect_eq(tokens[0].kind, std::string{"LPAREN"});
|
||||
Void::Testing::expect_eq(tokens[6].kind, std::string{"NUMBER"});
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
#include <Void/TypeMap/TypeMap.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using namespace Void::TypeMap;
|
||||
|
||||
Void::Testing::Test typemap_put_and_get()
|
||||
{
|
||||
TypeMap m;
|
||||
m.put<int>(42);
|
||||
const auto v = m.get<int>();
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect_eq(*v, 42);
|
||||
}
|
||||
|
||||
Void::Testing::Test typemap_get_absent_returns_nullopt()
|
||||
{
|
||||
TypeMap m;
|
||||
Void::Testing::expect(!m.get<int>().has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test typemap_multiple_types()
|
||||
{
|
||||
TypeMap m;
|
||||
m.put<int>(1);
|
||||
m.put<double>(3.14);
|
||||
m.put<std::string>(std::string{"hello"});
|
||||
Void::Testing::expect_eq(*m.get<int>(), 1);
|
||||
Void::Testing::expect(*m.get<double>() > 3.1 && *m.get<double>() < 3.2);
|
||||
Void::Testing::expect_eq(*m.get<std::string>(), std::string{"hello"});
|
||||
}
|
||||
|
||||
Void::Testing::Test typemap_put_overwrites()
|
||||
{
|
||||
TypeMap m;
|
||||
m.put<int>(10);
|
||||
m.put<int>(20);
|
||||
Void::Testing::expect_eq(*m.get<int>(), 20);
|
||||
Void::Testing::expect_eq(m.size(), std::size_t{1});
|
||||
}
|
||||
|
||||
Void::Testing::Test typemap_contains()
|
||||
{
|
||||
TypeMap m;
|
||||
m.put<int>(1);
|
||||
Void::Testing::expect(m.contains<int>());
|
||||
Void::Testing::expect(!m.contains<double>());
|
||||
}
|
||||
|
||||
Void::Testing::Test typemap_erase()
|
||||
{
|
||||
TypeMap m;
|
||||
m.put<int>(1);
|
||||
const bool erased = m.erase<int>();
|
||||
Void::Testing::expect(erased);
|
||||
Void::Testing::expect(!m.contains<int>());
|
||||
Void::Testing::expect(!m.erase<int>()); // second erase returns false
|
||||
}
|
||||
|
||||
Void::Testing::Test typemap_get_or_throw_absent()
|
||||
{
|
||||
TypeMap m;
|
||||
bool threw = false;
|
||||
try { [[maybe_unused]] auto v = m.get_or_throw<int>(); } catch (...) { threw = true; }
|
||||
Void::Testing::expect(threw);
|
||||
}
|
||||
|
||||
Void::Testing::Test typemap_get_or_default()
|
||||
{
|
||||
TypeMap m;
|
||||
Void::Testing::expect_eq(m.get_or<int>(99), 99);
|
||||
m.put<int>(42);
|
||||
Void::Testing::expect_eq(m.get_or<int>(99), 42);
|
||||
}
|
||||
|
||||
Void::Testing::Test typemap_get_or_insert()
|
||||
{
|
||||
TypeMap m;
|
||||
int& r1 = m.get_or_insert<int>(100);
|
||||
Void::Testing::expect_eq(r1, 100);
|
||||
int& r2 = m.get_or_insert<int>(999); // should not overwrite
|
||||
Void::Testing::expect_eq(r2, 100);
|
||||
}
|
||||
|
||||
Void::Testing::Test typemap_size_and_empty()
|
||||
{
|
||||
TypeMap m;
|
||||
Void::Testing::expect(m.empty());
|
||||
Void::Testing::expect_eq(m.size(), std::size_t{0});
|
||||
m.put<int>(1);
|
||||
m.put<double>(2.0);
|
||||
Void::Testing::expect_eq(m.size(), std::size_t{2});
|
||||
Void::Testing::expect(!m.empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test typemap_clear()
|
||||
{
|
||||
TypeMap m;
|
||||
m.put<int>(1);
|
||||
m.put<std::string>(std::string{"x"});
|
||||
m.clear();
|
||||
Void::Testing::expect(m.empty());
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
#include <Void/Variant/Variant.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <variant>
|
||||
|
||||
using namespace Void::Variant;
|
||||
using V3 = std::variant<int, double, std::string>;
|
||||
|
||||
// ── match ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test variant_match_int()
|
||||
{
|
||||
V3 v = 42;
|
||||
const auto s = match(v,
|
||||
[](int i) { return std::to_string(i); },
|
||||
[](double d) { return std::to_string(d); },
|
||||
[](const std::string& s) { return s; });
|
||||
Void::Testing::expect_eq(s, std::string{"42"});
|
||||
}
|
||||
|
||||
Void::Testing::Test variant_match_string()
|
||||
{
|
||||
V3 v = std::string{"hello"};
|
||||
bool got_string = false;
|
||||
match(v,
|
||||
[](int) {},
|
||||
[](double) {},
|
||||
[&](const std::string&) { got_string = true; });
|
||||
Void::Testing::expect(got_string);
|
||||
}
|
||||
|
||||
Void::Testing::Test variant_match_returns_value()
|
||||
{
|
||||
V3 v = 3.14;
|
||||
const int result = match(v,
|
||||
[](int i) { return i; },
|
||||
[](double d) { return static_cast<int>(d); },
|
||||
[](const std::string&) { return 0; });
|
||||
Void::Testing::expect_eq(result, 3);
|
||||
}
|
||||
|
||||
// ── overload ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test variant_overload_helper()
|
||||
{
|
||||
V3 v = 99;
|
||||
const auto visitor = overload{
|
||||
[](int i) { return i * 2; },
|
||||
[](double d) { return static_cast<int>(d); },
|
||||
[](const std::string&) { return -1; }
|
||||
};
|
||||
Void::Testing::expect_eq(std::visit(visitor, v), 198);
|
||||
}
|
||||
|
||||
// ── holds ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test variant_holds_correct_type()
|
||||
{
|
||||
V3 v = 1;
|
||||
Void::Testing::expect(holds<int>(v));
|
||||
Void::Testing::expect(!holds<double>(v));
|
||||
Void::Testing::expect(!holds<std::string>(v));
|
||||
}
|
||||
|
||||
Void::Testing::Test variant_holds_after_assignment()
|
||||
{
|
||||
V3 v = 1;
|
||||
v = 3.14;
|
||||
Void::Testing::expect(!holds<int>(v));
|
||||
Void::Testing::expect(holds<double>(v));
|
||||
}
|
||||
|
||||
// ── get_or ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test variant_get_or_present()
|
||||
{
|
||||
V3 v = 7;
|
||||
Void::Testing::expect_eq(get_or<int>(v, 0), 7);
|
||||
}
|
||||
|
||||
Void::Testing::Test variant_get_or_absent()
|
||||
{
|
||||
V3 v = 3.14;
|
||||
Void::Testing::expect_eq(get_or<int>(v, -1), -1);
|
||||
}
|
||||
|
||||
// ── try_get ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test variant_try_get_present()
|
||||
{
|
||||
V3 v = std::string{"world"};
|
||||
const auto r = try_get<std::string>(v);
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, std::string{"world"});
|
||||
}
|
||||
|
||||
Void::Testing::Test variant_try_get_absent()
|
||||
{
|
||||
V3 v = 1;
|
||||
Void::Testing::expect(!try_get<std::string>(v).has_value());
|
||||
}
|
||||
|
||||
// ── index_of ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test variant_index_of_compile_time()
|
||||
{
|
||||
static_assert(index_of<int, V3> == 0);
|
||||
static_assert(index_of<double, V3> == 1);
|
||||
static_assert(index_of<std::string, V3> == 2);
|
||||
Void::Testing::expect(true); // compile-time assertion passed
|
||||
}
|
||||
|
||||
// ── apply_to ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test variant_apply_to_matching()
|
||||
{
|
||||
V3 v = 5;
|
||||
const auto r = apply_to<int>(v, [](int i) { return i * 10; });
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, 50);
|
||||
}
|
||||
|
||||
Void::Testing::Test variant_apply_to_non_matching()
|
||||
{
|
||||
V3 v = 3.14;
|
||||
const auto r = apply_to<int>(v, [](int i) { return i; });
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
// ── narrow ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test variant_narrow_convertible()
|
||||
{
|
||||
V3 v = 7;
|
||||
const auto r = narrow<double>(v); // int is convertible to double
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, 7.0);
|
||||
}
|
||||
|
||||
Void::Testing::Test variant_narrow_not_convertible()
|
||||
{
|
||||
V3 v = std::string{"x"};
|
||||
const auto r = narrow<double>(v);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
Reference in new issue
Block a user