Add async/resilience/reflection primitives + FSM v2 rewrite
A round of new universal capabilities (all generic — templated/reflection based, no app coupling), verified by the test suite (1103 passing): Data reflection: - Reflect.hpp now (de)serializes chrono::duration, chrono::time_point, std::variant (tagged), std::array, and non-string-keyed std::map; Meta.hpp gains is_time_point_v et al. Async: - EventBus gains Mode::Async (worker-thread dispatch + flush()). - ThreadPool gains a bounded queue, try_submit(), and rejection stats. New modules / containers: - Resilience: TokenBucket, KeyedRateLimiter<Key>, CircuitBreaker, ResourceMonitor. - Containers: BufferPool<T> (size-class buffer reuse) and Cache<K,V> (per-entry TTL, LRU/LFU/FIFO eviction, hit/miss stats). - System: process/CPU/memory metrics (Metrics.hpp) and a streaming Process API. Plus FSM v2 (typed Success/Failure, sub-machines, parallel regions, history states, deferred events), Configuration/Logging reflection helpers, and the accompanying test suites. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
43b5a81504
commit
80293ee56f
93 files changed
+8500
-3312
No files matched your search
+193
-58
@@ -1,8 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <any>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
#include <typeindex>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
@@ -10,72 +15,202 @@
|
||||
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.
|
||||
// ── EventBus
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// Publish/subscribe bus keyed by event type.
|
||||
//
|
||||
// Mode::Sync (default) handlers run inline on the publisher's thread
|
||||
// inside
|
||||
// publish() — the original zero-overhead behavior.
|
||||
// Mode::Async publish() snapshots the handlers and a copy of
|
||||
// the
|
||||
// event onto an owned worker thread, so slow
|
||||
// handlers (network / DB I/O) never block the
|
||||
// publisher. flush() waits for everything submitted
|
||||
// before the call.
|
||||
//
|
||||
// In Sync mode the bus is not thread-safe (use external locking if shared).
|
||||
// In Async mode publish/subscribe/flush are safe to call from any thread.
|
||||
|
||||
class EventBus
|
||||
{
|
||||
public:
|
||||
using HandlerId = std::size_t;
|
||||
enum class Mode { Sync, Async };
|
||||
|
||||
// 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;
|
||||
}
|
||||
class EventBus
|
||||
{
|
||||
public:
|
||||
|
||||
// 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);
|
||||
}
|
||||
using HandlerId = std::size_t;
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
explicit EventBus(Mode mode = Mode::Sync) : mode_(mode)
|
||||
{
|
||||
if (mode_ == Mode::Async) {
|
||||
worker_ = std::thread([this] { run(); });
|
||||
}
|
||||
}
|
||||
|
||||
// Remove all handlers for a given event type.
|
||||
template <typename Event>
|
||||
void clear()
|
||||
{
|
||||
handlers_.erase(std::type_index{typeid(Event)});
|
||||
}
|
||||
~EventBus()
|
||||
{
|
||||
if (mode_ == Mode::Async) {
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
stop_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
worker_.join();
|
||||
}
|
||||
}
|
||||
|
||||
void clear_all() { handlers_.clear(); }
|
||||
EventBus(const EventBus&) = delete;
|
||||
EventBus& operator=(const EventBus&) = delete;
|
||||
EventBus(EventBus&&) = delete;
|
||||
EventBus& operator=(EventBus&&) = delete;
|
||||
|
||||
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();
|
||||
}
|
||||
// Subscribe to events of type Event. Returns a HandlerId for
|
||||
// unsubscription.
|
||||
template <typename Event>
|
||||
HandlerId subscribe(std::function<void(const Event&)> handler)
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
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;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
HandlerId id;
|
||||
std::function<void(const std::any&)> fn;
|
||||
};
|
||||
// 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)};
|
||||
if (mode_ == Mode::Sync) {
|
||||
const auto it = handlers_.find(key);
|
||||
if (it == handlers_.end()) {
|
||||
return;
|
||||
}
|
||||
for (const auto& e : it->second) {
|
||||
e.fn(event);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::unordered_map<std::type_index, std::vector<Entry>> handlers_;
|
||||
HandlerId next_id_{1};
|
||||
};
|
||||
// Async: snapshot the current handlers and queue a dispatch
|
||||
// carrying a copy of the event, so later unsubscribe()s don't
|
||||
// affect this publish.
|
||||
std::unique_lock lock{mu_};
|
||||
const auto it = handlers_.find(key);
|
||||
if (it == handlers_.end()) {
|
||||
return;
|
||||
}
|
||||
std::vector<std::function<void(const std::any&)>> snapshot;
|
||||
snapshot.reserve(it->second.size());
|
||||
for (const auto& e : it->second) {
|
||||
snapshot.push_back(e.fn);
|
||||
}
|
||||
tasks_.push([snap = std::move(snapshot), ev = std::any{event}] {
|
||||
for (const auto& fn : snap) {
|
||||
fn(ev);
|
||||
}
|
||||
});
|
||||
++enqueued_;
|
||||
lock.unlock();
|
||||
cv_.notify_one();
|
||||
}
|
||||
|
||||
// Async only: block until every event published before this call
|
||||
// has been dispatched. A no-op in Sync mode (delivery already
|
||||
// happened in publish()).
|
||||
void flush()
|
||||
{
|
||||
if (mode_ != Mode::Async) {
|
||||
return;
|
||||
}
|
||||
std::unique_lock lock{mu_};
|
||||
const auto target = enqueued_;
|
||||
done_cv_.wait(lock, [&] { return processed_ >= target; });
|
||||
}
|
||||
|
||||
// Unsubscribe by id. O(n) per event type — acceptable for small
|
||||
// handler counts.
|
||||
void unsubscribe(HandlerId id)
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
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()
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
handlers_.erase(std::type_index{typeid(Event)});
|
||||
}
|
||||
|
||||
void clear_all()
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
handlers_.clear();
|
||||
}
|
||||
|
||||
template <typename Event>
|
||||
[[nodiscard]] std::size_t subscriber_count() const
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
const auto it = handlers_.find(std::type_index{typeid(Event)});
|
||||
return it == handlers_.end() ? 0 : it->second.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] Mode mode() const noexcept { return mode_; }
|
||||
|
||||
private:
|
||||
|
||||
struct Entry {
|
||||
HandlerId id;
|
||||
std::function<void(const std::any&)> fn;
|
||||
};
|
||||
|
||||
void run()
|
||||
{
|
||||
for (;;) {
|
||||
std::function<void()> task;
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
cv_.wait(lock,
|
||||
[this] { return stop_ || !tasks_.empty(); });
|
||||
if (stop_ && tasks_.empty()) {
|
||||
return;
|
||||
}
|
||||
task = std::move(tasks_.front());
|
||||
tasks_.pop();
|
||||
}
|
||||
task();
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
++processed_;
|
||||
}
|
||||
done_cv_.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
Mode mode_;
|
||||
std::unordered_map<std::type_index, std::vector<Entry>> handlers_;
|
||||
HandlerId next_id_{1};
|
||||
|
||||
mutable std::mutex mu_;
|
||||
// Async machinery (unused in Sync mode).
|
||||
std::thread worker_;
|
||||
std::queue<std::function<void()>> tasks_;
|
||||
std::condition_variable cv_;
|
||||
std::condition_variable done_cv_;
|
||||
std::uint64_t enqueued_{0};
|
||||
std::uint64_t processed_{0};
|
||||
bool stop_{false};
|
||||
};
|
||||
|
||||
} // namespace Void::EventBus
|
||||
@@ -1,11 +1,14 @@
|
||||
#pragma once
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
@@ -18,15 +21,30 @@ namespace Void::Concurrency
|
||||
{
|
||||
public:
|
||||
|
||||
// A snapshot of throughput / backpressure counters.
|
||||
struct Stats {
|
||||
std::uint64_t submitted =
|
||||
0; // tasks accepted onto the queue
|
||||
std::uint64_t completed = 0; // tasks finished running
|
||||
std::uint64_t rejected = 0; // try_submit refusals (full)
|
||||
std::size_t pending = 0; // tasks currently queued
|
||||
};
|
||||
|
||||
// `max_queue == 0` keeps the queue unbounded (the historical
|
||||
// behavior). A non-zero bound makes submit() block for space and
|
||||
// try_submit() reject when the queue is full.
|
||||
explicit ThreadPool(
|
||||
std::size_t n = std::thread::hardware_concurrency())
|
||||
std::size_t n = std::thread::hardware_concurrency(),
|
||||
std::size_t max_queue = 0)
|
||||
: max_queue_{max_queue}
|
||||
{
|
||||
const std::size_t count = (n > 0) ? n : 1;
|
||||
workers_.reserve(count);
|
||||
for (std::size_t i = 0; i < count; ++i) {
|
||||
workers_.emplace_back([this] { worker_loop(); });
|
||||
}
|
||||
Void::Log::debug("Concurrency", "ThreadPool: started with {} threads", count);
|
||||
Void::Log::debug("Concurrency",
|
||||
"ThreadPool: started with {} threads", count);
|
||||
}
|
||||
|
||||
~ThreadPool()
|
||||
@@ -37,6 +55,7 @@ namespace Void::Concurrency
|
||||
stop_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
not_full_.notify_all();
|
||||
for (auto& w : workers_) {
|
||||
w.join();
|
||||
}
|
||||
@@ -47,6 +66,8 @@ namespace Void::Concurrency
|
||||
ThreadPool(ThreadPool&&) = delete;
|
||||
ThreadPool& operator=(ThreadPool&&) = delete;
|
||||
|
||||
// Enqueue a task. On a bounded pool this blocks until the queue has
|
||||
// space (backpressure); on an unbounded pool it never blocks.
|
||||
template <std::invocable F>
|
||||
auto submit(F&& f) -> std::future<std::invoke_result_t<F>>
|
||||
{
|
||||
@@ -56,12 +77,43 @@ namespace Void::Concurrency
|
||||
auto fut = task->get_future();
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
if (max_queue_ > 0) {
|
||||
not_full_.wait(lock, [this] {
|
||||
return stop_ || queue_.size() < max_queue_;
|
||||
});
|
||||
}
|
||||
if (stop_) {
|
||||
throw std::runtime_error(
|
||||
"Void::Concurrency::ThreadPool: submit after "
|
||||
"shutdown");
|
||||
}
|
||||
queue_.push([task] { (*task)(); });
|
||||
push_locked(task);
|
||||
}
|
||||
cv_.notify_one();
|
||||
return fut;
|
||||
}
|
||||
|
||||
// Non-blocking enqueue. Returns nullopt when a bounded queue is
|
||||
// full (recording a rejection) or after shutdown; otherwise the
|
||||
// future.
|
||||
template <std::invocable F>
|
||||
auto try_submit(F&& f)
|
||||
-> std::optional<std::future<std::invoke_result_t<F>>>
|
||||
{
|
||||
using R = std::invoke_result_t<F>;
|
||||
auto task = std::make_shared<std::packaged_task<R()>>(
|
||||
std::forward<F>(f));
|
||||
auto fut = task->get_future();
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
if (stop_) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (max_queue_ > 0 && queue_.size() >= max_queue_) {
|
||||
rejected_.fetch_add(1, std::memory_order_relaxed);
|
||||
return std::nullopt;
|
||||
}
|
||||
push_locked(task);
|
||||
}
|
||||
cv_.notify_one();
|
||||
return fut;
|
||||
@@ -78,8 +130,29 @@ namespace Void::Concurrency
|
||||
return queue_.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] Stats stats() const
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
return Stats{
|
||||
submitted_.load(std::memory_order_relaxed),
|
||||
completed_.load(std::memory_order_relaxed),
|
||||
rejected_.load(std::memory_order_relaxed),
|
||||
queue_.size(),
|
||||
};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
template <typename R>
|
||||
void push_locked(std::shared_ptr<std::packaged_task<R()>> task)
|
||||
{
|
||||
queue_.push([this, task] {
|
||||
(*task)();
|
||||
completed_.fetch_add(1, std::memory_order_relaxed);
|
||||
});
|
||||
submitted_.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
void worker_loop()
|
||||
{
|
||||
for (;;) {
|
||||
@@ -94,14 +167,22 @@ namespace Void::Concurrency
|
||||
task = std::move(queue_.front());
|
||||
queue_.pop();
|
||||
}
|
||||
if (max_queue_ > 0) {
|
||||
not_full_.notify_one();
|
||||
}
|
||||
task();
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t max_queue_;
|
||||
std::vector<std::thread> workers_;
|
||||
std::queue<std::function<void()>> queue_;
|
||||
mutable std::mutex mu_;
|
||||
std::condition_variable cv_;
|
||||
std::condition_variable not_full_;
|
||||
std::atomic<std::uint64_t> submitted_{0};
|
||||
std::atomic<std::uint64_t> completed_{0};
|
||||
std::atomic<std::uint64_t> rejected_{0};
|
||||
bool stop_{false};
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <expected>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
@@ -9,54 +11,156 @@
|
||||
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
|
||||
// ── 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 = {});
|
||||
class Parser
|
||||
{
|
||||
public:
|
||||
|
||||
// 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);
|
||||
explicit Parser(std::string program, std::string description = {});
|
||||
|
||||
// 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 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 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 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 a required positional argument.
|
||||
Parser& positional(std::string_view name, std::string_view description, 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 = "");
|
||||
|
||||
// Parse argc/argv. Returns error message on failure.
|
||||
[[nodiscard]] std::expected<void, std::string>
|
||||
parse(int argc, const char* const* argv) const;
|
||||
// Add a required positional argument.
|
||||
Parser& positional(std::string_view name,
|
||||
std::string_view description, std::string& out);
|
||||
|
||||
// Returns formatted help text.
|
||||
[[nodiscard]] std::string help() const;
|
||||
// Parse argc/argv. Returns error message on failure.
|
||||
[[nodiscard]] std::expected<void, std::string>
|
||||
parse(int argc, const char* const* argv) 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; };
|
||||
// Returns formatted help text.
|
||||
[[nodiscard]] std::string help() const;
|
||||
|
||||
std::string program_, description_;
|
||||
std::vector<FlagEntry> flags_;
|
||||
std::vector<OptionEntry> options_;
|
||||
std::vector<PosEntry> positionals_;
|
||||
};
|
||||
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_;
|
||||
};
|
||||
|
||||
// ── reflective options struct
|
||||
// ───────────────────────────────────────────────── Define a struct,
|
||||
// annotate its fields, and parse straight into it:
|
||||
//
|
||||
// struct Opts {
|
||||
// [[= arg::Short{'v'}]] [[= arg::Help{"verbose output"}]] bool
|
||||
// verbose = false;
|
||||
// [[= arg::Help{"output path"}]] std::string
|
||||
// out = "a.out"; std::optional<std::string> config; // --config
|
||||
// <v>
|
||||
// [[= arg::Positional{}]] std::string input;
|
||||
// };
|
||||
// auto o = Argparse::parse<Opts>(argc, argv); // std::expected<Opts,
|
||||
// string>
|
||||
//
|
||||
// Field → argument: bool → flag, std::string → option with default (the
|
||||
// field's initializer), std::optional<std::string> → optional option, a
|
||||
// field tagged
|
||||
// [[= arg::Positional]] → positional. Other field types are ignored.
|
||||
|
||||
struct Short {
|
||||
char c;
|
||||
};
|
||||
struct Help {
|
||||
Void::Meta::Str text;
|
||||
};
|
||||
struct Name {
|
||||
Void::Meta::Str text;
|
||||
}; // long-name override (without "--")
|
||||
struct Positional {
|
||||
};
|
||||
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
|
||||
template <typename Opts>
|
||||
[[nodiscard]] std::expected<Opts, std::string>
|
||||
parse(int argc, const char* const* argv, std::string program = "app",
|
||||
std::string description = {})
|
||||
{
|
||||
Opts out{};
|
||||
Parser parser{std::move(program), std::move(description)};
|
||||
|
||||
template for (constexpr auto m : Void::Meta::members_v<Opts>)
|
||||
{
|
||||
using MT = [:std::meta::type_of(m):];
|
||||
constexpr auto nm = Void::Meta::annotation_of<Name>(m);
|
||||
const std::string lng =
|
||||
std::string{"--"} +
|
||||
(nm.has_value() ? std::string{nm->text.view()}
|
||||
: std::string{std::meta::identifier_of(m)});
|
||||
constexpr auto sh = Void::Meta::annotation_of<Short>(m);
|
||||
const std::string sht =
|
||||
sh.has_value() ? (std::string{"-"} + sh->c) : std::string{};
|
||||
constexpr auto hp = Void::Meta::annotation_of<Help>(m);
|
||||
const std::string desc =
|
||||
hp.has_value() ? std::string{hp->text.view()} : std::string{};
|
||||
|
||||
if constexpr (Void::Meta::has_annotation<Positional>(m)) {
|
||||
parser.positional(std::meta::identifier_of(m), desc, out.[:m:]);
|
||||
} else if constexpr (std::same_as<MT, bool>) {
|
||||
parser.flag(lng, sht, desc, out.[:m:]);
|
||||
} else if constexpr (Void::Meta::is_optional_v<MT>) {
|
||||
parser.option(lng, sht, desc, out.[:m:]);
|
||||
} else if constexpr (std::same_as<MT, std::string>) {
|
||||
const std::string def = out.[:m:];
|
||||
parser.option_default(lng, sht, desc, out.[:m:], def);
|
||||
}
|
||||
// other field types: ignored
|
||||
}
|
||||
|
||||
auto r = parser.parse(argc, argv);
|
||||
if (!r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
#endif // VOID_HAS_META_REFLECTION
|
||||
|
||||
} // namespace Void::Argparse
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
@@ -39,31 +40,28 @@
|
||||
namespace Void::Configuration
|
||||
{
|
||||
|
||||
// ── field annotations ─────────────────────────────────────────────────
|
||||
// Annotate aggregate members to control binding:
|
||||
// struct Settings {
|
||||
// [[= Configuration::Key{"log_level"}]] std::string level = "info";
|
||||
// [[= Configuration::Required{}]] std::string host;
|
||||
// };
|
||||
struct Key {
|
||||
Void::Meta::Str name;
|
||||
};
|
||||
struct Required {
|
||||
};
|
||||
|
||||
#ifdef VOID_HAS_CONFIG_REFLECTION
|
||||
|
||||
namespace BindDetail
|
||||
{
|
||||
template <typename T> struct IsOptional : std::false_type {
|
||||
};
|
||||
template <typename U>
|
||||
struct IsOptional<std::optional<U>> : std::true_type {
|
||||
};
|
||||
|
||||
template <typename T> struct IsVector : std::false_type {
|
||||
};
|
||||
template <typename U> struct IsVector<std::vector<U>> : std::true_type {
|
||||
};
|
||||
|
||||
template <typename T> struct IsDuration : std::false_type {
|
||||
};
|
||||
template <typename Rep, typename Period>
|
||||
struct IsDuration<std::chrono::duration<Rep, Period>> : std::true_type {
|
||||
};
|
||||
|
||||
// Leaf / container shape detection comes from Void::Meta (single
|
||||
// source); Config additionally treats chrono durations as leaves.
|
||||
template <typename T>
|
||||
concept Leaf = std::is_same_v<T, std::string> ||
|
||||
std::is_same_v<T, bool> || std::is_arithmetic_v<T> ||
|
||||
std::is_enum_v<T> || IsDuration<T>::value;
|
||||
std::is_enum_v<T> || Void::Meta::is_duration_v<T>;
|
||||
|
||||
template <typename T>
|
||||
concept BindableAggregate =
|
||||
@@ -86,16 +84,20 @@ namespace Void::Configuration
|
||||
T out{};
|
||||
std::optional<Void::Result::Error> failure;
|
||||
|
||||
static constexpr auto members =
|
||||
std::define_static_array(std::meta::nonstatic_data_members_of(
|
||||
^^T, std::meta::access_context::current()));
|
||||
|
||||
template for (constexpr auto m : members)
|
||||
template for (constexpr auto m : Void::Meta::members_v<T>)
|
||||
{
|
||||
if (!failure) {
|
||||
constexpr auto name = std::meta::identifier_of(m);
|
||||
using MT = [:std::meta::type_of(m):];
|
||||
const auto key = join(prefix, name);
|
||||
// Key segment: a [[= Configuration::Key("…")]] override,
|
||||
// else the field identifier.
|
||||
constexpr auto ko = Void::Meta::annotation_of<Key>(m);
|
||||
const std::string seg =
|
||||
ko.has_value()
|
||||
? std::string{ko->name.view()}
|
||||
: std::string{std::meta::identifier_of(m)};
|
||||
const auto key = join(prefix, seg);
|
||||
[[maybe_unused]] constexpr bool required =
|
||||
Void::Meta::has_annotation<Required>(m);
|
||||
|
||||
if constexpr (BindableAggregate<MT> && !Leaf<MT>) {
|
||||
auto nested = bind_into<MT>(cfg, key);
|
||||
@@ -104,7 +106,7 @@ namespace Void::Configuration
|
||||
} else {
|
||||
out.[:m:] = std::move(*nested);
|
||||
}
|
||||
} else if constexpr (IsOptional<MT>::value) {
|
||||
} else if constexpr (Void::Meta::is_optional_v<MT>) {
|
||||
using U = typename MT::value_type;
|
||||
if (cfg.contains(key)) {
|
||||
auto v = cfg.get_as<U>(key);
|
||||
@@ -114,7 +116,7 @@ namespace Void::Configuration
|
||||
out.[:m:] = std::move(*v);
|
||||
}
|
||||
}
|
||||
} else if constexpr (IsVector<MT>::value) {
|
||||
} else if constexpr (Void::Meta::is_vector_v<MT>) {
|
||||
using U = typename MT::value_type;
|
||||
MT items;
|
||||
for (std::size_t i = 0;; ++i) {
|
||||
@@ -142,8 +144,11 @@ namespace Void::Configuration
|
||||
} else {
|
||||
out.[:m:] = std::move(*v);
|
||||
}
|
||||
} else if constexpr (required) {
|
||||
failure = Void::Result::Error{
|
||||
"missing required config key '" + key + "'"};
|
||||
}
|
||||
// absent key: keep the default member value
|
||||
// absent + not required: keep the default member value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,15 +4,17 @@
|
||||
#include <Void/Data/Ini.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Detail/Enum.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/Time/Format.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <initializer_list>
|
||||
@@ -32,495 +34,514 @@ extern char** environ; // NOLINT
|
||||
namespace Void::Configuration
|
||||
{
|
||||
|
||||
/// Layered key-value configuration store with dotted nested keys.
|
||||
///
|
||||
/// Values are plain strings; typed access via get_as<T>(). Layers are
|
||||
/// applied via overlay(): the last overlay wins on key conflicts.
|
||||
/// Typical usage:
|
||||
///
|
||||
/// auto cfg = Config::from_env_prefix("MYAPP_"); // MYAPP_LOG__LEVEL → log.level
|
||||
/// if (auto r = Config::from_ini("app.ini"); r.has_value())
|
||||
/// cfg.overlay(*r); // ini overrides env
|
||||
/// cfg.overlay(Config::from_args(argc, argv)); // --log.level=debug wins
|
||||
/// auto level = cfg.get_or("log.level", "info");
|
||||
/// auto retries = cfg.get_as<int>("net.retries"); // Result<int>
|
||||
///
|
||||
/// Sources: from_env / from_env_prefix (environment), from_file
|
||||
/// (KEY=VALUE), from_ini (sections become key prefixes), from_json
|
||||
/// (nested objects flatten into dotted keys), from_args (--key=value).
|
||||
class Config
|
||||
{
|
||||
public:
|
||||
/// Layered key-value configuration store with dotted nested keys.
|
||||
///
|
||||
/// Values are plain strings; typed access via get_as<T>(). Layers are
|
||||
/// applied via overlay(): the last overlay wins on key conflicts.
|
||||
/// Typical usage:
|
||||
///
|
||||
/// auto cfg = Config::from_env_prefix("MYAPP_"); // MYAPP_LOG__LEVEL →
|
||||
/// log.level if (auto r = Config::from_ini("app.ini"); r.has_value())
|
||||
/// cfg.overlay(*r); // ini overrides env
|
||||
/// cfg.overlay(Config::from_args(argc, argv)); // --log.level=debug
|
||||
/// wins auto level = cfg.get_or("log.level", "info"); auto retries =
|
||||
/// cfg.get_as<int>("net.retries"); // Result<int>
|
||||
///
|
||||
/// Sources: from_env / from_env_prefix (environment), from_file
|
||||
/// (KEY=VALUE), from_ini (sections become key prefixes), from_json
|
||||
/// (nested objects flatten into dotted keys), from_args (--key=value).
|
||||
class Config
|
||||
{
|
||||
public:
|
||||
|
||||
Config() = default;
|
||||
Config() = default;
|
||||
|
||||
/// Populate from specific named environment variables.
|
||||
/// Keys absent from the environment are silently skipped.
|
||||
[[nodiscard]] static Config
|
||||
from_env(std::initializer_list<std::string_view> keys)
|
||||
{
|
||||
Config cfg;
|
||||
for (auto key : keys) {
|
||||
if (auto r = get_env(key); r.has_value()) {
|
||||
cfg.values_.emplace(std::string{key}, std::move(*r));
|
||||
Void::Log::debug("Configuration", "from_env: loaded '{}'", key);
|
||||
/// Populate from specific named environment variables.
|
||||
/// Keys absent from the environment are silently skipped.
|
||||
[[nodiscard]] static Config
|
||||
from_env(std::initializer_list<std::string_view> keys)
|
||||
{
|
||||
Config cfg;
|
||||
for (auto key : keys) {
|
||||
if (auto r = get_env(key); r.has_value()) {
|
||||
cfg.values_.emplace(std::string{key}, std::move(*r));
|
||||
Void::Log::debug("Configuration",
|
||||
"from_env: loaded '{}'", key);
|
||||
}
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/// Parse a KEY=VALUE text file (one pair per line, # for comments).
|
||||
/// Lines without '=' produce a warning log and are skipped.
|
||||
[[nodiscard]] static Void::Result::Result<Config,
|
||||
Void::Result::Error>
|
||||
from_file(const std::filesystem::path& path)
|
||||
{
|
||||
auto text = Void::FileSystem::read_file(path);
|
||||
if (!text.has_value()) {
|
||||
return Void::Result::fail(
|
||||
std::format("Configuration::Config::from_file: {}",
|
||||
text.error().message()));
|
||||
}
|
||||
Config cfg;
|
||||
std::istringstream ss{*text};
|
||||
std::string line;
|
||||
int lineno = 0;
|
||||
while (std::getline(ss, line)) {
|
||||
++lineno;
|
||||
if (!line.empty() && line.back() == '\r') {
|
||||
line.pop_back();
|
||||
}
|
||||
std::string_view sv{line};
|
||||
while (!sv.empty() && sv.front() == ' ') {
|
||||
sv.remove_prefix(1);
|
||||
}
|
||||
if (sv.empty() || sv.front() == '#') {
|
||||
continue;
|
||||
}
|
||||
auto eq = sv.find('=');
|
||||
if (eq == std::string_view::npos) {
|
||||
Void::Log::warn("Configuration",
|
||||
"from_file: '{}' line {}: missing '='",
|
||||
path.string(), lineno);
|
||||
continue;
|
||||
}
|
||||
auto key = sv.substr(0, eq);
|
||||
while (!key.empty() && key.back() == ' ') {
|
||||
key.remove_suffix(1);
|
||||
}
|
||||
auto val = sv.substr(eq + 1);
|
||||
cfg.values_.emplace(std::string{key}, std::string{val});
|
||||
}
|
||||
Void::Log::debug("Configuration",
|
||||
"from_file: loaded {} keys from '{}'",
|
||||
cfg.values_.size(), path.string());
|
||||
return Void::Result::ok(std::move(cfg));
|
||||
}
|
||||
|
||||
/// Layer `other` on top: other's values win on key conflicts.
|
||||
void overlay(const Config& other)
|
||||
{
|
||||
for (const auto& [k, v] : other.values_) {
|
||||
values_.insert_or_assign(k, v);
|
||||
}
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/// Parse a KEY=VALUE text file (one pair per line, # for comments).
|
||||
/// Lines without '=' produce a warning log and are skipped.
|
||||
[[nodiscard]] static Void::Result::Result<Config, Void::Result::Error>
|
||||
from_file(const std::filesystem::path& path)
|
||||
{
|
||||
auto text = Void::FileSystem::read_file(path);
|
||||
if (!text.has_value()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Configuration::Config::from_file: {}", text.error().message()));
|
||||
/// Explicit per-key override (highest priority).
|
||||
void set(std::string_view key, std::string value)
|
||||
{
|
||||
values_.insert_or_assign(std::string{key}, std::move(value));
|
||||
}
|
||||
Config cfg;
|
||||
std::istringstream ss{*text};
|
||||
std::string line;
|
||||
int lineno = 0;
|
||||
while (std::getline(ss, line)) {
|
||||
++lineno;
|
||||
if (!line.empty() && line.back() == '\r') {
|
||||
line.pop_back();
|
||||
|
||||
/// Look up a key. Returns an error if the key is not present.
|
||||
[[nodiscard]] Void::Result::Result<std::string_view,
|
||||
Void::Result::Error>
|
||||
get(std::string_view key) const
|
||||
{
|
||||
auto it = values_.find(std::string{key});
|
||||
if (it == values_.end()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Configuration::Config::get: key '{}' not found", key));
|
||||
}
|
||||
std::string_view sv{line};
|
||||
while (!sv.empty() && sv.front() == ' ') {
|
||||
sv.remove_prefix(1);
|
||||
}
|
||||
if (sv.empty() || sv.front() == '#') {
|
||||
continue;
|
||||
}
|
||||
auto eq = sv.find('=');
|
||||
if (eq == std::string_view::npos) {
|
||||
Void::Log::warn("Configuration", "from_file: '{}' line {}: missing '='",
|
||||
path.string(), lineno);
|
||||
continue;
|
||||
}
|
||||
auto key = sv.substr(0, eq);
|
||||
while (!key.empty() && key.back() == ' ') {
|
||||
key.remove_suffix(1);
|
||||
}
|
||||
auto val = sv.substr(eq + 1);
|
||||
cfg.values_.emplace(std::string{key}, std::string{val});
|
||||
return Void::Result::ok(std::string_view{it->second});
|
||||
}
|
||||
Void::Log::debug("Configuration", "from_file: loaded {} keys from '{}'",
|
||||
cfg.values_.size(), path.string());
|
||||
return Void::Result::ok(std::move(cfg));
|
||||
}
|
||||
|
||||
/// Layer `other` on top: other's values win on key conflicts.
|
||||
void overlay(const Config& other)
|
||||
{
|
||||
for (const auto& [k, v] : other.values_) {
|
||||
values_.insert_or_assign(k, v);
|
||||
/// Look up a key, returning `fallback` when the key is absent.
|
||||
[[nodiscard]] std::string_view
|
||||
get_or(std::string_view key,
|
||||
std::string_view fallback = {}) const
|
||||
{
|
||||
auto it = values_.find(std::string{key});
|
||||
return it != values_.end() ? std::string_view{it->second}
|
||||
: fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/// Explicit per-key override (highest priority).
|
||||
void set(std::string_view key, std::string value)
|
||||
{
|
||||
values_.insert_or_assign(std::string{key}, std::move(value));
|
||||
}
|
||||
|
||||
/// Look up a key. Returns an error if the key is not present.
|
||||
[[nodiscard]] Void::Result::Result<std::string_view, Void::Result::Error>
|
||||
get(std::string_view key) const
|
||||
{
|
||||
auto it = values_.find(std::string{key});
|
||||
if (it == values_.end()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Configuration::Config::get: key '{}' not found", key));
|
||||
[[nodiscard]] std::size_t size() const noexcept
|
||||
{
|
||||
return values_.size();
|
||||
}
|
||||
[[nodiscard]] bool empty() const noexcept
|
||||
{
|
||||
return values_.empty();
|
||||
}
|
||||
return Void::Result::ok(std::string_view{it->second});
|
||||
}
|
||||
|
||||
/// Look up a key, returning `fallback` when the key is absent.
|
||||
[[nodiscard]] std::string_view
|
||||
get_or(std::string_view key, std::string_view fallback = {}) const
|
||||
{
|
||||
auto it = values_.find(std::string{key});
|
||||
return it != values_.end() ? std::string_view{it->second} : fallback;
|
||||
}
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
// Additional sources
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept
|
||||
{
|
||||
return values_.size();
|
||||
}
|
||||
[[nodiscard]] bool empty() const noexcept { return values_.empty(); }
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
// Additional sources
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Scan the whole environment for variables starting with `prefix`.
|
||||
/// The prefix is stripped, `__` becomes `.`, and the key is
|
||||
/// lowercased: MYAPP_LOG__LEVEL=debug → log.level=debug.
|
||||
[[nodiscard]] static Config from_env_prefix(std::string_view prefix)
|
||||
{
|
||||
Config cfg;
|
||||
/// Scan the whole environment for variables starting with `prefix`.
|
||||
/// The prefix is stripped, `__` becomes `.`, and the key is
|
||||
/// lowercased: MYAPP_LOG__LEVEL=debug → log.level=debug.
|
||||
[[nodiscard]] static Config from_env_prefix(std::string_view prefix)
|
||||
{
|
||||
Config cfg;
|
||||
#ifdef VOID_CONFIG_HAS_ENVIRON
|
||||
for (char** env = environ; *env != nullptr; ++env) {
|
||||
const std::string_view kv{*env};
|
||||
const auto eq = kv.find('=');
|
||||
if (eq == std::string_view::npos ||
|
||||
!kv.starts_with(prefix)) {
|
||||
continue;
|
||||
for (char** env = environ; *env != nullptr; ++env) {
|
||||
const std::string_view kv{*env};
|
||||
const auto eq = kv.find('=');
|
||||
if (eq == std::string_view::npos ||
|
||||
!kv.starts_with(prefix)) {
|
||||
continue;
|
||||
}
|
||||
auto raw_key = kv.substr(prefix.size(), eq - prefix.size());
|
||||
std::string key;
|
||||
key.reserve(raw_key.size());
|
||||
for (std::size_t i = 0; i < raw_key.size(); ++i) {
|
||||
if (raw_key[i] == '_' && i + 1 < raw_key.size() &&
|
||||
raw_key[i + 1] == '_') {
|
||||
key += '.';
|
||||
++i;
|
||||
} else {
|
||||
key += static_cast<char>(std::tolower(
|
||||
static_cast<unsigned char>(raw_key[i])));
|
||||
}
|
||||
}
|
||||
cfg.values_.emplace(std::move(key),
|
||||
std::string{kv.substr(eq + 1)});
|
||||
}
|
||||
auto raw_key = kv.substr(prefix.size(), eq - prefix.size());
|
||||
std::string key;
|
||||
key.reserve(raw_key.size());
|
||||
for (std::size_t i = 0; i < raw_key.size(); ++i) {
|
||||
if (raw_key[i] == '_' && i + 1 < raw_key.size() &&
|
||||
raw_key[i + 1] == '_') {
|
||||
key += '.';
|
||||
Void::Log::debug("Configuration",
|
||||
"from_env_prefix('{}'): {} keys", prefix,
|
||||
cfg.size());
|
||||
#else
|
||||
(void)prefix;
|
||||
#endif
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/// Parse an INI file: `[section]` + `key = value` becomes
|
||||
/// "section.key"; pairs before any section keep their bare key.
|
||||
[[nodiscard]] static Void::Result::Result<Config,
|
||||
Void::Result::Error>
|
||||
from_ini(const std::filesystem::path& path)
|
||||
{
|
||||
auto text = Void::FileSystem::read_file(path);
|
||||
if (!text.has_value()) {
|
||||
return Void::Result::fail(
|
||||
std::format("Configuration::Config::from_ini: {}",
|
||||
text.error().message()));
|
||||
}
|
||||
return from_ini_text(*text);
|
||||
}
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<Config,
|
||||
Void::Result::Error>
|
||||
from_ini_text(std::string_view text)
|
||||
{
|
||||
Void::Ini::IniFile ini;
|
||||
if (auto err = Void::Ini::IniFile::parse(ini, text);
|
||||
err.has_value()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Configuration::Config::from_ini: line {}: {}",
|
||||
err->line, err->message));
|
||||
}
|
||||
Config cfg;
|
||||
for (const auto& name : ini.sections()) {
|
||||
const auto* section = ini.section(name);
|
||||
if (section == nullptr) {
|
||||
continue;
|
||||
}
|
||||
for (const auto& [key, value] : *section) {
|
||||
auto full = name.empty() ? key : name + "." + key;
|
||||
cfg.values_.insert_or_assign(std::move(full), value);
|
||||
}
|
||||
}
|
||||
return Void::Result::ok(std::move(cfg));
|
||||
}
|
||||
|
||||
/// Parse a JSON file; nested objects flatten into dotted keys,
|
||||
/// arrays into numeric segments ("servers.0.host"). Scalars are
|
||||
/// stored in their canonical string form.
|
||||
[[nodiscard]] static Void::Result::Result<Config,
|
||||
Void::Result::Error>
|
||||
from_json(const std::filesystem::path& path)
|
||||
{
|
||||
auto text = Void::FileSystem::read_file(path);
|
||||
if (!text.has_value()) {
|
||||
return Void::Result::fail(
|
||||
std::format("Configuration::Config::from_json: {}",
|
||||
text.error().message()));
|
||||
}
|
||||
return from_json_text(*text);
|
||||
}
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<Config,
|
||||
Void::Result::Error>
|
||||
from_json_text(std::string_view text)
|
||||
{
|
||||
auto parsed = Void::Json::parse(text);
|
||||
if (!parsed.has_value()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Configuration::Config::from_json: line {} col {}: {}",
|
||||
parsed.error().line, parsed.error().col,
|
||||
parsed.error().message));
|
||||
}
|
||||
Config cfg;
|
||||
flatten_json(cfg, "", *parsed);
|
||||
return Void::Result::ok(std::move(cfg));
|
||||
}
|
||||
|
||||
/// Collect `--key=value`, `--key value` and bare `--flag`
|
||||
/// (stored as "true") arguments. Non-option arguments are ignored.
|
||||
[[nodiscard]] static Config from_args(int argc,
|
||||
const char* const* argv)
|
||||
{
|
||||
Config cfg;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string_view arg{argv[i]};
|
||||
if (!arg.starts_with("--") || arg.size() <= 2) {
|
||||
continue;
|
||||
}
|
||||
const auto body = arg.substr(2);
|
||||
if (const auto eq = body.find('=');
|
||||
eq != std::string_view::npos) {
|
||||
cfg.values_.insert_or_assign(
|
||||
std::string{body.substr(0, eq)},
|
||||
std::string{body.substr(eq + 1)});
|
||||
} else if (i + 1 < argc &&
|
||||
std::string_view{argv[i + 1]}.substr(0, 2) !=
|
||||
"--") {
|
||||
cfg.values_.insert_or_assign(std::string{body},
|
||||
std::string{argv[i + 1]});
|
||||
++i;
|
||||
} else {
|
||||
cfg.values_.insert_or_assign(std::string{body}, "true");
|
||||
}
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
// Typed access
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Look up and convert. Supported T: integral and floating types,
|
||||
/// bool ("true/false/1/0/yes/no/on/off", case-insensitive), enums
|
||||
/// (by enumerator name, reflection builds), std::string, and
|
||||
/// std::chrono durations ("250ms", "10s", "5m", "1h", "500us",
|
||||
/// "30ns" — converted to T, rejecting lossy narrowing).
|
||||
template <typename T>
|
||||
[[nodiscard]] Void::Result::Result<T, Void::Result::Error>
|
||||
get_as(std::string_view key) const
|
||||
{
|
||||
const auto it = values_.find(std::string{key});
|
||||
if (it == values_.end()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Configuration::Config::get_as: key '{}' not found",
|
||||
key));
|
||||
}
|
||||
return convert<T>(key, it->second);
|
||||
}
|
||||
|
||||
/// Typed lookup with fallback for missing keys. Conversion errors
|
||||
/// on a *present* key still surface the fallback but are logged.
|
||||
template <typename T>
|
||||
[[nodiscard]] T get_or_as(std::string_view key, T fallback) const
|
||||
{
|
||||
auto r = get_as<T>(key);
|
||||
if (r.has_value()) {
|
||||
return std::move(*r);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
// Key enumeration / subtrees
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
|
||||
/// All keys, sorted.
|
||||
[[nodiscard]] std::vector<std::string> keys() const
|
||||
{
|
||||
std::vector<std::string> out;
|
||||
out.reserve(values_.size());
|
||||
for (const auto& [k, _] : values_) {
|
||||
out.push_back(k);
|
||||
}
|
||||
std::sort(out.begin(), out.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
/// A new Config holding every key under "prefix." with the prefix
|
||||
/// stripped: subtree("log") of {log.level, log.file.path} yields
|
||||
/// {level, file.path}.
|
||||
[[nodiscard]] Config subtree(std::string_view prefix) const
|
||||
{
|
||||
Config out;
|
||||
const auto full = std::string{prefix} + ".";
|
||||
for (const auto& [k, v] : values_) {
|
||||
if (k.starts_with(full)) {
|
||||
out.values_.emplace(k.substr(full.size()), v);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool contains(std::string_view key) const
|
||||
{
|
||||
return values_.contains(std::string{key});
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static void flatten_json(Config& cfg, const std::string& prefix,
|
||||
const Void::Json::Value& v)
|
||||
{
|
||||
using Void::Json::Value;
|
||||
if (v.is_object()) {
|
||||
for (const auto& [k, child] : v.as_object()) {
|
||||
flatten_json(cfg, prefix.empty() ? k : prefix + "." + k,
|
||||
child);
|
||||
}
|
||||
} else if (v.is_array()) {
|
||||
std::size_t i = 0;
|
||||
for (const auto& child : v.as_array()) {
|
||||
flatten_json(cfg, prefix + "." + std::to_string(i),
|
||||
child);
|
||||
++i;
|
||||
}
|
||||
else {
|
||||
key += static_cast<char>(std::tolower(
|
||||
static_cast<unsigned char>(raw_key[i])));
|
||||
} else if (v.is_string()) {
|
||||
cfg.values_.insert_or_assign(prefix, v.as_string());
|
||||
} else if (v.is_bool()) {
|
||||
cfg.values_.insert_or_assign(prefix, v.as_bool() ? "true"
|
||||
: "false");
|
||||
} else if (v.is_number()) {
|
||||
const double d = v.as_number();
|
||||
if (d == static_cast<double>(static_cast<long long>(d))) {
|
||||
cfg.values_.insert_or_assign(
|
||||
prefix, std::to_string(static_cast<long long>(d)));
|
||||
} else {
|
||||
cfg.values_.insert_or_assign(prefix,
|
||||
std::format("{}", d));
|
||||
}
|
||||
}
|
||||
cfg.values_.emplace(std::move(key),
|
||||
std::string{kv.substr(eq + 1)});
|
||||
// null: key omitted
|
||||
}
|
||||
Void::Log::debug("Configuration",
|
||||
"from_env_prefix('{}'): {} keys", prefix,
|
||||
cfg.size());
|
||||
#else
|
||||
(void)prefix;
|
||||
#endif
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/// Parse an INI file: `[section]` + `key = value` becomes
|
||||
/// "section.key"; pairs before any section keep their bare key.
|
||||
[[nodiscard]] static Void::Result::Result<Config, Void::Result::Error>
|
||||
from_ini(const std::filesystem::path& path)
|
||||
{
|
||||
auto text = Void::FileSystem::read_file(path);
|
||||
if (!text.has_value()) {
|
||||
return Void::Result::fail(
|
||||
std::format("Configuration::Config::from_ini: {}",
|
||||
text.error().message()));
|
||||
}
|
||||
return from_ini_text(*text);
|
||||
}
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<Config, Void::Result::Error>
|
||||
from_ini_text(std::string_view text)
|
||||
{
|
||||
Void::Ini::IniFile ini;
|
||||
if (auto err = Void::Ini::IniFile::parse(ini, text);
|
||||
err.has_value()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Configuration::Config::from_ini: line {}: {}",
|
||||
err->line, err->message));
|
||||
}
|
||||
Config cfg;
|
||||
for (const auto& name : ini.sections()) {
|
||||
const auto* section = ini.section(name);
|
||||
if (section == nullptr) {
|
||||
continue;
|
||||
}
|
||||
for (const auto& [key, value] : *section) {
|
||||
auto full =
|
||||
name.empty() ? key : name + "." + key;
|
||||
cfg.values_.insert_or_assign(std::move(full), value);
|
||||
}
|
||||
}
|
||||
return Void::Result::ok(std::move(cfg));
|
||||
}
|
||||
|
||||
/// Parse a JSON file; nested objects flatten into dotted keys,
|
||||
/// arrays into numeric segments ("servers.0.host"). Scalars are
|
||||
/// stored in their canonical string form.
|
||||
[[nodiscard]] static Void::Result::Result<Config, Void::Result::Error>
|
||||
from_json(const std::filesystem::path& path)
|
||||
{
|
||||
auto text = Void::FileSystem::read_file(path);
|
||||
if (!text.has_value()) {
|
||||
return Void::Result::fail(
|
||||
std::format("Configuration::Config::from_json: {}",
|
||||
text.error().message()));
|
||||
}
|
||||
return from_json_text(*text);
|
||||
}
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<Config, Void::Result::Error>
|
||||
from_json_text(std::string_view text)
|
||||
{
|
||||
auto parsed = Void::Json::parse(text);
|
||||
if (!parsed.has_value()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Configuration::Config::from_json: line {} col {}: {}",
|
||||
parsed.error().line, parsed.error().col,
|
||||
parsed.error().message));
|
||||
}
|
||||
Config cfg;
|
||||
flatten_json(cfg, "", *parsed);
|
||||
return Void::Result::ok(std::move(cfg));
|
||||
}
|
||||
|
||||
/// Collect `--key=value`, `--key value` and bare `--flag`
|
||||
/// (stored as "true") arguments. Non-option arguments are ignored.
|
||||
[[nodiscard]] static Config from_args(int argc,
|
||||
const char* const* argv)
|
||||
{
|
||||
Config cfg;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string_view arg{argv[i]};
|
||||
if (!arg.starts_with("--") || arg.size() <= 2) {
|
||||
continue;
|
||||
}
|
||||
const auto body = arg.substr(2);
|
||||
if (const auto eq = body.find('=');
|
||||
eq != std::string_view::npos) {
|
||||
cfg.values_.insert_or_assign(
|
||||
std::string{body.substr(0, eq)},
|
||||
std::string{body.substr(eq + 1)});
|
||||
}
|
||||
else if (i + 1 < argc &&
|
||||
std::string_view{argv[i + 1]}.substr(0, 2) !=
|
||||
"--") {
|
||||
cfg.values_.insert_or_assign(std::string{body},
|
||||
std::string{argv[i + 1]});
|
||||
++i;
|
||||
}
|
||||
else {
|
||||
cfg.values_.insert_or_assign(std::string{body},
|
||||
"true");
|
||||
}
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
// Typed access
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Look up and convert. Supported T: integral and floating types,
|
||||
/// bool ("true/false/1/0/yes/no/on/off", case-insensitive), enums
|
||||
/// (by enumerator name, reflection builds), std::string, and
|
||||
/// std::chrono durations ("250ms", "10s", "5m", "1h", "500us",
|
||||
/// "30ns" — converted to T, rejecting lossy narrowing).
|
||||
template <typename T>
|
||||
[[nodiscard]] Void::Result::Result<T, Void::Result::Error>
|
||||
get_as(std::string_view key) const
|
||||
{
|
||||
const auto it = values_.find(std::string{key});
|
||||
if (it == values_.end()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Configuration::Config::get_as: key '{}' not found",
|
||||
key));
|
||||
}
|
||||
return convert<T>(key, it->second);
|
||||
}
|
||||
|
||||
/// Typed lookup with fallback for missing keys. Conversion errors
|
||||
/// on a *present* key still surface the fallback but are logged.
|
||||
template <typename T>
|
||||
[[nodiscard]] T get_or_as(std::string_view key, T fallback) const
|
||||
{
|
||||
auto r = get_as<T>(key);
|
||||
if (r.has_value()) {
|
||||
return std::move(*r);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
// Key enumeration / subtrees
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
|
||||
/// All keys, sorted.
|
||||
[[nodiscard]] std::vector<std::string> keys() const
|
||||
{
|
||||
std::vector<std::string> out;
|
||||
out.reserve(values_.size());
|
||||
for (const auto& [k, _] : values_) {
|
||||
out.push_back(k);
|
||||
}
|
||||
std::sort(out.begin(), out.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
/// A new Config holding every key under "prefix." with the prefix
|
||||
/// stripped: subtree("log") of {log.level, log.file.path} yields
|
||||
/// {level, file.path}.
|
||||
[[nodiscard]] Config subtree(std::string_view prefix) const
|
||||
{
|
||||
Config out;
|
||||
const auto full = std::string{prefix} + ".";
|
||||
for (const auto& [k, v] : values_) {
|
||||
if (k.starts_with(full)) {
|
||||
out.values_.emplace(k.substr(full.size()), v);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool contains(std::string_view key) const
|
||||
{
|
||||
return values_.contains(std::string{key});
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static void flatten_json(Config& cfg, const std::string& prefix,
|
||||
const Void::Json::Value& v)
|
||||
{
|
||||
using Void::Json::Value;
|
||||
if (v.is_object()) {
|
||||
for (const auto& [k, child] : v.as_object()) {
|
||||
flatten_json(
|
||||
cfg, prefix.empty() ? k : prefix + "." + k, child);
|
||||
}
|
||||
}
|
||||
else if (v.is_array()) {
|
||||
std::size_t i = 0;
|
||||
for (const auto& child : v.as_array()) {
|
||||
flatten_json(cfg, prefix + "." + std::to_string(i),
|
||||
child);
|
||||
++i;
|
||||
}
|
||||
}
|
||||
else if (v.is_string()) {
|
||||
cfg.values_.insert_or_assign(prefix, v.as_string());
|
||||
}
|
||||
else if (v.is_bool()) {
|
||||
cfg.values_.insert_or_assign(prefix,
|
||||
v.as_bool() ? "true" : "false");
|
||||
}
|
||||
else if (v.is_number()) {
|
||||
const double d = v.as_number();
|
||||
if (d == static_cast<double>(static_cast<long long>(d))) {
|
||||
cfg.values_.insert_or_assign(
|
||||
prefix,
|
||||
std::to_string(static_cast<long long>(d)));
|
||||
}
|
||||
else {
|
||||
cfg.values_.insert_or_assign(prefix,
|
||||
std::format("{}", d));
|
||||
}
|
||||
}
|
||||
// null: key omitted
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
struct IsDuration : std::false_type {};
|
||||
template <typename Rep, typename Period>
|
||||
struct IsDuration<std::chrono::duration<Rep, Period>>
|
||||
: std::true_type {};
|
||||
|
||||
template <typename T>
|
||||
static Void::Result::Result<T, Void::Result::Error>
|
||||
convert(std::string_view key, const std::string& raw)
|
||||
{
|
||||
auto fail = [&](std::string_view what) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Configuration::Config::get_as: key '{}': {} ('{}')",
|
||||
key, what, raw));
|
||||
template <typename T> struct IsDuration : std::false_type {
|
||||
};
|
||||
template <typename Rep, typename Period>
|
||||
struct IsDuration<std::chrono::duration<Rep, Period>>
|
||||
: std::true_type {
|
||||
};
|
||||
|
||||
if constexpr (std::is_same_v<T, std::string>) {
|
||||
return Void::Result::ok(raw);
|
||||
}
|
||||
else if constexpr (std::is_same_v<T, bool>) {
|
||||
std::string lower;
|
||||
lower.reserve(raw.size());
|
||||
for (const char c : raw) {
|
||||
lower += static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(c)));
|
||||
}
|
||||
if (lower == "true" || lower == "1" || lower == "yes" ||
|
||||
lower == "on") {
|
||||
return Void::Result::ok(true);
|
||||
}
|
||||
if (lower == "false" || lower == "0" || lower == "no" ||
|
||||
lower == "off") {
|
||||
return Void::Result::ok(false);
|
||||
}
|
||||
return fail("not a boolean");
|
||||
}
|
||||
else if constexpr (std::is_enum_v<T>) {
|
||||
template <typename T>
|
||||
static Void::Result::Result<T, Void::Result::Error>
|
||||
convert(std::string_view key, const std::string& raw)
|
||||
{
|
||||
auto fail = [&](std::string_view what) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Configuration::Config::get_as: key '{}': {} ('{}')",
|
||||
key, what, raw));
|
||||
};
|
||||
|
||||
if constexpr (std::is_same_v<T, std::string>) {
|
||||
return Void::Result::ok(raw);
|
||||
} else if constexpr (std::is_same_v<T, bool>) {
|
||||
std::string lower;
|
||||
lower.reserve(raw.size());
|
||||
for (const char c : raw) {
|
||||
lower += static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(c)));
|
||||
}
|
||||
if (lower == "true" || lower == "1" || lower == "yes" ||
|
||||
lower == "on") {
|
||||
return Void::Result::ok(true);
|
||||
}
|
||||
if (lower == "false" || lower == "0" || lower == "no" ||
|
||||
lower == "off") {
|
||||
return Void::Result::ok(false);
|
||||
}
|
||||
return fail("not a boolean");
|
||||
} else if constexpr (std::is_enum_v<T>) {
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
if (auto e = Void::Detail::enum_parse<T>(raw);
|
||||
e.has_value()) {
|
||||
return Void::Result::ok(*e);
|
||||
}
|
||||
return fail("no such enumerator");
|
||||
if (auto e = Void::Detail::enum_parse<T>(raw);
|
||||
e.has_value()) {
|
||||
return Void::Result::ok(*e);
|
||||
}
|
||||
return fail("no such enumerator");
|
||||
#else
|
||||
return fail("enum parsing requires reflection");
|
||||
return fail("enum parsing requires reflection");
|
||||
#endif
|
||||
}
|
||||
else if constexpr (IsDuration<T>::value) {
|
||||
auto parsed = parse_duration(raw);
|
||||
if (!parsed.has_value()) {
|
||||
return fail("not a duration (use e.g. 250ms, 10s, 5m)");
|
||||
}
|
||||
return Void::Result::ok(
|
||||
std::chrono::duration_cast<T>(*parsed));
|
||||
}
|
||||
else if constexpr (std::is_arithmetic_v<T>) {
|
||||
T value{};
|
||||
const char* begin = raw.data();
|
||||
const char* end = raw.data() + raw.size();
|
||||
const auto [ptr, ec] = std::from_chars(begin, end, value);
|
||||
if (ec != std::errc{} || ptr != end) {
|
||||
} else if constexpr (IsDuration<T>::value) {
|
||||
auto parsed = parse_duration(raw);
|
||||
if (!parsed.has_value()) {
|
||||
return fail("not a duration (use e.g. 250ms, 10s, 5m)");
|
||||
}
|
||||
return Void::Result::ok(
|
||||
std::chrono::duration_cast<T>(*parsed));
|
||||
} else if constexpr (std::is_arithmetic_v<T>) {
|
||||
T value{};
|
||||
const char* begin = raw.data();
|
||||
const char* end = raw.data() + raw.size();
|
||||
const auto [ptr, ec] = std::from_chars(begin, end, value);
|
||||
if (ec == std::errc{} && ptr == end) {
|
||||
return Void::Result::ok(value);
|
||||
}
|
||||
// Byte-size units for integral targets: "10MB", "1GiB".
|
||||
if constexpr (std::is_integral_v<T>) {
|
||||
if (auto bytes = parse_bytes(raw); bytes.has_value()) {
|
||||
return Void::Result::ok(static_cast<T>(*bytes));
|
||||
}
|
||||
return fail("not a number or byte size");
|
||||
}
|
||||
return fail("not a number");
|
||||
} else {
|
||||
static_assert(std::is_same_v<T, std::string>,
|
||||
"unsupported get_as<T> type");
|
||||
}
|
||||
return Void::Result::ok(value);
|
||||
}
|
||||
else {
|
||||
static_assert(std::is_same_v<T, std::string>,
|
||||
"unsupported get_as<T> type");
|
||||
}
|
||||
}
|
||||
|
||||
static std::optional<std::chrono::nanoseconds>
|
||||
parse_duration(const std::string& raw)
|
||||
{
|
||||
double number = 0;
|
||||
const char* begin = raw.data();
|
||||
const char* end = raw.data() + raw.size();
|
||||
const auto [ptr, ec] = std::from_chars(begin, end, number);
|
||||
if (ec != std::errc{} || ptr == begin) {
|
||||
return std::nullopt;
|
||||
static std::optional<std::chrono::nanoseconds>
|
||||
parse_duration(const std::string& raw)
|
||||
{
|
||||
// Single source of truth lives in Time/Format.hpp.
|
||||
return Void::Time::parse_duration(raw);
|
||||
}
|
||||
const std::string_view suffix{ptr, end};
|
||||
using namespace std::chrono;
|
||||
const auto as_ns = [&](auto unit) {
|
||||
return std::optional{duration_cast<nanoseconds>(
|
||||
duration<double, typename decltype(unit)::period>{
|
||||
number})};
|
||||
};
|
||||
if (suffix == "ns") {
|
||||
return as_ns(nanoseconds{});
|
||||
}
|
||||
if (suffix == "us") {
|
||||
return as_ns(microseconds{});
|
||||
}
|
||||
if (suffix == "ms") {
|
||||
return as_ns(milliseconds{});
|
||||
}
|
||||
if (suffix == "s" || suffix.empty()) {
|
||||
return as_ns(seconds{});
|
||||
}
|
||||
if (suffix == "m") {
|
||||
return as_ns(minutes{});
|
||||
}
|
||||
if (suffix == "h") {
|
||||
return as_ns(hours{});
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, std::string> values_;
|
||||
};
|
||||
// Parse a byte-size string: a number followed by an SI
|
||||
// (KB/MB/GB/TB, powers of 1000) or binary (KiB/MiB/GiB/TiB, powers
|
||||
// of 1024) unit. A bare "B" or empty suffix means bytes. Returns
|
||||
// nullopt otherwise.
|
||||
static std::optional<std::uint64_t>
|
||||
parse_bytes(const std::string& raw)
|
||||
{
|
||||
double number = 0;
|
||||
const char* begin = raw.data();
|
||||
const char* end = raw.data() + raw.size();
|
||||
const auto [ptr, ec] = std::from_chars(begin, end, number);
|
||||
if (ec != std::errc{} || ptr == begin) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::string_view suffix{ptr, end};
|
||||
while (!suffix.empty() && suffix.front() == ' ') {
|
||||
suffix.remove_prefix(1);
|
||||
}
|
||||
double mult = 0;
|
||||
if (suffix.empty() || suffix == "B") {
|
||||
mult = 1.0;
|
||||
} else if (suffix == "KB") {
|
||||
mult = 1e3;
|
||||
} else if (suffix == "MB") {
|
||||
mult = 1e6;
|
||||
} else if (suffix == "GB") {
|
||||
mult = 1e9;
|
||||
} else if (suffix == "TB") {
|
||||
mult = 1e12;
|
||||
} else if (suffix == "KiB") {
|
||||
mult = 1024.0;
|
||||
} else if (suffix == "MiB") {
|
||||
mult = 1024.0 * 1024.0;
|
||||
} else if (suffix == "GiB") {
|
||||
mult = 1024.0 * 1024.0 * 1024.0;
|
||||
} else if (suffix == "TiB") {
|
||||
mult = 1024.0 * 1024.0 * 1024.0 * 1024.0;
|
||||
} else {
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<std::uint64_t>(number * mult);
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, std::string> values_;
|
||||
};
|
||||
|
||||
} // namespace Void::Configuration
|
||||
@@ -0,0 +1,203 @@
|
||||
#pragma once
|
||||
|
||||
#include <bit>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::BufferPool
|
||||
{
|
||||
|
||||
// ── BufferPool<T>
|
||||
// ───────────────────────────────────────────────────────────── A pool of
|
||||
// reusable, variable-length buffers of T — e.g. audio sample blocks (int16
|
||||
// / float). Distinct from Containers/Pool.hpp's ObjectPool, which pools
|
||||
// fixed-size *objects*: this pools backing storage sized by request.
|
||||
//
|
||||
// acquire(n) hands back a Buffer of logical length n backed by capacity
|
||||
// rounded up to the next power-of-two size class; on drop the storage
|
||||
// returns to the pool's bucket for that size class, so a later acquire of
|
||||
// the same class reuses it with no reallocation.
|
||||
//
|
||||
// Not thread-safe — guard externally if shared.
|
||||
|
||||
template <typename T> class BufferPool
|
||||
{
|
||||
public:
|
||||
|
||||
BufferPool() = default;
|
||||
|
||||
BufferPool(const BufferPool&) = delete;
|
||||
BufferPool& operator=(const BufferPool&) = delete;
|
||||
BufferPool(BufferPool&&) = default;
|
||||
BufferPool& operator=(BufferPool&&) = default;
|
||||
|
||||
struct Stats {
|
||||
std::uint64_t allocations = 0; // fresh storage allocated
|
||||
std::uint64_t reuses = 0; // requests served from a bucket
|
||||
std::size_t pooled = 0; // buffers currently idle in buckets
|
||||
};
|
||||
|
||||
// An owning view returned by acquire(); recycles its storage on
|
||||
// drop.
|
||||
class Buffer
|
||||
{
|
||||
public:
|
||||
|
||||
Buffer() = default;
|
||||
|
||||
Buffer(const Buffer&) = delete;
|
||||
Buffer& operator=(const Buffer&) = delete;
|
||||
|
||||
Buffer(Buffer&& other) noexcept
|
||||
: pool_{other.pool_},
|
||||
storage_{std::move(other.storage_)},
|
||||
size_{other.size_}
|
||||
{
|
||||
other.pool_ = nullptr;
|
||||
other.size_ = 0;
|
||||
}
|
||||
|
||||
Buffer& operator=(Buffer&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
recycle();
|
||||
pool_ = other.pool_;
|
||||
storage_ = std::move(other.storage_);
|
||||
size_ = other.size_;
|
||||
other.pool_ = nullptr;
|
||||
other.size_ = 0;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
~Buffer() { recycle(); }
|
||||
|
||||
[[nodiscard]] T* data() noexcept { return storage_.data(); }
|
||||
[[nodiscard]] const T* data() const noexcept
|
||||
{
|
||||
return storage_.data();
|
||||
}
|
||||
[[nodiscard]] std::size_t size() const noexcept
|
||||
{
|
||||
return size_;
|
||||
}
|
||||
[[nodiscard]] bool empty() const noexcept
|
||||
{
|
||||
return size_ == 0;
|
||||
}
|
||||
// Backing capacity (the size class) — always >= size().
|
||||
[[nodiscard]] std::size_t capacity() const noexcept
|
||||
{
|
||||
return storage_.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] T& operator[](std::size_t i) noexcept
|
||||
{
|
||||
return storage_[i];
|
||||
}
|
||||
[[nodiscard]] const T&
|
||||
operator[](std::size_t i) const noexcept
|
||||
{
|
||||
return storage_[i];
|
||||
}
|
||||
|
||||
[[nodiscard]] T* begin() noexcept { return data(); }
|
||||
[[nodiscard]] T* end() noexcept { return data() + size_; }
|
||||
[[nodiscard]] const T* begin() const noexcept
|
||||
{
|
||||
return data();
|
||||
}
|
||||
[[nodiscard]] const T* end() const noexcept
|
||||
{
|
||||
return data() + size_;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::span<T> span() noexcept
|
||||
{
|
||||
return {data(), size_};
|
||||
}
|
||||
[[nodiscard]] std::span<const T> span() const noexcept
|
||||
{
|
||||
return {data(), size_};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
friend class BufferPool;
|
||||
|
||||
Buffer(BufferPool* pool, std::vector<T> storage,
|
||||
std::size_t n) noexcept
|
||||
: pool_{pool}, storage_{std::move(storage)}, size_{n}
|
||||
{
|
||||
}
|
||||
|
||||
void recycle() noexcept
|
||||
{
|
||||
if (pool_) {
|
||||
pool_->recycle(std::move(storage_));
|
||||
pool_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
BufferPool* pool_ = nullptr;
|
||||
std::vector<T> storage_;
|
||||
std::size_t size_ = 0;
|
||||
};
|
||||
|
||||
// Hand out a buffer of logical length n (capacity rounded up to a
|
||||
// power of two), reusing pooled storage of that size class when
|
||||
// available.
|
||||
[[nodiscard]] Buffer acquire(std::size_t n)
|
||||
{
|
||||
const std::size_t cls = size_class(n);
|
||||
std::vector<T> storage;
|
||||
auto bucket = free_.find(cls);
|
||||
if (bucket != free_.end() && !bucket->second.empty()) {
|
||||
storage = std::move(bucket->second.back());
|
||||
bucket->second.pop_back();
|
||||
++reuses_;
|
||||
} else {
|
||||
storage.resize(cls);
|
||||
++allocations_;
|
||||
}
|
||||
return Buffer{this, std::move(storage), n};
|
||||
}
|
||||
|
||||
[[nodiscard]] Stats stats() const
|
||||
{
|
||||
std::size_t pooled = 0;
|
||||
for (const auto& [cls, bucket] : free_) {
|
||||
pooled += bucket.size();
|
||||
}
|
||||
return Stats{allocations_, reuses_, pooled};
|
||||
}
|
||||
|
||||
// Drop all pooled (idle) storage. Outstanding Buffers are
|
||||
// unaffected.
|
||||
void shrink() noexcept { free_.clear(); }
|
||||
|
||||
private:
|
||||
|
||||
static std::size_t size_class(std::size_t n) noexcept
|
||||
{
|
||||
return n == 0 ? 0 : std::bit_ceil(n);
|
||||
}
|
||||
|
||||
void recycle(std::vector<T> storage)
|
||||
{
|
||||
if (storage.empty()) {
|
||||
return;
|
||||
}
|
||||
free_[storage.size()].push_back(std::move(storage));
|
||||
}
|
||||
|
||||
std::unordered_map<std::size_t, std::vector<std::vector<T>>> free_;
|
||||
std::uint64_t allocations_ = 0;
|
||||
std::uint64_t reuses_ = 0;
|
||||
};
|
||||
|
||||
} // namespace Void::BufferPool
|
||||
@@ -0,0 +1,268 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <list>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Cache
|
||||
{
|
||||
|
||||
// ── Cache<K, V>
|
||||
// ─────────────────────────────────────────────────────────────── A
|
||||
// fixed-capacity cache with per-entry TTL, a selectable eviction policy,
|
||||
// and hit/miss/eviction/expiration counters. Built on the same
|
||||
// doubly-linked-list + hash-map structure as Containers/LRU.hpp (which
|
||||
// stays the minimal primitive).
|
||||
//
|
||||
// Not thread-safe — guard externally if shared, like LruCache.
|
||||
//
|
||||
// Expiry is lazy: an entry past its TTL is treated as a miss and dropped on
|
||||
// the next access (or in bulk via sweep()). The clock is injectable for
|
||||
// tests.
|
||||
|
||||
enum class Policy {
|
||||
LRU, // evict the least-recently-used entry (default)
|
||||
LFU, // evict the least-frequently-used entry
|
||||
FIFO // evict the oldest inserted entry
|
||||
};
|
||||
|
||||
template <typename K, typename V> class Cache
|
||||
{
|
||||
public:
|
||||
|
||||
using Clock =
|
||||
std::function<std::chrono::steady_clock::time_point()>;
|
||||
using Duration = std::chrono::steady_clock::duration;
|
||||
using TimePoint = std::chrono::steady_clock::time_point;
|
||||
|
||||
struct Stats {
|
||||
std::uint64_t hits = 0;
|
||||
std::uint64_t misses = 0;
|
||||
std::uint64_t evictions =
|
||||
0; // dropped to make room (capacity)
|
||||
std::uint64_t expirations =
|
||||
0; // dropped because the TTL elapsed
|
||||
std::size_t size = 0;
|
||||
};
|
||||
|
||||
explicit Cache(std::size_t capacity, Policy policy = Policy::LRU,
|
||||
std::optional<Duration> default_ttl = std::nullopt,
|
||||
Clock clock = default_clock())
|
||||
: capacity_{capacity}, policy_{policy},
|
||||
default_ttl_{default_ttl}, clock_{std::move(clock)}
|
||||
{
|
||||
if (capacity == 0) {
|
||||
throw std::invalid_argument{"capacity must be > 0"};
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t capacity() const noexcept
|
||||
{
|
||||
return capacity_;
|
||||
}
|
||||
[[nodiscard]] std::size_t size() const noexcept
|
||||
{
|
||||
return map_.size();
|
||||
}
|
||||
[[nodiscard]] bool empty() const noexcept { return map_.empty(); }
|
||||
[[nodiscard]] bool full() const noexcept
|
||||
{
|
||||
return map_.size() == capacity_;
|
||||
}
|
||||
[[nodiscard]] Policy policy() const noexcept { return policy_; }
|
||||
|
||||
// Retrieve a value. nullopt on miss or expiry; updates recency /
|
||||
// frequency and the hit/miss counters on every call.
|
||||
[[nodiscard]] std::optional<V> get(const K& key)
|
||||
{
|
||||
auto it = map_.find(key);
|
||||
if (it == map_.end()) {
|
||||
++misses_;
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto now = clock_();
|
||||
if (expired(*it->second, now)) {
|
||||
drop(it);
|
||||
++expirations_;
|
||||
++misses_;
|
||||
return std::nullopt;
|
||||
}
|
||||
++hits_;
|
||||
touch(it->second);
|
||||
return it->second->value;
|
||||
}
|
||||
|
||||
// Peek without recency promotion and without touching hit/miss
|
||||
// stats. Still respects expiry (an expired entry is invisible and
|
||||
// dropped).
|
||||
[[nodiscard]] const V* peek(const K& key)
|
||||
{
|
||||
auto it = map_.find(key);
|
||||
if (it == map_.end()) {
|
||||
return nullptr;
|
||||
}
|
||||
if (expired(*it->second, clock_())) {
|
||||
drop(it);
|
||||
++expirations_;
|
||||
return nullptr;
|
||||
}
|
||||
return &it->second->value;
|
||||
}
|
||||
|
||||
// Insert or update with the cache's default TTL.
|
||||
void put(const K& key, V value)
|
||||
{
|
||||
put(key, std::move(value), default_ttl_);
|
||||
}
|
||||
|
||||
// Insert or update with an explicit TTL (nullopt = never expires).
|
||||
void put(const K& key, V value, std::optional<Duration> ttl)
|
||||
{
|
||||
const auto now = clock_();
|
||||
if (auto it = map_.find(key); it != map_.end()) {
|
||||
it->second->value = std::move(value);
|
||||
set_expiry(*it->second, ttl, now);
|
||||
touch(it->second);
|
||||
return;
|
||||
}
|
||||
if (map_.size() == capacity_) {
|
||||
evict_one();
|
||||
}
|
||||
list_.push_front(Node{key, std::move(value), 1, {}, false});
|
||||
set_expiry(list_.front(), ttl, now);
|
||||
map_[key] = list_.begin();
|
||||
}
|
||||
|
||||
bool erase(const K& key)
|
||||
{
|
||||
auto it = map_.find(key);
|
||||
if (it == map_.end()) {
|
||||
return false;
|
||||
}
|
||||
drop(it);
|
||||
return true;
|
||||
}
|
||||
|
||||
void clear() noexcept
|
||||
{
|
||||
list_.clear();
|
||||
map_.clear();
|
||||
}
|
||||
|
||||
// Present and not expired. Const: does not drop the expired entry.
|
||||
[[nodiscard]] bool contains(const K& key) const
|
||||
{
|
||||
auto it = map_.find(key);
|
||||
return it != map_.end() && !expired(*it->second, clock_());
|
||||
}
|
||||
|
||||
// Purge every expired entry; returns how many were removed.
|
||||
std::size_t sweep()
|
||||
{
|
||||
const auto now = clock_();
|
||||
std::size_t purged = 0;
|
||||
for (auto it = list_.begin(); it != list_.end();) {
|
||||
if (expired(*it, now)) {
|
||||
map_.erase(it->key);
|
||||
it = list_.erase(it);
|
||||
++purged;
|
||||
++expirations_;
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
return purged;
|
||||
}
|
||||
|
||||
[[nodiscard]] Stats stats() const
|
||||
{
|
||||
return Stats{hits_, misses_, evictions_, expirations_,
|
||||
map_.size()};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
struct Node {
|
||||
K key;
|
||||
V value;
|
||||
std::uint64_t freq = 0;
|
||||
TimePoint expiry{};
|
||||
bool has_expiry = false;
|
||||
};
|
||||
using List = std::list<Node>;
|
||||
using Map = std::unordered_map<K, typename List::iterator>;
|
||||
|
||||
static Clock default_clock()
|
||||
{
|
||||
return [] { return std::chrono::steady_clock::now(); };
|
||||
}
|
||||
|
||||
static bool expired(const Node& n, TimePoint now)
|
||||
{
|
||||
return n.has_expiry && now >= n.expiry;
|
||||
}
|
||||
|
||||
void set_expiry(Node& n, std::optional<Duration> ttl, TimePoint now)
|
||||
{
|
||||
n.has_expiry = ttl.has_value();
|
||||
if (ttl) {
|
||||
n.expiry = now + *ttl;
|
||||
}
|
||||
}
|
||||
|
||||
// Record a use: bump frequency and (for LRU) promote to
|
||||
// most-recent.
|
||||
void touch(typename List::iterator lit)
|
||||
{
|
||||
++lit->freq;
|
||||
if (policy_ == Policy::LRU) {
|
||||
list_.splice(list_.begin(), list_, lit);
|
||||
}
|
||||
}
|
||||
|
||||
void drop(typename Map::iterator it)
|
||||
{
|
||||
list_.erase(it->second);
|
||||
map_.erase(it);
|
||||
}
|
||||
|
||||
void evict_one()
|
||||
{
|
||||
typename List::iterator victim;
|
||||
if (policy_ == Policy::LFU) {
|
||||
victim = list_.begin();
|
||||
for (auto i = list_.begin(); i != list_.end(); ++i) {
|
||||
if (i->freq < victim->freq) {
|
||||
victim = i;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// LRU and FIFO both evict from the back: LRU keeps the list
|
||||
// in recency order via touch(); FIFO never reorders, so the
|
||||
// back is the oldest insertion.
|
||||
victim = std::prev(list_.end());
|
||||
}
|
||||
map_.erase(victim->key);
|
||||
list_.erase(victim);
|
||||
++evictions_;
|
||||
}
|
||||
|
||||
std::size_t capacity_;
|
||||
Policy policy_;
|
||||
std::optional<Duration> default_ttl_;
|
||||
Clock clock_;
|
||||
List list_;
|
||||
Map map_;
|
||||
std::uint64_t hits_ = 0;
|
||||
std::uint64_t misses_ = 0;
|
||||
std::uint64_t evictions_ = 0;
|
||||
std::uint64_t expirations_ = 0;
|
||||
};
|
||||
|
||||
} // namespace Void::Cache
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <ranges>
|
||||
#include <string>
|
||||
|
||||
namespace Void::Containers
|
||||
{
|
||||
/// Render any range's elements as "[e0, e1, …]" using the shared
|
||||
/// reflection renderer Void::Meta::repr (so structs print their fields):
|
||||
/// Containers::debug_dump(my_ring); // "[Point{x: 1, y: 2}, …]"
|
||||
template <std::ranges::input_range R>
|
||||
[[nodiscard]] std::string debug_dump(const R& range)
|
||||
{
|
||||
std::string out = "[";
|
||||
bool first = true;
|
||||
for (const auto& e : range) {
|
||||
if (!first) {
|
||||
out += ", ";
|
||||
}
|
||||
out += Void::Meta::repr(e);
|
||||
first = false;
|
||||
}
|
||||
out += ']';
|
||||
return out;
|
||||
}
|
||||
} // namespace Void::Containers
|
||||
+200
-81
@@ -1,114 +1,233 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <initializer_list>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#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, …).
|
||||
// ── 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>;
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
class Flags
|
||||
{
|
||||
public:
|
||||
|
||||
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);
|
||||
}
|
||||
using underlying = std::underlying_type_t<E>;
|
||||
|
||||
// ── query ─────────────────────────────────────────────────────────────────
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool test(E bit) const noexcept
|
||||
{
|
||||
return (bits_ & static_cast<underlying>(bit)) != 0;
|
||||
}
|
||||
// ── query
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr bool any() const noexcept { return bits_ != 0; }
|
||||
[[nodiscard]] constexpr bool none() const noexcept { return bits_ == 0; }
|
||||
[[nodiscard]] constexpr bool test(E bit) const noexcept
|
||||
{
|
||||
return (bits_ & static_cast<underlying>(bit)) != 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool all(Flags mask) const noexcept
|
||||
{
|
||||
return (bits_ & mask.bits_) == mask.bits_;
|
||||
}
|
||||
[[nodiscard]] constexpr bool any() const noexcept
|
||||
{
|
||||
return bits_ != 0;
|
||||
}
|
||||
[[nodiscard]] constexpr bool none() const noexcept
|
||||
{
|
||||
return bits_ == 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool any_of(Flags mask) const noexcept
|
||||
{
|
||||
return (bits_ & mask.bits_) != 0;
|
||||
}
|
||||
[[nodiscard]] constexpr bool all(Flags mask) const noexcept
|
||||
{
|
||||
return (bits_ & mask.bits_) == mask.bits_;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr underlying raw() const noexcept { return bits_; }
|
||||
[[nodiscard]] constexpr bool any_of(Flags mask) const noexcept
|
||||
{
|
||||
return (bits_ & mask.bits_) != 0;
|
||||
}
|
||||
|
||||
// ── mutation ──────────────────────────────────────────────────────────────
|
||||
[[nodiscard]] constexpr underlying raw() const noexcept
|
||||
{
|
||||
return bits_;
|
||||
}
|
||||
|
||||
constexpr Flags& set(E bit) noexcept
|
||||
{
|
||||
bits_ |= static_cast<underlying>(bit);
|
||||
return *this;
|
||||
}
|
||||
// ── mutation
|
||||
// ──────────────────────────────────────────────────────────────
|
||||
|
||||
constexpr Flags& unset(E bit) noexcept
|
||||
{
|
||||
bits_ &= ~static_cast<underlying>(bit);
|
||||
return *this;
|
||||
}
|
||||
constexpr Flags& set(E bit) noexcept
|
||||
{
|
||||
bits_ |= static_cast<underlying>(bit);
|
||||
return *this;
|
||||
}
|
||||
|
||||
constexpr Flags& toggle(E bit) noexcept
|
||||
{
|
||||
bits_ ^= static_cast<underlying>(bit);
|
||||
return *this;
|
||||
}
|
||||
constexpr Flags& unset(E bit) noexcept
|
||||
{
|
||||
bits_ &= ~static_cast<underlying>(bit);
|
||||
return *this;
|
||||
}
|
||||
|
||||
constexpr void clear() noexcept { bits_ = 0; }
|
||||
constexpr Flags& toggle(E bit) noexcept
|
||||
{
|
||||
bits_ ^= static_cast<underlying>(bit);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// ── operators ─────────────────────────────────────────────────────────────
|
||||
constexpr void clear() noexcept { bits_ = 0; }
|
||||
|
||||
[[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_)}; }
|
||||
// ── operators
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
|
||||
[[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}; }
|
||||
[[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_)};
|
||||
}
|
||||
|
||||
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; }
|
||||
[[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|=(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); }
|
||||
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;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool operator==(const Flags&) const noexcept = default;
|
||||
[[nodiscard]] constexpr explicit operator bool() const noexcept { return any(); }
|
||||
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); }
|
||||
|
||||
private:
|
||||
underlying bits_{0};
|
||||
};
|
||||
[[nodiscard]] constexpr bool
|
||||
operator==(const Flags&) const noexcept = default;
|
||||
[[nodiscard]] constexpr explicit operator bool() const noexcept
|
||||
{
|
||||
return any();
|
||||
}
|
||||
|
||||
// ── make_flags — convenience factory ─────────────────────────────────────────
|
||||
private:
|
||||
|
||||
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};
|
||||
}
|
||||
underlying bits_{0};
|
||||
};
|
||||
|
||||
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};
|
||||
}
|
||||
// ── 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};
|
||||
}
|
||||
|
||||
// ── reflective names (Void::Meta enum reflection)
|
||||
// ────────────────────────────
|
||||
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
|
||||
/// Render the set bits as their enumerator names, joined by `sep`
|
||||
/// (e.g. "Read|Write"). A zero-valued enumerator never appears.
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] std::string to_string(Flags<E> f, std::string_view sep = "|")
|
||||
{
|
||||
std::string out;
|
||||
for (const auto& [value, name] : Void::Meta::enum_entries<E>()) {
|
||||
if (f.test(value)) {
|
||||
if (!out.empty()) {
|
||||
out += sep;
|
||||
}
|
||||
out += name;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Parse a `sep`-separated list of enumerator names into a Flags<E>.
|
||||
/// Unknown names are ignored.
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] Flags<E> parse(std::string_view text, char sep = '|')
|
||||
{
|
||||
Flags<E> f;
|
||||
std::size_t pos = 0;
|
||||
while (pos <= text.size()) {
|
||||
const auto next = text.find(sep, pos);
|
||||
const auto end =
|
||||
(next == std::string_view::npos) ? text.size() : next;
|
||||
const auto token = text.substr(pos, end - pos);
|
||||
if (!token.empty()) {
|
||||
if (const auto e = Void::Meta::enum_parse<E>(token);
|
||||
e.has_value()) {
|
||||
f.set(*e);
|
||||
}
|
||||
}
|
||||
if (next == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = next + 1;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
#endif // VOID_HAS_META_REFLECTION
|
||||
|
||||
} // namespace Void::Flags
|
||||
@@ -0,0 +1,351 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Detail/Enum.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
#include <meta>
|
||||
#define VOID_HAS_META_REFLECTION 1
|
||||
#endif
|
||||
|
||||
// ── Void::Meta
|
||||
// ──────────────────────────────────────────────────────────────── The shared
|
||||
// C++26 P2996 reflection layer for VoidLibrary. One place for the member walk,
|
||||
// leaf-shape traits, annotation helpers, generic algorithms over data members
|
||||
// (equal / compare / hash / repr) and enum utilities. Every other module that
|
||||
// reflects structs or enums builds on this (Data/Json, Configuration/Bind,
|
||||
// Functional/Repr, Math, Text, Log, Time, ...).
|
||||
//
|
||||
// Annotations carry a value-based fixed-capacity string (`Meta::Str`) because
|
||||
// std::string_view is not a structural type and a const char* payload cannot be
|
||||
// promoted to a constant; domain vocabularies (json::Rename, config::Key,
|
||||
// arg::Help, ...) are small structs over `Str`.
|
||||
|
||||
namespace Void::Meta
|
||||
{
|
||||
// ── leaf / container shape traits (single source) ─────────────────────
|
||||
template <class> inline constexpr bool is_optional_v = false;
|
||||
template <class U>
|
||||
inline constexpr bool is_optional_v<std::optional<U>> = true;
|
||||
|
||||
template <class> inline constexpr bool is_vector_v = false;
|
||||
template <class U> inline constexpr bool is_vector_v<std::vector<U>> = true;
|
||||
|
||||
template <class> inline constexpr bool is_string_map_v = false;
|
||||
template <class U>
|
||||
inline constexpr bool is_string_map_v<std::map<std::string, U>> = true;
|
||||
|
||||
template <class> inline constexpr bool is_duration_v = false;
|
||||
template <class R, class P>
|
||||
inline constexpr bool is_duration_v<std::chrono::duration<R, P>> = true;
|
||||
|
||||
template <class> inline constexpr bool is_time_point_v = false;
|
||||
template <class C, class D>
|
||||
inline constexpr bool is_time_point_v<std::chrono::time_point<C, D>> = true;
|
||||
|
||||
template <class> inline constexpr bool is_variant_v = false;
|
||||
template <class... Ts>
|
||||
inline constexpr bool is_variant_v<std::variant<Ts...>> = true;
|
||||
|
||||
template <class> inline constexpr bool is_std_array_v = false;
|
||||
template <class U, std::size_t N>
|
||||
inline constexpr bool is_std_array_v<std::array<U, N>> = true;
|
||||
|
||||
// A keyed map whose key is *not* std::string. String-keyed maps stay on the
|
||||
// dedicated is_string_map_v object path; these serialize as an array of
|
||||
// {key, value} pairs so an arbitrary reflectable key type works.
|
||||
template <class> inline constexpr bool is_map_v = false;
|
||||
template <class K, class V, class C, class A>
|
||||
inline constexpr bool is_map_v<std::map<K, V, C, A>> =
|
||||
!std::same_as<K, std::string>;
|
||||
template <class K, class V, class H, class E, class A>
|
||||
inline constexpr bool is_map_v<std::unordered_map<K, V, H, E, A>> =
|
||||
!std::same_as<K, std::string>;
|
||||
|
||||
template <class T>
|
||||
concept Leaf = std::same_as<T, bool> || std::is_arithmetic_v<T> ||
|
||||
std::is_enum_v<T> || std::same_as<T, std::string>;
|
||||
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
|
||||
namespace meta = std::meta;
|
||||
|
||||
// ── member walk (the single reflection of a struct's data members) ────
|
||||
template <typename T>
|
||||
inline constexpr auto members_v =
|
||||
std::define_static_array(meta::nonstatic_data_members_of(
|
||||
^^T, meta::access_context::unchecked()));
|
||||
|
||||
/// Number of non-static data members of T.
|
||||
template <typename T> [[nodiscard]] consteval std::size_t field_count()
|
||||
{
|
||||
return members_v<T>.size();
|
||||
}
|
||||
|
||||
/// A class type with at least one reflectable data member.
|
||||
template <class T>
|
||||
concept Struct =
|
||||
(std::is_class_v<T> || std::is_union_v<T>) && (field_count<T>() > 0);
|
||||
|
||||
/// Identifier of a data-member reflection.
|
||||
[[nodiscard]] consteval std::string_view field_name(meta::info m)
|
||||
{
|
||||
return meta::identifier_of(m);
|
||||
}
|
||||
|
||||
/// The declared field names of T (in declaration order).
|
||||
template <typename T>
|
||||
[[nodiscard]] std::vector<std::string_view> field_names()
|
||||
{
|
||||
std::vector<std::string_view> out;
|
||||
out.reserve(field_count<T>());
|
||||
template for (constexpr auto m : members_v<T>)
|
||||
{
|
||||
out.push_back(meta::identifier_of(m));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Invoke `fn(name, fieldref)` for each data member of `obj`
|
||||
/// (mutable or const depending on `obj`).
|
||||
template <typename T, typename Fn> void for_each_field(T&& obj, Fn&& fn)
|
||||
{
|
||||
using U = std::remove_reference_t<T>;
|
||||
template for (constexpr auto m : members_v<U>)
|
||||
{
|
||||
fn(std::string_view{meta::identifier_of(m)}, obj.[:m:]);
|
||||
}
|
||||
}
|
||||
|
||||
// ── annotations ───────────────────────────────────────────────────────
|
||||
/// Value-based fixed-capacity string usable as an annotation payload
|
||||
/// (structural; copies up to 63 chars).
|
||||
struct Str {
|
||||
char data[64]{};
|
||||
std::size_t len{};
|
||||
consteval Str(const char* s)
|
||||
{
|
||||
while (s[len] != '\0' && len < 63) {
|
||||
data[len] = s[len];
|
||||
++len;
|
||||
}
|
||||
}
|
||||
[[nodiscard]] constexpr std::string_view view() const
|
||||
{
|
||||
return {data, len};
|
||||
}
|
||||
[[nodiscard]] constexpr operator std::string_view() const
|
||||
{
|
||||
return view();
|
||||
}
|
||||
};
|
||||
|
||||
/// True if reflection `m` carries an annotation of type `Tag`.
|
||||
template <typename Tag>
|
||||
[[nodiscard]] consteval bool has_annotation(meta::info m)
|
||||
{
|
||||
return !meta::annotations_of_with_type(m, ^^Tag).empty();
|
||||
}
|
||||
|
||||
/// The first `Tag` annotation on `m` (its value), or nullopt.
|
||||
template <typename Tag>
|
||||
[[nodiscard]] consteval std::optional<Tag> annotation_of(meta::info m)
|
||||
{
|
||||
for (meta::info a : meta::annotations_of_with_type(m, ^^Tag)) {
|
||||
return meta::extract<Tag>(a);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
/// The (unqualified) name of a type, e.g. type_name<Foo>() == "Foo".
|
||||
template <typename T> [[nodiscard]] std::string type_name()
|
||||
{
|
||||
if constexpr (meta::has_identifier(^^T)) {
|
||||
return std::string{meta::identifier_of(^^T)};
|
||||
} else {
|
||||
return std::string{meta::display_string_of(^^T)};
|
||||
}
|
||||
}
|
||||
|
||||
// ── enum utilities (extend Void::Detail enum reflection) ──────────────
|
||||
using Void::Detail::enum_cast;
|
||||
using Void::Detail::enum_name;
|
||||
using Void::Detail::enum_parse;
|
||||
|
||||
/// Number of enumerators of E.
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
inline constexpr std::size_t enum_count = meta::enumerators_of(^^E).size();
|
||||
|
||||
/// The enumerator values of E (declaration order).
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] consteval std::array<E, enum_count<E>> enum_values()
|
||||
{
|
||||
std::array<E, enum_count<E>> out{};
|
||||
std::size_t i = 0;
|
||||
template for (constexpr auto e :
|
||||
std::define_static_array(meta::enumerators_of(^^E)))
|
||||
{
|
||||
out[i++] = [:e:];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// (value, identifier) pairs for every enumerator of E (declaration order).
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] std::array<std::pair<E, std::string_view>, enum_count<E>>
|
||||
enum_entries()
|
||||
{
|
||||
std::array<std::pair<E, std::string_view>, enum_count<E>> out{};
|
||||
std::size_t i = 0;
|
||||
template for (constexpr auto e :
|
||||
std::define_static_array(meta::enumerators_of(^^E)))
|
||||
{
|
||||
out[i++] = {[:e:], meta::identifier_of(e)};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
#else // no reflection
|
||||
|
||||
template <class T>
|
||||
concept Struct = false;
|
||||
|
||||
#endif // VOID_HAS_META_REFLECTION
|
||||
|
||||
// ── repr (diagnostic rendering) ───────────────────────────────────────
|
||||
// 1. std::formatter<T> → std::format. 2. a .format() method. 3. reflect
|
||||
// the data members as `Type{a: 1, b: 2}`. 4. "<unrepresentable>".
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value);
|
||||
|
||||
template <typename T>
|
||||
concept Formattable = std::formattable<T, char>;
|
||||
|
||||
template <typename T>
|
||||
concept HasFormatMethod = requires(const T& v) {
|
||||
{ v.format() } -> std::convertible_to<std::string>;
|
||||
};
|
||||
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
template <typename T> [[nodiscard]] std::string reflect_struct(const T& obj)
|
||||
{
|
||||
std::string out;
|
||||
if constexpr (meta::has_identifier(^^T)) {
|
||||
out += meta::identifier_of(^^T);
|
||||
} else {
|
||||
out += "?";
|
||||
}
|
||||
out += '{';
|
||||
bool first = true;
|
||||
template for (constexpr auto m : members_v<T>)
|
||||
{
|
||||
if (!first) {
|
||||
out += ", ";
|
||||
}
|
||||
out += meta::identifier_of(m);
|
||||
out += ": ";
|
||||
out += repr(obj.[:m:]);
|
||||
first = false;
|
||||
}
|
||||
out += '}';
|
||||
return out;
|
||||
}
|
||||
#endif
|
||||
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value)
|
||||
{
|
||||
if constexpr (Formattable<T>) {
|
||||
return std::format("{}", value);
|
||||
} else if constexpr (HasFormatMethod<T>) {
|
||||
return std::string{value.format()};
|
||||
}
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
else if constexpr (std::is_class_v<T> || std::is_union_v<T>) {
|
||||
return reflect_struct(value);
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
return "<unrepresentable>";
|
||||
}
|
||||
}
|
||||
|
||||
// ── generic algorithms over data members ──────────────────────────────
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
|
||||
/// Member-wise equality for reflectable structs (recurses on members).
|
||||
template <typename T> [[nodiscard]] bool equal(const T& a, const T& b)
|
||||
{
|
||||
if constexpr (Struct<T> && !Leaf<T>) {
|
||||
bool eq = true;
|
||||
template for (constexpr auto m : members_v<T>)
|
||||
{
|
||||
if (eq && !equal(a.[:m:], b.[:m:])) {
|
||||
eq = false;
|
||||
}
|
||||
}
|
||||
return eq;
|
||||
} else {
|
||||
return a == b;
|
||||
}
|
||||
}
|
||||
|
||||
/// Lexicographic member-wise ordering for reflectable structs.
|
||||
template <typename T>
|
||||
[[nodiscard]] std::strong_ordering compare(const T& a, const T& b)
|
||||
{
|
||||
if constexpr (Struct<T> && !Leaf<T>) {
|
||||
std::strong_ordering result = std::strong_ordering::equal;
|
||||
template for (constexpr auto m : members_v<T>)
|
||||
{
|
||||
if (result == std::strong_ordering::equal) {
|
||||
result = compare(a.[:m:], b.[:m:]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} else {
|
||||
return a <=> b;
|
||||
}
|
||||
}
|
||||
|
||||
/// 64-bit member-folded hash for reflectable structs (recurses).
|
||||
template <typename T> [[nodiscard]] std::uint64_t hash(const T& v)
|
||||
{
|
||||
auto mix = [](std::uint64_t seed, std::uint64_t x) {
|
||||
x ^= x >> 33;
|
||||
x *= 0xff51afd7ed558ccdULL;
|
||||
x ^= x >> 33;
|
||||
return seed ^
|
||||
(x + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2));
|
||||
};
|
||||
if constexpr (Struct<T> && !Leaf<T>) {
|
||||
std::uint64_t h = 0xcbf29ce484222325ULL;
|
||||
template for (constexpr auto m : members_v<T>)
|
||||
{
|
||||
h = mix(h, hash(v.[:m:]));
|
||||
}
|
||||
return h;
|
||||
} else {
|
||||
return static_cast<std::uint64_t>(std::hash<T>{}(v));
|
||||
}
|
||||
}
|
||||
|
||||
#endif // VOID_HAS_META_REFLECTION
|
||||
|
||||
} // namespace Void::Meta
|
||||
+213
-112
@@ -1,5 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
@@ -9,130 +13,227 @@
|
||||
namespace Void::Csv
|
||||
{
|
||||
|
||||
using Row = std::vector<std::string>;
|
||||
using Table = std::vector<Row>;
|
||||
using Row = std::vector<std::string>;
|
||||
using Table = std::vector<Row>;
|
||||
|
||||
// ── parse ─────────────────────────────────────────────────────────────────────
|
||||
// RFC 4180-compatible parser. Fields may be quoted ("..."). CRLF and LF
|
||||
// both accepted as row terminators.
|
||||
// ── parse
|
||||
// ───────────────────────────────────────────────────────────────────── RFC
|
||||
// 4180-compatible parser. Fields may be quoted ("..."). CRLF and LF both
|
||||
// accepted as row terminators.
|
||||
|
||||
[[nodiscard]] inline Table parse(std::string_view text, char delim = ',')
|
||||
{
|
||||
Table result;
|
||||
Row row;
|
||||
std::string field;
|
||||
bool in_quote = false;
|
||||
[[nodiscard]] inline Table parse(std::string_view text, char delim = ',')
|
||||
{
|
||||
Table result;
|
||||
Row row;
|
||||
std::string field;
|
||||
bool in_quote = false;
|
||||
|
||||
for (std::size_t i = 0; i < text.size(); ++i) {
|
||||
const char c = text[i];
|
||||
for (std::size_t i = 0; i < text.size(); ++i) {
|
||||
const char c = text[i];
|
||||
|
||||
if (in_quote) {
|
||||
if (c == '"') {
|
||||
// Peek for doubled quote
|
||||
if (i + 1 < text.size() && text[i + 1] == '"') {
|
||||
field += '"'; ++i;
|
||||
} else {
|
||||
in_quote = false;
|
||||
}
|
||||
} else {
|
||||
field += c;
|
||||
}
|
||||
} else {
|
||||
if (c == '"') {
|
||||
in_quote = true;
|
||||
} else if (c == delim) {
|
||||
row.push_back(std::move(field));
|
||||
field.clear();
|
||||
} else if (c == '\n') {
|
||||
row.push_back(std::move(field));
|
||||
field.clear();
|
||||
result.push_back(std::move(row));
|
||||
row.clear();
|
||||
} else if (c == '\r') {
|
||||
// skip CR in CRLF
|
||||
} else {
|
||||
field += c;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (in_quote) {
|
||||
if (c == '"') {
|
||||
// Peek for doubled quote
|
||||
if (i + 1 < text.size() && text[i + 1] == '"') {
|
||||
field += '"';
|
||||
++i;
|
||||
} else {
|
||||
in_quote = false;
|
||||
}
|
||||
} else {
|
||||
field += c;
|
||||
}
|
||||
} else {
|
||||
if (c == '"') {
|
||||
in_quote = true;
|
||||
} else if (c == delim) {
|
||||
row.push_back(std::move(field));
|
||||
field.clear();
|
||||
} else if (c == '\n') {
|
||||
row.push_back(std::move(field));
|
||||
field.clear();
|
||||
result.push_back(std::move(row));
|
||||
row.clear();
|
||||
} else if (c == '\r') {
|
||||
// skip CR in CRLF
|
||||
} else {
|
||||
field += c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Flush last field/row
|
||||
row.push_back(std::move(field));
|
||||
if (!row.empty() && !(row.size() == 1 && row[0].empty())) {
|
||||
result.push_back(std::move(row));
|
||||
}
|
||||
// Flush last field/row
|
||||
row.push_back(std::move(field));
|
||||
if (!row.empty() && !(row.size() == 1 && row[0].empty())) {
|
||||
result.push_back(std::move(row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── serialize ─────────────────────────────────────────────────────────────────
|
||||
// Produces RFC 4180 CSV. Fields that contain the delimiter, quote, or newline
|
||||
// are wrapped in double quotes; embedded quotes are doubled.
|
||||
// ── serialize
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
// Produces RFC 4180 CSV. Fields that contain the delimiter, quote, or
|
||||
// newline are wrapped in double quotes; embedded quotes are doubled.
|
||||
|
||||
[[nodiscard]] inline std::string serialize(const Table& table,
|
||||
char delim = ',')
|
||||
{
|
||||
std::string out;
|
||||
for (const auto& row : table) {
|
||||
for (std::size_t i = 0; i < row.size(); ++i) {
|
||||
const auto& field = row[i];
|
||||
const bool needs_quote =
|
||||
field.find(delim) != std::string::npos ||
|
||||
field.find('"') != std::string::npos ||
|
||||
field.find('\n') != std::string::npos ||
|
||||
field.find('\r') != std::string::npos;
|
||||
if (needs_quote) {
|
||||
out += '"';
|
||||
for (char c : field) {
|
||||
if (c == '"') out += '"';
|
||||
out += c;
|
||||
}
|
||||
out += '"';
|
||||
} else {
|
||||
out += field;
|
||||
}
|
||||
if (i + 1 < row.size()) out += delim;
|
||||
}
|
||||
out += '\n';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
[[nodiscard]] inline std::string serialize(const Table& table,
|
||||
char delim = ',')
|
||||
{
|
||||
std::string out;
|
||||
for (const auto& row : table) {
|
||||
for (std::size_t i = 0; i < row.size(); ++i) {
|
||||
const auto& field = row[i];
|
||||
const bool needs_quote =
|
||||
field.find(delim) != std::string::npos ||
|
||||
field.find('"') != std::string::npos ||
|
||||
field.find('\n') != std::string::npos ||
|
||||
field.find('\r') != std::string::npos;
|
||||
if (needs_quote) {
|
||||
out += '"';
|
||||
for (char c : field) {
|
||||
if (c == '"') {
|
||||
out += '"';
|
||||
}
|
||||
out += c;
|
||||
}
|
||||
out += '"';
|
||||
} else {
|
||||
out += field;
|
||||
}
|
||||
if (i + 1 < row.size()) {
|
||||
out += delim;
|
||||
}
|
||||
}
|
||||
out += '\n';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── with_header convenience ───────────────────────────────────────────────────
|
||||
// ── with_header convenience
|
||||
// ───────────────────────────────────────────────────
|
||||
|
||||
struct CsvWithHeader
|
||||
{
|
||||
Row header;
|
||||
Table rows;
|
||||
struct CsvWithHeader {
|
||||
Row header;
|
||||
Table rows;
|
||||
|
||||
[[nodiscard]] std::optional<std::size_t>
|
||||
col_index(std::string_view name) const
|
||||
{
|
||||
for (std::size_t i = 0; i < header.size(); ++i) {
|
||||
if (header[i] == name) return i;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
[[nodiscard]] std::optional<std::size_t>
|
||||
col_index(std::string_view name) const
|
||||
{
|
||||
for (std::size_t i = 0; i < header.size(); ++i) {
|
||||
if (header[i] == name) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
get(const Row& row, std::string_view name) const
|
||||
{
|
||||
auto idx = col_index(name);
|
||||
if (!idx || *idx >= row.size()) return std::nullopt;
|
||||
return row[*idx];
|
||||
}
|
||||
};
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
get(const Row& row, std::string_view name) const
|
||||
{
|
||||
auto idx = col_index(name);
|
||||
if (!idx || *idx >= row.size()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return row[*idx];
|
||||
}
|
||||
};
|
||||
|
||||
[[nodiscard]] inline std::optional<CsvWithHeader>
|
||||
parse_with_header(std::string_view text, char delim = ',')
|
||||
{
|
||||
auto table = parse(text, delim);
|
||||
if (table.empty()) return std::nullopt;
|
||||
CsvWithHeader result;
|
||||
result.header = std::move(table[0]);
|
||||
result.rows.assign(std::make_move_iterator(table.begin() + 1),
|
||||
std::make_move_iterator(table.end()));
|
||||
return result;
|
||||
}
|
||||
[[nodiscard]] inline std::optional<CsvWithHeader>
|
||||
parse_with_header(std::string_view text, char delim = ',')
|
||||
{
|
||||
auto table = parse(text, delim);
|
||||
if (table.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
CsvWithHeader result;
|
||||
result.header = std::move(table[0]);
|
||||
result.rows.assign(std::make_move_iterator(table.begin() + 1),
|
||||
std::make_move_iterator(table.end()));
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── reflective struct ↔ row
|
||||
// ─────────────────────────────────────────────────── Map a flat aggregate
|
||||
// to/from a CSV Row by reflecting its data members (column order =
|
||||
// declaration order; header = field names). Supported field types:
|
||||
// std::string, arithmetic, bool.
|
||||
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
template <typename F>
|
||||
[[nodiscard]] std::string cell_to_string(const F& f)
|
||||
{
|
||||
if constexpr (std::same_as<F, std::string>) {
|
||||
return f;
|
||||
} else if constexpr (std::same_as<F, bool>) {
|
||||
return f ? "true" : "false";
|
||||
} else if constexpr (std::is_arithmetic_v<F>) {
|
||||
return std::format("{}", f);
|
||||
} else {
|
||||
return Void::Meta::repr(f);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
[[nodiscard]] bool cell_from_string(std::string_view s, F& f)
|
||||
{
|
||||
if constexpr (std::same_as<F, std::string>) {
|
||||
f = std::string{s};
|
||||
return true;
|
||||
} else if constexpr (std::same_as<F, bool>) {
|
||||
f = (s == "true" || s == "1");
|
||||
return true;
|
||||
} else if constexpr (std::is_integral_v<F>) {
|
||||
return std::from_chars(s.data(), s.data() + s.size(), f).ec ==
|
||||
std::errc{};
|
||||
} else if constexpr (std::is_floating_point_v<F>) {
|
||||
return std::from_chars(s.data(), s.data() + s.size(), f).ec ==
|
||||
std::errc{};
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
/// The header row (field names) for T.
|
||||
template <typename T> [[nodiscard]] Row header_row()
|
||||
{
|
||||
Row h;
|
||||
for (auto name : Void::Meta::field_names<T>()) {
|
||||
h.emplace_back(name);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/// Stringify a struct into a CSV Row (declaration order).
|
||||
template <typename T> [[nodiscard]] Row to_row(const T& v)
|
||||
{
|
||||
Row r;
|
||||
Void::Meta::for_each_field(v, [&](std::string_view, const auto& f) {
|
||||
r.push_back(Detail::cell_to_string(f));
|
||||
});
|
||||
return r;
|
||||
}
|
||||
|
||||
/// Parse a CSV Row back into a struct (by position). Returns nullopt if any
|
||||
/// cell fails to convert.
|
||||
template <typename T>
|
||||
[[nodiscard]] std::optional<T> from_row(const Row& row)
|
||||
{
|
||||
T out{};
|
||||
std::size_t i = 0;
|
||||
bool ok = true;
|
||||
Void::Meta::for_each_field(out, [&](std::string_view, auto& f) {
|
||||
if (i < row.size()) {
|
||||
ok = Detail::cell_from_string(row[i], f) && ok;
|
||||
}
|
||||
++i;
|
||||
});
|
||||
return ok ? std::optional<T>{std::move(out)} : std::nullopt;
|
||||
}
|
||||
|
||||
#endif // VOID_HAS_META_REFLECTION
|
||||
|
||||
} // namespace Void::Csv
|
||||
+942
-379
File diff suppressed because it is too large.
Load diff
+536
-334
@@ -1,9 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Detail/Enum.hpp>
|
||||
#include <Void/Time/Format.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
@@ -11,8 +16,10 @@
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
@@ -20,7 +27,8 @@
|
||||
#define VOID_HAS_JSON_REFLECTION 1
|
||||
#endif
|
||||
|
||||
// ── Reflection → JSON ─────────────────────────────────────────────────────────
|
||||
// ── Reflection → JSON
|
||||
// ─────────────────────────────────────────────────────────
|
||||
// Serialize/deserialize aggregate structs to Json::Value using C++26 P2996
|
||||
// reflection (GCC 16+, -freflection). Field names become object keys.
|
||||
//
|
||||
@@ -43,381 +51,575 @@
|
||||
namespace Void::Json
|
||||
{
|
||||
|
||||
struct ReflectError {
|
||||
std::string field; // dotted path of the offending field ("" if global)
|
||||
std::string message;
|
||||
};
|
||||
struct ReflectError {
|
||||
std::string
|
||||
field; // dotted path of the offending field ("" if global)
|
||||
std::string message;
|
||||
};
|
||||
|
||||
// ── customization point ───────────────────────────────────────────────────────
|
||||
// ── field annotations
|
||||
// ───────────────────────────────────────────────────────── Annotate
|
||||
// aggregate members to control (de)serialization:
|
||||
// struct User {
|
||||
// [[= Json::Rename{"user_id"}]] int id; // JSON key override
|
||||
// [[= Json::Skip{}]] int cache; // never
|
||||
// (de)serialized
|
||||
// [[= Json::Required{}]] std::string nm; // error if absent
|
||||
// [[= Json::Flatten{}]] Address addr; // inline nested
|
||||
// object
|
||||
// };
|
||||
struct Rename {
|
||||
Void::Meta::Str key;
|
||||
};
|
||||
struct Skip {
|
||||
};
|
||||
struct Required {
|
||||
};
|
||||
struct Flatten {
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
concept HasMemberToJson = requires(const T& t) {
|
||||
{ t.to_json() } -> std::same_as<Value>;
|
||||
};
|
||||
// ── customization point
|
||||
// ───────────────────────────────────────────────────────
|
||||
|
||||
template <typename T>
|
||||
concept HasMemberFromJson = requires(const Value& v) {
|
||||
{ T::from_json(v) } -> std::same_as<std::expected<T, ReflectError>>;
|
||||
};
|
||||
template <typename T>
|
||||
concept HasMemberToJson = requires(const T& t) {
|
||||
{ t.to_json() } -> std::same_as<Value>;
|
||||
};
|
||||
|
||||
// ── supported leaf / container shapes ─────────────────────────────────────────
|
||||
template <typename T>
|
||||
concept HasMemberFromJson = requires(const Value& v) {
|
||||
{ T::from_json(v) } -> std::same_as<std::expected<T, ReflectError>>;
|
||||
};
|
||||
|
||||
namespace ReflectDetail
|
||||
{
|
||||
template <typename T>
|
||||
struct IsOptional : std::false_type {};
|
||||
template <typename U>
|
||||
struct IsOptional<std::optional<U>> : std::true_type {};
|
||||
|
||||
template <typename T>
|
||||
struct IsVector : std::false_type {};
|
||||
template <typename U>
|
||||
struct IsVector<std::vector<U>> : std::true_type {};
|
||||
|
||||
template <typename T>
|
||||
struct IsStringMap : std::false_type {};
|
||||
template <typename U>
|
||||
struct IsStringMap<std::map<std::string, U>> : std::true_type {};
|
||||
} // namespace ReflectDetail
|
||||
// ── supported leaf / container shapes (single source: Void::Meta)
|
||||
// ─────────────
|
||||
|
||||
#ifdef VOID_HAS_JSON_REFLECTION
|
||||
|
||||
template <typename T>
|
||||
concept ReflectableAggregate =
|
||||
std::is_aggregate_v<T> && !std::is_array_v<T> &&
|
||||
std::is_default_constructible_v<T>;
|
||||
template <typename T>
|
||||
concept ReflectableAggregate =
|
||||
std::is_aggregate_v<T> && !std::is_array_v<T> &&
|
||||
std::is_default_constructible_v<T>;
|
||||
|
||||
#else
|
||||
|
||||
template <typename T>
|
||||
concept ReflectableAggregate = false;
|
||||
template <typename T>
|
||||
concept ReflectableAggregate = false;
|
||||
|
||||
#endif
|
||||
|
||||
template <typename T>
|
||||
concept JsonConvertible =
|
||||
HasMemberToJson<T> || std::same_as<T, bool> || std::is_arithmetic_v<T> ||
|
||||
std::is_enum_v<T> || std::same_as<T, std::string> ||
|
||||
ReflectDetail::IsOptional<T>::value || ReflectDetail::IsVector<T>::value ||
|
||||
ReflectDetail::IsStringMap<T>::value || ReflectableAggregate<T>;
|
||||
template <typename T>
|
||||
concept JsonConvertible =
|
||||
HasMemberToJson<T> || std::same_as<T, bool> ||
|
||||
std::is_arithmetic_v<T> || std::is_enum_v<T> ||
|
||||
std::same_as<T, std::string> || Void::Meta::is_optional_v<T> ||
|
||||
Void::Meta::is_vector_v<T> || Void::Meta::is_string_map_v<T> ||
|
||||
Void::Meta::is_duration_v<T> || Void::Meta::is_time_point_v<T> ||
|
||||
Void::Meta::is_variant_v<T> || Void::Meta::is_std_array_v<T> ||
|
||||
Void::Meta::is_map_v<T> || ReflectableAggregate<T>;
|
||||
|
||||
// Anything serializable through this header (customized or reflected).
|
||||
template <typename T>
|
||||
concept Reflectable = JsonConvertible<T>;
|
||||
// Anything serializable through this header (customized or reflected).
|
||||
template <typename T>
|
||||
concept Reflectable = JsonConvertible<T>;
|
||||
|
||||
// ── to_json ───────────────────────────────────────────────────────────────────
|
||||
// ── to_json
|
||||
// ───────────────────────────────────────────────────────────────────
|
||||
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] Value to_json(const T& v);
|
||||
template <Reflectable T> [[nodiscard]] Value to_json(const T& v);
|
||||
|
||||
namespace ReflectDetail
|
||||
{
|
||||
template <typename T>
|
||||
Value leaf_to_json(const T& v)
|
||||
{
|
||||
if constexpr (HasMemberToJson<T>) {
|
||||
return v.to_json();
|
||||
}
|
||||
else if constexpr (std::same_as<T, bool>) {
|
||||
return Value{v};
|
||||
}
|
||||
else if constexpr (std::is_enum_v<T>) {
|
||||
namespace ReflectDetail
|
||||
{
|
||||
template <typename T> Value leaf_to_json(const T& v)
|
||||
{
|
||||
if constexpr (HasMemberToJson<T>) {
|
||||
return v.to_json();
|
||||
} else if constexpr (std::same_as<T, bool>) {
|
||||
return Value{v};
|
||||
} else if constexpr (std::is_enum_v<T>) {
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
// Enum values serialize by name — stable across binary versions.
|
||||
return Value{Void::Detail::enum_name(v)};
|
||||
// Enum values serialize by name — stable across binary
|
||||
// versions.
|
||||
return Value{Void::Detail::enum_name(v)};
|
||||
#else
|
||||
return Value{static_cast<double>(
|
||||
static_cast<std::underlying_type_t<T>>(v))};
|
||||
return Value{static_cast<double>(
|
||||
static_cast<std::underlying_type_t<T>>(v))};
|
||||
#endif
|
||||
}
|
||||
else if constexpr (std::is_arithmetic_v<T>) {
|
||||
return Value{static_cast<double>(v)};
|
||||
}
|
||||
else if constexpr (std::same_as<T, std::string>) {
|
||||
return Value{v};
|
||||
}
|
||||
else if constexpr (IsOptional<T>::value) {
|
||||
return v ? Json::to_json(*v) : Value{nullptr};
|
||||
}
|
||||
else if constexpr (IsVector<T>::value) {
|
||||
auto arr = Json::array();
|
||||
arr.as_array().reserve(v.size());
|
||||
for (const auto& e : v) {
|
||||
arr.as_array().push_back(Json::to_json(e));
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
else if constexpr (IsStringMap<T>::value) {
|
||||
auto obj = Json::object();
|
||||
for (const auto& [k, e] : v) {
|
||||
obj.as_object().emplace_back(k, Json::to_json(e));
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
else {
|
||||
static_assert(ReflectableAggregate<T>,
|
||||
"type is not serializable via Json reflection");
|
||||
} else if constexpr (std::is_arithmetic_v<T>) {
|
||||
return Value{static_cast<double>(v)};
|
||||
} else if constexpr (std::same_as<T, std::string>) {
|
||||
return Value{v};
|
||||
} else if constexpr (Void::Meta::is_optional_v<T>) {
|
||||
return v ? Json::to_json(*v) : Value{nullptr};
|
||||
} else if constexpr (Void::Meta::is_vector_v<T>) {
|
||||
auto arr = Json::array();
|
||||
arr.as_array().reserve(v.size());
|
||||
for (const auto& e : v) {
|
||||
arr.as_array().push_back(Json::to_json(e));
|
||||
}
|
||||
return arr;
|
||||
} else if constexpr (Void::Meta::is_string_map_v<T>) {
|
||||
auto obj = Json::object();
|
||||
for (const auto& [k, e] : v) {
|
||||
obj.as_object().emplace_back(k, Json::to_json(e));
|
||||
}
|
||||
return obj;
|
||||
} else if constexpr (Void::Meta::is_duration_v<T>) {
|
||||
return Value{Void::Time::duration_to_string(v)};
|
||||
} else if constexpr (Void::Meta::is_time_point_v<T>) {
|
||||
// Encode as milliseconds-since-epoch (e.g. "1750000000000ms").
|
||||
// Millisecond magnitude stays exact through the double-based
|
||||
// parse_duration, where a native-nanosecond count would not.
|
||||
return Value{Void::Time::duration_to_string(
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
v.time_since_epoch()))};
|
||||
} else if constexpr (Void::Meta::is_std_array_v<T>) {
|
||||
auto arr = Json::array();
|
||||
arr.as_array().reserve(v.size());
|
||||
for (const auto& e : v) {
|
||||
arr.as_array().push_back(Json::to_json(e));
|
||||
}
|
||||
return arr;
|
||||
} else if constexpr (Void::Meta::is_map_v<T>) {
|
||||
// Non-string-keyed map: array of {key, value} objects.
|
||||
auto arr = Json::array();
|
||||
for (const auto& [k, e] : v) {
|
||||
auto pair = Json::object();
|
||||
pair.as_object().emplace_back("key", Json::to_json(k));
|
||||
pair.as_object().emplace_back("value", Json::to_json(e));
|
||||
arr.as_array().push_back(std::move(pair));
|
||||
}
|
||||
return arr;
|
||||
} else if constexpr (Void::Meta::is_variant_v<T>) {
|
||||
return std::visit(
|
||||
[](const auto& alt) -> Value {
|
||||
using Alt = std::decay_t<decltype(alt)>;
|
||||
auto obj = Json::object();
|
||||
obj.as_object().emplace_back(
|
||||
"type", Value{Void::Meta::type_name<Alt>()});
|
||||
obj.as_object().emplace_back("value",
|
||||
Json::to_json(alt));
|
||||
return obj;
|
||||
},
|
||||
v);
|
||||
} else {
|
||||
static_assert(ReflectableAggregate<T>,
|
||||
"type is not serializable via Json reflection");
|
||||
#ifdef VOID_HAS_JSON_REFLECTION
|
||||
auto obj = Json::object();
|
||||
static constexpr auto members = std::define_static_array(
|
||||
std::meta::nonstatic_data_members_of(
|
||||
^^T, std::meta::access_context::current()));
|
||||
template for (constexpr auto m : members) {
|
||||
obj.as_object().emplace_back(
|
||||
std::string{std::meta::identifier_of(m)},
|
||||
Json::to_json(v.[:m:]));
|
||||
}
|
||||
return obj;
|
||||
auto obj = Json::object();
|
||||
template for (constexpr auto m : Void::Meta::members_v<T>)
|
||||
{
|
||||
if constexpr (!Void::Meta::has_annotation<Skip>(m)) {
|
||||
if constexpr (Void::Meta::has_annotation<Flatten>(m)) {
|
||||
// Inline the nested object's keys into this object.
|
||||
auto sub = Json::to_json(v.[:m:]);
|
||||
if (sub.is_object()) {
|
||||
for (auto& kv : sub.as_object()) {
|
||||
obj.as_object().emplace_back(
|
||||
kv.first, std::move(kv.second));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
constexpr auto rn =
|
||||
Void::Meta::annotation_of<Rename>(m);
|
||||
std::string key =
|
||||
rn.has_value()
|
||||
? std::string{rn->key.view()}
|
||||
: std::string{std::meta::identifier_of(m)};
|
||||
obj.as_object().emplace_back(
|
||||
std::move(key), Json::to_json(v.[:m:]));
|
||||
}
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
} // namespace ReflectDetail
|
||||
}
|
||||
}
|
||||
} // namespace ReflectDetail
|
||||
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] Value to_json(const T& v)
|
||||
{
|
||||
return ReflectDetail::leaf_to_json(v);
|
||||
}
|
||||
template <Reflectable T> [[nodiscard]] Value to_json(const T& v)
|
||||
{
|
||||
return ReflectDetail::leaf_to_json(v);
|
||||
}
|
||||
|
||||
// ── from_json ─────────────────────────────────────────────────────────────────
|
||||
// ── from_json
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] std::expected<T, ReflectError> from_json(const Value& j);
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] std::expected<T, ReflectError> from_json(const Value& j);
|
||||
|
||||
namespace ReflectDetail
|
||||
{
|
||||
[[nodiscard]] inline ReflectError nest(std::string_view field,
|
||||
ReflectError inner)
|
||||
{
|
||||
if (inner.field.empty()) {
|
||||
inner.field = std::string{field};
|
||||
}
|
||||
else {
|
||||
inner.field = std::string{field} + "." + inner.field;
|
||||
}
|
||||
return inner;
|
||||
}
|
||||
namespace ReflectDetail
|
||||
{
|
||||
[[nodiscard]] inline ReflectError nest(std::string_view field,
|
||||
ReflectError inner)
|
||||
{
|
||||
if (inner.field.empty()) {
|
||||
inner.field = std::string{field};
|
||||
} else {
|
||||
inner.field = std::string{field} + "." + inner.field;
|
||||
}
|
||||
return inner;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
std::expected<T, ReflectError> leaf_from_json(const Value& j)
|
||||
{
|
||||
if constexpr (HasMemberFromJson<T>) {
|
||||
return T::from_json(j);
|
||||
}
|
||||
else if constexpr (std::same_as<T, bool>) {
|
||||
if (!j.is_bool()) {
|
||||
return std::unexpected{ReflectError{"", "expected bool"}};
|
||||
}
|
||||
return j.as_bool();
|
||||
}
|
||||
else if constexpr (std::is_enum_v<T>) {
|
||||
template <typename T>
|
||||
std::expected<T, ReflectError> leaf_from_json(const Value& j)
|
||||
{
|
||||
if constexpr (HasMemberFromJson<T>) {
|
||||
return T::from_json(j);
|
||||
} else if constexpr (std::same_as<T, bool>) {
|
||||
if (!j.is_bool()) {
|
||||
return std::unexpected{ReflectError{"", "expected bool"}};
|
||||
}
|
||||
return j.as_bool();
|
||||
} else if constexpr (std::is_enum_v<T>) {
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
if (!j.is_string()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected enum name string"}};
|
||||
}
|
||||
auto parsed = Void::Detail::enum_parse<T>(j.as_string());
|
||||
if (!parsed) {
|
||||
return std::unexpected{ReflectError{
|
||||
"", "unknown enumerator '" + j.as_string() + "'"}};
|
||||
}
|
||||
return *parsed;
|
||||
if (!j.is_string()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected enum name string"}};
|
||||
}
|
||||
auto parsed = Void::Detail::enum_parse<T>(j.as_string());
|
||||
if (!parsed) {
|
||||
return std::unexpected{ReflectError{
|
||||
"", "unknown enumerator '" + j.as_string() + "'"}};
|
||||
}
|
||||
return *parsed;
|
||||
#else
|
||||
if (!j.is_number()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected enum number"}};
|
||||
}
|
||||
return static_cast<T>(
|
||||
static_cast<std::underlying_type_t<T>>(j.as_number()));
|
||||
if (!j.is_number()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected enum number"}};
|
||||
}
|
||||
return static_cast<T>(
|
||||
static_cast<std::underlying_type_t<T>>(j.as_number()));
|
||||
#endif
|
||||
}
|
||||
else if constexpr (std::is_arithmetic_v<T>) {
|
||||
if (!j.is_number()) {
|
||||
return std::unexpected{ReflectError{"", "expected number"}};
|
||||
}
|
||||
return static_cast<T>(j.as_number());
|
||||
}
|
||||
else if constexpr (std::same_as<T, std::string>) {
|
||||
if (!j.is_string()) {
|
||||
return std::unexpected{ReflectError{"", "expected string"}};
|
||||
}
|
||||
return j.as_string();
|
||||
}
|
||||
else if constexpr (IsOptional<T>::value) {
|
||||
using U = typename T::value_type;
|
||||
if (j.is_null()) {
|
||||
return T{std::nullopt};
|
||||
}
|
||||
auto inner = Json::from_json<U>(j);
|
||||
if (!inner) {
|
||||
return std::unexpected{std::move(inner).error()};
|
||||
}
|
||||
return T{std::move(*inner)};
|
||||
}
|
||||
else if constexpr (IsVector<T>::value) {
|
||||
using U = typename T::value_type;
|
||||
if (!j.is_array()) {
|
||||
return std::unexpected{ReflectError{"", "expected array"}};
|
||||
}
|
||||
T out;
|
||||
out.reserve(j.as_array().size());
|
||||
std::size_t index = 0;
|
||||
for (const auto& e : j.as_array()) {
|
||||
auto inner = Json::from_json<U>(e);
|
||||
if (!inner) {
|
||||
return std::unexpected{nest(
|
||||
"[" + std::to_string(index) + "]",
|
||||
std::move(inner).error())};
|
||||
}
|
||||
out.push_back(std::move(*inner));
|
||||
++index;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
else if constexpr (IsStringMap<T>::value) {
|
||||
using U = typename T::mapped_type;
|
||||
if (!j.is_object()) {
|
||||
return std::unexpected{ReflectError{"", "expected object"}};
|
||||
}
|
||||
T out;
|
||||
for (const auto& [k, e] : j.as_object()) {
|
||||
auto inner = Json::from_json<U>(e);
|
||||
if (!inner) {
|
||||
return std::unexpected{nest(k, std::move(inner).error())};
|
||||
}
|
||||
out.emplace(k, std::move(*inner));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
else {
|
||||
static_assert(ReflectableAggregate<T>,
|
||||
"type is not deserializable via Json reflection");
|
||||
} else if constexpr (std::is_arithmetic_v<T>) {
|
||||
if (!j.is_number()) {
|
||||
return std::unexpected{ReflectError{"", "expected number"}};
|
||||
}
|
||||
return static_cast<T>(j.as_number());
|
||||
} else if constexpr (std::same_as<T, std::string>) {
|
||||
if (!j.is_string()) {
|
||||
return std::unexpected{ReflectError{"", "expected string"}};
|
||||
}
|
||||
return j.as_string();
|
||||
} else if constexpr (Void::Meta::is_optional_v<T>) {
|
||||
using U = typename T::value_type;
|
||||
if (j.is_null()) {
|
||||
return T{std::nullopt};
|
||||
}
|
||||
auto inner = Json::from_json<U>(j);
|
||||
if (!inner) {
|
||||
return std::unexpected{std::move(inner).error()};
|
||||
}
|
||||
return T{std::move(*inner)};
|
||||
} else if constexpr (Void::Meta::is_vector_v<T>) {
|
||||
using U = typename T::value_type;
|
||||
if (!j.is_array()) {
|
||||
return std::unexpected{ReflectError{"", "expected array"}};
|
||||
}
|
||||
T out;
|
||||
out.reserve(j.as_array().size());
|
||||
std::size_t index = 0;
|
||||
for (const auto& e : j.as_array()) {
|
||||
auto inner = Json::from_json<U>(e);
|
||||
if (!inner) {
|
||||
return std::unexpected{
|
||||
nest("[" + std::to_string(index) + "]",
|
||||
std::move(inner).error())};
|
||||
}
|
||||
out.push_back(std::move(*inner));
|
||||
++index;
|
||||
}
|
||||
return out;
|
||||
} else if constexpr (Void::Meta::is_string_map_v<T>) {
|
||||
using U = typename T::mapped_type;
|
||||
if (!j.is_object()) {
|
||||
return std::unexpected{ReflectError{"", "expected object"}};
|
||||
}
|
||||
T out;
|
||||
for (const auto& [k, e] : j.as_object()) {
|
||||
auto inner = Json::from_json<U>(e);
|
||||
if (!inner) {
|
||||
return std::unexpected{
|
||||
nest(k, std::move(inner).error())};
|
||||
}
|
||||
out.emplace(k, std::move(*inner));
|
||||
}
|
||||
return out;
|
||||
} else if constexpr (Void::Meta::is_duration_v<T>) {
|
||||
if (!j.is_string()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected duration string"}};
|
||||
}
|
||||
auto parsed = Void::Time::parse_duration(j.as_string());
|
||||
if (!parsed) {
|
||||
return std::unexpected{ReflectError{
|
||||
"", "invalid duration '" + j.as_string() + "'"}};
|
||||
}
|
||||
return std::chrono::duration_cast<T>(*parsed);
|
||||
} else if constexpr (Void::Meta::is_time_point_v<T>) {
|
||||
if (!j.is_string()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected time_point string"}};
|
||||
}
|
||||
auto parsed = Void::Time::parse_duration(j.as_string());
|
||||
if (!parsed) {
|
||||
return std::unexpected{ReflectError{
|
||||
"", "invalid time_point '" + j.as_string() + "'"}};
|
||||
}
|
||||
return T{std::chrono::duration_cast<typename T::duration>(
|
||||
*parsed)};
|
||||
} else if constexpr (Void::Meta::is_std_array_v<T>) {
|
||||
using U = typename T::value_type;
|
||||
if (!j.is_array()) {
|
||||
return std::unexpected{ReflectError{"", "expected array"}};
|
||||
}
|
||||
constexpr std::size_t N = std::tuple_size_v<T>;
|
||||
if (j.as_array().size() != N) {
|
||||
return std::unexpected{ReflectError{
|
||||
"", "expected array of length " + std::to_string(N)}};
|
||||
}
|
||||
T out{};
|
||||
std::size_t index = 0;
|
||||
for (const auto& e : j.as_array()) {
|
||||
auto inner = Json::from_json<U>(e);
|
||||
if (!inner) {
|
||||
return std::unexpected{
|
||||
nest("[" + std::to_string(index) + "]",
|
||||
std::move(inner).error())};
|
||||
}
|
||||
out[index] = std::move(*inner);
|
||||
++index;
|
||||
}
|
||||
return out;
|
||||
} else if constexpr (Void::Meta::is_map_v<T>) {
|
||||
using K = typename T::key_type;
|
||||
using MV = typename T::mapped_type;
|
||||
if (!j.is_array()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected array of key/value pairs"}};
|
||||
}
|
||||
T out;
|
||||
std::size_t index = 0;
|
||||
for (const auto& e : j.as_array()) {
|
||||
const auto where = "[" + std::to_string(index) + "]";
|
||||
const Value* kf = e.is_object() ? e.find("key") : nullptr;
|
||||
const Value* vf = e.is_object() ? e.find("value") : nullptr;
|
||||
if (!kf || !vf) {
|
||||
return std::unexpected{nest(
|
||||
where,
|
||||
ReflectError{"", "expected {key, value} object"})};
|
||||
}
|
||||
auto key = Json::from_json<K>(*kf);
|
||||
if (!key) {
|
||||
return std::unexpected{
|
||||
nest(where, std::move(key).error())};
|
||||
}
|
||||
auto val = Json::from_json<MV>(*vf);
|
||||
if (!val) {
|
||||
return std::unexpected{
|
||||
nest(where, std::move(val).error())};
|
||||
}
|
||||
out.emplace(std::move(*key), std::move(*val));
|
||||
++index;
|
||||
}
|
||||
return out;
|
||||
} else if constexpr (Void::Meta::is_variant_v<T>) {
|
||||
if (!j.is_object()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected tagged variant object"}};
|
||||
}
|
||||
const Value* tf = j.find("type");
|
||||
const Value* vf = j.find("value");
|
||||
if (!tf || !tf->is_string()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "variant missing 'type' tag"}};
|
||||
}
|
||||
if (!vf) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "variant missing 'value'"}};
|
||||
}
|
||||
const std::string tag = tf->as_string();
|
||||
std::optional<T> result;
|
||||
std::optional<ReflectError> failure;
|
||||
[&]<std::size_t... Is>(std::index_sequence<Is...>) {
|
||||
(
|
||||
[&] {
|
||||
if (result || failure) {
|
||||
return;
|
||||
}
|
||||
using Alt = std::variant_alternative_t<Is, T>;
|
||||
if (Void::Meta::type_name<Alt>() == tag) {
|
||||
auto inner = Json::from_json<Alt>(*vf);
|
||||
if (!inner) {
|
||||
failure = std::move(inner).error();
|
||||
} else {
|
||||
result = T{std::in_place_index<Is>,
|
||||
std::move(*inner)};
|
||||
}
|
||||
}
|
||||
}(),
|
||||
...);
|
||||
}(std::make_index_sequence<std::variant_size_v<T>>{});
|
||||
if (failure) {
|
||||
return std::unexpected{std::move(*failure)};
|
||||
}
|
||||
if (!result) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "unknown variant type '" + tag + "'"}};
|
||||
}
|
||||
return std::move(*result);
|
||||
} else {
|
||||
static_assert(ReflectableAggregate<T>,
|
||||
"type is not deserializable via Json reflection");
|
||||
#ifdef VOID_HAS_JSON_REFLECTION
|
||||
if (!j.is_object()) {
|
||||
return std::unexpected{ReflectError{"", "expected object"}};
|
||||
}
|
||||
T out{};
|
||||
static constexpr auto members = std::define_static_array(
|
||||
std::meta::nonstatic_data_members_of(
|
||||
^^T, std::meta::access_context::current()));
|
||||
std::optional<ReflectError> failure;
|
||||
template for (constexpr auto m : members) {
|
||||
if (!failure) {
|
||||
constexpr auto name = std::meta::identifier_of(m);
|
||||
using MT = [:std::meta::type_of(m):];
|
||||
if (const Value* field = j.find(name)) {
|
||||
auto inner = Json::from_json<MT>(*field);
|
||||
if (!inner) {
|
||||
failure = nest(name, std::move(inner).error());
|
||||
}
|
||||
else {
|
||||
out.[:m:] = std::move(*inner);
|
||||
}
|
||||
}
|
||||
// absent field: keep the default-initialized value
|
||||
}
|
||||
}
|
||||
if (failure) {
|
||||
return std::unexpected{std::move(*failure)};
|
||||
}
|
||||
return out;
|
||||
if (!j.is_object()) {
|
||||
return std::unexpected{ReflectError{"", "expected object"}};
|
||||
}
|
||||
T out{};
|
||||
std::optional<ReflectError> failure;
|
||||
template for (constexpr auto m : Void::Meta::members_v<T>)
|
||||
{
|
||||
if (!failure) {
|
||||
if constexpr (!Void::Meta::has_annotation<Skip>(m)) {
|
||||
using MT = [:std::meta::type_of(m):];
|
||||
if constexpr (Void::Meta::has_annotation<Flatten>(
|
||||
m)) {
|
||||
// Read the nested object's keys from this
|
||||
// object.
|
||||
auto inner = Json::from_json<MT>(j);
|
||||
if (!inner) {
|
||||
failure = std::move(inner).error();
|
||||
} else {
|
||||
out.[:m:] = std::move(*inner);
|
||||
}
|
||||
} else {
|
||||
constexpr auto rn =
|
||||
Void::Meta::annotation_of<Rename>(m);
|
||||
const std::string key =
|
||||
rn.has_value()
|
||||
? std::string{rn->key.view()}
|
||||
: std::string{
|
||||
std::meta::identifier_of(m)};
|
||||
if (const Value* field = j.find(key)) {
|
||||
auto inner = Json::from_json<MT>(*field);
|
||||
if (!inner) {
|
||||
failure =
|
||||
nest(key, std::move(inner).error());
|
||||
} else {
|
||||
out.[:m:] = std::move(*inner);
|
||||
}
|
||||
} else if constexpr (Void::Meta::has_annotation<
|
||||
Required>(m)) {
|
||||
failure = ReflectError{
|
||||
key, "required field is missing"};
|
||||
}
|
||||
// absent + not required: keep the default value
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failure) {
|
||||
return std::unexpected{std::move(*failure)};
|
||||
}
|
||||
return out;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
} // namespace ReflectDetail
|
||||
}
|
||||
}
|
||||
} // namespace ReflectDetail
|
||||
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] std::expected<T, ReflectError> from_json(const Value& j)
|
||||
{
|
||||
return ReflectDetail::leaf_from_json<T>(j);
|
||||
}
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] std::expected<T, ReflectError> from_json(const Value& j)
|
||||
{
|
||||
return ReflectDetail::leaf_from_json<T>(j);
|
||||
}
|
||||
|
||||
// ── versioned envelope + migrations ───────────────────────────────────────────
|
||||
// ── versioned envelope + migrations
|
||||
// ───────────────────────────────────────────
|
||||
|
||||
// Specialize to bump a state type's schema version:
|
||||
// template <> struct Void::Json::StateTraits<MyState> {
|
||||
// static constexpr std::uint32_t version = 3;
|
||||
// };
|
||||
template <typename T>
|
||||
struct StateTraits {
|
||||
static constexpr std::uint32_t version = 1;
|
||||
};
|
||||
// Specialize to bump a state type's schema version:
|
||||
// template <> struct Void::Json::StateTraits<MyState> {
|
||||
// static constexpr std::uint32_t version = 3;
|
||||
// };
|
||||
template <typename T> struct StateTraits {
|
||||
static constexpr std::uint32_t version = 1;
|
||||
};
|
||||
|
||||
// Ordered chain of per-version JSON transforms. Each step upgrades the bare
|
||||
// "data" payload from `from_version` to `from_version + 1`.
|
||||
class MigrationChain
|
||||
{
|
||||
public:
|
||||
using Step = std::function<Value(Value)>;
|
||||
// Ordered chain of per-version JSON transforms. Each step upgrades the bare
|
||||
// "data" payload from `from_version` to `from_version + 1`.
|
||||
class MigrationChain
|
||||
{
|
||||
public:
|
||||
|
||||
MigrationChain& add(std::uint32_t from_version, Step step)
|
||||
{
|
||||
steps_.emplace(from_version, std::move(step));
|
||||
return *this;
|
||||
}
|
||||
using State = std::function<Value(Value)>;
|
||||
|
||||
[[nodiscard]] std::expected<Value, ReflectError>
|
||||
migrate(Value data, std::uint32_t from, std::uint32_t to) const
|
||||
{
|
||||
while (from < to) {
|
||||
auto it = steps_.find(from);
|
||||
if (it == steps_.end()) {
|
||||
return std::unexpected{ReflectError{
|
||||
"__version", "no migration step from version " +
|
||||
std::to_string(from)}};
|
||||
}
|
||||
data = it->second(std::move(data));
|
||||
++from;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
MigrationChain& add(std::uint32_t from_version, State step)
|
||||
{
|
||||
steps_.emplace(from_version, std::move(step));
|
||||
return *this;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool empty() const noexcept { return steps_.empty(); }
|
||||
[[nodiscard]] std::expected<Value, ReflectError>
|
||||
migrate(Value data, std::uint32_t from, std::uint32_t to) const
|
||||
{
|
||||
while (from < to) {
|
||||
auto it = steps_.find(from);
|
||||
if (it == steps_.end()) {
|
||||
return std::unexpected{ReflectError{
|
||||
"__version", "no migration step from version " +
|
||||
std::to_string(from)}};
|
||||
}
|
||||
data = it->second(std::move(data));
|
||||
++from;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
private:
|
||||
std::map<std::uint32_t, Step> steps_;
|
||||
};
|
||||
[[nodiscard]] bool empty() const noexcept { return steps_.empty(); }
|
||||
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] Value to_versioned_json(const T& v)
|
||||
{
|
||||
auto envelope = object();
|
||||
envelope.as_object().emplace_back(
|
||||
"__version", Value{static_cast<double>(StateTraits<T>::version)});
|
||||
envelope.as_object().emplace_back("data", to_json(v));
|
||||
return envelope;
|
||||
}
|
||||
private:
|
||||
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] std::expected<T, ReflectError>
|
||||
from_versioned_json(const Value& envelope,
|
||||
const MigrationChain& migrations = {})
|
||||
{
|
||||
if (!envelope.is_object()) {
|
||||
return std::unexpected{ReflectError{"", "expected envelope object"}};
|
||||
}
|
||||
const Value* version = envelope.find("__version");
|
||||
const Value* data = envelope.find("data");
|
||||
if (!version || !version->is_number() || !data) {
|
||||
return std::unexpected{
|
||||
ReflectError{"__version", "malformed versioned envelope"}};
|
||||
}
|
||||
const auto from = static_cast<std::uint32_t>(version->as_number());
|
||||
constexpr auto to = StateTraits<T>::version;
|
||||
if (from > to) {
|
||||
return std::unexpected{ReflectError{
|
||||
"__version", "stored version " + std::to_string(from) +
|
||||
" is newer than supported version " +
|
||||
std::to_string(to)}};
|
||||
}
|
||||
if (from == to) {
|
||||
return from_json<T>(*data);
|
||||
}
|
||||
auto migrated = migrations.migrate(*data, from, to);
|
||||
if (!migrated) {
|
||||
return std::unexpected{std::move(migrated).error()};
|
||||
}
|
||||
return from_json<T>(*migrated);
|
||||
}
|
||||
std::map<std::uint32_t, State> steps_;
|
||||
};
|
||||
|
||||
template <Reflectable T> [[nodiscard]] Value to_versioned_json(const T& v)
|
||||
{
|
||||
auto envelope = object();
|
||||
envelope.as_object().emplace_back(
|
||||
"__version", Value{static_cast<double>(StateTraits<T>::version)});
|
||||
envelope.as_object().emplace_back("data", to_json(v));
|
||||
return envelope;
|
||||
}
|
||||
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] std::expected<T, ReflectError>
|
||||
from_versioned_json(const Value& envelope,
|
||||
const MigrationChain& migrations = {})
|
||||
{
|
||||
if (!envelope.is_object()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected envelope object"}};
|
||||
}
|
||||
const Value* version = envelope.find("__version");
|
||||
const Value* data = envelope.find("data");
|
||||
if (!version || !version->is_number() || !data) {
|
||||
return std::unexpected{
|
||||
ReflectError{"__version", "malformed versioned envelope"}};
|
||||
}
|
||||
const auto from = static_cast<std::uint32_t>(version->as_number());
|
||||
constexpr auto to = StateTraits<T>::version;
|
||||
if (from > to) {
|
||||
return std::unexpected{ReflectError{
|
||||
"__version", "stored version " + std::to_string(from) +
|
||||
" is newer than supported version " +
|
||||
std::to_string(to)}};
|
||||
}
|
||||
if (from == to) {
|
||||
return from_json<T>(*data);
|
||||
}
|
||||
auto migrated = migrations.migrate(*data, from, to);
|
||||
if (!migrated) {
|
||||
return std::unexpected{std::move(migrated).error()};
|
||||
}
|
||||
return from_json<T>(*migrated);
|
||||
}
|
||||
|
||||
} // namespace Void::Json
|
||||
@@ -3,7 +3,7 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/MpscQueue.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
#include <Void/Fsm/StateKey.hpp>
|
||||
|
||||
#include <any>
|
||||
#include <atomic>
|
||||
|
||||
@@ -2,29 +2,21 @@
|
||||
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
/// A declarable transition edge (from a reactive state's table).
|
||||
struct EdgeInfo {
|
||||
std::string event; // event type name, or "(timeout)"
|
||||
std::string target; // target state, "(success)"/"(fail)"
|
||||
bool guarded{false};
|
||||
};
|
||||
|
||||
/// A registered state plus the edges that are statically knowable
|
||||
/// (reactive states only; imperative run()-chosen edges are not).
|
||||
/// A registered state. Behaviour (and therefore transitions) is chosen
|
||||
/// imperatively inside each state's entry, so edges are not statically
|
||||
/// knowable — the description is node-level.
|
||||
struct StateInfo {
|
||||
std::string name;
|
||||
bool reactive{false};
|
||||
bool initial{false};
|
||||
std::vector<EdgeInfo> edges;
|
||||
};
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
/// Render a state description as a Mermaid `stateDiagram-v2` string.
|
||||
/// Render a state description as a Mermaid `stateDiagram-v2` string:
|
||||
/// the initial marker plus one node per registered state.
|
||||
[[nodiscard]] inline std::string
|
||||
to_mermaid(std::span<const StateInfo> states)
|
||||
{
|
||||
@@ -35,13 +27,7 @@ namespace Void::Fsm
|
||||
}
|
||||
}
|
||||
for (const auto& s : states) {
|
||||
for (const auto& e : s.edges) {
|
||||
out += " " + s.name + " --> " + e.target + " : " + e.event;
|
||||
if (e.guarded) {
|
||||
out += " [guard]";
|
||||
}
|
||||
out += "\n";
|
||||
}
|
||||
out += " " + s.name + "\n";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -1,271 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Fsm/Detail/Result.hpp>
|
||||
#include <Void/Fsm/Detail/TypeName.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
|
||||
#include <any>
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <typeinfo>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
// The declarative transition DSL for reactive states, lifted out of the
|
||||
// Machine template so the core stays small. Every type is parameterised by the
|
||||
// owning machine's `Derived` (guards/actions take `Derived&`); the machine's
|
||||
// typed Success/Failure (nested types, default void) are reflected from
|
||||
// `Derived` for finish()/fail(). Machine::Reactive aliases these and the engine
|
||||
// drives them; see include/Void/Fsm/Machine.hpp.
|
||||
|
||||
namespace Void::Fsm::Detail
|
||||
{
|
||||
namespace Coro = Void::Coro;
|
||||
|
||||
/// One declared transition: event type, optional guard/action, the Step to
|
||||
/// take, plus names for introspection. An `internal` entry runs its action
|
||||
/// and stays in the state (no exit/enter/transition).
|
||||
template <typename Derived> struct EventEntry {
|
||||
const std::type_info* type{nullptr};
|
||||
std::function<bool(Derived&, const std::any&)> guard;
|
||||
std::function<Coro::Task<void>(Derived&, const std::any&)> action;
|
||||
Step step;
|
||||
bool internal{false};
|
||||
std::string event_name; // for introspection
|
||||
std::string target_name; // for introspection
|
||||
};
|
||||
|
||||
/// A reactive state's full transition table (events + an optional timeout,
|
||||
/// deferred event types, and entry/exit actions).
|
||||
template <typename Derived> struct TransitionTable {
|
||||
std::vector<EventEntry<Derived>> events;
|
||||
bool has_timeout{false};
|
||||
std::chrono::steady_clock::duration timeout_after{};
|
||||
Step timeout_step;
|
||||
std::string timeout_target_name;
|
||||
// Event types deferred while in this state (held, re-posted on the
|
||||
// next transition) instead of dropped.
|
||||
std::vector<const std::type_info*> deferred;
|
||||
// Entry/exit actions (run by the reactive loop around the state).
|
||||
std::function<Coro::Task<void>(Derived&)> enter_action;
|
||||
std::function<Coro::Task<void>(Derived&)> exit_action;
|
||||
};
|
||||
|
||||
/// Fluent builder for one event row: `on.event<E>().guard(..).action(..)
|
||||
/// .to<S>()` (or `.finish(v)` / `.fail(v)`).
|
||||
template <typename Derived, typename E> class EventClause
|
||||
{
|
||||
public:
|
||||
|
||||
explicit EventClause(TransitionTable<Derived>& table)
|
||||
: m_table(&table)
|
||||
{
|
||||
}
|
||||
|
||||
EventClause& guard(std::function<bool(Derived&, const E&)> g)
|
||||
{
|
||||
m_guard = std::move(g);
|
||||
return *this;
|
||||
}
|
||||
|
||||
EventClause&
|
||||
action(std::function<Coro::Task<void>(Derived&, const E&)> a)
|
||||
{
|
||||
m_action = std::move(a);
|
||||
return *this;
|
||||
}
|
||||
|
||||
EventClause& action(std::function<void(Derived&, const E&)> a)
|
||||
{
|
||||
m_action = [a = std::move(a)](Derived& d,
|
||||
const E& e) -> Coro::Task<void> {
|
||||
a(d, e);
|
||||
co_return;
|
||||
};
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename S> void to()
|
||||
{
|
||||
if constexpr (requires { typename Derived::States; }) {
|
||||
static_assert(Derived::States::template contains<S>(),
|
||||
"to<S>: S is not in this machine's "
|
||||
"States<...> list");
|
||||
}
|
||||
commit(Step::transition(typeid(S)), type_name<S>());
|
||||
}
|
||||
|
||||
void finish()
|
||||
requires std::is_void_v<SuccessOf<Derived>>
|
||||
{
|
||||
commit(Step::success(std::any{}), "(success)");
|
||||
}
|
||||
template <typename V>
|
||||
void finish(V&& value)
|
||||
requires(!std::is_void_v<SuccessOf<Derived>>)
|
||||
{
|
||||
commit(Step::success(std::any{
|
||||
SuccessOf<Derived>(std::forward<V>(value))}),
|
||||
"(success)");
|
||||
}
|
||||
|
||||
void fail()
|
||||
requires std::is_void_v<FailureOf<Derived>>
|
||||
{
|
||||
commit(Step::failure(std::any{}), "(fail)");
|
||||
}
|
||||
template <typename V>
|
||||
void fail(V&& value)
|
||||
requires(!std::is_void_v<FailureOf<Derived>>)
|
||||
{
|
||||
commit(Step::failure(std::any{
|
||||
FailureOf<Derived>{std::forward<V>(value)}}),
|
||||
"(fail)");
|
||||
}
|
||||
|
||||
/// Internal transition: run `fn` on the event but stay in the
|
||||
/// state (no exit/enter, no transition).
|
||||
void internal(std::function<void(Derived&, const E&)> fn)
|
||||
{
|
||||
action(std::move(fn));
|
||||
commit(Step::success(std::any{}), "(internal)", true);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
void commit(Step step, std::string target, bool is_internal = false)
|
||||
{
|
||||
EventEntry<Derived> entry;
|
||||
entry.type = &typeid(E);
|
||||
if (m_guard) {
|
||||
entry.guard = [g = std::move(m_guard)](Derived& d,
|
||||
const std::any& a) {
|
||||
return g(d, std::any_cast<const E&>(a));
|
||||
};
|
||||
}
|
||||
if (m_action) {
|
||||
entry.action =
|
||||
[a = std::move(m_action)](
|
||||
Derived& d,
|
||||
const std::any& any) -> Coro::Task<void> {
|
||||
co_await a(d, std::any_cast<const E&>(any));
|
||||
};
|
||||
}
|
||||
entry.step = std::move(step);
|
||||
entry.internal = is_internal;
|
||||
entry.event_name = type_name<E>();
|
||||
entry.target_name = std::move(target);
|
||||
m_table->events.push_back(std::move(entry));
|
||||
}
|
||||
|
||||
TransitionTable<Derived>* m_table;
|
||||
std::function<bool(Derived&, const E&)> m_guard;
|
||||
std::function<Coro::Task<void>(Derived&, const E&)> m_action;
|
||||
};
|
||||
|
||||
/// Fluent builder for the timeout row: `on.after(d).to<S>()` / `.fail(v)`.
|
||||
template <typename Derived> class AfterClause
|
||||
{
|
||||
public:
|
||||
|
||||
AfterClause(TransitionTable<Derived>& table,
|
||||
std::chrono::steady_clock::duration after)
|
||||
: m_table(&table), m_after(after)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename S> void to()
|
||||
{
|
||||
if constexpr (requires { typename Derived::States; }) {
|
||||
static_assert(Derived::States::template contains<S>(),
|
||||
"after().to<S>: S not in States<...>");
|
||||
}
|
||||
m_table->has_timeout = true;
|
||||
m_table->timeout_after = m_after;
|
||||
m_table->timeout_step = Step::transition(typeid(S));
|
||||
m_table->timeout_target_name = type_name<S>();
|
||||
}
|
||||
|
||||
void fail()
|
||||
requires std::is_void_v<FailureOf<Derived>>
|
||||
{
|
||||
m_table->has_timeout = true;
|
||||
m_table->timeout_after = m_after;
|
||||
m_table->timeout_step = Step::failure(std::any{});
|
||||
m_table->timeout_target_name = "(fail)";
|
||||
}
|
||||
template <typename V>
|
||||
void fail(V&& value)
|
||||
requires(!std::is_void_v<FailureOf<Derived>>)
|
||||
{
|
||||
m_table->has_timeout = true;
|
||||
m_table->timeout_after = m_after;
|
||||
m_table->timeout_step = Step::failure(
|
||||
std::any{FailureOf<Derived>{std::forward<V>(value)}});
|
||||
m_table->timeout_target_name = "(fail)";
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
TransitionTable<Derived>* m_table;
|
||||
std::chrono::steady_clock::duration m_after;
|
||||
};
|
||||
|
||||
/// Entry point handed to `transitions(TransitionBuilder& on)`.
|
||||
template <typename Derived> class TransitionBuilder
|
||||
{
|
||||
public:
|
||||
|
||||
explicit TransitionBuilder(TransitionTable<Derived>& table)
|
||||
: m_table(&table)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename E> [[nodiscard]] EventClause<Derived, E> event()
|
||||
{
|
||||
return EventClause<Derived, E>{*m_table};
|
||||
}
|
||||
|
||||
template <typename Rep, typename Period>
|
||||
[[nodiscard]] AfterClause<Derived>
|
||||
after(std::chrono::duration<Rep, Period> d)
|
||||
{
|
||||
return AfterClause<Derived>{
|
||||
*m_table, std::chrono::duration_cast<
|
||||
std::chrono::steady_clock::duration>(d)};
|
||||
}
|
||||
|
||||
/// Defer event `E` while in this state: hold it (don't drop) and
|
||||
/// re-post it after the next transition (UML deferred events).
|
||||
template <typename E> void defer()
|
||||
{
|
||||
m_table->deferred.push_back(&typeid(E));
|
||||
}
|
||||
|
||||
/// Entry action — run when the state is entered (before it waits).
|
||||
void enter(std::function<void(Derived&)> fn)
|
||||
{
|
||||
m_table->enter_action =
|
||||
[fn = std::move(fn)](Derived& d) -> Coro::Task<void> {
|
||||
fn(d);
|
||||
co_return;
|
||||
};
|
||||
}
|
||||
/// Exit action — run when the state is left (on any transition).
|
||||
void exit(std::function<void(Derived&)> fn)
|
||||
{
|
||||
m_table->exit_action =
|
||||
[fn = std::move(fn)](Derived& d) -> Coro::Task<void> {
|
||||
fn(d);
|
||||
co_return;
|
||||
};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
TransitionTable<Derived>* m_table;
|
||||
};
|
||||
} // namespace Void::Fsm::Detail
|
||||
+109
-210
@@ -1,10 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
#include <Void/Fsm/Detail/Reactive.hpp>
|
||||
#include <Void/Fsm/Detail/Result.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
#include <Void/Fsm/Detail/StateList.hpp>
|
||||
#include <Void/Fsm/Machine.hpp>
|
||||
#include <Void/Fsm/StateKey.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <any>
|
||||
@@ -23,122 +25,137 @@
|
||||
// Signature-inferred state roles. There is ONE state base (`State`); the engine
|
||||
// discovers what each state does purely from its member signatures via P2996 —
|
||||
// no `override`, no framework-mandated names:
|
||||
// - entry : a member returning Step / Coro::Task<Step>, no params
|
||||
// - entry : a member returning State / Coro::Task<StateKey>>, no
|
||||
// params
|
||||
// - startup-entry: the same taking the sub-machine's startup-data argument
|
||||
// - reactive : a member taking TransitionBuilder<D>&
|
||||
// - result handlers (continuation): members taking `ChildSuccess auto` /
|
||||
// `ChildFailure auto` (the boxes below)
|
||||
// - result handlers (continuation): members taking `ChildSuccess` /
|
||||
// `ChildFailure` (the type-erased result structs below)
|
||||
// All discovery is invocability-based (types known at the generation site), so
|
||||
// no parameter-type reflection (P3096) is required.
|
||||
// no parameter-type reflection (P3096) is required. Event handling is
|
||||
// imperative inside an entry (co_await await_event<E>()), so there is no
|
||||
// reactive role.
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
// Defined in Machine.hpp; forward-declared so InitialStateOf can pattern
|
||||
// match the state list.
|
||||
template <typename...> struct States;
|
||||
|
||||
/// The success value of a launched sub-machine, handed to a continuation
|
||||
/// handler written `ok(ChildSuccess auto s)` — `s.value` is the sub's
|
||||
/// typed Success (absent for a void-result sub).
|
||||
template <typename T> struct ChildSuccessBox {
|
||||
T value;
|
||||
};
|
||||
template <> struct ChildSuccessBox<void> {
|
||||
/// handler written `ok(ChildSuccess s)`. The sub's typed Success is read
|
||||
/// with `s.as<T>()` (the value is empty for a void-result sub).
|
||||
struct ChildSuccess {
|
||||
std::any value;
|
||||
template <typename T> [[nodiscard]] T as() const
|
||||
{
|
||||
return std::any_cast<T>(value);
|
||||
}
|
||||
};
|
||||
|
||||
/// The failure value of a launched sub-machine (`no(ChildFailure auto f)`;
|
||||
/// `f.value` is the sub's typed Failure, absent for void).
|
||||
template <typename T> struct ChildFailureBox {
|
||||
T value;
|
||||
};
|
||||
template <> struct ChildFailureBox<void> {
|
||||
/// The failure value of a launched sub-machine, handed to `no(ChildFailure
|
||||
/// f)`. The sub's typed Failure is read with `f.as<T>()` (empty for void).
|
||||
struct ChildFailure {
|
||||
std::any value;
|
||||
template <typename T> [[nodiscard]] T as() const
|
||||
{
|
||||
return std::any_cast<T>(value);
|
||||
}
|
||||
};
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
template <class> inline constexpr bool is_csucc = false;
|
||||
template <class T>
|
||||
inline constexpr bool is_csucc<ChildSuccessBox<T>> = true;
|
||||
template <class> inline constexpr bool is_cfail = false;
|
||||
template <class T>
|
||||
inline constexpr bool is_cfail<ChildFailureBox<T>> = true;
|
||||
} // namespace Detail
|
||||
|
||||
template <class X>
|
||||
concept ChildSuccess = Detail::is_csucc<std::remove_cvref_t<X>>;
|
||||
template <class X>
|
||||
concept ChildFailure = Detail::is_cfail<std::remove_cvref_t<X>>;
|
||||
/// Marker to designate a state's entry when several members match the entry
|
||||
/// signature: annotate the chosen one `[[= Void::Fsm::entry]]`. Unmarked,
|
||||
/// the first-declared matching member is used.
|
||||
inline constexpr struct EntryTag {
|
||||
} entry;
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
namespace Coro = Void::Coro;
|
||||
namespace meta = std::meta;
|
||||
|
||||
/// The owning machine type of a state S (via State::self()).
|
||||
template <typename S>
|
||||
using MachineOf =
|
||||
std::remove_cvref_t<decltype(std::declval<S&>().self())>;
|
||||
// InitialStateOf / FirstStateOf live in Detail/StateList.hpp (they
|
||||
// reflect the nested `struct States { … }`).
|
||||
|
||||
template <typename> struct first_state_helper;
|
||||
template <typename F, typename... R>
|
||||
struct first_state_helper<States<F, R...>> {
|
||||
using type = F;
|
||||
};
|
||||
|
||||
/// A machine's initial state type: its nested `Initial` if declared,
|
||||
/// else the first entry of `States<...>`.
|
||||
template <typename M> consteval auto initial_state_probe()
|
||||
/// True if member `m` carries the `[[= Void::Fsm::entry]]` annotation.
|
||||
/// Routed through the shared Void::Meta annotation helper.
|
||||
consteval bool is_entry_marked(meta::info m)
|
||||
{
|
||||
if constexpr (requires { typename M::Initial; }) {
|
||||
return std::type_identity<typename M::Initial>{};
|
||||
} else {
|
||||
return std::type_identity<
|
||||
typename first_state_helper<typename M::States>::type>{};
|
||||
}
|
||||
return Void::Meta::has_annotation<EntryTag>(m);
|
||||
}
|
||||
template <typename M>
|
||||
using InitialStateOf =
|
||||
typename decltype(initial_state_probe<M>())::type;
|
||||
|
||||
/// Wrap a ready Step in a Task. (The reflection selectors below must
|
||||
/// Wrap a ready State in a Task. (The reflection selectors below must
|
||||
/// NOT be coroutines — `template for` + member splicing fails inside a
|
||||
/// coroutine body in this build — so they return a Task instead.)
|
||||
inline Coro::Task<Step> ready_task(Step s) { co_return s; }
|
||||
inline Coro::Task<StateKey> ready_task(StateKey s) { co_return s; }
|
||||
|
||||
// ── entry (0-arg member returning Step / Task<Step>) ──────────────
|
||||
template <typename S> Coro::Task<Step> invoke_entry(S& s)
|
||||
// ── entry (0-arg member returning StateKey / Task<StateKey>) ──────
|
||||
// When several members match, one annotated `[[= Fsm::entry]]` wins;
|
||||
// otherwise the first-declared match is used.
|
||||
template <typename S> Coro::Task<StateKey> invoke_entry(S& s)
|
||||
{
|
||||
static constexpr auto members = std::define_static_array(
|
||||
meta::members_of(^^S, meta::access_context::current()));
|
||||
// Pass 1: a member annotated [[= Fsm::entry]] takes precedence.
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (requires(S& x) { x.[:m:](); }) {
|
||||
if constexpr (is_entry_marked(m) &&
|
||||
requires(S& x) { x.[:m:](); }) {
|
||||
using R = decltype(std::declval<S&>().[:m:]());
|
||||
if constexpr (std::is_same_v<R, Step>) {
|
||||
if constexpr (std::is_same_v<R, StateKey>) {
|
||||
return ready_task(s.[:m:]());
|
||||
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
|
||||
} else if constexpr (std::is_same_v<R,
|
||||
Coro::Task<StateKey>>) {
|
||||
return s.[:m:]();
|
||||
}
|
||||
}
|
||||
}
|
||||
return ready_task(Step::fault(FsmError{
|
||||
"state has no entry (a no-arg method returning Step)"}));
|
||||
// Pass 2: the first-declared matching member.
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (requires(S& x) { x.[:m:](); }) {
|
||||
using R = decltype(std::declval<S&>().[:m:]());
|
||||
if constexpr (std::is_same_v<R, StateKey>) {
|
||||
return ready_task(s.[:m:]());
|
||||
} else if constexpr (std::is_same_v<R,
|
||||
Coro::Task<StateKey>>) {
|
||||
return s.[:m:]();
|
||||
}
|
||||
}
|
||||
}
|
||||
return ready_task(StateKey::fault(FsmError{
|
||||
"state has no entry (a no-arg method returning StateKey)"}));
|
||||
}
|
||||
|
||||
// ── startup-entry (member taking the startup-data argument[s]) ────
|
||||
// Same precedence as invoke_entry: an annotated `[[= Fsm::entry]]`
|
||||
// data-taking member wins, else the first-declared one; if none takes
|
||||
// the data, fall back to the plain (nullary) entry.
|
||||
template <typename S, typename... DataT>
|
||||
Coro::Task<Step> invoke_startup(S& s, DataT... data)
|
||||
Coro::Task<StateKey> invoke_startup(S& s, DataT... data)
|
||||
{
|
||||
static constexpr auto members = std::define_static_array(
|
||||
meta::members_of(^^S, meta::access_context::current()));
|
||||
// Pass 1: an annotated data-taking member takes precedence.
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (is_entry_marked(m) &&
|
||||
requires(S& x, DataT... d) { x.[:m:](d...); }) {
|
||||
using R = decltype(std::declval<S&>().[:m:](
|
||||
std::declval<DataT>()...));
|
||||
if constexpr (std::is_same_v<R, StateKey>) {
|
||||
return ready_task(s.[:m:](std::move(data)...));
|
||||
} else if constexpr (std::is_same_v<R,
|
||||
Coro::Task<StateKey>>) {
|
||||
return s.[:m:](std::move(data)...);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pass 2: the first-declared data-taking member.
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (requires(S& x, DataT... d) { x.[:m:](d...); }) {
|
||||
using R = decltype(std::declval<S&>().[:m:](
|
||||
std::declval<DataT>()...));
|
||||
if constexpr (std::is_same_v<R, Step>) {
|
||||
if constexpr (std::is_same_v<R, StateKey>) {
|
||||
return ready_task(s.[:m:](std::move(data)...));
|
||||
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
|
||||
} else if constexpr (std::is_same_v<R,
|
||||
Coro::Task<StateKey>>) {
|
||||
return s.[:m:](std::move(data)...);
|
||||
}
|
||||
}
|
||||
@@ -149,7 +166,7 @@ namespace Void::Fsm
|
||||
|
||||
// ── continuation handler (member taking a ChildSuccess/Failure box)
|
||||
template <typename S, typename Box>
|
||||
Coro::Task<Step> invoke_handler(S& s, Box box)
|
||||
Coro::Task<StateKey> invoke_handler(S& s, Box box)
|
||||
{
|
||||
static constexpr auto members = std::define_static_array(
|
||||
meta::members_of(^^S, meta::access_context::current()));
|
||||
@@ -158,161 +175,43 @@ namespace Void::Fsm
|
||||
if constexpr (requires(S& x, Box b) { x.[:m:](b); }) {
|
||||
using R =
|
||||
decltype(std::declval<S&>().[:m:](std::declval<Box>()));
|
||||
if constexpr (std::is_same_v<R, Step>) {
|
||||
if constexpr (std::is_same_v<R, StateKey>) {
|
||||
return ready_task(s.[:m:](std::move(box)));
|
||||
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
|
||||
} else if constexpr (std::is_same_v<R,
|
||||
Coro::Task<StateKey>>) {
|
||||
return s.[:m:](std::move(box));
|
||||
}
|
||||
}
|
||||
}
|
||||
return ready_task(Step::fault(
|
||||
return ready_task(StateKey::fault(
|
||||
FsmError{"continuation has no handler for this sub-machine "
|
||||
"result (ChildSuccess auto / ChildFailure auto)"}));
|
||||
"result (ChildSuccess / ChildFailure)"}));
|
||||
}
|
||||
|
||||
/// Dispatch a sub-machine's LaunchResult into the Next state's
|
||||
/// signature-matched handler. Knows Next and Sub (so the box types are
|
||||
/// concrete); built at the startMachine call site.
|
||||
/// signature-matched handler (`ok(ChildSuccess)` / `no(ChildFailure)`).
|
||||
/// The typed payload rides type-erased in the result struct's `value`;
|
||||
/// the handler reads it with `.as<T>()`. (Sub is retained in the
|
||||
/// signature so the call site stays `dispatch_result<Next, Sub>`.)
|
||||
template <typename Next, typename Sub>
|
||||
Coro::Task<Step> dispatch_result(Next& s, LaunchResult lr)
|
||||
Coro::Task<StateKey> dispatch_result(Next& s, LaunchResult lr)
|
||||
{
|
||||
using Succ = SuccessOf<Sub>;
|
||||
using Fail = FailureOf<Sub>;
|
||||
if (lr.kind == LaunchResult::Kind::Failure) {
|
||||
ChildFailureBox<Fail> box;
|
||||
if constexpr (!std::is_void_v<Fail>) {
|
||||
box.value = std::any_cast<Fail>(std::move(lr.failure));
|
||||
}
|
||||
return invoke_handler(s, std::move(box));
|
||||
return invoke_handler(s, ChildFailure{std::move(lr.failure)});
|
||||
}
|
||||
ChildSuccessBox<Succ> box;
|
||||
if constexpr (!std::is_void_v<Succ>) {
|
||||
box.value = std::any_cast<Succ>(std::move(lr.value));
|
||||
}
|
||||
return invoke_handler(s, std::move(box));
|
||||
return invoke_handler(s, ChildSuccess{std::move(lr.value)});
|
||||
}
|
||||
|
||||
// ── reactive (member taking TransitionBuilder<D>&) ────────────────
|
||||
template <typename S> consteval bool has_transitions()
|
||||
{
|
||||
using D = MachineOf<S>;
|
||||
bool found = false;
|
||||
template for (constexpr auto m :
|
||||
std::define_static_array(meta::members_of(
|
||||
^^S, meta::access_context::current())))
|
||||
{
|
||||
if constexpr (requires(S& x, TransitionBuilder<D>& b) {
|
||||
x.[:m:](b);
|
||||
}) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/// Fill `table` from S's transitions-shaped member (if any).
|
||||
template <typename S, typename D>
|
||||
void collect_transitions(S& s, TransitionTable<D>& table)
|
||||
{
|
||||
TransitionBuilder<D> builder{table};
|
||||
static constexpr auto members = std::define_static_array(
|
||||
meta::members_of(^^S, meta::access_context::current()));
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (requires(S& x, TransitionBuilder<D>& b) {
|
||||
x.[:m:](b);
|
||||
}) {
|
||||
s.[:m:](builder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The reactive drive loop (relocated from the old Reactive::run()):
|
||||
/// wait for a declared event or the timeout, check guards in order, run
|
||||
/// the action, transition.
|
||||
template <typename S> Coro::Task<Step> drive_reactive(S& s)
|
||||
{
|
||||
using D = MachineOf<S>;
|
||||
TransitionTable<D> table;
|
||||
collect_transitions(s, table);
|
||||
// Await the declared event types *and* the deferred ones (so a
|
||||
// deferred event wakes us to be held, not dropped).
|
||||
std::vector<const std::type_info*> types;
|
||||
types.reserve(table.events.size() + table.deferred.size());
|
||||
for (const auto& e : table.events) {
|
||||
types.push_back(e.type);
|
||||
}
|
||||
for (const auto* dt : table.deferred) {
|
||||
types.push_back(dt);
|
||||
}
|
||||
D& d = s.self();
|
||||
if (table.enter_action) {
|
||||
co_await table.enter_action(d);
|
||||
}
|
||||
// Events deferred while here, re-posted on exit.
|
||||
std::vector<EventEnvelope> held;
|
||||
auto leave = [&](Step step) -> Coro::Task<Step> {
|
||||
if (table.exit_action) {
|
||||
co_await table.exit_action(d);
|
||||
}
|
||||
for (auto& h : held) {
|
||||
s.machine().repost(std::move(h));
|
||||
}
|
||||
co_return std::move(step);
|
||||
};
|
||||
for (;;) {
|
||||
std::optional<std::chrono::steady_clock::time_point> deadline;
|
||||
if (table.has_timeout) {
|
||||
deadline =
|
||||
std::chrono::steady_clock::now() + table.timeout_after;
|
||||
}
|
||||
auto ev = co_await s.machine().await_any_event(types, deadline);
|
||||
if (!ev) {
|
||||
co_return co_await leave(std::move(table.timeout_step));
|
||||
}
|
||||
bool matched = false;
|
||||
for (auto& e : table.events) {
|
||||
if (*e.type != *ev->type) {
|
||||
continue;
|
||||
}
|
||||
if (e.guard && !e.guard(d, ev->value)) {
|
||||
continue;
|
||||
}
|
||||
if (e.action) {
|
||||
co_await e.action(d, ev->value);
|
||||
}
|
||||
matched = true;
|
||||
if (!e.internal) {
|
||||
co_return co_await leave(std::move(e.step));
|
||||
}
|
||||
break; // internal: handled, stay in the state
|
||||
}
|
||||
if (!matched) {
|
||||
// No entry took it: hold if deferred, else drop.
|
||||
const bool is_deferred = std::any_of(
|
||||
table.deferred.begin(), table.deferred.end(),
|
||||
[&](const std::type_info* t) {
|
||||
return *t == *ev->type;
|
||||
});
|
||||
if (is_deferred) {
|
||||
held.push_back(std::move(*ev));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-state driver thunk built at registration (S is complete):
|
||||
/// reactive states run the table, others run the entry.
|
||||
/// Per-state driver thunk built at registration (S is complete): run
|
||||
/// the state's entry. Event handling, timeouts, guards and deferral are
|
||||
/// all expressed imperatively inside the entry (await_event / await_any
|
||||
/// / await_event_for / delay), so there is no separate reactive driver.
|
||||
template <typename S>
|
||||
[[nodiscard]] std::function<Coro::Task<Step>(StateBase&)> make_driver()
|
||||
[[nodiscard]] std::function<Coro::Task<StateKey>(StateBase&)>
|
||||
make_driver()
|
||||
{
|
||||
return [](StateBase& base) -> Coro::Task<Step> {
|
||||
S& s = static_cast<S&>(base);
|
||||
if constexpr (has_transitions<S>()) {
|
||||
co_return co_await drive_reactive(s);
|
||||
} else {
|
||||
co_return co_await invoke_entry(s);
|
||||
}
|
||||
return [](StateBase& base) -> Coro::Task<StateKey> {
|
||||
co_return co_await invoke_entry(static_cast<S&>(base));
|
||||
};
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
|
||||
#include <concepts>
|
||||
#include <meta>
|
||||
#include <type_traits>
|
||||
|
||||
// State-list reflection helpers. A machine declares its states as a nested
|
||||
// struct of forward declarations:
|
||||
// struct States { struct Idle; struct Run; struct Done; };
|
||||
// defined out-of-line in the .cpp, and the Machine base auto-registers them by
|
||||
// reflecting `members_of(^^States)` — the first nested state is the initial one
|
||||
// unless the machine declares `using Initial = S;`. These helpers replace the
|
||||
// old `Fsm::States<Ss...>` template: the list is now an ordinary struct whose
|
||||
// nested state types are enumerated via P2996 (already a hard dependency of the
|
||||
// module — see Detail/Roles.hpp).
|
||||
|
||||
namespace Void::Fsm::Detail
|
||||
{
|
||||
namespace meta = std::meta;
|
||||
|
||||
/// True if reflection `m` names a nested type that is one of this machine's
|
||||
/// states (a class deriving StateBase) — filters out the
|
||||
/// injected-class-name and any non-state members.
|
||||
template <meta::info M> consteval bool is_state_member()
|
||||
{
|
||||
if constexpr (meta::is_type(M)) {
|
||||
using S = typename[:M:];
|
||||
return std::is_class_v<S> && std::derived_from<S, StateBase>;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reflection of the first state member of `StatesT` (declaration order),
|
||||
/// or
|
||||
/// `^^void` when the list has none.
|
||||
template <typename StatesT> consteval meta::info first_state_member()
|
||||
{
|
||||
template for (constexpr auto m :
|
||||
std::define_static_array(meta::members_of(
|
||||
^^StatesT, meta::access_context::current())))
|
||||
{
|
||||
if constexpr (is_state_member<m>()) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
return ^^void;
|
||||
}
|
||||
|
||||
/// The first declared state type of `StatesT` (void if empty).
|
||||
template <typename StatesT>
|
||||
using FirstStateOf = typename[:first_state_member<StatesT>():];
|
||||
|
||||
/// A machine's initial state type: its nested `Initial` if declared, else
|
||||
/// the first member of its `States` list.
|
||||
template <typename M> consteval auto initial_state_probe()
|
||||
{
|
||||
if constexpr (requires { typename M::Initial; }) {
|
||||
return std::type_identity<typename M::Initial>{};
|
||||
} else {
|
||||
return std::type_identity<FirstStateOf<typename M::States>>{};
|
||||
}
|
||||
}
|
||||
template <typename M>
|
||||
using InitialStateOf = typename decltype(initial_state_probe<M>())::type;
|
||||
|
||||
/// Compile-time membership test: is `S` one of `StatesT`'s state members?
|
||||
/// Drives the next<S>() / startMachine<,Next>() target validation.
|
||||
template <typename StatesT, typename S> consteval bool states_contains()
|
||||
{
|
||||
bool found = false;
|
||||
template for (constexpr auto m :
|
||||
std::define_static_array(meta::members_of(
|
||||
^^StatesT, meta::access_context::current())))
|
||||
{
|
||||
if constexpr (is_state_member<m>()) {
|
||||
if constexpr (std::is_same_v<typename[:m:], S>) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/// Register every state member of `StatesT` on `machine` (declaration order
|
||||
/// = registration order). Instantiated from the derived machine's .cpp
|
||||
/// constructor, where the out-of-line state definitions are complete.
|
||||
template <typename StatesT, typename M>
|
||||
void register_states_from(M& machine)
|
||||
{
|
||||
template for (constexpr auto m :
|
||||
std::define_static_array(meta::members_of(
|
||||
^^StatesT, meta::access_context::current())))
|
||||
{
|
||||
if constexpr (is_state_member<m>()) {
|
||||
machine.template add<typename[:m:]>();
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace Void::Fsm::Detail
|
||||
@@ -2,13 +2,14 @@
|
||||
|
||||
// Umbrella header for the FSM module. The implementation is split for
|
||||
// maintainability:
|
||||
// - Machine.hpp — the Machine<Derived, ResultT> template + States
|
||||
// list, nested State / Reactive bases, lifecycle,
|
||||
// events, nesting, persistence.
|
||||
// - Detail/Reactive.hpp — the declarative transition DSL
|
||||
// (TransitionBuilder / EventClause / AfterClause).
|
||||
// - Machine.hpp — the Machine<Derived> template, the nested State
|
||||
// base, lifecycle, events, nesting, persistence.
|
||||
// - Detail/StateList.hpp — reflection over the nested `struct States { … }`
|
||||
// (auto-registration, initial-state, membership).
|
||||
// - Detail/Roles.hpp — signature-inferred state roles (entry,
|
||||
// startup-entry, continuation handlers).
|
||||
// - Detail/Awaiter.hpp — the unified event awaiter.
|
||||
// - Detail/Introspect.hpp — StateInfo / EdgeInfo + to_mermaid.
|
||||
// - Detail/Introspect.hpp — StateInfo + to_mermaid (node-level diagram).
|
||||
// - Detail/Engine.{hpp,cpp} — the non-template execution context.
|
||||
// Include <Void/Fsm/Fsm.hpp> to get the whole machine API as before.
|
||||
|
||||
|
||||
+112
-151
@@ -6,11 +6,11 @@
|
||||
#include <Void/Fsm/Detail/Awaiter.hpp>
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
#include <Void/Fsm/Detail/Introspect.hpp>
|
||||
#include <Void/Fsm/Detail/Reactive.hpp>
|
||||
#include <Void/Fsm/Detail/Result.hpp>
|
||||
#include <Void/Fsm/Detail/Roles.hpp>
|
||||
#include <Void/Fsm/Detail/StateList.hpp>
|
||||
#include <Void/Fsm/Detail/TypeName.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
#include <Void/Fsm/StateKey.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
|
||||
@@ -43,20 +43,6 @@
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
/// Compile-time list of a machine's states. Declare it in the derived
|
||||
/// machine to auto-register every state and enable compile-time
|
||||
/// validation of next<S>() targets:
|
||||
/// using States = Void::Fsm::States<Idle, Running, Done>;
|
||||
/// The first entry is the initial state unless `using Initial = S;`.
|
||||
template <typename... Ss> struct States {
|
||||
static constexpr std::size_t size = sizeof...(Ss);
|
||||
|
||||
template <typename S> static constexpr bool contains()
|
||||
{
|
||||
return (std::is_same_v<S, Ss> || ...);
|
||||
}
|
||||
};
|
||||
|
||||
/// Options for a Machine (namespace scope to dodge the GCC
|
||||
/// nested-default-arg trap).
|
||||
struct MachineOptions {
|
||||
@@ -76,25 +62,33 @@ namespace Void::Fsm
|
||||
|
||||
// ── Machine<Derived> ──────────────────────────────────────────────────
|
||||
//
|
||||
// Inheritance + coroutine workflow FSM, CRTP for typed access. Derive it,
|
||||
// declare states as nested structs deriving the single `State`, list them
|
||||
// in `using States = Fsm::States<...>`. The engine infers each state's role
|
||||
// from member signatures (entry / reactive table / continuation handlers);
|
||||
// states reach their machine (data + sub-methods) via self(). Result types
|
||||
// are the nested `Success`/`Failure` (default void).
|
||||
// Inheritance + coroutine workflow FSM, CRTP for typed access. Derive it
|
||||
// and declare the states as a nested struct of forward declarations:
|
||||
// struct States { struct FirstState; struct SecondState; … };
|
||||
// defined out-of-line (typically in a .cpp), each deriving the single
|
||||
// `State`. The Machine base auto-registers them by reflecting `States`
|
||||
// (Detail/StateList.hpp) — the first declared state is the initial one
|
||||
// unless `using Initial = S;`. All behaviour lives inside a state: the
|
||||
// engine infers each state's role from its member signatures (entry /
|
||||
// startup-entry / continuation handlers); states reach their machine (data
|
||||
// + sub-methods) via self(). Events are handled imperatively inside an
|
||||
// entry (co_await await_event<E>()) — there is no declarative transition
|
||||
// table. Result types are the nested `Success`/`Failure` (default void).
|
||||
//
|
||||
// // header
|
||||
// class Login : public Void::Fsm::Machine<Login> {
|
||||
// public:
|
||||
// using Success = Token;
|
||||
// int attempts = 0;
|
||||
// struct Check : State { // entry by signature
|
||||
// Coro::Task<Step> run() {
|
||||
// if (++self().attempts > 3) co_return fail();
|
||||
// co_return self().service<IAuth>().ok() ? succeed(Token{})
|
||||
// : next<Check>();
|
||||
// }
|
||||
// };
|
||||
// using States = Void::Fsm::States<Check>;
|
||||
// struct States { struct Check; };
|
||||
// };
|
||||
// // source (namespace scope)
|
||||
// struct Login::States::Check : Login::State { // entry by signature
|
||||
// Coro::Task<StateKey>> run() {
|
||||
// if (++self().attempts > 3) co_return fail();
|
||||
// co_return self().service<IAuth>().ok() ? succeed(Token{})
|
||||
// : next<Check>();
|
||||
// }
|
||||
// };
|
||||
template <typename Derived> class Machine
|
||||
{
|
||||
@@ -135,43 +129,44 @@ namespace Void::Fsm
|
||||
protected:
|
||||
|
||||
/// Transition to another state. Validated at compile
|
||||
/// time when the machine declares `using States`.
|
||||
template <typename S> [[nodiscard]] Step next() const
|
||||
/// time when the machine declares a `States` list.
|
||||
template <typename S> [[nodiscard]] StateKey next() const
|
||||
{
|
||||
if constexpr (requires { typename Derived::States; }) {
|
||||
static_assert(
|
||||
Derived::States::template contains<S>(),
|
||||
"next<S>: S is not in this machine's "
|
||||
"States<...> list");
|
||||
static_assert(Detail::states_contains<
|
||||
typename Derived::States, S>(),
|
||||
"next<S>: S is not in this machine's "
|
||||
"States { … } list");
|
||||
}
|
||||
return Step::transition(typeid(S));
|
||||
return StateKey::transition(typeid(S));
|
||||
}
|
||||
|
||||
/// Transition to a state registered dynamically
|
||||
/// (add<S>()/add_if<S>()), skipping the static check.
|
||||
template <typename S>
|
||||
[[nodiscard]] Step next_dynamic() const
|
||||
[[nodiscard]] StateKey next_dynamic() const
|
||||
{
|
||||
return Step::transition(typeid(S));
|
||||
return StateKey::transition(typeid(S));
|
||||
}
|
||||
|
||||
/// Free jump to any registered state — no declared
|
||||
/// transition required ("each state can be moved to
|
||||
/// another state"). Like next_dynamic, skips the
|
||||
/// States<...> compile-time check; runtime-fails only if S
|
||||
/// States{ … } compile-time check; runtime-fails only if S
|
||||
/// was never registered.
|
||||
template <typename S> [[nodiscard]] Step goto_state() const
|
||||
template <typename S>
|
||||
[[nodiscard]] StateKey goto_state() const
|
||||
{
|
||||
return Step::transition(typeid(S));
|
||||
return StateKey::transition(typeid(S));
|
||||
}
|
||||
|
||||
/// Route to a fallback state if `step` is a failure,
|
||||
/// otherwise pass it through — for error policies:
|
||||
/// co_return next_or<Recovery>(co_await try_work());
|
||||
template <typename S>
|
||||
[[nodiscard]] Step next_or(Step step) const
|
||||
[[nodiscard]] StateKey next_or(StateKey step) const
|
||||
{
|
||||
if (step.kind() == Step::Kind::Fail) {
|
||||
if (step.kind() == StateKey::Kind::Fail) {
|
||||
return next<S>();
|
||||
}
|
||||
return step;
|
||||
@@ -209,32 +204,32 @@ namespace Void::Fsm
|
||||
|
||||
/// Finish with the machine's typed Success result (nested
|
||||
/// `Success`; nullary when it is void).
|
||||
[[nodiscard]] Step succeed() const
|
||||
[[nodiscard]] StateKey succeed() const
|
||||
requires std::is_void_v<Detail::SuccessOf<Derived>>
|
||||
{
|
||||
return Step::success(std::any{});
|
||||
return StateKey::success(std::any{});
|
||||
}
|
||||
template <typename V>
|
||||
[[nodiscard]] Step succeed(V&& value) const
|
||||
[[nodiscard]] StateKey succeed(V&& value) const
|
||||
requires(!std::is_void_v<Detail::SuccessOf<Derived>>)
|
||||
{
|
||||
return Step::success(
|
||||
return StateKey::success(
|
||||
std::any{Detail::SuccessOf<Derived>(
|
||||
std::forward<V>(value))});
|
||||
}
|
||||
|
||||
/// Finish with the machine's typed Failure result (nested
|
||||
/// `Failure`; nullary when it is void).
|
||||
[[nodiscard]] Step fail() const
|
||||
[[nodiscard]] StateKey fail() const
|
||||
requires std::is_void_v<Detail::FailureOf<Derived>>
|
||||
{
|
||||
return Step::failure(std::any{});
|
||||
return StateKey::failure(std::any{});
|
||||
}
|
||||
template <typename V>
|
||||
[[nodiscard]] Step fail(V&& value) const
|
||||
[[nodiscard]] StateKey fail(V&& value) const
|
||||
requires(!std::is_void_v<Detail::FailureOf<Derived>>)
|
||||
{
|
||||
return Step::failure(
|
||||
return StateKey::failure(
|
||||
std::any{Detail::FailureOf<Derived>{
|
||||
std::forward<V>(value)}});
|
||||
}
|
||||
@@ -311,11 +306,11 @@ namespace Void::Fsm
|
||||
/// initial-state startup-entry; shares this machine's
|
||||
/// executor/events/services), then transition to `Next`.
|
||||
/// When Sub finishes the engine calls Next's signature
|
||||
/// -matched handler — a member taking `ChildSuccess auto`
|
||||
/// (Sub succeeded) or `ChildFailure auto` (Sub failed):
|
||||
/// -matched handler — a member taking `ChildSuccess`
|
||||
/// (Sub succeeded) or `ChildFailure` (Sub failed):
|
||||
/// co_return startMachine<Login, AfterLogin>(seed);
|
||||
template <typename Sub, typename Next, typename... Args>
|
||||
[[nodiscard]] Step startMachine(Args&&... args) const
|
||||
[[nodiscard]] StateKey startMachine(Args&&... args) const
|
||||
{
|
||||
return m_machine->template start_machine<Sub, Next>(
|
||||
std::forward<Args>(args)...);
|
||||
@@ -337,37 +332,35 @@ namespace Void::Fsm
|
||||
// There is a single base, `State`. The engine infers what each
|
||||
// state does from member signatures (no `override`, no fixed
|
||||
// names):
|
||||
// - entry : a member returning Step/Coro::Task<Step>,
|
||||
// - entry : a member returning
|
||||
// State/Coro::Task<StateKey>>,
|
||||
// no params (a startup-data overload may take
|
||||
// the sub's startup argument);
|
||||
// - reactive : a member taking `TransitionBuilder&` (the
|
||||
// declarative table below);
|
||||
// - continuation : members taking `ChildSuccess auto` /
|
||||
// `ChildFailure auto` (the sub's typed result
|
||||
// after `startMachine<Sub, This>()`).
|
||||
// - continuation : members taking `ChildSuccess` /
|
||||
// `ChildFailure` (the sub's typed result, read
|
||||
// via .as<T>(), after `startMachine<Sub,
|
||||
// This>`).
|
||||
//
|
||||
// struct Idle : State { // reactive
|
||||
// void transitions(TransitionBuilder& on) {
|
||||
// on.event<Go>().to<Running>();
|
||||
// on.after(5s).to<TimedOut>(); } };
|
||||
// Events are handled imperatively inside an entry:
|
||||
// struct Idle : State { // entry
|
||||
// Coro::Task<StateKey> run() {
|
||||
// auto e = co_await await_any<Go, Stop>();
|
||||
// co_return std::holds_alternative<Go>(e) ? next<Running>()
|
||||
// : next<Done>(); }
|
||||
// };
|
||||
// struct After : State { // continuation
|
||||
// Coro::Task<Step> ok(ChildSuccess auto s){ ... }
|
||||
// Coro::Task<Step> no(ChildFailure auto f){ ... } };
|
||||
//
|
||||
// The declarative DSL lives in Detail/Reactive.hpp; these aliases
|
||||
// give the `transitions(TransitionBuilder&)` member its type.
|
||||
using TransitionTable = Detail::TransitionTable<Derived>;
|
||||
using TransitionBuilder = Detail::TransitionBuilder<Derived>;
|
||||
// Coro::Task<StateKey> ok(ChildSuccess s){ ... }
|
||||
// Coro::Task<StateKey> no(ChildFailure f){ ... } };
|
||||
|
||||
// ── construction ──────────────────────────────────────────────
|
||||
explicit Machine(Options options = {}) : m_options(options)
|
||||
{
|
||||
if constexpr (requires { typename Derived::States; }) {
|
||||
register_states(typename Derived::States{});
|
||||
if constexpr (requires { typename Derived::Initial; }) {
|
||||
m_initial = &typeid(typename Derived::Initial);
|
||||
} else {
|
||||
m_initial = first_type(typename Derived::States{});
|
||||
Detail::register_states_from<typename Derived::States>(
|
||||
*this);
|
||||
using Init = Detail::InitialStateOf<Derived>;
|
||||
if constexpr (!std::is_void_v<Init>) {
|
||||
m_initial = &typeid(Init);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -397,20 +390,8 @@ namespace Void::Fsm
|
||||
s->m_machine = this;
|
||||
return s;
|
||||
});
|
||||
// Signature-inferred driver thunk (entry or reactive table).
|
||||
// Signature-inferred driver thunk (runs the state's entry).
|
||||
m_drivers.emplace(key, Detail::make_driver<S>());
|
||||
// describe() collector: fills a table if S is reactive.
|
||||
m_collectors.emplace(
|
||||
key,
|
||||
[](Detail::StateBase& base,
|
||||
TransitionTable& table) -> bool {
|
||||
if constexpr (Detail::has_transitions<S>()) {
|
||||
Detail::collect_transitions(static_cast<S&>(base),
|
||||
table);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
template <typename S> void initial()
|
||||
@@ -459,7 +440,6 @@ namespace Void::Fsm
|
||||
m_names.erase(m_names.begin() + idx);
|
||||
m_factories.erase(key);
|
||||
m_drivers.erase(key);
|
||||
m_collectors.erase(key);
|
||||
m_index.erase(idxIt);
|
||||
// Re-pack the indices of states that followed S.
|
||||
for (auto& [k, v] : m_index) {
|
||||
@@ -973,12 +953,13 @@ namespace Void::Fsm
|
||||
/// machine's shared executor, then enter `Next` carrying Sub's
|
||||
/// outcome as a LaunchResult. Reached via State::startMachine.
|
||||
template <typename Sub, typename Next, typename... Args>
|
||||
[[nodiscard]] Step start_machine(Args&&... args)
|
||||
[[nodiscard]] StateKey start_machine(Args&&... args)
|
||||
{
|
||||
if constexpr (requires { typename Derived::States; }) {
|
||||
static_assert(
|
||||
Derived::States::template contains<Next>(),
|
||||
"startMachine<Sub, Next>: Next is not in States<...>");
|
||||
Detail::states_contains<typename Derived::States,
|
||||
Next>(),
|
||||
"startMachine<Sub, Next>: Next is not in States { … }");
|
||||
}
|
||||
using Init = Detail::InitialStateOf<Sub>;
|
||||
auto launcher =
|
||||
@@ -993,7 +974,7 @@ namespace Void::Fsm
|
||||
child.m_startup_injector =
|
||||
[... d = std::move(data)](
|
||||
Detail::StateBase& base) mutable
|
||||
-> Coro::Task<Step> {
|
||||
-> Coro::Task<StateKey> {
|
||||
return Detail::invoke_startup<Init>(
|
||||
static_cast<Init&>(base), std::move(d)...);
|
||||
};
|
||||
@@ -1017,14 +998,14 @@ namespace Void::Fsm
|
||||
}
|
||||
co_return lr;
|
||||
};
|
||||
Step::Dispatch dispatch =
|
||||
StateKey::Dispatch dispatch =
|
||||
[](Detail::StateBase& base,
|
||||
LaunchResult lr) -> Coro::Task<Step> {
|
||||
LaunchResult lr) -> Coro::Task<StateKey> {
|
||||
return Detail::dispatch_result<Next, Sub>(
|
||||
static_cast<Next&>(base), std::move(lr));
|
||||
};
|
||||
return Step::launch(typeid(Next), std::move(launcher),
|
||||
std::move(dispatch));
|
||||
return StateKey::launch(typeid(Next), std::move(launcher),
|
||||
std::move(dispatch));
|
||||
}
|
||||
|
||||
// ── observation ───────────────────────────────────────────────
|
||||
@@ -1066,12 +1047,12 @@ namespace Void::Fsm
|
||||
}
|
||||
|
||||
// ── introspection / diagram ───────────────────────────────────
|
||||
// EdgeInfo / StateInfo are namespace-scope (Detail/Introspect.hpp).
|
||||
// StateInfo is namespace-scope (Detail/Introspect.hpp).
|
||||
|
||||
/// Structural description: every registered state plus the
|
||||
/// transitions declared by reactive states (imperative states'
|
||||
/// run()-chosen transitions are not statically knowable, so
|
||||
/// they appear as nodes without edges).
|
||||
/// Structural description: every registered state (name + whether
|
||||
/// it is the initial state). Transitions are chosen imperatively
|
||||
/// inside each state's entry, so they are not statically knowable —
|
||||
/// the description is node-level (no edges).
|
||||
[[nodiscard]] std::vector<StateInfo> describe()
|
||||
{
|
||||
std::vector<StateInfo> out;
|
||||
@@ -1082,22 +1063,6 @@ namespace Void::Fsm
|
||||
StateInfo si;
|
||||
si.name = name;
|
||||
si.initial = (name == initial_name);
|
||||
const auto* ti = m_name_to_type.at(name);
|
||||
const std::type_index key{*ti};
|
||||
auto state = m_factories.at(key)();
|
||||
TransitionTable table;
|
||||
si.reactive = m_collectors.at(key)(*state, table);
|
||||
if (si.reactive) {
|
||||
for (const auto& e : table.events) {
|
||||
si.edges.push_back(
|
||||
EdgeInfo{e.event_name, e.target_name,
|
||||
static_cast<bool>(e.guard)});
|
||||
}
|
||||
if (table.has_timeout) {
|
||||
si.edges.push_back(EdgeInfo{
|
||||
"(timeout)", table.timeout_target_name, false});
|
||||
}
|
||||
}
|
||||
out.push_back(std::move(si));
|
||||
}
|
||||
return out;
|
||||
@@ -1151,6 +1116,15 @@ namespace Void::Fsm
|
||||
virtual void on_serialize(Json::Value& /*data*/) const {}
|
||||
virtual void on_restore(const Json::Value& /*data*/) {}
|
||||
|
||||
/// Machine-level entry/exit hooks (default no-ops; override for
|
||||
/// machine-wide setup/teardown). `on_machine_enter()` runs once
|
||||
/// before the initial state is entered; `on_machine_exit()` runs
|
||||
/// once when the machine reaches a terminal outcome (Success,
|
||||
/// Failure, or a system Fault). Per-state entry/exit lives on the
|
||||
/// state itself (State::on_enter()/on_exit()).
|
||||
virtual void on_machine_enter() {}
|
||||
virtual void on_machine_exit() {}
|
||||
|
||||
/// Called on every transition (and the initial entry). Default
|
||||
/// logs at debug; override for custom observability.
|
||||
virtual void on_transition(std::string_view from,
|
||||
@@ -1176,21 +1150,6 @@ namespace Void::Fsm
|
||||
m_status.store(Status::Running);
|
||||
}
|
||||
|
||||
template <typename... Ss> void register_states(States<Ss...>)
|
||||
{
|
||||
(add<Ss>(), ...);
|
||||
}
|
||||
|
||||
template <typename First, typename... Rest>
|
||||
static const std::type_info* first_type(States<First, Rest...>)
|
||||
{
|
||||
return &typeid(First);
|
||||
}
|
||||
static const std::type_info* first_type(States<>)
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template <typename S> [[nodiscard]] std::string state_name()
|
||||
{
|
||||
#ifdef VOID_HAS_FSM_REFLECTION
|
||||
@@ -1261,6 +1220,7 @@ namespace Void::Fsm
|
||||
fault("no initial state");
|
||||
co_return;
|
||||
}
|
||||
on_machine_enter();
|
||||
bool first = true;
|
||||
for (;;) {
|
||||
// Apply an external jump<S>() at this transition boundary.
|
||||
@@ -1274,6 +1234,7 @@ namespace Void::Fsm
|
||||
const auto it = m_factories.find(std::type_index{*cur});
|
||||
if (it == m_factories.end()) {
|
||||
fault("transition to unregistered state");
|
||||
on_machine_exit();
|
||||
co_return;
|
||||
}
|
||||
set_current(cur);
|
||||
@@ -1282,7 +1243,7 @@ namespace Void::Fsm
|
||||
// Decide how the state runs: a launched sub's result (via
|
||||
// the bound dispatcher), the startup injector for the first
|
||||
// state, or the signature-inferred driver thunk.
|
||||
Step step;
|
||||
StateKey step;
|
||||
if (m_pending_dispatch) {
|
||||
LaunchResult pending = std::move(*m_pending_result);
|
||||
auto dispatch = std::move(m_pending_dispatch);
|
||||
@@ -1290,6 +1251,7 @@ namespace Void::Fsm
|
||||
m_pending_dispatch = nullptr;
|
||||
if (pending.kind == LaunchResult::Kind::Fault) {
|
||||
fault(std::move(pending.fault.message));
|
||||
on_machine_exit();
|
||||
co_return;
|
||||
}
|
||||
step = co_await dispatch(*state, std::move(pending));
|
||||
@@ -1305,28 +1267,31 @@ namespace Void::Fsm
|
||||
co_await state->on_exit();
|
||||
fire_after(current_state());
|
||||
switch (step.kind()) {
|
||||
case Step::Kind::Transition:
|
||||
case StateKey::Kind::Transition:
|
||||
cur = step.target();
|
||||
continue;
|
||||
case Step::Kind::Launch:
|
||||
case StateKey::Kind::Launch:
|
||||
m_pending_result.emplace(
|
||||
co_await step.run_launch());
|
||||
m_pending_dispatch = step.take_dispatch();
|
||||
cur = step.target();
|
||||
continue;
|
||||
case Step::Kind::Success:
|
||||
case StateKey::Kind::Success:
|
||||
m_result_value = std::move(step.payload());
|
||||
m_status.store(Status::Succeeded,
|
||||
std::memory_order_release);
|
||||
on_machine_exit();
|
||||
co_return;
|
||||
case Step::Kind::Fail:
|
||||
case StateKey::Kind::Fail:
|
||||
m_result_value = std::move(step.payload());
|
||||
m_status.store(Status::Failed,
|
||||
std::memory_order_release);
|
||||
on_machine_exit();
|
||||
co_return;
|
||||
case Step::Kind::Fault:
|
||||
case StateKey::Kind::Fault:
|
||||
fault(std::any_cast<FsmError>(step.payload())
|
||||
.message);
|
||||
on_machine_exit();
|
||||
co_return;
|
||||
}
|
||||
}
|
||||
@@ -1385,15 +1350,11 @@ namespace Void::Fsm
|
||||
std::type_index,
|
||||
std::function<std::unique_ptr<Detail::StateBase>()>>
|
||||
m_factories;
|
||||
// Per-state signature-inferred driver thunk (entry / reactive).
|
||||
std::unordered_map<std::type_index, std::function<Coro::Task<Step>(
|
||||
Detail::StateBase&)>>
|
||||
m_drivers;
|
||||
// Per-state describe() collector (reactive table, if any).
|
||||
// Per-state signature-inferred driver thunk (runs the entry).
|
||||
std::unordered_map<
|
||||
std::type_index,
|
||||
std::function<bool(Detail::StateBase&, TransitionTable&)>>
|
||||
m_collectors;
|
||||
std::function<Coro::Task<StateKey>(Detail::StateBase&)>>
|
||||
m_drivers;
|
||||
std::unordered_map<std::type_index, int> m_index;
|
||||
std::vector<std::string> m_names;
|
||||
std::unordered_map<std::string, const std::type_info*>
|
||||
@@ -1421,11 +1382,11 @@ namespace Void::Fsm
|
||||
// Set by a Launch step's sub-machine result; consumed by the next
|
||||
// state via the bound dispatcher below.
|
||||
std::optional<LaunchResult> m_pending_result;
|
||||
Step::Dispatch m_pending_dispatch;
|
||||
StateKey::Dispatch m_pending_dispatch;
|
||||
|
||||
// Seeds the initial state's startup-entry with launch data (set by
|
||||
// the parent's launcher before driving this machine).
|
||||
std::function<Coro::Task<Step>(Detail::StateBase&)>
|
||||
std::function<Coro::Task<StateKey>(Detail::StateBase&)>
|
||||
m_startup_injector;
|
||||
|
||||
// External jump request (jump<S>()); applied by drive() at the
|
||||
@@ -1437,5 +1398,5 @@ namespace Void::Fsm
|
||||
// suspended frame chain of a machine parked on an event.
|
||||
std::optional<Coro::Task<void>> m_driver;
|
||||
};
|
||||
|
||||
template <typename Derived> using State = Machine<Derived>::State;
|
||||
} // namespace Void::Fsm
|
||||
@@ -1,6 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
#include <Void/Fsm/StateKey.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
@@ -46,15 +46,16 @@ namespace Void::Fsm
|
||||
/// What a state's entry returns: move to another state, finish with a typed
|
||||
/// Success / Failure, or launch a sub-machine. Built only through the State
|
||||
/// helpers (next<S>() / succeed(...) / fail(...) / startMachine).
|
||||
class Step
|
||||
class StateKey
|
||||
{
|
||||
public:
|
||||
|
||||
enum class Kind { Transition, Success, Fail, Launch, Fault };
|
||||
|
||||
[[nodiscard]] static Step transition(const std::type_info& target)
|
||||
[[nodiscard]] static StateKey
|
||||
transition(const std::type_info& target)
|
||||
{
|
||||
Step s;
|
||||
StateKey s;
|
||||
s.m_kind = Kind::Transition;
|
||||
s.m_target = ⌖
|
||||
return s;
|
||||
@@ -62,9 +63,9 @@ namespace Void::Fsm
|
||||
|
||||
/// Signal a system fault (programming error) — distinct from a
|
||||
/// typed Failure. Routed to Machine::system_error().
|
||||
[[nodiscard]] static Step fault(FsmError error)
|
||||
[[nodiscard]] static StateKey fault(FsmError error)
|
||||
{
|
||||
Step s;
|
||||
StateKey s;
|
||||
s.m_kind = Kind::Fault;
|
||||
s.m_payload = std::any{std::move(error)};
|
||||
return s;
|
||||
@@ -72,17 +73,17 @@ namespace Void::Fsm
|
||||
|
||||
/// A bound dispatcher: given the entered Next state and the sub's
|
||||
/// LaunchResult, calls Next's signature-matched handler.
|
||||
using Dispatch = std::function<Coro::Task<Step>(Detail::StateBase&,
|
||||
LaunchResult)>;
|
||||
using Dispatch = std::function<Coro::Task<StateKey>(
|
||||
Detail::StateBase&, LaunchResult)>;
|
||||
|
||||
/// Launch a sub-machine, then enter `target` (a continuation state)
|
||||
/// with the sub's LaunchResult, dispatched via `dispatch`.
|
||||
[[nodiscard]] static Step
|
||||
[[nodiscard]] static StateKey
|
||||
launch(const std::type_info& target,
|
||||
std::function<Coro::Task<LaunchResult>()> launcher,
|
||||
Dispatch dispatch)
|
||||
{
|
||||
Step s;
|
||||
StateKey s;
|
||||
s.m_kind = Kind::Launch;
|
||||
s.m_target = ⌖
|
||||
s.m_launcher = std::move(launcher);
|
||||
@@ -91,18 +92,18 @@ namespace Void::Fsm
|
||||
}
|
||||
|
||||
/// Finish with a typed Success payload (empty std::any for void).
|
||||
[[nodiscard]] static Step success(std::any value)
|
||||
[[nodiscard]] static StateKey success(std::any value)
|
||||
{
|
||||
Step s;
|
||||
StateKey s;
|
||||
s.m_kind = Kind::Success;
|
||||
s.m_payload = std::move(value);
|
||||
return s;
|
||||
}
|
||||
|
||||
/// Finish with a typed Failure payload (empty std::any for void).
|
||||
[[nodiscard]] static Step failure(std::any value)
|
||||
[[nodiscard]] static StateKey failure(std::any value)
|
||||
{
|
||||
Step s;
|
||||
StateKey s;
|
||||
s.m_kind = Kind::Fail;
|
||||
s.m_payload = std::move(value);
|
||||
return s;
|
||||
@@ -1,81 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <concepts>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#if __has_include(<meta>) && defined(__cpp_consteval)
|
||||
#include <meta>
|
||||
#include <string>
|
||||
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
#define VOID_RESULT_HAS_REFLECTION 1
|
||||
#endif
|
||||
|
||||
namespace Void::Result::Detail
|
||||
{
|
||||
/// Render a value for diagnostic / log output.
|
||||
///
|
||||
/// Resolution order:
|
||||
/// 1. If a `std::formatter<T>` exists, use `std::format("{}", v)`.
|
||||
/// 2. Otherwise, if `T` exposes a `.format()` method returning
|
||||
/// something convertible to `std::string`, call it.
|
||||
/// 3. Otherwise, if C++26 reflection is available, walk the
|
||||
/// non-static data members of `T` and render
|
||||
/// `Type{field1: value1, field2: value2}`.
|
||||
/// 4. Otherwise, return `"<unrepresentable>"`.
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value);
|
||||
|
||||
template <typename T>
|
||||
concept Formattable = std::formattable<T, char>;
|
||||
|
||||
template <typename T>
|
||||
concept HasFormatMethod = requires(const T& v) {
|
||||
{ v.format() } -> std::convertible_to<std::string>;
|
||||
};
|
||||
|
||||
#ifdef VOID_RESULT_HAS_REFLECTION
|
||||
template <typename T> [[nodiscard]] std::string reflect_struct(const T& obj)
|
||||
{
|
||||
std::string out;
|
||||
if constexpr (std::meta::has_identifier(^^T)) {
|
||||
out += std::meta::identifier_of(^^T);
|
||||
} else {
|
||||
out += "?";
|
||||
}
|
||||
out += '{';
|
||||
static constexpr auto members =
|
||||
std::define_static_array(std::meta::nonstatic_data_members_of(
|
||||
^^T, std::meta::access_context::unchecked()));
|
||||
bool first = true;
|
||||
template for (constexpr auto member : members)
|
||||
{
|
||||
if (!first) {
|
||||
out += ", ";
|
||||
}
|
||||
out += std::meta::identifier_of(member);
|
||||
out += ": ";
|
||||
out += repr(obj.[:member:]);
|
||||
first = false;
|
||||
}
|
||||
out += '}';
|
||||
return out;
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Render a value for diagnostic / log output. Thin alias over the shared
|
||||
/// reflection layer `Void::Meta::repr`:
|
||||
/// 1. std::formatter<T> → std::format("{}", v)
|
||||
/// 2. a `.format()` method returning something string-convertible
|
||||
/// 3. C++26 reflection: `Type{field1: value1, field2: value2}`
|
||||
/// 4. otherwise `"<unrepresentable>"`
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value)
|
||||
{
|
||||
if constexpr (Formattable<T>) {
|
||||
return std::format("{}", value);
|
||||
} else if constexpr (HasFormatMethod<T>) {
|
||||
return std::string{value.format()};
|
||||
}
|
||||
#ifdef VOID_RESULT_HAS_REFLECTION
|
||||
else if constexpr (std::is_class_v<T> || std::is_union_v<T>) {
|
||||
return reflect_struct(value);
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
return "<unrepresentable>";
|
||||
}
|
||||
return Void::Meta::repr(value);
|
||||
}
|
||||
|
||||
} // namespace Void::Result::Detail
|
||||
@@ -5,122 +5,209 @@
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <expected>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
namespace Void::Retry
|
||||
{
|
||||
|
||||
// ── Backoff policies ──────────────────────────────────────────────────────────
|
||||
// ── Backoff policies
|
||||
// ──────────────────────────────────────────────────────────
|
||||
|
||||
struct NoDelay
|
||||
{
|
||||
[[nodiscard]] std::chrono::milliseconds delay(std::size_t /*attempt*/) const noexcept
|
||||
{
|
||||
return std::chrono::milliseconds{0};
|
||||
}
|
||||
};
|
||||
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};
|
||||
struct ConstantDelay {
|
||||
std::chrono::milliseconds interval{100};
|
||||
|
||||
[[nodiscard]] std::chrono::milliseconds delay(std::size_t) const noexcept
|
||||
{
|
||||
return interval;
|
||||
}
|
||||
};
|
||||
[[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};
|
||||
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};
|
||||
}
|
||||
};
|
||||
[[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};
|
||||
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)};
|
||||
}
|
||||
};
|
||||
[[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 ────────────────────────────────────────────────────────────────────
|
||||
// ── Jitter
|
||||
// ──────────────────────────────────────────────────────────────────── Wrap
|
||||
// any backoff to randomize its delay and avoid thundering-herd retries.
|
||||
// Full: uniform in [0, base]
|
||||
// Equal: base/2 + uniform in [0, base/2] (keeps a guaranteed floor)
|
||||
|
||||
template <typename Backoff = ExponentialBackoff>
|
||||
struct Policy
|
||||
{
|
||||
std::size_t max_attempts{3};
|
||||
Backoff backoff{};
|
||||
enum class JitterMode { Full, Equal };
|
||||
|
||||
using BackoffType = Backoff;
|
||||
};
|
||||
template <typename Backoff = ExponentialBackoff> struct Jittered {
|
||||
Backoff inner{};
|
||||
JitterMode mode{JitterMode::Full};
|
||||
|
||||
// ── 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.
|
||||
[[nodiscard]] std::chrono::milliseconds
|
||||
delay(std::size_t attempt) const
|
||||
{
|
||||
const auto base = inner.delay(attempt).count();
|
||||
if (base <= 0) {
|
||||
return std::chrono::milliseconds{0};
|
||||
}
|
||||
thread_local std::mt19937_64 rng{std::random_device{}()};
|
||||
const long long floor =
|
||||
(mode == JitterMode::Equal) ? base / 2 : 0;
|
||||
std::uniform_int_distribution<long long> dist{0, base - floor};
|
||||
return std::chrono::milliseconds{floor + dist(rng)};
|
||||
}
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
// ── Policy
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
|
||||
// ── retry_or_throw — throws on final failure ──────────────────────────────────
|
||||
template <typename Backoff = ExponentialBackoff> struct Policy {
|
||||
std::size_t max_attempts{3};
|
||||
Backoff backoff{};
|
||||
// Total wall-clock budget across all attempts (0 = unlimited). Once
|
||||
// the elapsed time reaches this, no further attempts are made and
|
||||
// the inter- attempt sleep is clamped so it never overshoots the
|
||||
// budget.
|
||||
std::chrono::milliseconds max_elapsed{0};
|
||||
|
||||
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;
|
||||
}
|
||||
using BackoffType = Backoff;
|
||||
};
|
||||
|
||||
// ── retry_while — retries while a predicate on the result holds ───────────────
|
||||
// Useful for retrying on specific error codes without expected<T,E>.
|
||||
namespace Detail
|
||||
{
|
||||
// Sleep for `wait`, honoring a total budget measured from `start`.
|
||||
// Returns false if the budget is exhausted (caller should stop
|
||||
// retrying).
|
||||
template <typename Policy>
|
||||
[[nodiscard]] inline bool
|
||||
backoff_sleep(const Policy& policy, std::size_t attempt,
|
||||
std::chrono::steady_clock::time_point start)
|
||||
{
|
||||
using namespace std::chrono;
|
||||
if (policy.max_elapsed.count() > 0) {
|
||||
const auto elapsed =
|
||||
duration_cast<milliseconds>(steady_clock::now() - start);
|
||||
if (elapsed >= policy.max_elapsed) {
|
||||
return false;
|
||||
}
|
||||
auto wait = policy.backoff.delay(attempt);
|
||||
const auto rem = policy.max_elapsed - elapsed;
|
||||
wait = std::min(wait, rem);
|
||||
if (wait.count() > 0) {
|
||||
std::this_thread::sleep_for(wait);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const auto wait = policy.backoff.delay(attempt);
|
||||
if (wait.count() > 0) {
|
||||
std::this_thread::sleep_for(wait);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
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;
|
||||
}
|
||||
// ── 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>;
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
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) {
|
||||
if (!Detail::backoff_sleep(policy, attempt, start)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
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)
|
||||
{
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
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) {
|
||||
if (!Detail::backoff_sleep(policy, attempt, start)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
} // namespace Void::Retry
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <initializer_list>
|
||||
#include <span>
|
||||
#include <string>
|
||||
@@ -24,6 +26,23 @@ namespace Void::Logging
|
||||
explicit FieldScope(
|
||||
std::initializer_list<std::pair<std::string, std::string>>
|
||||
fields);
|
||||
explicit FieldScope(
|
||||
std::vector<std::pair<std::string, std::string>> fields);
|
||||
|
||||
/// Reflect an aggregate's data members into structured fields
|
||||
/// (key = field name, value = Void::Meta::repr of the value):
|
||||
/// auto fs = Logging::FieldScope::from(request);
|
||||
template <typename T>
|
||||
[[nodiscard]] static FieldScope from(const T& obj)
|
||||
{
|
||||
std::vector<std::pair<std::string, std::string>> fields;
|
||||
Void::Meta::for_each_field(
|
||||
obj, [&](std::string_view name, const auto& value) {
|
||||
fields.emplace_back(std::string{name},
|
||||
Void::Meta::repr(value));
|
||||
});
|
||||
return FieldScope{std::move(fields)};
|
||||
}
|
||||
|
||||
~FieldScope() noexcept;
|
||||
|
||||
|
||||
@@ -134,12 +134,45 @@ namespace Void::Logging
|
||||
ColorPolicy m_colors;
|
||||
};
|
||||
|
||||
/// An allow/deny list applied to an entry's structured fields by the
|
||||
/// json/logfmt sinks. `include` empty means "all keys" (still subject to
|
||||
/// `exclude`); a non-empty `include` admits only those keys. `exclude`
|
||||
/// always wins.
|
||||
struct FieldFilter {
|
||||
std::vector<std::string> include;
|
||||
std::vector<std::string> exclude;
|
||||
|
||||
[[nodiscard]] bool allows(std::string_view key) const
|
||||
{
|
||||
for (const auto& e : exclude) {
|
||||
if (e == key) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (include.empty()) {
|
||||
return true;
|
||||
}
|
||||
for (const auto& i : include) {
|
||||
if (i == key) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/// One compact JSON object per entry (includes fields when present).
|
||||
class JsonLinesFormatter final : public Formatter
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] std::string format(const Entry& entry) const override;
|
||||
|
||||
void set_field_filter(FieldFilter f) { m_fields = std::move(f); }
|
||||
|
||||
private:
|
||||
|
||||
FieldFilter m_fields;
|
||||
};
|
||||
|
||||
/// logfmt: time=... level=... thread=... msg="..." plus scopes/fields.
|
||||
@@ -148,6 +181,12 @@ namespace Void::Logging
|
||||
public:
|
||||
|
||||
[[nodiscard]] std::string format(const Entry& entry) const override;
|
||||
|
||||
void set_field_filter(FieldFilter f) { m_fields = std::move(f); }
|
||||
|
||||
private:
|
||||
|
||||
FieldFilter m_fields;
|
||||
};
|
||||
|
||||
namespace FormatDetail
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Resilience
|
||||
{
|
||||
|
||||
// ── CircuitBreaker
|
||||
// ──────────────────────────────────────────────────────────── A
|
||||
// three-state breaker that stops hammering a failing dependency.
|
||||
//
|
||||
// Closed calls flow; `failure_threshold` consecutive failures trip it
|
||||
// Open. Open calls are rejected until `cooldown` elapses, then one
|
||||
// probe is let
|
||||
// through (HalfOpen).
|
||||
// HalfOpen `success_threshold` probe successes close it; any failure
|
||||
// re-opens.
|
||||
//
|
||||
// Use allow()/record_success()/record_failure() to gate work directly, or
|
||||
// execute() to wrap a std::expected-returning step. Thread-safe; clock
|
||||
// injectable for deterministic tests.
|
||||
|
||||
template <typename R>
|
||||
concept HasHasValue = requires(const R& r) {
|
||||
{ r.has_value() } -> std::convertible_to<bool>;
|
||||
};
|
||||
|
||||
class CircuitBreaker
|
||||
{
|
||||
public:
|
||||
|
||||
enum class State { Closed, Open, HalfOpen };
|
||||
|
||||
using Clock =
|
||||
std::function<std::chrono::steady_clock::time_point()>;
|
||||
using Duration = std::chrono::steady_clock::duration;
|
||||
using TimePoint = std::chrono::steady_clock::time_point;
|
||||
|
||||
CircuitBreaker(std::size_t failure_threshold, Duration cooldown,
|
||||
std::size_t success_threshold = 1,
|
||||
Clock clock = default_clock())
|
||||
: failure_threshold_{failure_threshold}, cooldown_{cooldown},
|
||||
success_threshold_{success_threshold},
|
||||
clock_{std::move(clock)}
|
||||
{
|
||||
}
|
||||
|
||||
// Whether a call may proceed now. Transitions Open -> HalfOpen once
|
||||
// the cooldown has elapsed (admitting a probe).
|
||||
[[nodiscard]] bool allow()
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
if (state_ == State::Open &&
|
||||
clock_() - opened_at_ >= cooldown_) {
|
||||
state_ = State::HalfOpen;
|
||||
successes_ = 0;
|
||||
}
|
||||
return state_ != State::Open;
|
||||
}
|
||||
|
||||
void record_success()
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
if (state_ == State::HalfOpen) {
|
||||
if (++successes_ >= success_threshold_) {
|
||||
state_ = State::Closed;
|
||||
failures_ = 0;
|
||||
}
|
||||
} else {
|
||||
failures_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void record_failure()
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
if (state_ == State::HalfOpen) {
|
||||
trip();
|
||||
} else if (++failures_ >= failure_threshold_) {
|
||||
trip();
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] State state()
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
return state_;
|
||||
}
|
||||
|
||||
// Gate a std::expected-returning callable. Returns nullopt when the
|
||||
// circuit rejects the call; otherwise runs it, records the outcome,
|
||||
// and returns its result.
|
||||
template <std::invocable F>
|
||||
requires HasHasValue<std::invoke_result_t<F>>
|
||||
auto execute(F&& fn) -> std::optional<std::invoke_result_t<F>>
|
||||
{
|
||||
if (!allow()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
auto result = std::forward<F>(fn)();
|
||||
if (result.has_value()) {
|
||||
record_success();
|
||||
} else {
|
||||
record_failure();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static Clock default_clock()
|
||||
{
|
||||
return [] { return std::chrono::steady_clock::now(); };
|
||||
}
|
||||
|
||||
void trip()
|
||||
{
|
||||
state_ = State::Open;
|
||||
opened_at_ = clock_();
|
||||
}
|
||||
|
||||
std::size_t failure_threshold_;
|
||||
Duration cooldown_;
|
||||
std::size_t success_threshold_;
|
||||
Clock clock_;
|
||||
|
||||
State state_ = State::Closed;
|
||||
std::size_t failures_ = 0;
|
||||
std::size_t successes_ = 0;
|
||||
TimePoint opened_at_{};
|
||||
std::mutex mu_;
|
||||
};
|
||||
|
||||
} // namespace Void::Resilience
|
||||
@@ -0,0 +1,123 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Resilience/RateLimiter.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Resilience
|
||||
{
|
||||
|
||||
// ── KeyedRateLimiter<Key> ───────────────────────────────────────────────
|
||||
// A rate limiter that maintains an independent TokenBucket per distinct
|
||||
// Key. Every key shares the same capacity + refill rate; buckets are
|
||||
// created lazily on first use and can be reclaimed with cleanup(). Thread-
|
||||
// safe. Generic over the key type (e.g. a client id, IP, or user name).
|
||||
|
||||
template <typename Key, typename Hash = std::hash<Key>>
|
||||
class KeyedRateLimiter
|
||||
{
|
||||
public:
|
||||
|
||||
using Clock = TokenBucket::Clock;
|
||||
|
||||
// `capacity` is the burst size; `refill_per_sec` the sustained rate.
|
||||
// The clock is shared with every bucket so tests stay deterministic.
|
||||
explicit KeyedRateLimiter(double capacity, double refill_per_sec,
|
||||
Clock clock = default_clock())
|
||||
: capacity_{capacity}, rate_{refill_per_sec},
|
||||
clock_{std::move(clock)}
|
||||
{
|
||||
}
|
||||
|
||||
// Consume `tokens` for `key`. Returns false (without consuming) when
|
||||
// the key's bucket is exhausted.
|
||||
[[nodiscard]] bool allow(const Key& key, double tokens = 1.0)
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
return entry(key).bucket->try_acquire(tokens);
|
||||
}
|
||||
|
||||
// Tokens currently available to `key` (creates the bucket if new).
|
||||
[[nodiscard]] double remaining(const Key& key)
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
return entry(key).bucket->available();
|
||||
}
|
||||
|
||||
// Forget a key's bucket (its next use starts full).
|
||||
void reset(const Key& key)
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
map_.erase(key);
|
||||
}
|
||||
|
||||
// Drop buckets not touched within `max_age`. Returns how many were
|
||||
// removed. Call periodically to bound memory for churny key spaces.
|
||||
std::size_t cleanup(std::chrono::steady_clock::duration max_age)
|
||||
{
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
std::lock_guard lock{mu_};
|
||||
std::size_t removed = 0;
|
||||
for (auto it = map_.begin(); it != map_.end();) {
|
||||
if (now - it->second.last_seen >= max_age) {
|
||||
it = map_.erase(it);
|
||||
++removed;
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
// Number of keys currently tracked.
|
||||
[[nodiscard]] std::size_t tracked() const
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
return map_.size();
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static Clock default_clock()
|
||||
{
|
||||
return [] { return std::chrono::steady_clock::now(); };
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
// TokenBucket owns a std::mutex (non-movable), so hold it by
|
||||
// pointer to keep Entry movable for the hash map.
|
||||
std::unique_ptr<TokenBucket> bucket;
|
||||
std::chrono::steady_clock::time_point last_seen;
|
||||
};
|
||||
|
||||
Entry& entry(const Key& key)
|
||||
{
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
auto it = map_.find(key);
|
||||
if (it == map_.end()) {
|
||||
it = map_
|
||||
.emplace(key,
|
||||
Entry{std::make_unique<TokenBucket>(
|
||||
capacity_, rate_, clock_),
|
||||
now})
|
||||
.first;
|
||||
} else {
|
||||
it->second.last_seen = now;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
double capacity_;
|
||||
double rate_;
|
||||
Clock clock_;
|
||||
mutable std::mutex mu_;
|
||||
std::unordered_map<Key, Entry, Hash> map_;
|
||||
};
|
||||
|
||||
} // namespace Void::Resilience
|
||||
@@ -0,0 +1,82 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Resilience
|
||||
{
|
||||
|
||||
// ── TokenBucket
|
||||
// ─────────────────────────────────────────────────────────────── A
|
||||
// token-bucket rate limiter. The bucket holds up to `capacity` tokens and
|
||||
// refills continuously at `refill_per_sec` tokens per second.
|
||||
// try_acquire(n) consumes n tokens when available. Thread-safe; the clock
|
||||
// is injectable so the refill behaviour is deterministic in tests.
|
||||
|
||||
class TokenBucket
|
||||
{
|
||||
public:
|
||||
|
||||
using Clock =
|
||||
std::function<std::chrono::steady_clock::time_point()>;
|
||||
using TimePoint = std::chrono::steady_clock::time_point;
|
||||
|
||||
TokenBucket(double capacity, double refill_per_sec,
|
||||
Clock clock = default_clock())
|
||||
: capacity_{capacity}, rate_{refill_per_sec}, tokens_{capacity},
|
||||
clock_{std::move(clock)}, last_{clock_()}
|
||||
{
|
||||
}
|
||||
|
||||
// Consume `tokens` if the bucket (after refilling for elapsed time)
|
||||
// holds at least that many. Returns false without consuming
|
||||
// anything otherwise.
|
||||
[[nodiscard]] bool try_acquire(double tokens = 1.0)
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
refill();
|
||||
if (tokens_ >= tokens) {
|
||||
tokens_ -= tokens;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Current token count after refilling for elapsed time.
|
||||
[[nodiscard]] double available()
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
refill();
|
||||
return tokens_;
|
||||
}
|
||||
|
||||
[[nodiscard]] double capacity() const noexcept { return capacity_; }
|
||||
|
||||
private:
|
||||
|
||||
static Clock default_clock()
|
||||
{
|
||||
return [] { return std::chrono::steady_clock::now(); };
|
||||
}
|
||||
|
||||
void refill()
|
||||
{
|
||||
const auto now = clock_();
|
||||
const std::chrono::duration<double> elapsed = now - last_;
|
||||
last_ = now;
|
||||
tokens_ =
|
||||
std::min(capacity_, tokens_ + elapsed.count() * rate_);
|
||||
}
|
||||
|
||||
double capacity_;
|
||||
double rate_;
|
||||
double tokens_;
|
||||
Clock clock_;
|
||||
TimePoint last_;
|
||||
std::mutex mu_;
|
||||
};
|
||||
|
||||
} // namespace Void::Resilience
|
||||
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
// Umbrella header for the Resilience module: rate limiting, circuit breaking,
|
||||
// and resource monitoring. These complement Functional/Retry.hpp (retry with
|
||||
// backoff) rather than replacing it.
|
||||
|
||||
#include <Void/Resilience/CircuitBreaker.hpp>
|
||||
#include <Void/Resilience/KeyedRateLimiter.hpp>
|
||||
#include <Void/Resilience/RateLimiter.hpp>
|
||||
#include <Void/Resilience/ResourceMonitor.hpp>
|
||||
@@ -0,0 +1,117 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Resilience
|
||||
{
|
||||
|
||||
// ── ResourceMonitor
|
||||
// ─────────────────────────────────────────────────────────── Tracks usage
|
||||
// of a bounded resource (memory budget, in-flight requests, queue depth,
|
||||
// ...) against a limit, with hysteresis watermark callbacks.
|
||||
//
|
||||
// try_acquire() refuses to exceed the limit. Crossing the high watermark
|
||||
// upward fires on_high_watermark once; dropping back to the low watermark
|
||||
// fires on_low_watermark once (the gap prevents callback flapping).
|
||||
// Callbacks run outside the internal lock.
|
||||
|
||||
class ResourceMonitor
|
||||
{
|
||||
public:
|
||||
|
||||
using Callback = std::function<void(std::uint64_t usage)>;
|
||||
|
||||
// high/low are fractions of `limit` in [0, 1]; high should exceed
|
||||
// low.
|
||||
explicit ResourceMonitor(std::uint64_t limit, double high = 0.9,
|
||||
double low = 0.7)
|
||||
: limit_{limit}, high_{static_cast<std::uint64_t>(
|
||||
static_cast<double>(limit) * high)},
|
||||
low_{static_cast<std::uint64_t>(static_cast<double>(limit) *
|
||||
low)}
|
||||
{
|
||||
}
|
||||
|
||||
void on_high_watermark(Callback cb) { on_high_ = std::move(cb); }
|
||||
void on_low_watermark(Callback cb) { on_low_ = std::move(cb); }
|
||||
|
||||
// Reserve `amount`. Returns false (reserving nothing) if it would
|
||||
// exceed the limit. May fire the high-watermark callback when
|
||||
// crossing upward.
|
||||
[[nodiscard]] bool try_acquire(std::uint64_t amount = 1)
|
||||
{
|
||||
Callback fire;
|
||||
std::uint64_t at = 0;
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
if (usage_ + amount > limit_) {
|
||||
return false;
|
||||
}
|
||||
usage_ += amount;
|
||||
if (!alarmed_ && usage_ >= high_) {
|
||||
alarmed_ = true;
|
||||
fire = on_high_;
|
||||
at = usage_;
|
||||
}
|
||||
}
|
||||
if (fire) {
|
||||
fire(at);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Release `amount` (clamped at zero). May fire the low-watermark
|
||||
// callback when dropping back through the low threshold.
|
||||
void release(std::uint64_t amount = 1)
|
||||
{
|
||||
Callback fire;
|
||||
std::uint64_t at = 0;
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
usage_ = (amount >= usage_) ? 0 : usage_ - amount;
|
||||
if (alarmed_ && usage_ <= low_) {
|
||||
alarmed_ = false;
|
||||
fire = on_low_;
|
||||
at = usage_;
|
||||
}
|
||||
}
|
||||
if (fire) {
|
||||
fire(at);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint64_t usage() const
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
return usage_;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint64_t limit() const noexcept
|
||||
{
|
||||
return limit_;
|
||||
}
|
||||
|
||||
[[nodiscard]] double utilization() const
|
||||
{
|
||||
std::lock_guard lock{mu_};
|
||||
return limit_ == 0 ? 0.0
|
||||
: static_cast<double>(usage_) /
|
||||
static_cast<double>(limit_);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::uint64_t limit_;
|
||||
std::uint64_t high_;
|
||||
std::uint64_t low_;
|
||||
std::uint64_t usage_ = 0;
|
||||
bool alarmed_ = false;
|
||||
Callback on_high_;
|
||||
Callback on_low_;
|
||||
mutable std::mutex mu_;
|
||||
};
|
||||
|
||||
} // namespace Void::Resilience
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Service/Service.hpp>
|
||||
|
||||
#include <memory>
|
||||
@@ -14,6 +15,16 @@
|
||||
|
||||
namespace Void::Service
|
||||
{
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
/// The reflected (unqualified) name of an interface type — a sensible
|
||||
/// default service name when an IService impl doesn't override
|
||||
/// service_name(). E.g. interface_name<IClock>() == "IClock".
|
||||
template <typename I> [[nodiscard]] std::string interface_name()
|
||||
{
|
||||
return Void::Meta::type_name<I>();
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Type-keyed service container: providers register an implementation
|
||||
/// against an interface type, consumers resolve by that interface and
|
||||
/// never name the concrete type — the core of the dependency-inversion
|
||||
@@ -32,6 +43,16 @@ namespace Void::Service
|
||||
ServiceRegistry(const ServiceRegistry&) = delete;
|
||||
ServiceRegistry& operator=(const ServiceRegistry&) = delete;
|
||||
|
||||
/// Create a scoped child registry that overlays `parent`: lookups
|
||||
/// fall through to the parent when a key is not provided locally,
|
||||
/// and a local provide<I>() shadows the parent's entry. Lifecycle
|
||||
/// (start_all/stop_all) covers only locally-provided services. The
|
||||
/// parent must outlive this registry.
|
||||
explicit ServiceRegistry(const ServiceRegistry* parent)
|
||||
: m_parent{parent}
|
||||
{
|
||||
}
|
||||
|
||||
/// Register (or replace) the implementation for interface I.
|
||||
/// If I derives IService, the instance joins the lifecycle.
|
||||
template <typename I> void provide(std::shared_ptr<I> impl)
|
||||
@@ -54,15 +75,18 @@ namespace Void::Service
|
||||
m_services.insert_or_assign(key, std::move(entry));
|
||||
}
|
||||
|
||||
/// Resolve I, or nullptr if not provided.
|
||||
/// Resolve I, or nullptr if not provided. Falls through to the
|
||||
/// parent registry (if any) on a local miss.
|
||||
template <typename I> [[nodiscard]] std::shared_ptr<I> get() const
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
const auto it = m_services.find(std::type_index{typeid(I)});
|
||||
if (it == m_services.end()) {
|
||||
return nullptr;
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
const auto it = m_services.find(std::type_index{typeid(I)});
|
||||
if (it != m_services.end()) {
|
||||
return std::static_pointer_cast<I>(it->second.impl);
|
||||
}
|
||||
}
|
||||
return std::static_pointer_cast<I>(it->second.impl);
|
||||
return m_parent ? m_parent->get<I>() : nullptr;
|
||||
}
|
||||
|
||||
/// Resolve I; throws std::runtime_error if not provided.
|
||||
@@ -79,8 +103,13 @@ namespace Void::Service
|
||||
|
||||
template <typename I> [[nodiscard]] bool has() const
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
return m_services.contains(std::type_index{typeid(I)});
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
if (m_services.contains(std::type_index{typeid(I)})) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return m_parent ? m_parent->has<I>() : false;
|
||||
}
|
||||
|
||||
/// Call on_start() on every lifecycle service, registration
|
||||
@@ -119,6 +148,7 @@ namespace Void::Service
|
||||
IService* service = nullptr; // non-null iff I : IService
|
||||
};
|
||||
|
||||
const ServiceRegistry* m_parent = nullptr;
|
||||
mutable std::shared_mutex m_mutex;
|
||||
std::unordered_map<std::type_index, Entry> m_services;
|
||||
std::vector<std::type_index> m_order;
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
|
||||
#if defined(__linux__)
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <sys/sysinfo.h>
|
||||
#include <sys/times.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
// Generic, app-agnostic process/system resource queries. Used to feed monitors
|
||||
// (e.g. Void::Resilience::ResourceMonitor) with real samples. Linux is fully
|
||||
// supported; other platforms return nullopt / 0 so callers degrade gracefully.
|
||||
|
||||
namespace Void::SystemInfo
|
||||
{
|
||||
|
||||
// ── memory ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// Resident set size (physical memory) of the current process, in bytes.
|
||||
/// nullopt if it cannot be determined on this platform.
|
||||
[[nodiscard]] inline std::optional<std::uint64_t> process_memory_bytes()
|
||||
{
|
||||
#if defined(__linux__)
|
||||
// /proc/self/statm: "size resident shared text lib data dt" in pages.
|
||||
std::ifstream statm{"/proc/self/statm"};
|
||||
std::uint64_t total_pages = 0, resident_pages = 0;
|
||||
if (statm >> total_pages >> resident_pages) {
|
||||
const long page = ::sysconf(_SC_PAGESIZE);
|
||||
if (page > 0) {
|
||||
return resident_pages * static_cast<std::uint64_t>(page);
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
#else
|
||||
return std::nullopt;
|
||||
#endif
|
||||
}
|
||||
|
||||
struct SystemMemory {
|
||||
std::uint64_t total = 0; ///< total physical RAM, bytes
|
||||
std::uint64_t available = 0; ///< approx. RAM available to new work
|
||||
};
|
||||
|
||||
/// Total and (approximately) available system memory in bytes.
|
||||
[[nodiscard]] inline std::optional<SystemMemory> system_memory()
|
||||
{
|
||||
#if defined(__linux__)
|
||||
struct ::sysinfo info{};
|
||||
if (::sysinfo(&info) != 0) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1;
|
||||
SystemMemory m;
|
||||
m.total = static_cast<std::uint64_t>(info.totalram) * unit;
|
||||
// freeram excludes reclaimable cache/buffers, so this is conservative.
|
||||
m.available =
|
||||
(static_cast<std::uint64_t>(info.freeram) + info.bufferram) * unit;
|
||||
return m;
|
||||
#else
|
||||
return std::nullopt;
|
||||
#endif
|
||||
}
|
||||
|
||||
// ── CPU ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Samples this process's CPU usage between successive calls. usage()
|
||||
/// returns the fraction of a single core consumed since the previous
|
||||
/// usage() call (0.0 = idle, 1.0 = one core saturated; may exceed 1.0 on
|
||||
/// multi-core workloads). The first call establishes the baseline and
|
||||
/// returns 0.
|
||||
class CpuSampler
|
||||
{
|
||||
public:
|
||||
|
||||
CpuSampler() { reset(); }
|
||||
|
||||
void reset()
|
||||
{
|
||||
wall_ = std::chrono::steady_clock::now();
|
||||
#if defined(__linux__)
|
||||
struct ::tms t{};
|
||||
last_ticks_ = (::times(&t) == static_cast<::clock_t>(-1))
|
||||
? 0
|
||||
: (t.tms_utime + t.tms_stime);
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] double usage()
|
||||
{
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
const std::chrono::duration<double> wall = now - wall_;
|
||||
wall_ = now;
|
||||
#if defined(__linux__)
|
||||
const long hz = ::sysconf(_SC_CLK_TCK);
|
||||
struct ::tms t{};
|
||||
if (hz <= 0 || ::times(&t) == static_cast<::clock_t>(-1) ||
|
||||
wall.count() <= 0.0) {
|
||||
return 0.0;
|
||||
}
|
||||
const std::int64_t ticks = t.tms_utime + t.tms_stime;
|
||||
const double cpu_seconds =
|
||||
static_cast<double>(ticks - last_ticks_) /
|
||||
static_cast<double>(hz);
|
||||
last_ticks_ = ticks;
|
||||
return cpu_seconds / wall.count();
|
||||
#else
|
||||
return 0.0;
|
||||
#endif
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::chrono::steady_clock::time_point wall_;
|
||||
#if defined(__linux__)
|
||||
std::int64_t last_ticks_ = 0;
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace Void::SystemInfo
|
||||
@@ -5,40 +5,62 @@
|
||||
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Process
|
||||
{
|
||||
|
||||
/// Captured output from a completed subprocess.
|
||||
struct Output {
|
||||
int exit_code{0};
|
||||
std::string out; ///< captured stdout
|
||||
std::string err; ///< captured stderr
|
||||
};
|
||||
/// Captured output from a completed subprocess.
|
||||
struct Output {
|
||||
int exit_code{0};
|
||||
std::string out; ///< captured stdout
|
||||
std::string err; ///< captured stderr
|
||||
};
|
||||
|
||||
/// Run an executable synchronously, capturing stdout and stderr separately.
|
||||
///
|
||||
/// @param executable Path to the binary (searched via PATH when relative).
|
||||
/// @param args Additional arguments passed after argv[0].
|
||||
/// @param stdin_data Data written to the process's stdin before reading.
|
||||
/// @param timeout Wall-clock limit; zero means no limit. On expiry the
|
||||
/// process receives SIGTERM and the call returns.
|
||||
///
|
||||
/// Returns an error only when process creation itself fails (pipe or fork
|
||||
/// failure). A process that exits non-zero still yields a successful Result
|
||||
/// with the appropriate exit_code. A process whose executable is not found
|
||||
/// exits with code 127 (POSIX convention).
|
||||
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
|
||||
run(const std::filesystem::path& executable,
|
||||
std::vector<std::string> args = {},
|
||||
std::string_view stdin_data = {},
|
||||
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
|
||||
/// Live line callbacks for run_streaming(). Each fires (on the calling
|
||||
/// thread, as output arrives) with one line of output, newline stripped.
|
||||
/// Either may be left empty. The full output is still accumulated into the
|
||||
/// returned Output.
|
||||
struct StreamCallbacks {
|
||||
std::function<void(std::string_view line)> on_stdout;
|
||||
std::function<void(std::string_view line)> on_stderr;
|
||||
};
|
||||
|
||||
/// Run a command through /bin/sh -c "command".
|
||||
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
|
||||
shell(std::string_view command,
|
||||
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
|
||||
/// Run an executable synchronously, capturing stdout and stderr separately.
|
||||
///
|
||||
/// @param executable Path to the binary (searched via PATH when relative).
|
||||
/// @param args Additional arguments passed after argv[0].
|
||||
/// @param stdin_data Data written to the process's stdin before reading.
|
||||
/// @param timeout Wall-clock limit; zero means no limit. On expiry the
|
||||
/// process receives SIGTERM and the call returns.
|
||||
///
|
||||
/// Returns an error only when process creation itself fails (pipe or fork
|
||||
/// failure). A process that exits non-zero still yields a successful Result
|
||||
/// with the appropriate exit_code. A process whose executable is not found
|
||||
/// exits with code 127 (POSIX convention).
|
||||
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
|
||||
run(const std::filesystem::path& executable,
|
||||
std::vector<std::string> args = {},
|
||||
std::string_view stdin_data = {},
|
||||
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
|
||||
|
||||
/// Like run(), but invokes `callbacks` line-by-line as stdout/stderr
|
||||
/// arrive, for progress reporting on long-running or streaming processes.
|
||||
/// The complete output is still captured into the returned Output.
|
||||
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
|
||||
run_streaming(
|
||||
const std::filesystem::path& executable,
|
||||
std::vector<std::string> args,
|
||||
const StreamCallbacks& callbacks,
|
||||
std::string_view stdin_data = {},
|
||||
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
|
||||
|
||||
/// Run a command through /bin/sh -c "command".
|
||||
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
|
||||
shell(std::string_view command,
|
||||
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
|
||||
|
||||
} // namespace Void::Process
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
// Reflection-readable test metadata. Annotate a suite's test methods:
|
||||
// struct MathTests : Void::Testing::Suite<MathTests> {
|
||||
// [[= Testing::tag("integration")]] Void::Testing::Test db() { … }
|
||||
// [[= Testing::skip("flaky #42")]] Void::Testing::Test wip() { … }
|
||||
// };
|
||||
// Multiple `tag(...)` annotations attach multiple tags. A `name(...)` on the
|
||||
// suite struct overrides its reported suite label (default: the struct name).
|
||||
|
||||
namespace Void::Testing
|
||||
{
|
||||
/// A test tag (repeatable).
|
||||
struct Tag {
|
||||
Void::Meta::Str value;
|
||||
};
|
||||
/// Mark a test skipped, with a reason.
|
||||
struct Skip {
|
||||
Void::Meta::Str reason;
|
||||
};
|
||||
/// Override a suite's reported label (annotate the suite struct).
|
||||
struct Name {
|
||||
Void::Meta::Str value;
|
||||
};
|
||||
|
||||
/// Annotation factories so tests read `[[= Testing::tag("x")]]`.
|
||||
[[nodiscard]] consteval Tag tag(const char* value) { return Tag{value}; }
|
||||
[[nodiscard]] consteval Skip skip(const char* reason)
|
||||
{
|
||||
return Skip{reason};
|
||||
}
|
||||
[[nodiscard]] consteval Name name(const char* value) { return Name{value}; }
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,175 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Testing/Annotations.hpp>
|
||||
#include <Void/Testing/Config.hpp>
|
||||
#include <Void/Testing/Detail/Registry.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
#include <meta>
|
||||
#define VOID_TESTING_HAS_REFLECTION 1
|
||||
#endif
|
||||
|
||||
// ── Reflection-based test registration
|
||||
// ──────────────────────────────────────── Derive a test suite from
|
||||
// `Suite<Derived>` (CRTP). Every public, 0-argument member function returning
|
||||
// `Test`/`DisabledTest` (i.e. void) — except `setup` and `teardown` — is
|
||||
// auto-registered as a test by reflecting `Derived`. No CMake scan, no macros,
|
||||
// no registrar line: a `[[gnu::used]]` static in the base forces registration
|
||||
// at program start even though the suite is never instantiated for its own
|
||||
// sake.
|
||||
//
|
||||
// struct MathTests : Void::Testing::Suite<MathTests> {
|
||||
// void setup() { … } // optional, per-test
|
||||
// Void::Testing::Test addition() { expect_eq(1 + 1, 2); }
|
||||
// [[= Testing::tag("slow")]] Void::Testing::Test big() { … }
|
||||
// [[= Testing::skip("wip")]] Void::Testing::Test later() { … }
|
||||
// };
|
||||
//
|
||||
// The suite label defaults to the struct's name; `[[= Testing::name("Math")]]`
|
||||
// on the struct overrides it.
|
||||
|
||||
namespace Void::Testing
|
||||
{
|
||||
|
||||
#ifdef VOID_TESTING_HAS_REFLECTION
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
namespace meta = std::meta;
|
||||
|
||||
/// A reflected member is a test if it is a public, non-special,
|
||||
/// 0-argument member function returning void, other than the
|
||||
/// setup/teardown lifecycle hooks.
|
||||
consteval bool is_test_method(meta::info m)
|
||||
{
|
||||
if (!meta::is_function(m) || meta::is_special_member_function(m)) {
|
||||
return false;
|
||||
}
|
||||
if (meta::is_static_member(m)) {
|
||||
return false;
|
||||
}
|
||||
if (meta::parameters_of(m).size() != 0) {
|
||||
return false;
|
||||
}
|
||||
if (meta::dealias(meta::return_type_of(m)) != ^^void) {
|
||||
return false;
|
||||
}
|
||||
const std::string_view id = meta::identifier_of(m);
|
||||
return id != "setup" && id != "teardown";
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
namespace meta = std::meta;
|
||||
|
||||
template <typename Derived> class Suite
|
||||
{
|
||||
protected:
|
||||
|
||||
Suite() = default;
|
||||
|
||||
private:
|
||||
|
||||
/// Run one reflected test method against a fresh Derived instance,
|
||||
/// wrapping it in setup()/teardown() when present.
|
||||
template <meta::info M> static void run_method()
|
||||
{
|
||||
Derived d{};
|
||||
if constexpr (requires { d.setup(); }) {
|
||||
d.setup();
|
||||
}
|
||||
try {
|
||||
d.[:M:]();
|
||||
} catch (...) {
|
||||
if constexpr (requires { d.teardown(); }) {
|
||||
d.teardown();
|
||||
}
|
||||
throw;
|
||||
}
|
||||
if constexpr (requires { d.teardown(); }) {
|
||||
d.teardown();
|
||||
}
|
||||
}
|
||||
|
||||
static std::string suite_label()
|
||||
{
|
||||
if constexpr (constexpr auto n =
|
||||
Void::Meta::annotation_of<Name>(^^Derived);
|
||||
n.has_value()) {
|
||||
return std::string{n->value.view()};
|
||||
} else {
|
||||
return Void::Meta::type_name<Derived>();
|
||||
}
|
||||
}
|
||||
|
||||
static void register_all()
|
||||
{
|
||||
auto& reg = Detail::Registry::instance();
|
||||
const std::string suite = suite_label();
|
||||
|
||||
template for (constexpr auto m :
|
||||
std::define_static_array(meta::members_of(
|
||||
^^Derived,
|
||||
meta::access_context::unchecked())))
|
||||
{
|
||||
if constexpr (Detail::is_test_method(m)) {
|
||||
constexpr auto loc = meta::source_location_of(m);
|
||||
|
||||
std::vector<std::string> tags;
|
||||
template for (constexpr auto a :
|
||||
std::define_static_array(
|
||||
meta::annotations_of_with_type(
|
||||
m, ^^Tag)))
|
||||
{
|
||||
constexpr Tag t = meta::extract<Tag>(a);
|
||||
tags.emplace_back(t.value.view());
|
||||
}
|
||||
|
||||
bool disabled = false;
|
||||
std::string skip_reason;
|
||||
if constexpr (constexpr auto s =
|
||||
Void::Meta::annotation_of<Skip>(m);
|
||||
s.has_value()) {
|
||||
disabled = true;
|
||||
skip_reason = std::string{s->reason.view()};
|
||||
}
|
||||
|
||||
reg.add(TestCase{
|
||||
.run = [] { run_method<m>(); },
|
||||
.name = std::string{meta::identifier_of(m)},
|
||||
.suite = suite,
|
||||
.file = loc.file_name(),
|
||||
.line = static_cast<int>(loc.line()),
|
||||
.disabled = disabled,
|
||||
.skip_reason = std::move(skip_reason),
|
||||
.tags = std::move(tags),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Registrar {
|
||||
Registrar() { register_all(); }
|
||||
};
|
||||
// Force the static initializer to run even though Derived is never
|
||||
// instantiated for its own sake (no test object, no registrar
|
||||
// line).
|
||||
[[gnu::used]] static inline Registrar _registrar{};
|
||||
};
|
||||
|
||||
#else // no reflection — Suite is unavailable; use the CMake scanner path
|
||||
|
||||
template <typename Derived> class Suite
|
||||
{
|
||||
protected:
|
||||
|
||||
Suite() = default;
|
||||
};
|
||||
|
||||
#endif // VOID_TESTING_HAS_REFLECTION
|
||||
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <concepts>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
#include <meta>
|
||||
#define VOID_MOCK_HAS_REFLECTION 1
|
||||
#endif
|
||||
|
||||
// ── Reflection helpers for mocking
|
||||
// ──────────────────────────────────────────── This toolchain's P2996 has rich
|
||||
// introspection + define_aggregate (it can even generate a MockFunction<Sig>
|
||||
// data member per interface virtual), but it has NO code injection, so the
|
||||
// virtual *override functions* a full auto-mock needs cannot be synthesized.
|
||||
// These helpers therefore cover the achievable ground: list an interface's
|
||||
// virtual methods and statically check a hand-written mock implements all of
|
||||
// them.
|
||||
|
||||
namespace Void::TestingMock
|
||||
{
|
||||
|
||||
#ifdef VOID_MOCK_HAS_REFLECTION
|
||||
|
||||
namespace meta = std::meta;
|
||||
|
||||
/// The identifiers of every virtual member function of interface `I`
|
||||
/// (excluding the destructor), in declaration order.
|
||||
template <typename I> [[nodiscard]] std::vector<std::string> method_names()
|
||||
{
|
||||
std::vector<std::string> out;
|
||||
template for (constexpr auto m :
|
||||
std::define_static_array(meta::members_of(
|
||||
^^I, meta::access_context::unchecked())))
|
||||
{
|
||||
if constexpr (meta::is_function(m) && meta::is_virtual(m) &&
|
||||
!meta::is_destructor(m)) {
|
||||
out.emplace_back(meta::identifier_of(m));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Number of virtual methods (excluding the destructor) on `I`.
|
||||
template <typename I> [[nodiscard]] consteval std::size_t method_count()
|
||||
{
|
||||
std::size_t n = 0;
|
||||
template for (constexpr auto m :
|
||||
std::define_static_array(meta::members_of(
|
||||
^^I, meta::access_context::unchecked())))
|
||||
{
|
||||
if constexpr (meta::is_function(m) && meta::is_virtual(m) &&
|
||||
!meta::is_destructor(m)) {
|
||||
++n;
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/// True if `Mock` is a complete, instantiable implementation of interface
|
||||
/// `I` — i.e. it derives `I` and overrides every pure-virtual method (so no
|
||||
/// abstract methods remain). A compile-time completeness check:
|
||||
/// static_assert(TestingMock::covers<MockDb, IDatabase>());
|
||||
template <typename Mock, typename I> [[nodiscard]] consteval bool covers()
|
||||
{
|
||||
return std::derived_from<Mock, I> && !std::is_abstract_v<Mock>;
|
||||
}
|
||||
|
||||
#endif // VOID_MOCK_HAS_REFLECTION
|
||||
|
||||
} // namespace Void::TestingMock
|
||||
+177
-82
@@ -1,106 +1,201 @@
|
||||
#pragma once
|
||||
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <format>
|
||||
#include <optional>
|
||||
#include <ratio>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
|
||||
namespace Void::Time
|
||||
{
|
||||
|
||||
/// Format a duration as a compact human-readable string.
|
||||
///
|
||||
/// Examples:
|
||||
/// 350ns → "350ns"
|
||||
/// 4500ns → "4.5µs"
|
||||
/// 2300µs → "2.3ms"
|
||||
/// 1500ms → "1.5s"
|
||||
/// 90s → "1m 30s"
|
||||
/// 5400s → "1h 30m"
|
||||
[[nodiscard]] inline std::string
|
||||
format_duration(std::chrono::nanoseconds d) noexcept
|
||||
{
|
||||
const auto ns = d.count();
|
||||
if (ns < 0) {
|
||||
return "0ns";
|
||||
}
|
||||
if (ns < 1'000) {
|
||||
return std::format("{}ns", ns);
|
||||
}
|
||||
if (ns < 1'000'000) {
|
||||
const double us = static_cast<double>(ns) / 1'000.0;
|
||||
if (us < 10.0) {
|
||||
return std::format("{:.1f}\xc2\xb5s", us); // µs in UTF-8
|
||||
/// Format a duration as a compact human-readable string.
|
||||
///
|
||||
/// Examples:
|
||||
/// 350ns → "350ns"
|
||||
/// 4500ns → "4.5µs"
|
||||
/// 2300µs → "2.3ms"
|
||||
/// 1500ms → "1.5s"
|
||||
/// 90s → "1m 30s"
|
||||
/// 5400s → "1h 30m"
|
||||
[[nodiscard]] inline std::string
|
||||
format_duration(std::chrono::nanoseconds d) noexcept
|
||||
{
|
||||
const auto ns = d.count();
|
||||
if (ns < 0) {
|
||||
return "0ns";
|
||||
}
|
||||
return std::format("{:.0f}\xc2\xb5s", us);
|
||||
}
|
||||
if (ns < 1'000'000'000LL) {
|
||||
const double ms = static_cast<double>(ns) / 1'000'000.0;
|
||||
if (ms < 10.0) {
|
||||
return std::format("{:.1f}ms", ms);
|
||||
if (ns < 1'000) {
|
||||
return std::format("{}ns", ns);
|
||||
}
|
||||
return std::format("{:.0f}ms", ms);
|
||||
if (ns < 1'000'000) {
|
||||
const double us = static_cast<double>(ns) / 1'000.0;
|
||||
if (us < 10.0) {
|
||||
return std::format("{:.1f}\xc2\xb5s", us); // µs in UTF-8
|
||||
}
|
||||
return std::format("{:.0f}\xc2\xb5s", us);
|
||||
}
|
||||
if (ns < 1'000'000'000LL) {
|
||||
const double ms = static_cast<double>(ns) / 1'000'000.0;
|
||||
if (ms < 10.0) {
|
||||
return std::format("{:.1f}ms", ms);
|
||||
}
|
||||
return std::format("{:.0f}ms", ms);
|
||||
}
|
||||
const long long total_s =
|
||||
std::chrono::duration_cast<std::chrono::seconds>(d).count();
|
||||
if (total_s < 60) {
|
||||
const double s = static_cast<double>(ns) / 1'000'000'000.0;
|
||||
return std::format("{:.1f}s", s);
|
||||
}
|
||||
if (total_s < 3600) {
|
||||
const long long m = total_s / 60;
|
||||
const long long s = total_s % 60;
|
||||
return std::format("{}m {}s", m, s);
|
||||
}
|
||||
const long long h = total_s / 3600;
|
||||
const long long m = (total_s % 3600) / 60;
|
||||
return std::format("{}h {}m", h, m);
|
||||
}
|
||||
const long long total_s =
|
||||
std::chrono::duration_cast<std::chrono::seconds>(d).count();
|
||||
if (total_s < 60) {
|
||||
const double s = static_cast<double>(ns) / 1'000'000'000.0;
|
||||
return std::format("{:.1f}s", s);
|
||||
}
|
||||
if (total_s < 3600) {
|
||||
const long long m = total_s / 60;
|
||||
const long long s = total_s % 60;
|
||||
return std::format("{}m {}s", m, s);
|
||||
}
|
||||
const long long h = total_s / 3600;
|
||||
const long long m = (total_s % 3600) / 60;
|
||||
return std::format("{}h {}m", h, m);
|
||||
}
|
||||
|
||||
/// Format any chrono duration via the nanosecond overload.
|
||||
template <typename Rep, typename Period>
|
||||
[[nodiscard]] std::string
|
||||
format_duration(std::chrono::duration<Rep, Period> d) noexcept
|
||||
{
|
||||
return format_duration(
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(d));
|
||||
}
|
||||
/// Format any chrono duration via the nanosecond overload.
|
||||
template <typename Rep, typename Period>
|
||||
[[nodiscard]] std::string
|
||||
format_duration(std::chrono::duration<Rep, Period> d) noexcept
|
||||
{
|
||||
return format_duration(
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(d));
|
||||
}
|
||||
|
||||
/// Return the current UTC time formatted as ISO 8601 with second precision.
|
||||
/// Example: "2026-05-14T10:30:00Z"
|
||||
[[nodiscard]] inline std::string utc_now_iso8601()
|
||||
{
|
||||
const auto now =
|
||||
std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
|
||||
std::tm tm{};
|
||||
/// Parse a single-unit duration string into nanoseconds.
|
||||
///
|
||||
/// Grammar: a number (integer or floating) followed by one of the suffixes
|
||||
/// `ns`, `us`, `ms`, `s`, `m`, `h`. An empty suffix is treated as seconds.
|
||||
/// Returns nullopt on any malformed input. This is the one source of truth
|
||||
/// for duration parsing — Configuration and Json reflection both route
|
||||
/// through it.
|
||||
[[nodiscard]] inline std::optional<std::chrono::nanoseconds>
|
||||
parse_duration(std::string_view raw)
|
||||
{
|
||||
double number = 0;
|
||||
const char* begin = raw.data();
|
||||
const char* end = raw.data() + raw.size();
|
||||
const auto [ptr, ec] = std::from_chars(begin, end, number);
|
||||
if (ec != std::errc{} || ptr == begin) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::string_view suffix{ptr, end};
|
||||
using namespace std::chrono;
|
||||
const auto as_ns = [&](auto unit) {
|
||||
return std::optional{duration_cast<nanoseconds>(
|
||||
duration<double, typename decltype(unit)::period>{number})};
|
||||
};
|
||||
if (suffix == "ns") {
|
||||
return as_ns(nanoseconds{});
|
||||
}
|
||||
if (suffix == "us") {
|
||||
return as_ns(microseconds{});
|
||||
}
|
||||
if (suffix == "ms") {
|
||||
return as_ns(milliseconds{});
|
||||
}
|
||||
if (suffix == "s" || suffix.empty()) {
|
||||
return as_ns(seconds{});
|
||||
}
|
||||
if (suffix == "m") {
|
||||
return as_ns(minutes{});
|
||||
}
|
||||
if (suffix == "h") {
|
||||
return as_ns(hours{});
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
/// The parse_duration suffix for a duration period, when it maps to a
|
||||
/// known single unit; nullopt for non-standard periods.
|
||||
template <class Period>
|
||||
[[nodiscard]] constexpr std::optional<std::string_view>
|
||||
duration_suffix()
|
||||
{
|
||||
if constexpr (std::is_same_v<Period, std::nano>) {
|
||||
return "ns";
|
||||
} else if constexpr (std::is_same_v<Period, std::micro>) {
|
||||
return "us";
|
||||
} else if constexpr (std::is_same_v<Period, std::milli>) {
|
||||
return "ms";
|
||||
} else if constexpr (std::is_same_v<Period, std::ratio<1>>) {
|
||||
return "s";
|
||||
} else if constexpr (std::is_same_v<Period, std::ratio<60>>) {
|
||||
return "m";
|
||||
} else if constexpr (std::is_same_v<Period, std::ratio<3600>>) {
|
||||
return "h";
|
||||
} else {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
/// Emit a duration as a canonical, round-trippable single-unit string that
|
||||
/// parse_duration accepts (e.g. milliseconds{250} -> "250ms"). The
|
||||
/// duration's own period is used when it is one of the standard chrono
|
||||
/// aliases; any other period falls back to a nanosecond count ("<n>ns"),
|
||||
/// which is exact for the realistic cases. The inverse of parse_duration
|
||||
/// for the standard aliases.
|
||||
template <class Rep, class Period>
|
||||
[[nodiscard]] std::string
|
||||
duration_to_string(std::chrono::duration<Rep, Period> d)
|
||||
{
|
||||
constexpr auto suffix = Detail::duration_suffix<Period>();
|
||||
if constexpr (suffix.has_value()) {
|
||||
return std::format("{}{}", d.count(), *suffix);
|
||||
} else {
|
||||
const auto ns =
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(d);
|
||||
return std::format("{}ns", ns.count());
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the current UTC time formatted as ISO 8601 with second precision.
|
||||
/// Example: "2026-05-14T10:30:00Z"
|
||||
[[nodiscard]] inline std::string utc_now_iso8601()
|
||||
{
|
||||
const auto now = std::chrono::system_clock::to_time_t(
|
||||
std::chrono::system_clock::now());
|
||||
std::tm tm{};
|
||||
#ifdef _WIN32
|
||||
gmtime_s(&tm, &now);
|
||||
gmtime_s(&tm, &now);
|
||||
#else
|
||||
gmtime_r(&now, &tm);
|
||||
gmtime_r(&now, &tm);
|
||||
#endif
|
||||
return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
|
||||
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
|
||||
tm.tm_hour, tm.tm_min, tm.tm_sec);
|
||||
}
|
||||
return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
|
||||
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
|
||||
tm.tm_hour, tm.tm_min, tm.tm_sec);
|
||||
}
|
||||
|
||||
/// Return the current UTC time formatted as ISO 8601 with millisecond precision.
|
||||
/// Example: "2026-05-14T10:30:00.123Z"
|
||||
[[nodiscard]] inline std::string utc_now_iso8601_ms()
|
||||
{
|
||||
const auto now_tp = std::chrono::system_clock::now();
|
||||
const auto now_t = std::chrono::system_clock::to_time_t(now_tp);
|
||||
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
now_tp.time_since_epoch()) %
|
||||
1000;
|
||||
std::tm tm{};
|
||||
/// Return the current UTC time formatted as ISO 8601 with millisecond
|
||||
/// precision. Example: "2026-05-14T10:30:00.123Z"
|
||||
[[nodiscard]] inline std::string utc_now_iso8601_ms()
|
||||
{
|
||||
const auto now_tp = std::chrono::system_clock::now();
|
||||
const auto now_t = std::chrono::system_clock::to_time_t(now_tp);
|
||||
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
now_tp.time_since_epoch()) %
|
||||
1000;
|
||||
std::tm tm{};
|
||||
#ifdef _WIN32
|
||||
gmtime_s(&tm, &now_t);
|
||||
gmtime_s(&tm, &now_t);
|
||||
#else
|
||||
gmtime_r(&now_t, &tm);
|
||||
gmtime_r(&now_t, &tm);
|
||||
#endif
|
||||
return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
|
||||
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
|
||||
tm.tm_hour, tm.tm_min, tm.tm_sec, ms.count());
|
||||
}
|
||||
return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
|
||||
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
|
||||
tm.tm_hour, tm.tm_min, tm.tm_sec, ms.count());
|
||||
}
|
||||
|
||||
} // namespace Void::Time
|
||||
Reference in new issue
Block a user