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,160 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Histogram
|
||||
{
|
||||
|
||||
// ── Histogram<K> ──────────────────────────────────────────────────────────────
|
||||
// Frequency counter for discrete keys.
|
||||
|
||||
template <typename K>
|
||||
class Histogram
|
||||
{
|
||||
public:
|
||||
// Increment the count for key by n (default 1).
|
||||
void add(const K& key, std::size_t n = 1)
|
||||
{
|
||||
counts_[key] += n;
|
||||
total_ += n;
|
||||
}
|
||||
|
||||
// Remove a key entirely.
|
||||
bool erase(const K& key)
|
||||
{
|
||||
const auto it = counts_.find(key);
|
||||
if (it == counts_.end()) return false;
|
||||
total_ -= it->second;
|
||||
counts_.erase(it);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Get count for key (0 if not present).
|
||||
[[nodiscard]] std::size_t count(const K& key) const
|
||||
{
|
||||
const auto it = counts_.find(key);
|
||||
return it != counts_.end() ? it->second : 0;
|
||||
}
|
||||
|
||||
// Frequency as a fraction of total (0 if total == 0).
|
||||
[[nodiscard]] double frequency(const K& key) const
|
||||
{
|
||||
if (total_ == 0) return 0.0;
|
||||
return static_cast<double>(count(key)) / static_cast<double>(total_);
|
||||
}
|
||||
|
||||
// True if key has been observed.
|
||||
[[nodiscard]] bool contains(const K& key) const { return counts_.count(key) > 0; }
|
||||
|
||||
// Most common key (nullopt if empty).
|
||||
[[nodiscard]] std::optional<K> mode() const
|
||||
{
|
||||
if (counts_.empty()) return std::nullopt;
|
||||
const auto it = std::max_element(counts_.begin(), counts_.end(),
|
||||
[](const auto& a, const auto& b) { return a.second < b.second; });
|
||||
return it->first;
|
||||
}
|
||||
|
||||
// Least common key (nullopt if empty).
|
||||
[[nodiscard]] std::optional<K> least_common() const
|
||||
{
|
||||
if (counts_.empty()) return std::nullopt;
|
||||
const auto it = std::min_element(counts_.begin(), counts_.end(),
|
||||
[](const auto& a, const auto& b) { return a.second < b.second; });
|
||||
return it->first;
|
||||
}
|
||||
|
||||
// All key-count pairs sorted by count descending.
|
||||
[[nodiscard]] std::vector<std::pair<K, std::size_t>> top_k(std::size_t k) const
|
||||
{
|
||||
std::vector<std::pair<K, std::size_t>> v{counts_.begin(), counts_.end()};
|
||||
const std::size_t n = std::min(k, v.size());
|
||||
std::partial_sort(v.begin(), v.begin() + static_cast<std::ptrdiff_t>(n), v.end(),
|
||||
[](const auto& a, const auto& b) { return a.second > b.second; });
|
||||
v.resize(n);
|
||||
return v;
|
||||
}
|
||||
|
||||
// Total observations.
|
||||
[[nodiscard]] std::size_t total() const noexcept { return total_; }
|
||||
[[nodiscard]] std::size_t distinct() const noexcept { return counts_.size(); }
|
||||
[[nodiscard]] bool empty() const noexcept { return counts_.empty(); }
|
||||
|
||||
void clear() noexcept { counts_.clear(); total_ = 0; }
|
||||
|
||||
// Merge another histogram into this one.
|
||||
void merge(const Histogram& other)
|
||||
{
|
||||
for (const auto& [k, v] : other.counts_) { counts_[k] += v; }
|
||||
total_ += other.total_;
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::unordered_map<K, std::size_t>& counts() const noexcept
|
||||
{
|
||||
return counts_;
|
||||
}
|
||||
|
||||
private:
|
||||
std::unordered_map<K, std::size_t> counts_;
|
||||
std::size_t total_{0};
|
||||
};
|
||||
|
||||
// ── FixedBinHistogram ─────────────────────────────────────────────────────────
|
||||
// Numeric histogram with fixed-width equal-width bins over [min, max).
|
||||
|
||||
class FixedBinHistogram
|
||||
{
|
||||
public:
|
||||
// n_bins bins covering [min_val, max_val).
|
||||
FixedBinHistogram(double min_val, double max_val, std::size_t n_bins)
|
||||
: min_{min_val}, max_{max_val}, bins_(n_bins, 0)
|
||||
{
|
||||
if (n_bins == 0) throw std::invalid_argument{"n_bins must be > 0"};
|
||||
if (min_ >= max_) throw std::invalid_argument{"min must be < max"};
|
||||
width_ = (max_ - min_) / static_cast<double>(n_bins);
|
||||
}
|
||||
|
||||
// Record a value. Values outside [min, max) are clamped to edge bins.
|
||||
void add(double v)
|
||||
{
|
||||
std::size_t idx;
|
||||
if (v <= min_) {
|
||||
idx = 0;
|
||||
} else if (v >= max_) {
|
||||
idx = bins_.size() - 1;
|
||||
} else {
|
||||
idx = static_cast<std::size_t>((v - min_) / width_);
|
||||
if (idx >= bins_.size()) idx = bins_.size() - 1;
|
||||
}
|
||||
++bins_[idx];
|
||||
++total_;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t bin_count(std::size_t idx) const
|
||||
{
|
||||
if (idx >= bins_.size()) throw std::out_of_range{"bin index out of range"};
|
||||
return bins_[idx];
|
||||
}
|
||||
|
||||
[[nodiscard]] double bin_low(std::size_t idx) const noexcept { return min_ + width_ * static_cast<double>(idx); }
|
||||
[[nodiscard]] double bin_high(std::size_t idx) const noexcept { return bin_low(idx) + width_; }
|
||||
|
||||
[[nodiscard]] std::size_t n_bins() const noexcept { return bins_.size(); }
|
||||
[[nodiscard]] std::size_t total() const noexcept { return total_; }
|
||||
[[nodiscard]] double width() const noexcept { return width_; }
|
||||
|
||||
void clear() noexcept { for (auto& b : bins_) b = 0; total_ = 0; }
|
||||
|
||||
private:
|
||||
double min_, max_, width_;
|
||||
std::vector<std::size_t> bins_;
|
||||
std::size_t total_{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Histogram
|
||||
@@ -0,0 +1,248 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <numeric>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Void::Matrix
|
||||
{
|
||||
|
||||
// ── Matrix<T, Rows, Cols> ─────────────────────────────────────────────────────
|
||||
// Compile-time-sized matrix stored in row-major order.
|
||||
|
||||
template <typename T, std::size_t Rows, std::size_t Cols>
|
||||
class Matrix
|
||||
{
|
||||
static_assert(Rows > 0 && Cols > 0, "Matrix dimensions must be positive");
|
||||
|
||||
public:
|
||||
using value_type = T;
|
||||
static constexpr std::size_t rows = Rows;
|
||||
static constexpr std::size_t cols = Cols;
|
||||
|
||||
constexpr Matrix() { data_.fill(T{}); }
|
||||
|
||||
explicit constexpr Matrix(T fill_value) { data_.fill(fill_value); }
|
||||
|
||||
// Row-major initializer: Matrix<int,2,2>{{1,2,3,4}}
|
||||
constexpr Matrix(std::array<T, Rows * Cols> d) : data_{d} {}
|
||||
|
||||
[[nodiscard]] constexpr T& at(std::size_t r, std::size_t c)
|
||||
{
|
||||
if (r >= Rows || c >= Cols) throw std::out_of_range{"Matrix::at"};
|
||||
return data_[r * Cols + c];
|
||||
}
|
||||
[[nodiscard]] constexpr const T& at(std::size_t r, std::size_t c) const
|
||||
{
|
||||
if (r >= Rows || c >= Cols) throw std::out_of_range{"Matrix::at"};
|
||||
return data_[r * Cols + c];
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr T& operator()(std::size_t r, std::size_t c) noexcept
|
||||
{
|
||||
return data_[r * Cols + c];
|
||||
}
|
||||
[[nodiscard]] constexpr const T& operator()(std::size_t r, std::size_t c) const noexcept
|
||||
{
|
||||
return data_[r * Cols + c];
|
||||
}
|
||||
|
||||
// ── arithmetic ────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr Matrix operator+(const Matrix& o) const noexcept
|
||||
{
|
||||
Matrix result;
|
||||
for (std::size_t i = 0; i < Rows * Cols; ++i)
|
||||
result.data_[i] = data_[i] + o.data_[i];
|
||||
return result;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Matrix operator-(const Matrix& o) const noexcept
|
||||
{
|
||||
Matrix result;
|
||||
for (std::size_t i = 0; i < Rows * Cols; ++i)
|
||||
result.data_[i] = data_[i] - o.data_[i];
|
||||
return result;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Matrix operator*(T scalar) const noexcept
|
||||
{
|
||||
Matrix result;
|
||||
for (std::size_t i = 0; i < Rows * Cols; ++i)
|
||||
result.data_[i] = data_[i] * scalar;
|
||||
return result;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Matrix operator-() const noexcept
|
||||
{
|
||||
Matrix result;
|
||||
for (std::size_t i = 0; i < Rows * Cols; ++i)
|
||||
result.data_[i] = -data_[i];
|
||||
return result;
|
||||
}
|
||||
|
||||
constexpr Matrix& operator+=(const Matrix& o) noexcept
|
||||
{
|
||||
for (std::size_t i = 0; i < Rows * Cols; ++i) data_[i] += o.data_[i];
|
||||
return *this;
|
||||
}
|
||||
|
||||
constexpr Matrix& operator-=(const Matrix& o) noexcept
|
||||
{
|
||||
for (std::size_t i = 0; i < Rows * Cols; ++i) data_[i] -= o.data_[i];
|
||||
return *this;
|
||||
}
|
||||
|
||||
constexpr Matrix& operator*=(T scalar) noexcept
|
||||
{
|
||||
for (std::size_t i = 0; i < Rows * Cols; ++i) data_[i] *= scalar;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// ── matrix multiplication ─────────────────────────────────────────────────
|
||||
|
||||
template <std::size_t K>
|
||||
[[nodiscard]] constexpr Matrix<T, Rows, K>
|
||||
operator*(const Matrix<T, Cols, K>& rhs) const noexcept
|
||||
{
|
||||
Matrix<T, Rows, K> result;
|
||||
for (std::size_t r = 0; r < Rows; ++r)
|
||||
for (std::size_t k = 0; k < Cols; ++k)
|
||||
for (std::size_t c = 0; c < K; ++c)
|
||||
result(r, c) += (*this)(r, k) * rhs(k, c);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── transpose ─────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr Matrix<T, Cols, Rows> transposed() const noexcept
|
||||
{
|
||||
Matrix<T, Cols, Rows> result;
|
||||
for (std::size_t r = 0; r < Rows; ++r)
|
||||
for (std::size_t c = 0; c < Cols; ++c)
|
||||
result(c, r) = (*this)(r, c);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── comparison ────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr bool operator==(const Matrix& o) const noexcept
|
||||
{
|
||||
return data_ == o.data_;
|
||||
}
|
||||
[[nodiscard]] constexpr bool operator!=(const Matrix& o) const noexcept
|
||||
{
|
||||
return !(*this == o);
|
||||
}
|
||||
|
||||
// ── aggregates ────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr T sum() const noexcept
|
||||
{
|
||||
return std::accumulate(data_.begin(), data_.end(), T{});
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr T trace() const noexcept
|
||||
requires (Rows == Cols)
|
||||
{
|
||||
T t{};
|
||||
for (std::size_t i = 0; i < Rows; ++i) t += (*this)(i, i);
|
||||
return t;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr T frobenius_sq() const noexcept
|
||||
{
|
||||
T s{};
|
||||
for (const auto& v : data_) s += v * v;
|
||||
return s;
|
||||
}
|
||||
|
||||
// ── factory ───────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] static constexpr Matrix identity() noexcept
|
||||
requires (Rows == Cols)
|
||||
{
|
||||
Matrix m;
|
||||
for (std::size_t i = 0; i < Rows; ++i) m(i, i) = T{1};
|
||||
return m;
|
||||
}
|
||||
|
||||
[[nodiscard]] static constexpr Matrix zeros() noexcept { return Matrix{}; }
|
||||
[[nodiscard]] static constexpr Matrix ones() noexcept { return Matrix{T{1}}; }
|
||||
|
||||
// ── element access helpers ────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr const std::array<T, Rows * Cols>& flat() const noexcept
|
||||
{
|
||||
return data_;
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<T, Rows * Cols> data_;
|
||||
};
|
||||
|
||||
// Scalar * Matrix
|
||||
template <typename T, std::size_t R, std::size_t C>
|
||||
[[nodiscard]] constexpr Matrix<T, R, C> operator*(T scalar, const Matrix<T, R, C>& m) noexcept
|
||||
{
|
||||
return m * scalar;
|
||||
}
|
||||
|
||||
// ── Type aliases ──────────────────────────────────────────────────────────────
|
||||
|
||||
template <typename T> using Mat2 = Matrix<T, 2, 2>;
|
||||
template <typename T> using Mat3 = Matrix<T, 3, 3>;
|
||||
template <typename T> using Mat4 = Matrix<T, 4, 4>;
|
||||
template <typename T> using Vec2 = Matrix<T, 2, 1>;
|
||||
template <typename T> using Vec3 = Matrix<T, 3, 1>;
|
||||
template <typename T> using Vec4 = Matrix<T, 4, 1>;
|
||||
|
||||
using Mat2f = Mat2<float>;
|
||||
using Mat3f = Mat3<float>;
|
||||
using Mat4f = Mat4<float>;
|
||||
using Mat2d = Mat2<double>;
|
||||
using Mat3d = Mat3<double>;
|
||||
using Mat4d = Mat4<double>;
|
||||
|
||||
// ── dot product for column vectors ───────────────────────────────────────────
|
||||
|
||||
template <typename T, std::size_t N>
|
||||
[[nodiscard]] constexpr T dot(const Matrix<T, N, 1>& a, const Matrix<T, N, 1>& b) noexcept
|
||||
{
|
||||
T s{};
|
||||
for (std::size_t i = 0; i < N; ++i) s += a(i, 0) * b(i, 0);
|
||||
return s;
|
||||
}
|
||||
|
||||
// ── 2×2 determinant ───────────────────────────────────────────────────────────
|
||||
|
||||
template <typename T>
|
||||
[[nodiscard]] constexpr T det(const Mat2<T>& m) noexcept
|
||||
{
|
||||
return m(0, 0) * m(1, 1) - m(0, 1) * m(1, 0);
|
||||
}
|
||||
|
||||
// ── 2×2 inverse ───────────────────────────────────────────────────────────────
|
||||
|
||||
template <typename T>
|
||||
[[nodiscard]] constexpr std::optional<Mat2<T>> inverse(const Mat2<T>& m) noexcept
|
||||
{
|
||||
const T d = det(m);
|
||||
if (d == T{}) return std::nullopt;
|
||||
return Mat2<T>{{m(1, 1) / d, -m(0, 1) / d,
|
||||
-m(1, 0) / d, m(0, 0) / d}};
|
||||
}
|
||||
|
||||
// ── 3×3 determinant ───────────────────────────────────────────────────────────
|
||||
|
||||
template <typename T>
|
||||
[[nodiscard]] constexpr T det(const Mat3<T>& m) noexcept
|
||||
{
|
||||
return m(0,0) * (m(1,1)*m(2,2) - m(1,2)*m(2,1))
|
||||
- m(0,1) * (m(1,0)*m(2,2) - m(1,2)*m(2,0))
|
||||
+ m(0,2) * (m(1,0)*m(2,1) - m(1,1)*m(2,0));
|
||||
}
|
||||
|
||||
} // namespace Void::Matrix
|
||||
@@ -0,0 +1,183 @@
|
||||
#pragma once
|
||||
|
||||
#include <concepts>
|
||||
#include <cstdlib>
|
||||
#include <expected>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
|
||||
namespace Void::Numeric
|
||||
{
|
||||
|
||||
// ── Error tags ────────────────────────────────────────────────────────────────
|
||||
|
||||
enum class Error
|
||||
{
|
||||
Overflow,
|
||||
Underflow,
|
||||
DivisionByZero,
|
||||
InvalidInput,
|
||||
};
|
||||
|
||||
[[nodiscard]] constexpr std::string_view to_string(Error e) noexcept
|
||||
{
|
||||
switch (e) {
|
||||
case Error::Overflow: return "overflow";
|
||||
case Error::Underflow: return "underflow";
|
||||
case Error::DivisionByZero: return "division by zero";
|
||||
case Error::InvalidInput: return "invalid input";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
// ── Checked arithmetic ────────────────────────────────────────────────────────
|
||||
|
||||
template <std::integral T>
|
||||
[[nodiscard]] constexpr std::expected<T, Error> checked_add(T a, T b) noexcept
|
||||
{
|
||||
T result;
|
||||
if (__builtin_add_overflow(a, b, &result)) {
|
||||
return std::unexpected{b > 0 ? Error::Overflow : Error::Underflow};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
[[nodiscard]] constexpr std::expected<T, Error> checked_sub(T a, T b) noexcept
|
||||
{
|
||||
T result;
|
||||
if (__builtin_sub_overflow(a, b, &result)) {
|
||||
return std::unexpected{b > 0 ? Error::Underflow : Error::Overflow};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
[[nodiscard]] constexpr std::expected<T, Error> checked_mul(T a, T b) noexcept
|
||||
{
|
||||
T result;
|
||||
if (__builtin_mul_overflow(a, b, &result)) {
|
||||
return std::unexpected{Error::Overflow};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
[[nodiscard]] constexpr std::expected<T, Error> checked_div(T a, T b) noexcept
|
||||
{
|
||||
if (b == T{0}) return std::unexpected{Error::DivisionByZero};
|
||||
if constexpr (std::is_signed_v<T>) {
|
||||
if (a == std::numeric_limits<T>::min() && b == T{-1}) {
|
||||
return std::unexpected{Error::Overflow};
|
||||
}
|
||||
}
|
||||
return a / b;
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
[[nodiscard]] constexpr std::expected<T, Error>
|
||||
checked_neg(T a) noexcept
|
||||
{
|
||||
if constexpr (std::is_unsigned_v<T>) {
|
||||
if (a != T{0}) return std::unexpected{Error::Underflow};
|
||||
return T{0};
|
||||
} else {
|
||||
if (a == std::numeric_limits<T>::min()) return std::unexpected{Error::Overflow};
|
||||
return static_cast<T>(-a);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Saturating arithmetic (never overflows, clamps to min/max) ───────────────
|
||||
|
||||
template <std::integral T>
|
||||
[[nodiscard]] constexpr T saturating_add(T a, T b) noexcept
|
||||
{
|
||||
return checked_add(a, b).value_or(
|
||||
b > 0 ? std::numeric_limits<T>::max() : std::numeric_limits<T>::min());
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
[[nodiscard]] constexpr T saturating_sub(T a, T b) noexcept
|
||||
{
|
||||
return checked_sub(a, b).value_or(
|
||||
b > 0 ? std::numeric_limits<T>::min() : std::numeric_limits<T>::max());
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
[[nodiscard]] constexpr T saturating_mul(T a, T b) noexcept
|
||||
{
|
||||
return checked_mul(a, b).value_or(
|
||||
(a > 0) == (b > 0) ? std::numeric_limits<T>::max()
|
||||
: std::numeric_limits<T>::min());
|
||||
}
|
||||
|
||||
// ── Wrapping arithmetic (defined modular wrap) ───────────────────────────────
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T wrapping_add(T a, T b) noexcept { return static_cast<T>(a + b); }
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T wrapping_sub(T a, T b) noexcept { return static_cast<T>(a - b); }
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T wrapping_mul(T a, T b) noexcept { return static_cast<T>(a * b); }
|
||||
|
||||
// ── Clamping ─────────────────────────────────────────────────────────────────
|
||||
|
||||
template <typename T>
|
||||
requires std::totally_ordered<T>
|
||||
[[nodiscard]] constexpr T clamp(T val, T lo, T hi) noexcept
|
||||
{
|
||||
if (val < lo) return lo;
|
||||
if (val > hi) return hi;
|
||||
return val;
|
||||
}
|
||||
|
||||
// ── Numeric parsing ───────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] inline std::expected<int, Error>
|
||||
parse_int(std::string_view s, int base = 10) noexcept
|
||||
{
|
||||
if (s.empty()) return std::unexpected{Error::InvalidInput};
|
||||
char* end = nullptr;
|
||||
const long v = std::strtol(s.data(), &end, base);
|
||||
if (end == s.data() || end != s.data() + s.size()) {
|
||||
return std::unexpected{Error::InvalidInput};
|
||||
}
|
||||
if (v > std::numeric_limits<int>::max()) return std::unexpected{Error::Overflow};
|
||||
if (v < std::numeric_limits<int>::min()) return std::unexpected{Error::Underflow};
|
||||
return static_cast<int>(v);
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::expected<double, Error>
|
||||
parse_double(std::string_view s) noexcept
|
||||
{
|
||||
if (s.empty()) return std::unexpected{Error::InvalidInput};
|
||||
char* end = nullptr;
|
||||
const double v = std::strtod(s.data(), &end);
|
||||
if (end == s.data() || end != s.data() + s.size()) {
|
||||
return std::unexpected{Error::InvalidInput};
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// ── Integer traits helpers ────────────────────────────────────────────────────
|
||||
|
||||
template <std::integral T>
|
||||
[[nodiscard]] constexpr bool in_range(long long v) noexcept
|
||||
{
|
||||
return v >= static_cast<long long>(std::numeric_limits<T>::min()) &&
|
||||
v <= static_cast<long long>(std::numeric_limits<T>::max());
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
[[nodiscard]] constexpr std::optional<T>
|
||||
narrow_cast(long long v) noexcept
|
||||
{
|
||||
if (!in_range<T>(v)) return std::nullopt;
|
||||
return static_cast<T>(v);
|
||||
}
|
||||
|
||||
} // namespace Void::Numeric
|
||||
@@ -0,0 +1,163 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <random>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Random
|
||||
{
|
||||
|
||||
// ── Xoshiro256** PRNG (fast, good quality, no stdlib overhead) ───────────────
|
||||
|
||||
class Xoshiro256
|
||||
{
|
||||
public:
|
||||
using result_type = std::uint64_t;
|
||||
|
||||
explicit Xoshiro256(std::uint64_t seed = 0xdeadbeefcafe1234ull) noexcept
|
||||
{
|
||||
// SplitMix64 seeder
|
||||
auto splitmix = [](std::uint64_t& s) noexcept -> std::uint64_t {
|
||||
s += 0x9e3779b97f4a7c15ull;
|
||||
std::uint64_t z = s;
|
||||
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
|
||||
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
|
||||
return z ^ (z >> 31);
|
||||
};
|
||||
s_[0] = splitmix(seed);
|
||||
s_[1] = splitmix(seed);
|
||||
s_[2] = splitmix(seed);
|
||||
s_[3] = splitmix(seed);
|
||||
}
|
||||
|
||||
static constexpr result_type min() noexcept { return 0; }
|
||||
static constexpr result_type max() noexcept
|
||||
{
|
||||
return std::numeric_limits<result_type>::max();
|
||||
}
|
||||
|
||||
result_type operator()() noexcept
|
||||
{
|
||||
const std::uint64_t r = rotl(s_[1] * 5, 7) * 9;
|
||||
const std::uint64_t t = s_[1] << 17;
|
||||
s_[2] ^= s_[0];
|
||||
s_[3] ^= s_[1];
|
||||
s_[1] ^= s_[2];
|
||||
s_[0] ^= s_[3];
|
||||
s_[2] ^= t;
|
||||
s_[3] = rotl(s_[3], 45);
|
||||
return r;
|
||||
}
|
||||
|
||||
void discard(unsigned long long n) noexcept
|
||||
{
|
||||
while (n--) operator()();
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr std::uint64_t rotl(std::uint64_t x, int k) noexcept
|
||||
{
|
||||
return (x << k) | (x >> (64 - k));
|
||||
}
|
||||
std::uint64_t s_[4];
|
||||
};
|
||||
|
||||
// ── Thread-local default generator ───────────────────────────────────────────
|
||||
|
||||
inline Xoshiro256& global_rng() noexcept
|
||||
{
|
||||
static thread_local Xoshiro256 rng{std::random_device{}()};
|
||||
return rng;
|
||||
}
|
||||
|
||||
// ── Distributions ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// Uniform integer in [lo, hi] (inclusive).
|
||||
template <std::integral T>
|
||||
[[nodiscard]] T uniform_int(T lo, T hi) noexcept
|
||||
{
|
||||
std::uniform_int_distribution<T> d{lo, hi};
|
||||
return d(global_rng());
|
||||
}
|
||||
|
||||
/// Uniform real in [lo, hi).
|
||||
template <std::floating_point T = double>
|
||||
[[nodiscard]] T uniform_real(T lo = T{0}, T hi = T{1}) noexcept
|
||||
{
|
||||
std::uniform_real_distribution<T> d{lo, hi};
|
||||
return d(global_rng());
|
||||
}
|
||||
|
||||
/// Bernoulli trial: true with probability p.
|
||||
[[nodiscard]] inline bool coin_flip(double p = 0.5) noexcept
|
||||
{
|
||||
std::bernoulli_distribution d{p};
|
||||
return d(global_rng());
|
||||
}
|
||||
|
||||
/// Normal (Gaussian) sample.
|
||||
[[nodiscard]] inline double normal(double mean = 0.0,
|
||||
double stddev = 1.0) noexcept
|
||||
{
|
||||
std::normal_distribution<double> d{mean, stddev};
|
||||
return d(global_rng());
|
||||
}
|
||||
|
||||
/// Pick a random element from a non-empty span. UB if span is empty.
|
||||
template <typename T>
|
||||
[[nodiscard]] const T& choice(std::span<const T> items) noexcept
|
||||
{
|
||||
return items[uniform_int<std::size_t>(0, items.size() - 1)];
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
[[nodiscard]] T& choice(std::span<T> items) noexcept
|
||||
{
|
||||
return items[uniform_int<std::size_t>(0, items.size() - 1)];
|
||||
}
|
||||
|
||||
/// Shuffle a container in place using Fisher-Yates.
|
||||
template <typename Container>
|
||||
void shuffle(Container& c) noexcept
|
||||
{
|
||||
std::ranges::shuffle(c, global_rng());
|
||||
}
|
||||
|
||||
/// Fill a span with random bytes.
|
||||
inline void fill_random(std::span<std::byte> buf) noexcept
|
||||
{
|
||||
for (auto& b : buf) {
|
||||
b = static_cast<std::byte>(uniform_int<int>(0, 255));
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a random alphanumeric string of length n.
|
||||
[[nodiscard]] inline std::string random_string(std::size_t n)
|
||||
{
|
||||
constexpr std::string_view chars =
|
||||
"abcdefghijklmnopqrstuvwxyz"
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
"0123456789";
|
||||
std::string s;
|
||||
s.reserve(n);
|
||||
for (std::size_t i = 0; i < n; ++i) {
|
||||
s += chars[uniform_int<std::size_t>(0, chars.size() - 1)];
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/// Sample k distinct indices from [0, n).
|
||||
[[nodiscard]] inline std::vector<std::size_t> sample_indices(std::size_t n,
|
||||
std::size_t k)
|
||||
{
|
||||
std::vector<std::size_t> pool(n);
|
||||
std::iota(pool.begin(), pool.end(), std::size_t{0});
|
||||
shuffle(pool);
|
||||
pool.resize(k);
|
||||
return pool;
|
||||
}
|
||||
|
||||
} // namespace Void::Random
|
||||
Reference in new issue
Block a user