Restructure into umbrella modules (~55 -> 16 targets)
Headers move, CMake targets merge, C++ namespaces stay unchanged: - Core: Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant - Functional: Pipeline, Either, Result, Retry - Containers: Ring, Pool, PriorityQueue, LRU, Trie, Graph, DisjointSet, Bitset, Interval - Math: +Matrix, Numeric, Random, Histogram - Text: Str, Format, Tokenizer, Diff, Encoding, Semver - Data: Json, Csv, Ini - Async: Coro, Concurrency, EventBus, Observable - Time: +Bench - Log: Log facade + Logging framework (facade now header-only, breaking the Stacktrace<->Log link cycle the merge would have created) - System: FileSystem + Process - Configuration: +Argparse - Unchanged: Stacktrace, Plugin, StateMachine, Testing, TestingMock, Detail Module system fixes: - OPTIONAL_DEPS resolution deferred to void_finalize_modules() so it no longer depends on the alphabetical discovery order of src/ subdirs (Testing -> Text would have been silently dropped). - Every header-only module now has a tracked module.cmake; previously the empty src/<Name> marker dirs were untracked, so a fresh clone would have silently skipped those modules. - VOID_HAS_LOGGING/CONCURRENCY/STR consumers renamed to LOG/ASYNC/TEXT. Tests move to tests/standalone/<Umbrella>/<Feature>.cpp (Result suite files prefixed: ResultBasic etc.). Test count verified identical (831) before and after. README/CLAUDE.md module tables updated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
da2e93c405
commit
28b94883fd
156 files changed
+278
-220
No files matched your search
@@ -0,0 +1,219 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
namespace Void::Bitset
|
||||
{
|
||||
|
||||
// ── Bitset<N> ─────────────────────────────────────────────────────────────────
|
||||
// Fixed-size bitset stored as an array of uint64_t words.
|
||||
// All operations are O(N/64).
|
||||
|
||||
template <std::size_t N>
|
||||
class Bitset
|
||||
{
|
||||
static constexpr std::size_t Words = (N + 63) / 64;
|
||||
|
||||
public:
|
||||
constexpr Bitset() noexcept { words_.fill(0); }
|
||||
|
||||
// Set bit at position (throws if out of range).
|
||||
constexpr Bitset& set(std::size_t pos)
|
||||
{
|
||||
check(pos);
|
||||
words_[pos / 64] |= mask(pos);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Clear bit at position.
|
||||
constexpr Bitset& reset(std::size_t pos)
|
||||
{
|
||||
check(pos);
|
||||
words_[pos / 64] &= ~mask(pos);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Flip bit at position.
|
||||
constexpr Bitset& flip(std::size_t pos)
|
||||
{
|
||||
check(pos);
|
||||
words_[pos / 64] ^= mask(pos);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Test bit at position.
|
||||
[[nodiscard]] constexpr bool test(std::size_t pos) const
|
||||
{
|
||||
check(pos);
|
||||
return (words_[pos / 64] & mask(pos)) != 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool operator[](std::size_t pos) const { return test(pos); }
|
||||
|
||||
// Set / clear / flip all bits.
|
||||
constexpr Bitset& set_all() noexcept { for (auto& w : words_) w = ~uint64_t{0}; trim(); return *this; }
|
||||
constexpr Bitset& reset_all() noexcept { words_.fill(0); return *this; }
|
||||
constexpr Bitset& flip_all() noexcept { for (auto& w : words_) w = ~w; trim(); return *this; }
|
||||
|
||||
// Count of set bits.
|
||||
[[nodiscard]] constexpr std::size_t count() const noexcept
|
||||
{
|
||||
std::size_t n = 0;
|
||||
for (auto w : words_) n += popcount(w);
|
||||
return n;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool none() const noexcept
|
||||
{
|
||||
for (auto w : words_) if (w) return false;
|
||||
return true;
|
||||
}
|
||||
[[nodiscard]] constexpr bool any() const noexcept { return !none(); }
|
||||
[[nodiscard]] constexpr bool all() const noexcept { return count() == N; }
|
||||
|
||||
static constexpr std::size_t size() noexcept { return N; }
|
||||
|
||||
// ── bitwise ops ───────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr Bitset operator&(const Bitset& o) const noexcept
|
||||
{
|
||||
Bitset r;
|
||||
for (std::size_t i = 0; i < Words; ++i) r.words_[i] = words_[i] & o.words_[i];
|
||||
return r;
|
||||
}
|
||||
[[nodiscard]] constexpr Bitset operator|(const Bitset& o) const noexcept
|
||||
{
|
||||
Bitset r;
|
||||
for (std::size_t i = 0; i < Words; ++i) r.words_[i] = words_[i] | o.words_[i];
|
||||
return r;
|
||||
}
|
||||
[[nodiscard]] constexpr Bitset operator^(const Bitset& o) const noexcept
|
||||
{
|
||||
Bitset r;
|
||||
for (std::size_t i = 0; i < Words; ++i) r.words_[i] = words_[i] ^ o.words_[i];
|
||||
return r;
|
||||
}
|
||||
[[nodiscard]] constexpr Bitset operator~() const noexcept
|
||||
{
|
||||
Bitset r = *this;
|
||||
r.flip_all();
|
||||
return r;
|
||||
}
|
||||
|
||||
constexpr Bitset& operator&=(const Bitset& o) noexcept
|
||||
{
|
||||
for (std::size_t i = 0; i < Words; ++i) words_[i] &= o.words_[i];
|
||||
return *this;
|
||||
}
|
||||
constexpr Bitset& operator|=(const Bitset& o) noexcept
|
||||
{
|
||||
for (std::size_t i = 0; i < Words; ++i) words_[i] |= o.words_[i];
|
||||
return *this;
|
||||
}
|
||||
constexpr Bitset& operator^=(const Bitset& o) noexcept
|
||||
{
|
||||
for (std::size_t i = 0; i < Words; ++i) words_[i] ^= o.words_[i];
|
||||
return *this;
|
||||
}
|
||||
|
||||
// ── shift ─────────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr Bitset operator<<(std::size_t shift) const noexcept
|
||||
{
|
||||
if (shift >= N) return Bitset{};
|
||||
Bitset r;
|
||||
const std::size_t word_shift = shift / 64;
|
||||
const std::size_t bit_shift = shift % 64;
|
||||
for (std::size_t i = Words; i-- > 0;) {
|
||||
if (i >= word_shift)
|
||||
r.words_[i] = words_[i - word_shift] << bit_shift;
|
||||
if (bit_shift && i > word_shift)
|
||||
r.words_[i] |= words_[i - word_shift - 1] >> (64 - bit_shift);
|
||||
}
|
||||
r.trim();
|
||||
return r;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Bitset operator>>(std::size_t shift) const noexcept
|
||||
{
|
||||
if (shift >= N) return Bitset{};
|
||||
Bitset r;
|
||||
const std::size_t word_shift = shift / 64;
|
||||
const std::size_t bit_shift = shift % 64;
|
||||
for (std::size_t i = 0; i < Words; ++i) {
|
||||
if (i + word_shift < Words)
|
||||
r.words_[i] = words_[i + word_shift] >> bit_shift;
|
||||
if (bit_shift && i + word_shift + 1 < Words)
|
||||
r.words_[i] |= words_[i + word_shift + 1] << (64 - bit_shift);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
// ── comparison ────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr bool operator==(const Bitset& o) const noexcept
|
||||
{
|
||||
return words_ == o.words_;
|
||||
}
|
||||
[[nodiscard]] constexpr bool operator!=(const Bitset& o) const noexcept
|
||||
{
|
||||
return !(*this == o);
|
||||
}
|
||||
|
||||
// ── string conversion ─────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] std::string to_string() const
|
||||
{
|
||||
std::string s(N, '0');
|
||||
for (std::size_t i = 0; i < N; ++i)
|
||||
if (test(N - 1 - i)) s[i] = '1';
|
||||
return s;
|
||||
}
|
||||
|
||||
// ── index of first set bit (-1 if none) ──────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr std::size_t find_first() const noexcept
|
||||
{
|
||||
for (std::size_t w = 0; w < Words; ++w) {
|
||||
if (words_[w] == 0) continue;
|
||||
return w * 64 + ctz(words_[w]);
|
||||
}
|
||||
return N; // sentinel: no bit set
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<std::uint64_t, Words> words_;
|
||||
|
||||
static constexpr std::uint64_t mask(std::size_t pos) noexcept
|
||||
{
|
||||
return std::uint64_t{1} << (pos % 64);
|
||||
}
|
||||
|
||||
constexpr void check(std::size_t pos) const
|
||||
{
|
||||
if (pos >= N) throw std::out_of_range{"Bitset: position out of range"};
|
||||
}
|
||||
|
||||
// Clear bits above N in the last word.
|
||||
constexpr void trim() noexcept
|
||||
{
|
||||
if constexpr (N % 64 != 0)
|
||||
words_[Words - 1] &= (std::uint64_t{1} << (N % 64)) - 1;
|
||||
}
|
||||
|
||||
static constexpr std::size_t popcount(std::uint64_t w) noexcept
|
||||
{
|
||||
return static_cast<std::size_t>(__builtin_popcountll(w));
|
||||
}
|
||||
|
||||
static constexpr std::size_t ctz(std::uint64_t w) noexcept
|
||||
{
|
||||
return static_cast<std::size_t>(__builtin_ctzll(w));
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::Bitset
|
||||
@@ -0,0 +1,92 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <numeric>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::DisjointSet
|
||||
{
|
||||
|
||||
// ── DisjointSet ───────────────────────────────────────────────────────────────
|
||||
// Union-Find with path compression and union by rank.
|
||||
// Elements are integers in [0, n). O(α(n)) per operation (inverse Ackermann).
|
||||
//
|
||||
// DisjointSet ds{5};
|
||||
// ds.unite(0, 1);
|
||||
// ds.unite(1, 2);
|
||||
// ds.connected(0, 2); // true
|
||||
// ds.count(); // 3 components (0-1-2, 3, 4)
|
||||
|
||||
class DisjointSet
|
||||
{
|
||||
public:
|
||||
explicit DisjointSet(std::size_t n)
|
||||
: parent_(n), rank_(n, 0), component_count_{n}
|
||||
{
|
||||
std::iota(parent_.begin(), parent_.end(), std::size_t{0});
|
||||
}
|
||||
|
||||
// Find root of element x (with path compression).
|
||||
[[nodiscard]] std::size_t find(std::size_t x)
|
||||
{
|
||||
check(x);
|
||||
if (parent_[x] != x)
|
||||
parent_[x] = find(parent_[x]);
|
||||
return parent_[x];
|
||||
}
|
||||
|
||||
// Merge the components containing x and y.
|
||||
// Returns true if they were in different components.
|
||||
bool unite(std::size_t x, std::size_t y)
|
||||
{
|
||||
check(x); check(y);
|
||||
const std::size_t rx = find(x);
|
||||
const std::size_t ry = find(y);
|
||||
if (rx == ry) return false;
|
||||
if (rank_[rx] < rank_[ry]) {
|
||||
parent_[rx] = ry;
|
||||
} else if (rank_[rx] > rank_[ry]) {
|
||||
parent_[ry] = rx;
|
||||
} else {
|
||||
parent_[ry] = rx;
|
||||
++rank_[rx];
|
||||
}
|
||||
--component_count_;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool connected(std::size_t x, std::size_t y)
|
||||
{
|
||||
return find(x) == find(y);
|
||||
}
|
||||
|
||||
// Number of disjoint components.
|
||||
[[nodiscard]] std::size_t count() const noexcept { return component_count_; }
|
||||
|
||||
// Total number of elements.
|
||||
[[nodiscard]] std::size_t size() const noexcept { return parent_.size(); }
|
||||
|
||||
// Component size of the component containing x.
|
||||
[[nodiscard]] std::size_t component_size(std::size_t x)
|
||||
{
|
||||
const std::size_t root = find(x);
|
||||
std::size_t n = 0;
|
||||
for (std::size_t i = 0; i < parent_.size(); ++i)
|
||||
if (find(i) == root) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<std::size_t> parent_;
|
||||
std::vector<std::size_t> rank_;
|
||||
std::size_t component_count_;
|
||||
|
||||
void check(std::size_t x) const
|
||||
{
|
||||
if (x >= parent_.size())
|
||||
throw std::out_of_range{"DisjointSet: index out of range"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::DisjointSet
|
||||
@@ -0,0 +1,205 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <ranges>
|
||||
#include <span>
|
||||
#include <stdexcept>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Graph
|
||||
{
|
||||
|
||||
// ── DiGraph<V, E> ─────────────────────────────────────────────────────────────
|
||||
// Directed graph with vertex labels of type V and edge weights of type E.
|
||||
// Vertices are identified by a user-supplied key of type V (must be hashable).
|
||||
|
||||
template <typename V, typename E = int>
|
||||
class DiGraph
|
||||
{
|
||||
public:
|
||||
struct Edge
|
||||
{
|
||||
V to;
|
||||
E weight;
|
||||
};
|
||||
|
||||
void add_vertex(const V& v) { adj_[v]; }
|
||||
|
||||
void add_edge(const V& from, const V& to, E weight = E{})
|
||||
{
|
||||
adj_[from].push_back({to, weight});
|
||||
adj_.try_emplace(to);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool has_vertex(const V& v) const
|
||||
{
|
||||
return adj_.contains(v);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool has_edge(const V& from, const V& to) const
|
||||
{
|
||||
auto it = adj_.find(from);
|
||||
if (it == adj_.end()) return false;
|
||||
return std::ranges::any_of(it->second,
|
||||
[&](const Edge& e) { return e.to == to; });
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::vector<Edge>& neighbors(const V& v) const
|
||||
{
|
||||
return adj_.at(v);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t vertex_count() const noexcept
|
||||
{
|
||||
return adj_.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t edge_count() const noexcept
|
||||
{
|
||||
std::size_t n = 0;
|
||||
for (const auto& [_, edges] : adj_) n += edges.size();
|
||||
return n;
|
||||
}
|
||||
|
||||
// ── BFS ──────────────────────────────────────────────────────────────────
|
||||
|
||||
void bfs(const V& start,
|
||||
std::function<void(const V&)> visit) const
|
||||
{
|
||||
if (!adj_.contains(start)) return;
|
||||
std::unordered_set<V> visited;
|
||||
std::queue<V> q;
|
||||
visited.insert(start);
|
||||
q.push(start);
|
||||
while (!q.empty()) {
|
||||
const V cur = q.front(); q.pop();
|
||||
visit(cur);
|
||||
for (const auto& e : adj_.at(cur)) {
|
||||
if (!visited.contains(e.to)) {
|
||||
visited.insert(e.to);
|
||||
q.push(e.to);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<V> bfs_order(const V& start) const
|
||||
{
|
||||
std::vector<V> result;
|
||||
bfs(start, [&](const V& v) { result.push_back(v); });
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── DFS ──────────────────────────────────────────────────────────────────
|
||||
|
||||
void dfs(const V& start,
|
||||
std::function<void(const V&)> visit) const
|
||||
{
|
||||
std::unordered_set<V> visited;
|
||||
dfs_impl(start, visited, visit);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<V> dfs_order(const V& start) const
|
||||
{
|
||||
std::vector<V> result;
|
||||
dfs(start, [&](const V& v) { result.push_back(v); });
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── Topological sort (Kahn's algorithm) ──────────────────────────────────
|
||||
// Returns nullopt if the graph has a cycle.
|
||||
|
||||
[[nodiscard]] std::optional<std::vector<V>> topological_sort() const
|
||||
{
|
||||
std::unordered_map<V, int> in_degree;
|
||||
for (const auto& [v, _] : adj_) in_degree[v] = 0;
|
||||
for (const auto& [v, edges] : adj_) {
|
||||
for (const auto& e : edges) in_degree[e.to]++;
|
||||
}
|
||||
|
||||
std::queue<V> q;
|
||||
for (const auto& [v, deg] : in_degree) {
|
||||
if (deg == 0) q.push(v);
|
||||
}
|
||||
|
||||
std::vector<V> order;
|
||||
while (!q.empty()) {
|
||||
V cur = q.front(); q.pop();
|
||||
order.push_back(cur);
|
||||
for (const auto& e : adj_.at(cur)) {
|
||||
if (--in_degree[e.to] == 0) q.push(e.to);
|
||||
}
|
||||
}
|
||||
|
||||
if (order.size() != adj_.size()) return std::nullopt; // cycle
|
||||
return order;
|
||||
}
|
||||
|
||||
// ── Reachability ─────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] bool can_reach(const V& from, const V& to) const
|
||||
{
|
||||
bool found = false;
|
||||
bfs(from, [&](const V& v) { if (v == to) found = true; });
|
||||
return found;
|
||||
}
|
||||
|
||||
// ── Shortest path (BFS, unweighted) ──────────────────────────────────────
|
||||
|
||||
[[nodiscard]] std::optional<std::vector<V>>
|
||||
shortest_path(const V& from, const V& to) const
|
||||
{
|
||||
if (!adj_.contains(from) || !adj_.contains(to)) return std::nullopt;
|
||||
std::unordered_map<V, V> parent;
|
||||
std::unordered_set<V> visited;
|
||||
std::queue<V> q;
|
||||
visited.insert(from);
|
||||
q.push(from);
|
||||
bool found = false;
|
||||
while (!q.empty() && !found) {
|
||||
V cur = q.front(); q.pop();
|
||||
for (const auto& e : adj_.at(cur)) {
|
||||
if (!visited.contains(e.to)) {
|
||||
visited.insert(e.to);
|
||||
parent[e.to] = cur;
|
||||
if (e.to == to) { found = true; break; }
|
||||
q.push(e.to);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!found && from != to) return std::nullopt;
|
||||
std::vector<V> path;
|
||||
V cur = to;
|
||||
while (cur != from) {
|
||||
path.push_back(cur);
|
||||
cur = parent.at(cur);
|
||||
}
|
||||
path.push_back(from);
|
||||
std::ranges::reverse(path);
|
||||
return path;
|
||||
}
|
||||
|
||||
private:
|
||||
void dfs_impl(const V& v, std::unordered_set<V>& visited,
|
||||
std::function<void(const V&)>& visit) const
|
||||
{
|
||||
if (visited.contains(v)) return;
|
||||
visited.insert(v);
|
||||
visit(v);
|
||||
if (adj_.contains(v)) {
|
||||
for (const auto& e : adj_.at(v)) {
|
||||
dfs_impl(e.to, visited, visit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::unordered_map<V, std::vector<Edge>> adj_;
|
||||
};
|
||||
|
||||
} // namespace Void::Graph
|
||||
@@ -0,0 +1,92 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <concepts>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Void::Interval
|
||||
{
|
||||
|
||||
// ── Interval<T> ───────────────────────────────────────────────────────────────
|
||||
// Half-open [lo, hi) interval. T must be totally ordered.
|
||||
|
||||
template <std::totally_ordered T>
|
||||
struct Interval
|
||||
{
|
||||
T lo{};
|
||||
T hi{};
|
||||
|
||||
// Construct [lo, hi). Throws if lo > hi.
|
||||
constexpr Interval(T lo_, T hi_) : lo{std::move(lo_)}, hi{std::move(hi_)}
|
||||
{
|
||||
if (lo > hi) throw std::invalid_argument{"Interval: lo > hi"};
|
||||
}
|
||||
|
||||
// ── query ─────────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr bool contains(const T& v) const noexcept
|
||||
{
|
||||
return v >= lo && v < hi;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool contains_closed(const T& v) const noexcept
|
||||
{
|
||||
return v >= lo && v <= hi;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool empty() const noexcept { return lo >= hi; }
|
||||
|
||||
[[nodiscard]] constexpr auto length() const { return hi - lo; }
|
||||
|
||||
[[nodiscard]] constexpr bool overlaps(const Interval& o) const noexcept
|
||||
{
|
||||
return lo < o.hi && o.lo < hi;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool adjacent(const Interval& o) const noexcept
|
||||
{
|
||||
return hi == o.lo || o.hi == lo;
|
||||
}
|
||||
|
||||
// ── set operations ────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr Interval hull(const Interval& o) const noexcept
|
||||
{
|
||||
return Interval{std::min(lo, o.lo), std::max(hi, o.hi)};
|
||||
}
|
||||
|
||||
// Returns the intersection, or an empty [lo,lo) if disjoint.
|
||||
[[nodiscard]] constexpr Interval intersection(const Interval& o) const noexcept
|
||||
{
|
||||
const T new_lo = std::max(lo, o.lo);
|
||||
const T new_hi = std::min(hi, o.hi);
|
||||
if (new_lo >= new_hi) return Interval{lo, lo};
|
||||
return Interval{new_lo, new_hi};
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr T clamp(const T& v) const noexcept
|
||||
{
|
||||
return std::clamp(v, lo, hi);
|
||||
}
|
||||
|
||||
// ── comparison ────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr bool operator==(const Interval&) const noexcept = default;
|
||||
};
|
||||
|
||||
// ── factory helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
template <std::totally_ordered T>
|
||||
[[nodiscard]] constexpr Interval<T> make_interval(T lo, T hi)
|
||||
{
|
||||
return Interval<T>{std::move(lo), std::move(hi)};
|
||||
}
|
||||
|
||||
// Closed [lo, hi] interval as [lo, hi+1) — only safe for integer types.
|
||||
template <std::integral T>
|
||||
[[nodiscard]] constexpr Interval<T> closed(T lo, T hi)
|
||||
{
|
||||
return Interval<T>{lo, static_cast<T>(hi + 1)};
|
||||
}
|
||||
|
||||
} // namespace Void::Interval
|
||||
@@ -0,0 +1,99 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <list>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::LRU
|
||||
{
|
||||
|
||||
// ── LruCache<K, V> ────────────────────────────────────────────────────────────
|
||||
// Fixed-capacity LRU cache. get() promotes to MRU; put() evicts LRU when full.
|
||||
// All operations are O(1) amortized via a doubly-linked list + hash map.
|
||||
|
||||
template <typename K, typename V>
|
||||
class LruCache
|
||||
{
|
||||
using List = std::list<std::pair<K, V>>;
|
||||
using Map = std::unordered_map<K, typename List::iterator>;
|
||||
|
||||
public:
|
||||
explicit LruCache(std::size_t capacity)
|
||||
: capacity_{capacity}
|
||||
{
|
||||
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_; }
|
||||
|
||||
// Retrieve a value. Returns nullopt on miss; promotes the entry on hit.
|
||||
[[nodiscard]] std::optional<V> get(const K& key)
|
||||
{
|
||||
auto it = map_.find(key);
|
||||
if (it == map_.end()) return std::nullopt;
|
||||
list_.splice(list_.begin(), list_, it->second);
|
||||
return it->second->second;
|
||||
}
|
||||
|
||||
// Peek without changing recency order.
|
||||
[[nodiscard]] const V* peek(const K& key) const
|
||||
{
|
||||
auto it = map_.find(key);
|
||||
if (it == map_.end()) return nullptr;
|
||||
return &it->second->second;
|
||||
}
|
||||
|
||||
// Insert or update. If the key already exists its recency is updated.
|
||||
// If the cache is full the least-recently-used entry is evicted.
|
||||
void put(const K& key, V value)
|
||||
{
|
||||
auto it = map_.find(key);
|
||||
if (it != map_.end()) {
|
||||
it->second->second = std::move(value);
|
||||
list_.splice(list_.begin(), list_, it->second);
|
||||
return;
|
||||
}
|
||||
if (map_.size() == capacity_) {
|
||||
map_.erase(list_.back().first);
|
||||
list_.pop_back();
|
||||
}
|
||||
list_.emplace_front(key, std::move(value));
|
||||
map_[key] = list_.begin();
|
||||
}
|
||||
|
||||
bool erase(const K& key)
|
||||
{
|
||||
auto it = map_.find(key);
|
||||
if (it == map_.end()) return false;
|
||||
list_.erase(it->second);
|
||||
map_.erase(it);
|
||||
return true;
|
||||
}
|
||||
|
||||
void clear() noexcept
|
||||
{
|
||||
list_.clear();
|
||||
map_.clear();
|
||||
}
|
||||
|
||||
[[nodiscard]] bool contains(const K& key) const
|
||||
{
|
||||
return map_.contains(key);
|
||||
}
|
||||
|
||||
// Iterate entries in MRU→LRU order (const).
|
||||
[[nodiscard]] const List& entries() const noexcept { return list_; }
|
||||
|
||||
private:
|
||||
std::size_t capacity_;
|
||||
List list_;
|
||||
Map map_;
|
||||
};
|
||||
|
||||
} // namespace Void::LRU
|
||||
@@ -0,0 +1,166 @@
|
||||
#pragma once
|
||||
|
||||
#include <cassert>
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <new>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Pool
|
||||
{
|
||||
|
||||
// ── ObjectPool<T, ChunkSize> ──────────────────────────────────────────────────
|
||||
// A slab-based object pool. acquire() returns a unique_ptr<T> with a custom
|
||||
// deleter that returns the object to the pool instead of freeing memory.
|
||||
// Objects are constructed in-place; the pool owns the backing storage.
|
||||
//
|
||||
// Thread-safety: NOT thread-safe. Add external synchronisation if needed.
|
||||
|
||||
template <typename T, std::size_t ChunkSize = 32>
|
||||
class ObjectPool
|
||||
{
|
||||
public:
|
||||
ObjectPool() = default;
|
||||
|
||||
ObjectPool(const ObjectPool&) = delete;
|
||||
ObjectPool& operator=(const ObjectPool&) = delete;
|
||||
ObjectPool(ObjectPool&&) = default;
|
||||
ObjectPool& operator=(ObjectPool&&) = default;
|
||||
|
||||
~ObjectPool() = default;
|
||||
|
||||
struct Deleter
|
||||
{
|
||||
ObjectPool* pool;
|
||||
void operator()(T* p) const noexcept { pool->release(p); }
|
||||
};
|
||||
|
||||
using Ptr = std::unique_ptr<T, Deleter>;
|
||||
|
||||
template <typename... Args>
|
||||
[[nodiscard]] Ptr acquire(Args&&... args)
|
||||
{
|
||||
T* slot = pop_free();
|
||||
if (!slot) {
|
||||
slot = allocate_slot();
|
||||
}
|
||||
std::construct_at(slot, std::forward<Args>(args)...);
|
||||
return Ptr{slot, Deleter{this}};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t capacity() const noexcept
|
||||
{
|
||||
return slabs_.size() * ChunkSize;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t available() const noexcept
|
||||
{
|
||||
return free_.size();
|
||||
}
|
||||
|
||||
private:
|
||||
void release(T* p) noexcept
|
||||
{
|
||||
std::destroy_at(p);
|
||||
free_.push_back(p);
|
||||
}
|
||||
|
||||
T* pop_free() noexcept
|
||||
{
|
||||
if (free_.empty()) return nullptr;
|
||||
T* p = free_.back();
|
||||
free_.pop_back();
|
||||
return p;
|
||||
}
|
||||
|
||||
T* allocate_slot()
|
||||
{
|
||||
// Grow by one slab; keep all subsequent objects from the same slab
|
||||
// available in free_.
|
||||
auto& slab = slabs_.emplace_back();
|
||||
slab = std::make_unique<Slab>();
|
||||
// Push all but the first slot into free_.
|
||||
for (std::size_t i = 1; i < ChunkSize; ++i) {
|
||||
free_.push_back(reinterpret_cast<T*>(&slab->storage[i]));
|
||||
}
|
||||
return reinterpret_cast<T*>(&slab->storage[0]);
|
||||
}
|
||||
|
||||
struct alignas(alignof(T)) Slot
|
||||
{
|
||||
std::byte storage[sizeof(T)];
|
||||
};
|
||||
|
||||
struct Slab
|
||||
{
|
||||
Slot storage[ChunkSize];
|
||||
};
|
||||
|
||||
std::vector<std::unique_ptr<Slab>> slabs_;
|
||||
std::vector<T*> free_;
|
||||
};
|
||||
|
||||
// ── FixedPool<T, N> ───────────────────────────────────────────────────────────
|
||||
// A fixed-capacity pool allocated in-place (no heap after construction).
|
||||
// Capacity is known at compile time; acquire() returns nullptr when full.
|
||||
|
||||
template <typename T, std::size_t N>
|
||||
class FixedPool
|
||||
{
|
||||
public:
|
||||
FixedPool() noexcept
|
||||
{
|
||||
for (std::size_t i = 0; i < N; ++i) {
|
||||
free_[i] = slot_ptr(i);
|
||||
}
|
||||
free_count_ = N;
|
||||
}
|
||||
|
||||
FixedPool(const FixedPool&) = delete;
|
||||
FixedPool& operator=(const FixedPool&) = delete;
|
||||
|
||||
struct Deleter
|
||||
{
|
||||
FixedPool* pool;
|
||||
void operator()(T* p) const noexcept { pool->release(p); }
|
||||
};
|
||||
|
||||
using Ptr = std::unique_ptr<T, Deleter>;
|
||||
|
||||
template <typename... Args>
|
||||
[[nodiscard]] Ptr acquire(Args&&... args) noexcept(
|
||||
std::is_nothrow_constructible_v<T, Args...>)
|
||||
{
|
||||
if (free_count_ == 0) return nullptr;
|
||||
T* slot = free_[--free_count_];
|
||||
std::construct_at(slot, std::forward<Args>(args)...);
|
||||
return Ptr{slot, Deleter{this}};
|
||||
}
|
||||
|
||||
[[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; }
|
||||
[[nodiscard]] std::size_t available() const noexcept { return free_count_; }
|
||||
|
||||
private:
|
||||
void release(T* p) noexcept
|
||||
{
|
||||
std::destroy_at(p);
|
||||
free_[free_count_++] = p;
|
||||
}
|
||||
|
||||
T* slot_ptr(std::size_t i) noexcept
|
||||
{
|
||||
return reinterpret_cast<T*>(&storage_[i]);
|
||||
}
|
||||
|
||||
struct alignas(alignof(T)) Slot
|
||||
{
|
||||
std::byte storage[sizeof(T)];
|
||||
};
|
||||
|
||||
Slot storage_[N];
|
||||
T* free_[N];
|
||||
std::size_t free_count_{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Pool
|
||||
@@ -0,0 +1,150 @@
|
||||
#pragma once
|
||||
|
||||
#include <cassert>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::PriorityQueue
|
||||
{
|
||||
|
||||
// ── PriorityQueue<K, P> ───────────────────────────────────────────────────────
|
||||
// Indexed min-heap (by priority P) with O(log n) push/pop/update.
|
||||
// K is the key type (must be hashable). P is the priority type.
|
||||
// Equal priorities maintain stable-ish order (not guaranteed).
|
||||
|
||||
template <typename K, typename P, typename Cmp = std::less<P>>
|
||||
class PriorityQueue
|
||||
{
|
||||
public:
|
||||
explicit PriorityQueue(Cmp cmp = {}) : cmp_{cmp} {}
|
||||
|
||||
// Push a key with priority. If key already exists, equivalent to update().
|
||||
void push(K key, P priority)
|
||||
{
|
||||
const auto it = index_.find(key);
|
||||
if (it != index_.end()) {
|
||||
heap_[it->second].priority = priority;
|
||||
bubble_up(it->second);
|
||||
bubble_down(it->second);
|
||||
return;
|
||||
}
|
||||
const std::size_t i = heap_.size();
|
||||
heap_.push_back({std::move(key), std::move(priority)});
|
||||
index_[heap_.back().key] = i;
|
||||
bubble_up(i);
|
||||
}
|
||||
|
||||
// Returns the top (min) element without removing it.
|
||||
[[nodiscard]] const K& top_key() const
|
||||
{
|
||||
if (heap_.empty()) throw std::out_of_range{"PriorityQueue is empty"};
|
||||
return heap_[0].key;
|
||||
}
|
||||
|
||||
[[nodiscard]] const P& top_priority() const
|
||||
{
|
||||
if (heap_.empty()) throw std::out_of_range{"PriorityQueue is empty"};
|
||||
return heap_[0].priority;
|
||||
}
|
||||
|
||||
// Remove and return the top key.
|
||||
K pop()
|
||||
{
|
||||
if (heap_.empty()) throw std::out_of_range{"PriorityQueue is empty"};
|
||||
K result = std::move(heap_[0].key);
|
||||
index_.erase(result);
|
||||
if (heap_.size() > 1) {
|
||||
heap_[0] = std::move(heap_.back());
|
||||
index_[heap_[0].key] = 0;
|
||||
}
|
||||
heap_.pop_back();
|
||||
if (!heap_.empty()) bubble_down(0);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Update the priority of an existing key. No-op if key not found.
|
||||
void update(const K& key, P priority)
|
||||
{
|
||||
const auto it = index_.find(key);
|
||||
if (it == index_.end()) return;
|
||||
heap_[it->second].priority = std::move(priority);
|
||||
bubble_up(it->second);
|
||||
bubble_down(it->second);
|
||||
}
|
||||
|
||||
// Remove a specific key. No-op if not found.
|
||||
void erase(const K& key)
|
||||
{
|
||||
const auto it = index_.find(key);
|
||||
if (it == index_.end()) return;
|
||||
const std::size_t i = it->second;
|
||||
index_.erase(it);
|
||||
if (i == heap_.size() - 1) { heap_.pop_back(); return; }
|
||||
heap_[i] = std::move(heap_.back());
|
||||
index_[heap_[i].key] = i;
|
||||
heap_.pop_back();
|
||||
bubble_up(i);
|
||||
bubble_down(i);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool contains(const K& key) const { return index_.count(key) > 0; }
|
||||
[[nodiscard]] std::optional<P> priority_of(const K& key) const
|
||||
{
|
||||
const auto it = index_.find(key);
|
||||
if (it == index_.end()) return std::nullopt;
|
||||
return heap_[it->second].priority;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept { return heap_.size(); }
|
||||
[[nodiscard]] bool empty() const noexcept { return heap_.empty(); }
|
||||
void clear() { heap_.clear(); index_.clear(); }
|
||||
|
||||
private:
|
||||
struct Entry { K key; P priority; };
|
||||
|
||||
std::vector<Entry> heap_;
|
||||
std::unordered_map<K, std::size_t> index_;
|
||||
Cmp cmp_;
|
||||
|
||||
void swap_entries(std::size_t i, std::size_t j)
|
||||
{
|
||||
index_[heap_[i].key] = j;
|
||||
index_[heap_[j].key] = i;
|
||||
std::swap(heap_[i], heap_[j]);
|
||||
}
|
||||
|
||||
void bubble_up(std::size_t i)
|
||||
{
|
||||
while (i > 0) {
|
||||
const std::size_t parent = (i - 1) / 2;
|
||||
if (!cmp_(heap_[i].priority, heap_[parent].priority)) break;
|
||||
swap_entries(i, parent);
|
||||
i = parent;
|
||||
}
|
||||
}
|
||||
|
||||
void bubble_down(std::size_t i)
|
||||
{
|
||||
const std::size_t n = heap_.size();
|
||||
while (true) {
|
||||
std::size_t smallest = i;
|
||||
const std::size_t l = 2 * i + 1, r = 2 * i + 2;
|
||||
if (l < n && cmp_(heap_[l].priority, heap_[smallest].priority)) smallest = l;
|
||||
if (r < n && cmp_(heap_[r].priority, heap_[smallest].priority)) smallest = r;
|
||||
if (smallest == i) break;
|
||||
swap_entries(i, smallest);
|
||||
i = smallest;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── MaxPriorityQueue — max-heap variant ───────────────────────────────────────
|
||||
|
||||
template <typename K, typename P>
|
||||
using MaxPriorityQueue = PriorityQueue<K, P, std::greater<P>>;
|
||||
|
||||
} // namespace Void::PriorityQueue
|
||||
@@ -0,0 +1,179 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <cassert>
|
||||
#include <cstddef>
|
||||
#include <new>
|
||||
#include <optional>
|
||||
#include <type_traits>
|
||||
|
||||
namespace Void::Ring
|
||||
{
|
||||
|
||||
// ── SpscRing<T, N> ────────────────────────────────────────────────────────────
|
||||
// Single-producer / single-consumer lock-free ring buffer.
|
||||
// Capacity is N (must be a power of two). The buffer holds at most N-1 items.
|
||||
// All operations are wait-free.
|
||||
|
||||
template <typename T, std::size_t N>
|
||||
requires(N >= 2 && (N & (N - 1)) == 0) // power of two
|
||||
class SpscRing
|
||||
{
|
||||
public:
|
||||
SpscRing() = default;
|
||||
|
||||
SpscRing(const SpscRing&) = delete;
|
||||
SpscRing& operator=(const SpscRing&) = delete;
|
||||
|
||||
// Producer side — push returns false when the buffer is full.
|
||||
[[nodiscard]] bool push(const T& val)
|
||||
noexcept(std::is_nothrow_copy_constructible_v<T>)
|
||||
{
|
||||
const std::size_t head = head_.load(std::memory_order_relaxed);
|
||||
const std::size_t next = (head + 1) & mask_;
|
||||
if (next == tail_.load(std::memory_order_acquire)) return false;
|
||||
std::construct_at(slot_ptr(head), val);
|
||||
head_.store(next, std::memory_order_release);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool push(T&& val)
|
||||
noexcept(std::is_nothrow_move_constructible_v<T>)
|
||||
{
|
||||
const std::size_t head = head_.load(std::memory_order_relaxed);
|
||||
const std::size_t next = (head + 1) & mask_;
|
||||
if (next == tail_.load(std::memory_order_acquire)) return false;
|
||||
std::construct_at(slot_ptr(head), std::move(val));
|
||||
head_.store(next, std::memory_order_release);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Consumer side — pop returns nullopt when the buffer is empty.
|
||||
[[nodiscard]] std::optional<T> pop() noexcept(
|
||||
std::is_nothrow_move_constructible_v<T> &&
|
||||
std::is_nothrow_destructible_v<T>)
|
||||
{
|
||||
const std::size_t tail = tail_.load(std::memory_order_relaxed);
|
||||
if (tail == head_.load(std::memory_order_acquire)) return std::nullopt;
|
||||
T val{std::move(*slot_ptr(tail))};
|
||||
std::destroy_at(slot_ptr(tail));
|
||||
tail_.store((tail + 1) & mask_, std::memory_order_release);
|
||||
return val;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool empty() const noexcept
|
||||
{
|
||||
return tail_.load(std::memory_order_acquire) ==
|
||||
head_.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool full() const noexcept
|
||||
{
|
||||
const std::size_t next =
|
||||
(head_.load(std::memory_order_acquire) + 1) & mask_;
|
||||
return next == tail_.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
[[nodiscard]] static constexpr std::size_t capacity() noexcept
|
||||
{
|
||||
return N - 1;
|
||||
}
|
||||
|
||||
private:
|
||||
T* slot_ptr(std::size_t i) noexcept
|
||||
{
|
||||
return std::launder(reinterpret_cast<T*>(&storage_[i]));
|
||||
}
|
||||
|
||||
static constexpr std::size_t mask_ = N - 1;
|
||||
|
||||
struct alignas(alignof(T)) Slot
|
||||
{
|
||||
std::byte storage[sizeof(T)];
|
||||
};
|
||||
|
||||
// Pad to separate cache lines to avoid false sharing.
|
||||
alignas(64) std::atomic<std::size_t> head_{0};
|
||||
alignas(64) std::atomic<std::size_t> tail_{0};
|
||||
Slot storage_[N];
|
||||
};
|
||||
|
||||
// ── MpscRing<T, N> ────────────────────────────────────────────────────────────
|
||||
// Multi-producer / single-consumer ring buffer using a compare-exchange loop
|
||||
// on the head pointer. Consumer is still single-threaded.
|
||||
|
||||
template <typename T, std::size_t N>
|
||||
requires(N >= 2 && (N & (N - 1)) == 0)
|
||||
class MpscRing
|
||||
{
|
||||
public:
|
||||
MpscRing() = default;
|
||||
|
||||
MpscRing(const MpscRing&) = delete;
|
||||
MpscRing& operator=(const MpscRing&) = delete;
|
||||
|
||||
[[nodiscard]] bool push(T val) noexcept(
|
||||
std::is_nothrow_move_constructible_v<T>)
|
||||
{
|
||||
std::size_t head = head_.load(std::memory_order_relaxed);
|
||||
std::size_t next;
|
||||
do {
|
||||
next = (head + 1) & mask_;
|
||||
if (next == tail_.load(std::memory_order_acquire)) return false;
|
||||
} while (!head_.compare_exchange_weak(head, next,
|
||||
std::memory_order_acq_rel,
|
||||
std::memory_order_relaxed));
|
||||
std::construct_at(slot_ptr(head), std::move(val));
|
||||
// Signal that this slot is ready.
|
||||
ready_[head].store(true, std::memory_order_release);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<T> pop() noexcept(
|
||||
std::is_nothrow_move_constructible_v<T>)
|
||||
{
|
||||
const std::size_t tail = tail_.load(std::memory_order_relaxed);
|
||||
if (tail == head_.load(std::memory_order_acquire)) return std::nullopt;
|
||||
// Spin until the producing thread has written the value.
|
||||
while (!ready_[tail].load(std::memory_order_acquire)) {
|
||||
// wait — producer is still copying; this is still wait-free on the
|
||||
// hot path (single iteration in practice).
|
||||
}
|
||||
T val{std::move(*slot_ptr(tail))};
|
||||
std::destroy_at(slot_ptr(tail));
|
||||
ready_[tail].store(false, std::memory_order_release);
|
||||
tail_.store((tail + 1) & mask_, std::memory_order_release);
|
||||
return val;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool empty() const noexcept
|
||||
{
|
||||
return tail_.load(std::memory_order_acquire) ==
|
||||
head_.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
[[nodiscard]] static constexpr std::size_t capacity() noexcept
|
||||
{
|
||||
return N - 1;
|
||||
}
|
||||
|
||||
private:
|
||||
T* slot_ptr(std::size_t i) noexcept
|
||||
{
|
||||
return std::launder(reinterpret_cast<T*>(&storage_[i]));
|
||||
}
|
||||
|
||||
static constexpr std::size_t mask_ = N - 1;
|
||||
|
||||
struct alignas(alignof(T)) Slot
|
||||
{
|
||||
std::byte storage[sizeof(T)];
|
||||
};
|
||||
|
||||
alignas(64) std::atomic<std::size_t> head_{0};
|
||||
alignas(64) std::atomic<std::size_t> tail_{0};
|
||||
Slot storage_[N];
|
||||
std::atomic<bool> ready_[N]{};
|
||||
};
|
||||
|
||||
} // namespace Void::Ring
|
||||
@@ -0,0 +1,124 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Trie
|
||||
{
|
||||
|
||||
// ── Trie ──────────────────────────────────────────────────────────────────────
|
||||
// Prefix tree over std::string keys with optional associated values of type V.
|
||||
// Stores words character-by-character; each node has up to 256 children.
|
||||
|
||||
template <typename V = bool>
|
||||
class Trie
|
||||
{
|
||||
struct Node
|
||||
{
|
||||
std::unordered_map<char, std::unique_ptr<Node>> children;
|
||||
std::optional<V> value; // set only at end-of-word nodes
|
||||
};
|
||||
|
||||
public:
|
||||
Trie() : root_{std::make_unique<Node>()} {}
|
||||
|
||||
void insert(std::string_view key, V value = V{})
|
||||
{
|
||||
Node* cur = root_.get();
|
||||
for (char c : key) {
|
||||
auto& child = cur->children[c];
|
||||
if (!child) child = std::make_unique<Node>();
|
||||
cur = child.get();
|
||||
}
|
||||
if (!cur->value.has_value()) ++size_;
|
||||
cur->value = std::move(value);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool contains(std::string_view key) const
|
||||
{
|
||||
const Node* node = find_node(key);
|
||||
return node && node->value.has_value();
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<V> get(std::string_view key) const
|
||||
{
|
||||
const Node* node = find_node(key);
|
||||
if (!node) return std::nullopt;
|
||||
return node->value;
|
||||
}
|
||||
|
||||
bool erase(std::string_view key)
|
||||
{
|
||||
return erase_impl(root_.get(), key, 0);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool starts_with(std::string_view prefix) const
|
||||
{
|
||||
return find_node(prefix) != nullptr;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<std::string>
|
||||
keys_with_prefix(std::string_view prefix) const
|
||||
{
|
||||
std::vector<std::string> result;
|
||||
const Node* node = find_node(prefix);
|
||||
if (!node) return result;
|
||||
std::string buf{prefix};
|
||||
collect(node, buf, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept { return size_; }
|
||||
[[nodiscard]] bool empty() const noexcept { return size_ == 0; }
|
||||
|
||||
private:
|
||||
const Node* find_node(std::string_view key) const
|
||||
{
|
||||
const Node* cur = root_.get();
|
||||
for (char c : key) {
|
||||
auto it = cur->children.find(c);
|
||||
if (it == cur->children.end()) return nullptr;
|
||||
cur = it->second.get();
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
void collect(const Node* node, std::string& buf,
|
||||
std::vector<std::string>& out) const
|
||||
{
|
||||
if (node->value.has_value()) out.push_back(buf);
|
||||
for (const auto& [c, child] : node->children) {
|
||||
buf += c;
|
||||
collect(child.get(), buf, out);
|
||||
buf.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
bool erase_impl(Node* node, std::string_view key, std::size_t depth)
|
||||
{
|
||||
if (depth == key.size()) {
|
||||
if (!node->value.has_value()) return false;
|
||||
node->value.reset();
|
||||
--size_;
|
||||
return true;
|
||||
}
|
||||
auto it = node->children.find(key[depth]);
|
||||
if (it == node->children.end()) return false;
|
||||
const bool erased = erase_impl(it->second.get(), key, depth + 1);
|
||||
// Prune leaf nodes that hold no value and have no children
|
||||
if (erased && it->second->children.empty() &&
|
||||
!it->second->value.has_value()) {
|
||||
node->children.erase(it);
|
||||
}
|
||||
return erased;
|
||||
}
|
||||
|
||||
std::unique_ptr<Node> root_;
|
||||
std::size_t size_{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Trie
|
||||
Reference in new issue
Block a user