Add Hash, Random, Uuid, Encoding, Bits, Math modules + make Testing deps optional
New header-only modules: - Void::Hash — FNV-1a 32/64, CRC-32, DJB2, MurmurHash3-32, UDL literals - Void::Random — Xoshiro256** PRNG, uniform_int/real, coin_flip, shuffle, random_string - Void::Uuid — v4 (random), v5_lite (name-based), parse, RFC 4122 namespaces - Void::Encoding — Base64 (standard + URL-safe), Hex encode/decode - Void::Bits — popcount, bit extract/deposit, rotation, align, byteswap, masks - Void::Math — Vec2/Vec3/Vec4, Mat4 (identity, translation, scale, rotation) Testing module: move Stacktrace from INTERNAL_DEPS to OPTIONAL_DEPS. Added Detail/Color.hpp shim that delegates to Stacktrace::Color when present or provides inline ANSI fallback otherwise. All Stacktrace calls in SignalHandler, ConsoleReporter, and Runner are gated on VOID_HAS_STACKTRACE. Fix Repr.hpp reflect_struct to handle template specializations that lack std::meta::identifier_of (now guarded by has_identifier check). 33/33 tests pass. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
42268c6c35
commit
a09e000f0f
65 files changed
+4959
-138
No files matched your search
@@ -0,0 +1,178 @@
|
||||
#pragma once
|
||||
|
||||
#include <bit>
|
||||
#include <concepts>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
|
||||
namespace Void::Bits
|
||||
{
|
||||
|
||||
// ── Queries ───────────────────────────────────────────────────────────────────
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr int popcount(T v) noexcept
|
||||
{
|
||||
return std::popcount(v);
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr int count_leading_zeros(T v) noexcept
|
||||
{
|
||||
return std::countl_zero(v);
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr int count_trailing_zeros(T v) noexcept
|
||||
{
|
||||
return std::countr_zero(v);
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr int count_leading_ones(T v) noexcept
|
||||
{
|
||||
return std::countl_one(v);
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr int count_trailing_ones(T v) noexcept
|
||||
{
|
||||
return std::countr_one(v);
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr bool has_single_bit(T v) noexcept
|
||||
{
|
||||
return std::has_single_bit(v);
|
||||
}
|
||||
|
||||
/// Number of bits needed to represent v (floor(log2(v)) + 1). Zero for v=0.
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr int bit_width(T v) noexcept
|
||||
{
|
||||
return std::bit_width(v);
|
||||
}
|
||||
|
||||
// ── Rotation ─────────────────────────────────────────────────────────────────
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T rotl(T v, int s) noexcept
|
||||
{
|
||||
return std::rotl(v, s);
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T rotr(T v, int s) noexcept
|
||||
{
|
||||
return std::rotr(v, s);
|
||||
}
|
||||
|
||||
// ── Bit manipulation ─────────────────────────────────────────────────────────
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr bool test_bit(T v, int bit) noexcept
|
||||
{
|
||||
return (v >> bit) & T{1};
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T set_bit(T v, int bit) noexcept
|
||||
{
|
||||
return v | (T{1} << bit);
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T clear_bit(T v, int bit) noexcept
|
||||
{
|
||||
return v & ~(T{1} << bit);
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T toggle_bit(T v, int bit) noexcept
|
||||
{
|
||||
return v ^ (T{1} << bit);
|
||||
}
|
||||
|
||||
/// Extract bits [lo, lo+len) from v.
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T extract_bits(T v, int lo, int len) noexcept
|
||||
{
|
||||
return (v >> lo) & ((T{1} << len) - T{1});
|
||||
}
|
||||
|
||||
/// Deposit val into bits [lo, lo+len) of dest.
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T deposit_bits(T dest, T val, int lo, int len) noexcept
|
||||
{
|
||||
const T mask = ((T{1} << len) - T{1}) << lo;
|
||||
return (dest & ~mask) | ((val << lo) & mask);
|
||||
}
|
||||
|
||||
// ── Byte swap / endian ────────────────────────────────────────────────────────
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T byteswap(T v) noexcept
|
||||
{
|
||||
return std::byteswap(v);
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T to_little_endian(T v) noexcept
|
||||
{
|
||||
if constexpr (std::endian::native == std::endian::little) return v;
|
||||
return std::byteswap(v);
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T to_big_endian(T v) noexcept
|
||||
{
|
||||
if constexpr (std::endian::native == std::endian::big) return v;
|
||||
return std::byteswap(v);
|
||||
}
|
||||
|
||||
// ── Power-of-two helpers ─────────────────────────────────────────────────────
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T ceil_pow2(T v) noexcept
|
||||
{
|
||||
return std::bit_ceil(v);
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T floor_pow2(T v) noexcept
|
||||
{
|
||||
return std::bit_floor(v);
|
||||
}
|
||||
|
||||
/// Round v up to the next multiple of align (align must be a power of two).
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T align_up(T v, T align) noexcept
|
||||
{
|
||||
return (v + align - T{1}) & ~(align - T{1});
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T align_down(T v, T align) noexcept
|
||||
{
|
||||
return v & ~(align - T{1});
|
||||
}
|
||||
|
||||
// ── Masks ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Create a mask with `n` low bits set.
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T low_mask(int n) noexcept
|
||||
{
|
||||
if (n == 0) return T{0};
|
||||
if (n >= std::numeric_limits<T>::digits) return ~T{0};
|
||||
return (T{1} << n) - T{1};
|
||||
}
|
||||
|
||||
/// Create a mask with bits [lo, hi] set.
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] constexpr T range_mask(int lo, int hi) noexcept
|
||||
{
|
||||
return low_mask<T>(hi - lo + 1) << lo;
|
||||
}
|
||||
|
||||
} // namespace Void::Bits
|
||||
@@ -0,0 +1,112 @@
|
||||
#pragma once
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
|
||||
namespace Void::Concurrency
|
||||
{
|
||||
|
||||
// Bounded multi-producer multi-consumer channel.
|
||||
// send/receive block until space/item is available or the channel is
|
||||
// closed.
|
||||
template <typename T> class Channel
|
||||
{
|
||||
public:
|
||||
|
||||
explicit Channel(std::size_t capacity) : cap_{capacity} {}
|
||||
|
||||
Channel(const Channel&) = delete;
|
||||
Channel& operator=(const Channel&) = delete;
|
||||
|
||||
// Block until space is available. Returns false if the channel is
|
||||
// closed.
|
||||
bool send(T value)
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
not_full_.wait(
|
||||
lock, [this] { return buf_.size() < cap_ || closed_; });
|
||||
if (closed_) {
|
||||
return false;
|
||||
}
|
||||
buf_.push(std::move(value));
|
||||
not_empty_.notify_one();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Block until an item is available. Returns nullopt if closed and
|
||||
// empty.
|
||||
std::optional<T> receive()
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
not_empty_.wait(lock,
|
||||
[this] { return !buf_.empty() || closed_; });
|
||||
if (buf_.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
auto val = std::move(buf_.front());
|
||||
buf_.pop();
|
||||
not_full_.notify_one();
|
||||
return val;
|
||||
}
|
||||
|
||||
// Non-blocking send. Returns false if full or closed.
|
||||
bool try_send(T value)
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
if (closed_ || buf_.size() >= cap_) {
|
||||
return false;
|
||||
}
|
||||
buf_.push(std::move(value));
|
||||
not_empty_.notify_one();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Non-blocking receive. Returns nullopt if empty.
|
||||
std::optional<T> try_receive()
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
if (buf_.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
auto val = std::move(buf_.front());
|
||||
buf_.pop();
|
||||
not_full_.notify_one();
|
||||
return val;
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
closed_ = true;
|
||||
}
|
||||
not_full_.notify_all();
|
||||
not_empty_.notify_all();
|
||||
}
|
||||
|
||||
bool is_closed() const
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
return closed_;
|
||||
}
|
||||
|
||||
std::size_t size() const
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
return buf_.size();
|
||||
}
|
||||
|
||||
std::size_t capacity() const noexcept { return cap_; }
|
||||
|
||||
private:
|
||||
|
||||
std::size_t cap_;
|
||||
std::queue<T> buf_;
|
||||
mutable std::mutex mu_;
|
||||
std::condition_variable not_full_;
|
||||
std::condition_variable not_empty_;
|
||||
bool closed_{false};
|
||||
};
|
||||
|
||||
} // namespace Void::Concurrency
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
#include <Void/Concurrency/ThreadPool.hpp>
|
||||
#include <concepts>
|
||||
#include <future>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Concurrency
|
||||
{
|
||||
|
||||
// Submit one task per index in [first, last) to pool; block until all done.
|
||||
// Exceptions from tasks propagate via std::future::get() to the caller.
|
||||
template <std::integral I, std::invocable<I> F>
|
||||
void parallel_for(I first, I last, F&& f, ThreadPool& pool)
|
||||
{
|
||||
if (first >= last) {
|
||||
return;
|
||||
}
|
||||
std::vector<std::future<void>> futures;
|
||||
futures.reserve(static_cast<std::size_t>(last - first));
|
||||
for (auto i = first; i < last; ++i) {
|
||||
futures.push_back(pool.submit([f, i] { f(i); }));
|
||||
}
|
||||
for (auto& fut : futures) {
|
||||
fut.get();
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience overload that creates a temporary pool sized to hardware
|
||||
// concurrency.
|
||||
template <std::integral I, std::invocable<I> F>
|
||||
void parallel_for(I first, I last, F&& f)
|
||||
{
|
||||
ThreadPool pool;
|
||||
parallel_for(first, last, std::forward<F>(f), pool);
|
||||
}
|
||||
|
||||
} // namespace Void::Concurrency
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <condition_variable>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Concurrency
|
||||
{
|
||||
|
||||
class ThreadPool
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ThreadPool(
|
||||
std::size_t n = std::thread::hardware_concurrency())
|
||||
{
|
||||
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::log(
|
||||
Void::Log::Level::Debug, "Concurrency",
|
||||
std::format("ThreadPool: started with {} threads", count));
|
||||
}
|
||||
|
||||
~ThreadPool()
|
||||
{
|
||||
Void::Log::log(Void::Log::Level::Debug, "Concurrency",
|
||||
"ThreadPool: stopping");
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
stop_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
for (auto& w : workers_) {
|
||||
w.join();
|
||||
}
|
||||
}
|
||||
|
||||
ThreadPool(const ThreadPool&) = delete;
|
||||
ThreadPool& operator=(const ThreadPool&) = delete;
|
||||
ThreadPool(ThreadPool&&) = delete;
|
||||
ThreadPool& operator=(ThreadPool&&) = delete;
|
||||
|
||||
template <std::invocable F>
|
||||
auto submit(F&& f) -> 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_) {
|
||||
throw std::runtime_error(
|
||||
"Void::Concurrency::ThreadPool: submit after "
|
||||
"shutdown");
|
||||
}
|
||||
queue_.push([task] { (*task)(); });
|
||||
}
|
||||
cv_.notify_one();
|
||||
return fut;
|
||||
}
|
||||
|
||||
std::size_t thread_count() const noexcept
|
||||
{
|
||||
return workers_.size();
|
||||
}
|
||||
|
||||
std::size_t pending_count() const
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
return queue_.size();
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
void worker_loop()
|
||||
{
|
||||
for (;;) {
|
||||
std::function<void()> task;
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
cv_.wait(lock,
|
||||
[this] { return stop_ || !queue_.empty(); });
|
||||
if (stop_ && queue_.empty()) {
|
||||
return;
|
||||
}
|
||||
task = std::move(queue_.front());
|
||||
queue_.pop();
|
||||
}
|
||||
task();
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::thread> workers_;
|
||||
std::queue<std::function<void()>> queue_;
|
||||
mutable std::mutex mu_;
|
||||
std::condition_variable cv_;
|
||||
bool stop_{false};
|
||||
};
|
||||
|
||||
} // namespace Void::Concurrency
|
||||
@@ -0,0 +1,144 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Configuration/Env.hpp>
|
||||
#include <Void/FileSystem/Path.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Result/Error.hpp>
|
||||
#include <Void/Result/Result.hpp>
|
||||
|
||||
#include <format>
|
||||
#include <initializer_list>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace Void::Configuration
|
||||
{
|
||||
|
||||
/// Layered key-value configuration store.
|
||||
///
|
||||
/// Values are plain strings. Layers are applied via overlay(): the last
|
||||
/// overlay wins on key conflicts. Typical usage:
|
||||
///
|
||||
/// auto cfg = Config::from_env({"DB_HOST", "DB_PORT"});
|
||||
/// if (auto r = Config::from_file(".env"); r.has_value())
|
||||
/// cfg.overlay(*r); // file values override env
|
||||
/// cfg.set("DB_PORT", "5433"); // explicit override wins everything
|
||||
class Config
|
||||
{
|
||||
public:
|
||||
|
||||
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::log(
|
||||
Void::Log::Level::Debug, "Configuration",
|
||||
std::format("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::log(
|
||||
Void::Log::Level::Warning, "Configuration",
|
||||
std::format("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::log(
|
||||
Void::Log::Level::Debug, "Configuration",
|
||||
std::format("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);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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));
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept
|
||||
{
|
||||
return values_.size();
|
||||
}
|
||||
[[nodiscard]] bool empty() const noexcept { return values_.empty(); }
|
||||
|
||||
private:
|
||||
|
||||
std::unordered_map<std::string, std::string> values_;
|
||||
};
|
||||
|
||||
} // namespace Void::Configuration
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Result/Error.hpp>
|
||||
#include <Void/Result/Result.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Configuration
|
||||
{
|
||||
|
||||
/// Look up a single environment variable by name.
|
||||
/// Returns an error if the variable is not set.
|
||||
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
|
||||
get_env(std::string_view name)
|
||||
{
|
||||
std::string name_str{name};
|
||||
const char* val = std::getenv(name_str.c_str()); // NOLINT(concurrency-mt-unsafe)
|
||||
if (!val) {
|
||||
return Void::Result::fail(
|
||||
std::format("Configuration::get_env: '{}' is not set", name));
|
||||
}
|
||||
return Void::Result::ok(std::string{val});
|
||||
}
|
||||
|
||||
/// Look up a single environment variable, returning `fallback` if not set.
|
||||
[[nodiscard]] inline std::string
|
||||
get_env_or(std::string_view name, std::string_view fallback = {})
|
||||
{
|
||||
std::string name_str{name};
|
||||
const char* val = std::getenv(name_str.c_str()); // NOLINT(concurrency-mt-unsafe)
|
||||
return val ? std::string{val} : std::string{fallback};
|
||||
}
|
||||
|
||||
} // namespace Void::Configuration
|
||||
@@ -0,0 +1,68 @@
|
||||
#pragma once
|
||||
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
#include <meta>
|
||||
#define VOID_HAS_ENUM_REFLECTION 1
|
||||
#endif
|
||||
|
||||
namespace Void::Detail
|
||||
{
|
||||
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
|
||||
/// Return the identifier string for an enum value, or "?" if not found.
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] std::string_view enum_name(E value) noexcept
|
||||
{
|
||||
static constexpr auto enumerators =
|
||||
std::define_static_array(std::meta::enumerators_of(^^E));
|
||||
template for (constexpr auto e : enumerators) {
|
||||
if (value == [:e:]) {
|
||||
return std::meta::identifier_of(e);
|
||||
}
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/// Cast an enum value to a different enum type by matching identifier names.
|
||||
/// Returns the first enumerator of Target whose identifier equals that of
|
||||
/// the source value, or static_cast<Target>(0) if no match is found.
|
||||
template <typename Target, typename Source>
|
||||
requires std::is_enum_v<Target> && std::is_enum_v<Source>
|
||||
[[nodiscard]] Target enum_cast(Source value) noexcept
|
||||
{
|
||||
const auto src_name = enum_name(value);
|
||||
static constexpr auto target_enumerators =
|
||||
std::define_static_array(std::meta::enumerators_of(^^Target));
|
||||
template for (constexpr auto e : target_enumerators) {
|
||||
if (std::meta::identifier_of(e) == src_name) {
|
||||
return [:e:];
|
||||
}
|
||||
}
|
||||
return static_cast<Target>(0);
|
||||
}
|
||||
|
||||
/// Parse a string into an enum value by matching enumerator identifier names.
|
||||
/// Returns std::nullopt if no enumerator name matches.
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] std::optional<E> enum_parse(std::string_view name) noexcept
|
||||
{
|
||||
static constexpr auto enumerators =
|
||||
std::define_static_array(std::meta::enumerators_of(^^E));
|
||||
template for (constexpr auto e : enumerators) {
|
||||
if (std::meta::identifier_of(e) == name) {
|
||||
return [:e:];
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
#endif // VOID_HAS_ENUM_REFLECTION
|
||||
|
||||
} // namespace Void::Detail
|
||||
@@ -0,0 +1,126 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Encoding::Base64
|
||||
{
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
constexpr std::string_view alphabet =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
constexpr std::string_view alphabet_url =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
|
||||
[[nodiscard]] constexpr std::array<std::int8_t, 256>
|
||||
make_decode_table(std::string_view alpha) noexcept
|
||||
{
|
||||
std::array<std::int8_t, 256> t{};
|
||||
t.fill(-1);
|
||||
for (std::size_t i = 0; i < 64; ++i) {
|
||||
t[static_cast<unsigned char>(alpha[i])] = static_cast<std::int8_t>(i);
|
||||
}
|
||||
t[static_cast<unsigned char>('=')] = -2; // padding sentinel
|
||||
return t;
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
/// Encode bytes to standard Base64 (with padding).
|
||||
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
|
||||
{
|
||||
const auto& alpha = Detail::alphabet;
|
||||
std::string out;
|
||||
out.reserve(((data.size() + 2) / 3) * 4);
|
||||
std::size_t i = 0;
|
||||
for (; i + 2 < data.size(); i += 3) {
|
||||
const auto a = static_cast<std::uint8_t>(data[i]);
|
||||
const auto b = static_cast<std::uint8_t>(data[i + 1]);
|
||||
const auto c = static_cast<std::uint8_t>(data[i + 2]);
|
||||
out += alpha[a >> 2];
|
||||
out += alpha[((a & 3) << 4) | (b >> 4)];
|
||||
out += alpha[((b & 15) << 2) | (c >> 6)];
|
||||
out += alpha[c & 63];
|
||||
}
|
||||
if (data.size() - i == 2) {
|
||||
const auto a = static_cast<std::uint8_t>(data[i]);
|
||||
const auto b = static_cast<std::uint8_t>(data[i + 1]);
|
||||
out += alpha[a >> 2];
|
||||
out += alpha[((a & 3) << 4) | (b >> 4)];
|
||||
out += alpha[(b & 15) << 2];
|
||||
out += '=';
|
||||
} else if (data.size() - i == 1) {
|
||||
const auto a = static_cast<std::uint8_t>(data[i]);
|
||||
out += alpha[a >> 2];
|
||||
out += alpha[(a & 3) << 4];
|
||||
out += '=';
|
||||
out += '=';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Encode a string_view to standard Base64.
|
||||
[[nodiscard]] inline std::string encode(std::string_view s)
|
||||
{
|
||||
return encode(std::as_bytes(std::span{s.data(), s.size()}));
|
||||
}
|
||||
|
||||
/// Encode to URL-safe Base64 (no padding).
|
||||
[[nodiscard]] inline std::string encode_url(std::string_view s)
|
||||
{
|
||||
const auto& alpha = Detail::alphabet_url;
|
||||
auto data = std::as_bytes(std::span{s.data(), s.size()});
|
||||
std::string out;
|
||||
out.reserve(((data.size() + 2) / 3) * 4);
|
||||
std::size_t i = 0;
|
||||
for (; i + 2 < data.size(); i += 3) {
|
||||
const auto a = static_cast<std::uint8_t>(data[i]);
|
||||
const auto b = static_cast<std::uint8_t>(data[i + 1]);
|
||||
const auto c = static_cast<std::uint8_t>(data[i + 2]);
|
||||
out += alpha[a >> 2];
|
||||
out += alpha[((a & 3) << 4) | (b >> 4)];
|
||||
out += alpha[((b & 15) << 2) | (c >> 6)];
|
||||
out += alpha[c & 63];
|
||||
}
|
||||
if (data.size() - i == 2) {
|
||||
const auto a = static_cast<std::uint8_t>(data[i]);
|
||||
const auto b = static_cast<std::uint8_t>(data[i + 1]);
|
||||
out += alpha[a >> 2];
|
||||
out += alpha[((a & 3) << 4) | (b >> 4)];
|
||||
out += alpha[(b & 15) << 2];
|
||||
} else if (data.size() - i == 1) {
|
||||
const auto a = static_cast<std::uint8_t>(data[i]);
|
||||
out += alpha[a >> 2];
|
||||
out += alpha[(a & 3) << 4];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Decode standard Base64 (with or without padding). Returns nullopt on error.
|
||||
[[nodiscard]] inline std::optional<std::string> decode(std::string_view s)
|
||||
{
|
||||
static constexpr auto table = Detail::make_decode_table(Detail::alphabet);
|
||||
std::string out;
|
||||
out.reserve((s.size() / 4) * 3);
|
||||
int buf = 0, bits = 0;
|
||||
for (unsigned char c : s) {
|
||||
if (c == ' ' || c == '\n' || c == '\r' || c == '\t') continue;
|
||||
const std::int8_t v = table[c];
|
||||
if (v == -2) break; // padding
|
||||
if (v == -1) return std::nullopt;
|
||||
buf = (buf << 6) | v;
|
||||
bits += 6;
|
||||
if (bits >= 8) {
|
||||
bits -= 8;
|
||||
out += static_cast<char>((buf >> bits) & 0xFF);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Void::Encoding::Base64
|
||||
@@ -0,0 +1,71 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Encoding::Hex
|
||||
{
|
||||
|
||||
/// Encode bytes to lowercase hex string.
|
||||
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
|
||||
{
|
||||
constexpr std::string_view digits = "0123456789abcdef";
|
||||
std::string out;
|
||||
out.reserve(data.size() * 2);
|
||||
for (auto b : data) {
|
||||
const auto v = static_cast<std::uint8_t>(b);
|
||||
out += digits[v >> 4];
|
||||
out += digits[v & 0xF];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::string encode(std::string_view s)
|
||||
{
|
||||
return encode(std::as_bytes(std::span{s.data(), s.size()}));
|
||||
}
|
||||
|
||||
/// Decode hex string to bytes. Returns nullopt on invalid input.
|
||||
[[nodiscard]] inline std::optional<std::string> decode(std::string_view s)
|
||||
{
|
||||
if (s.size() % 2 != 0) return std::nullopt;
|
||||
auto hex_val = [](char c) -> std::optional<std::uint8_t> {
|
||||
if (c >= '0' && c <= '9') return static_cast<std::uint8_t>(c - '0');
|
||||
if (c >= 'a' && c <= 'f') return static_cast<std::uint8_t>(c - 'a' + 10);
|
||||
if (c >= 'A' && c <= 'F') return static_cast<std::uint8_t>(c - 'A' + 10);
|
||||
return std::nullopt;
|
||||
};
|
||||
std::string out;
|
||||
out.reserve(s.size() / 2);
|
||||
for (std::size_t i = 0; i < s.size(); i += 2) {
|
||||
auto hi = hex_val(s[i]);
|
||||
auto lo = hex_val(s[i + 1]);
|
||||
if (!hi || !lo) return std::nullopt;
|
||||
out += static_cast<char>((*hi << 4) | *lo);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Uppercase hex encoding.
|
||||
[[nodiscard]] inline std::string encode_upper(std::span<const std::byte> data)
|
||||
{
|
||||
constexpr std::string_view digits = "0123456789ABCDEF";
|
||||
std::string out;
|
||||
out.reserve(data.size() * 2);
|
||||
for (auto b : data) {
|
||||
const auto v = static_cast<std::uint8_t>(b);
|
||||
out += digits[v >> 4];
|
||||
out += digits[v & 0xF];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::string encode_upper(std::string_view s)
|
||||
{
|
||||
return encode_upper(std::as_bytes(std::span{s.data(), s.size()}));
|
||||
}
|
||||
|
||||
} // namespace Void::Encoding::Hex
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Result/Error.hpp>
|
||||
#include <Void/Result/Result.hpp>
|
||||
|
||||
@@ -26,16 +27,25 @@ namespace Void::FileSystem
|
||||
{
|
||||
std::ifstream f{path, std::ios::binary};
|
||||
if (!f.is_open()) {
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Warning, "FileSystem",
|
||||
std::format("read_file: cannot open '{}'", path.string()));
|
||||
return Void::Result::fail(std::format(
|
||||
"FileSystem::read_file: cannot open '{}'", path.string()));
|
||||
}
|
||||
std::string content{std::istreambuf_iterator<char>(f),
|
||||
std::istreambuf_iterator<char>()};
|
||||
if (f.bad()) {
|
||||
Void::Log::log(Void::Log::Level::Warning, "FileSystem",
|
||||
std::format("read_file: I/O error reading '{}'",
|
||||
path.string()));
|
||||
return Void::Result::fail(
|
||||
std::format("FileSystem::read_file: I/O error reading '{}'",
|
||||
path.string()));
|
||||
}
|
||||
Void::Log::log(Void::Log::Level::Debug, "FileSystem",
|
||||
std::format("read_file: '{}' ({} bytes)", path.string(),
|
||||
content.size()));
|
||||
return Void::Result::ok(std::move(content));
|
||||
}
|
||||
|
||||
@@ -48,12 +58,18 @@ namespace Void::FileSystem
|
||||
{
|
||||
std::ofstream f{path, std::ios::binary | std::ios::trunc};
|
||||
if (!f.is_open()) {
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Warning, "FileSystem",
|
||||
std::format("write_file: cannot open '{}'", path.string()));
|
||||
return Void::Result::fail(std::format(
|
||||
"FileSystem::write_file: cannot open '{}'", path.string()));
|
||||
}
|
||||
f.write(content.data(), static_cast<std::streamsize>(content.size()));
|
||||
f.flush();
|
||||
if (!f.good()) {
|
||||
Void::Log::log(Void::Log::Level::Warning, "FileSystem",
|
||||
std::format("write_file: I/O error writing '{}'",
|
||||
path.string()));
|
||||
return Void::Result::fail(
|
||||
std::format("FileSystem::write_file: I/O error writing '{}'",
|
||||
path.string()));
|
||||
@@ -83,10 +99,17 @@ namespace Void::FileSystem
|
||||
if (ec) {
|
||||
std::error_code ignore;
|
||||
std::filesystem::remove(staging, ignore);
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Warning, "FileSystem",
|
||||
std::format("atomic_write: rename failed for '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
return Void::Result::fail(std::format(
|
||||
"FileSystem::atomic_write: rename failed for '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
}
|
||||
Void::Log::log(Void::Log::Level::Debug, "FileSystem",
|
||||
std::format("atomic_write: '{}' committed ({} bytes)",
|
||||
path.string(), content.size()));
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -101,10 +124,17 @@ namespace Void::FileSystem
|
||||
}
|
||||
std::filesystem::create_directories(path, ec);
|
||||
if (ec) {
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Warning, "FileSystem",
|
||||
std::format("ensure_directory: cannot create '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
return Void::Result::fail(std::format(
|
||||
"FileSystem::ensure_directory: cannot create '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
}
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Debug, "FileSystem",
|
||||
std::format("ensure_directory: created '{}'", path.string()));
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -116,6 +146,9 @@ namespace Void::FileSystem
|
||||
std::error_code ec;
|
||||
std::filesystem::remove_all(path, ec);
|
||||
if (ec) {
|
||||
Void::Log::log(Void::Log::Level::Warning, "FileSystem",
|
||||
std::format("remove_path: cannot remove '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
return Void::Result::fail(
|
||||
std::format("FileSystem::remove_path: cannot remove '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Result/Error.hpp>
|
||||
#include <Void/Result/Result.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::FileSystem
|
||||
{
|
||||
|
||||
/// Return true if path exists (file, directory, or symlink).
|
||||
[[nodiscard]] inline bool exists(const std::filesystem::path& path) noexcept
|
||||
{
|
||||
std::error_code ec;
|
||||
return std::filesystem::exists(path, ec);
|
||||
}
|
||||
|
||||
/// Return the size of a regular file in bytes.
|
||||
[[nodiscard]] inline Void::Result::Result<std::uintmax_t, Void::Result::Error>
|
||||
file_size(const std::filesystem::path& path)
|
||||
{
|
||||
std::error_code ec;
|
||||
auto sz = std::filesystem::file_size(path, ec);
|
||||
if (ec) {
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Warning, "FileSystem",
|
||||
std::format("file_size: cannot stat '{}': {}", path.string(),
|
||||
ec.message()));
|
||||
return Void::Result::fail(
|
||||
std::format("FileSystem::file_size: cannot stat '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
}
|
||||
return Void::Result::ok(sz);
|
||||
}
|
||||
|
||||
/// Return the last-write time of a path.
|
||||
[[nodiscard]] inline Void::Result::
|
||||
Result<std::filesystem::file_time_type, Void::Result::Error>
|
||||
last_modified(const std::filesystem::path& path)
|
||||
{
|
||||
std::error_code ec;
|
||||
auto t = std::filesystem::last_write_time(path, ec);
|
||||
if (ec) {
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Warning, "FileSystem",
|
||||
std::format("last_modified: cannot stat '{}': {}", path.string(),
|
||||
ec.message()));
|
||||
return Void::Result::fail(
|
||||
std::format("FileSystem::last_modified: cannot stat '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
}
|
||||
return Void::Result::ok(t);
|
||||
}
|
||||
|
||||
/// List all entries in a directory (non-recursive, filesystem order).
|
||||
[[nodiscard]] inline Void::Result::
|
||||
Result<std::vector<std::filesystem::path>, Void::Result::Error>
|
||||
list_directory(const std::filesystem::path& path)
|
||||
{
|
||||
std::error_code ec;
|
||||
std::vector<std::filesystem::path> entries;
|
||||
for (const auto& entry :
|
||||
std::filesystem::directory_iterator{path, ec}) {
|
||||
if (ec) {
|
||||
break;
|
||||
}
|
||||
entries.push_back(entry.path());
|
||||
}
|
||||
if (ec) {
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Warning, "FileSystem",
|
||||
std::format("list_directory: cannot iterate '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
return Void::Result::fail(
|
||||
std::format("FileSystem::list_directory: cannot iterate '{}': {}",
|
||||
path.string(), ec.message()));
|
||||
}
|
||||
Void::Log::log(Void::Log::Level::Debug, "FileSystem",
|
||||
std::format("list_directory: '{}' ({} entries)",
|
||||
path.string(), entries.size()));
|
||||
return Void::Result::ok(std::move(entries));
|
||||
}
|
||||
|
||||
/// Copy a single file. Set overwrite=true to allow replacing an existing dst.
|
||||
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
||||
copy_file(const std::filesystem::path& src,
|
||||
const std::filesystem::path& dst,
|
||||
bool overwrite = false)
|
||||
{
|
||||
std::error_code ec;
|
||||
auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing
|
||||
: std::filesystem::copy_options::none;
|
||||
std::filesystem::copy_file(src, dst, opts, ec);
|
||||
if (ec) {
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Warning, "FileSystem",
|
||||
std::format("copy_file: '{}' -> '{}': {}", src.string(),
|
||||
dst.string(), ec.message()));
|
||||
return Void::Result::fail(
|
||||
std::format("FileSystem::copy_file: '{}' -> '{}': {}",
|
||||
src.string(), dst.string(), ec.message()));
|
||||
}
|
||||
Void::Log::log(Void::Log::Level::Debug, "FileSystem",
|
||||
std::format("copy_file: '{}' -> '{}'", src.string(),
|
||||
dst.string()));
|
||||
return {};
|
||||
}
|
||||
|
||||
/// Recursively copy a directory tree from src to dst.
|
||||
/// dst must not already exist; its parent must be accessible.
|
||||
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
||||
copy_dir(const std::filesystem::path& src,
|
||||
const std::filesystem::path& dst)
|
||||
{
|
||||
std::error_code ec;
|
||||
std::filesystem::copy(src, dst, std::filesystem::copy_options::recursive,
|
||||
ec);
|
||||
if (ec) {
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Warning, "FileSystem",
|
||||
std::format("copy_dir: '{}' -> '{}': {}", src.string(),
|
||||
dst.string(), ec.message()));
|
||||
return Void::Result::fail(
|
||||
std::format("FileSystem::copy_dir: '{}' -> '{}': {}",
|
||||
src.string(), dst.string(), ec.message()));
|
||||
}
|
||||
Void::Log::log(Void::Log::Level::Debug, "FileSystem",
|
||||
std::format("copy_dir: '{}' -> '{}'", src.string(),
|
||||
dst.string()));
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace Void::FileSystem
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/FileSystem/Path.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
@@ -36,6 +37,9 @@ namespace Void::FileSystem
|
||||
~TempDir() noexcept
|
||||
{
|
||||
if (!m_path.empty()) {
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Debug, "FileSystem",
|
||||
std::format("TempDir: removed '{}'", m_path.string()));
|
||||
std::error_code ignore;
|
||||
std::filesystem::remove_all(m_path, ignore);
|
||||
}
|
||||
@@ -109,6 +113,9 @@ namespace Void::FileSystem
|
||||
base / std::format("{}{:016x}", prefix, seed);
|
||||
std::error_code ec;
|
||||
if (std::filesystem::create_directory(candidate, ec)) {
|
||||
Void::Log::log(Void::Log::Level::Debug, "FileSystem",
|
||||
std::format("TempDir: created '{}'",
|
||||
candidate.string()));
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Hash
|
||||
{
|
||||
|
||||
// ── FNV-1a (32-bit) ──────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr std::uint32_t fnv1a32(std::string_view s) noexcept
|
||||
{
|
||||
std::uint32_t h = 2166136261u;
|
||||
for (unsigned char c : s) {
|
||||
h ^= c;
|
||||
h *= 16777619u;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::uint32_t
|
||||
fnv1a32(std::span<const std::byte> data) noexcept
|
||||
{
|
||||
std::uint32_t h = 2166136261u;
|
||||
for (auto b : data) {
|
||||
h ^= static_cast<unsigned char>(b);
|
||||
h *= 16777619u;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
// ── FNV-1a (64-bit) ──────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr std::uint64_t fnv1a64(std::string_view s) noexcept
|
||||
{
|
||||
std::uint64_t h = 14695981039346656037ull;
|
||||
for (unsigned char c : s) {
|
||||
h ^= c;
|
||||
h *= 1099511628211ull;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::uint64_t
|
||||
fnv1a64(std::span<const std::byte> data) noexcept
|
||||
{
|
||||
std::uint64_t h = 14695981039346656037ull;
|
||||
for (auto b : data) {
|
||||
h ^= static_cast<unsigned char>(b);
|
||||
h *= 1099511628211ull;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
// ── CRC-32 (ISO 3309 / Ethernet polynomial) ───────────────────────────────────
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
[[nodiscard]] constexpr std::array<std::uint32_t, 256> make_crc32_table() noexcept
|
||||
{
|
||||
std::array<std::uint32_t, 256> t{};
|
||||
for (std::uint32_t i = 0; i < 256; ++i) {
|
||||
std::uint32_t c = i;
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
c = (c & 1) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1);
|
||||
}
|
||||
t[i] = c;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
[[nodiscard]] inline std::uint32_t crc32(std::string_view s) noexcept
|
||||
{
|
||||
static constexpr auto table = Detail::make_crc32_table();
|
||||
std::uint32_t c = 0xFFFFFFFFu;
|
||||
for (unsigned char b : s) {
|
||||
c = table[(c ^ b) & 0xFF] ^ (c >> 8);
|
||||
}
|
||||
return c ^ 0xFFFFFFFFu;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::uint32_t
|
||||
crc32(std::span<const std::byte> data) noexcept
|
||||
{
|
||||
static constexpr auto table = Detail::make_crc32_table();
|
||||
std::uint32_t c = 0xFFFFFFFFu;
|
||||
for (auto b : data) {
|
||||
c = table[(c ^ static_cast<unsigned char>(b)) & 0xFF] ^ (c >> 8);
|
||||
}
|
||||
return c ^ 0xFFFFFFFFu;
|
||||
}
|
||||
|
||||
// ── DJB2 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] constexpr std::uint64_t djb2(std::string_view s) noexcept
|
||||
{
|
||||
std::uint64_t h = 5381;
|
||||
for (unsigned char c : s) {
|
||||
h = ((h << 5) + h) ^ c;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
// ── MurmurHash3 (32-bit, x86) ─────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] inline std::uint32_t murmur3_32(std::string_view key,
|
||||
std::uint32_t seed = 0) noexcept
|
||||
{
|
||||
const auto* data = reinterpret_cast<const std::uint8_t*>(key.data());
|
||||
const std::size_t len = key.size();
|
||||
const std::size_t nblocks = len / 4;
|
||||
|
||||
std::uint32_t h = seed;
|
||||
constexpr std::uint32_t c1 = 0xcc9e2d51u;
|
||||
constexpr std::uint32_t c2 = 0x1b873593u;
|
||||
|
||||
for (std::size_t i = 0; i < nblocks; ++i) {
|
||||
std::uint32_t k;
|
||||
__builtin_memcpy(&k, data + i * 4, 4);
|
||||
k *= c1;
|
||||
k = (k << 15) | (k >> 17);
|
||||
k *= c2;
|
||||
h ^= k;
|
||||
h = (h << 13) | (h >> 19);
|
||||
h = h * 5 + 0xe6546b64u;
|
||||
}
|
||||
|
||||
const auto* tail = data + nblocks * 4;
|
||||
std::uint32_t k = 0;
|
||||
switch (len & 3) {
|
||||
case 3: k ^= static_cast<std::uint32_t>(tail[2]) << 16; [[fallthrough]];
|
||||
case 2: k ^= static_cast<std::uint32_t>(tail[1]) << 8; [[fallthrough]];
|
||||
case 1:
|
||||
k ^= static_cast<std::uint32_t>(tail[0]);
|
||||
k *= c1;
|
||||
k = (k << 15) | (k >> 17);
|
||||
k *= c2;
|
||||
h ^= k;
|
||||
}
|
||||
|
||||
h ^= static_cast<std::uint32_t>(len);
|
||||
h ^= h >> 16;
|
||||
h *= 0x85ebca6bu;
|
||||
h ^= h >> 13;
|
||||
h *= 0xc2b2ae35u;
|
||||
h ^= h >> 16;
|
||||
return h;
|
||||
}
|
||||
|
||||
// ── Convenience: string literal compile-time hash ────────────────────────────
|
||||
|
||||
inline namespace Literals
|
||||
{
|
||||
[[nodiscard]] consteval std::uint32_t
|
||||
operator""_fnv32(const char* s, std::size_t n) noexcept
|
||||
{
|
||||
return fnv1a32(std::string_view{s, n});
|
||||
}
|
||||
|
||||
[[nodiscard]] consteval std::uint64_t
|
||||
operator""_fnv64(const char* s, std::size_t n) noexcept
|
||||
{
|
||||
return fnv1a64(std::string_view{s, n});
|
||||
}
|
||||
} // namespace Literals
|
||||
|
||||
} // namespace Void::Hash
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
#include <functional>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Log
|
||||
{
|
||||
|
||||
enum class Level : unsigned char {
|
||||
Trace = 0,
|
||||
Debug,
|
||||
Info,
|
||||
Warning,
|
||||
Error,
|
||||
Fatal
|
||||
};
|
||||
|
||||
/// Signature for any log consumer. Three arguments:
|
||||
/// level — severity of the event
|
||||
/// module — short library-internal label (e.g. "FileSystem",
|
||||
/// "Concurrency") message — human-readable description
|
||||
using Sink = std::function<void(
|
||||
Level level, std::string_view module, std::string_view message)>;
|
||||
|
||||
/// Install the global sink. Any previously installed sink is replaced.
|
||||
/// Pass a default-constructed (empty) Sink to silence all output.
|
||||
/// Thread-safe: the new sink is visible to all threads after this returns.
|
||||
void set_sink(Sink sink);
|
||||
|
||||
/// Emit one log event through the global sink.
|
||||
/// No-op (zero allocation) if no sink is installed.
|
||||
/// Thread-safe with respect to set_sink() and concurrent log() calls.
|
||||
void log(Level level, std::string_view module, std::string_view message);
|
||||
|
||||
} // namespace Void::Log
|
||||
@@ -0,0 +1,69 @@
|
||||
#pragma once
|
||||
#include <Void/Detail/Enum.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Logging/Logger.hpp>
|
||||
|
||||
// Bridge between Void::Log (the thin emission layer used by all modules) and
|
||||
// Void::Logging::Logger (the full sink implementation).
|
||||
//
|
||||
// Include this header only in translation units that also link Void::Logging.
|
||||
// All other code that merely calls Void::Log::log() needs only Log.hpp.
|
||||
//
|
||||
// Example:
|
||||
// #include <Void/Log/LoggingAdapter.hpp>
|
||||
// #include <Void/Logging/ConsoleLogger.hpp>
|
||||
//
|
||||
// Void::Logging::ConsoleLogger logger;
|
||||
// Void::Log::set_sink(Void::Log::make_sink(logger));
|
||||
|
||||
namespace Void::Log
|
||||
{
|
||||
|
||||
/// Map a Void::Log::Level to the corresponding Void::Logging::Level.
|
||||
/// Uses reflection to match by enumerator name; falls back to a
|
||||
/// hand-written table for non-reflecting compilers.
|
||||
[[nodiscard]] inline Void::Logging::Level
|
||||
to_logging_level(Void::Log::Level level) noexcept
|
||||
{
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
return Void::Detail::enum_cast<Void::Logging::Level>(level);
|
||||
#else
|
||||
switch (level) {
|
||||
case Level::Trace:
|
||||
return Void::Logging::Level::Trace;
|
||||
case Level::Debug:
|
||||
return Void::Logging::Level::Debug;
|
||||
case Level::Info:
|
||||
return Void::Logging::Level::Info;
|
||||
case Level::Warning:
|
||||
return Void::Logging::Level::Warning;
|
||||
case Level::Error:
|
||||
return Void::Logging::Level::Error;
|
||||
case Level::Fatal:
|
||||
return Void::Logging::Level::Fatal;
|
||||
}
|
||||
return Void::Logging::Level::Info;
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Create a Sink that routes events to a Void::Logging::Logger.
|
||||
///
|
||||
/// The module name is prepended to the message as "[module] " so the
|
||||
/// scope/tag information survives without requiring push_scope() calls on
|
||||
/// the internal logger.
|
||||
///
|
||||
/// Lifetime: the returned Sink holds a reference to logger; logger must
|
||||
/// outlive any call made through the Sink.
|
||||
[[nodiscard]] inline Sink make_sink(Void::Logging::Logger& logger)
|
||||
{
|
||||
return [&logger](Level level, std::string_view module,
|
||||
std::string_view message) {
|
||||
auto full = std::string{"["};
|
||||
full += module;
|
||||
full += "] ";
|
||||
full += message;
|
||||
logger.log(to_logging_level(level), full);
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace Void::Log
|
||||
@@ -55,6 +55,7 @@ namespace Void::Logging
|
||||
|
||||
private:
|
||||
|
||||
std::filesystem::path m_path;
|
||||
std::ofstream m_file;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Detail/Enum.hpp>
|
||||
|
||||
#include <format>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
@@ -28,29 +30,32 @@ namespace Void::Logging
|
||||
return std::to_underlying(a) >= std::to_underlying(b);
|
||||
}
|
||||
|
||||
/// Convert a Level to its canonical string representation.
|
||||
/// Defined inline so it is usable in constexpr contexts and
|
||||
/// visible to every translation unit without ODR violations.
|
||||
/// Convert a Level to its identifier string via reflection when available,
|
||||
/// falling back to a hand-written table for non-reflecting compilers.
|
||||
[[nodiscard]] constexpr std::string_view to_string(Level level) noexcept
|
||||
{
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
return Void::Detail::enum_name(level);
|
||||
#else
|
||||
switch (level) {
|
||||
case Level::Disabled:
|
||||
return "DISABLED";
|
||||
return "Disabled";
|
||||
case Level::Trace:
|
||||
return "TRACE";
|
||||
return "Trace";
|
||||
case Level::Debug:
|
||||
return "DEBUG";
|
||||
return "Debug";
|
||||
case Level::Info:
|
||||
return "INFO";
|
||||
return "Info";
|
||||
case Level::Warning:
|
||||
return "WARN";
|
||||
return "Warning";
|
||||
case Level::Error:
|
||||
return "ERROR";
|
||||
return "Error";
|
||||
case Level::Fatal:
|
||||
return "FATAL";
|
||||
return "Fatal";
|
||||
default:
|
||||
return "UNK";
|
||||
return "?";
|
||||
}
|
||||
#endif
|
||||
}
|
||||
} // namespace Void::Logging
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Math/Vec.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <concepts>
|
||||
|
||||
namespace Void::Math
|
||||
{
|
||||
|
||||
// ── Mat4 (column-major, row-major storage) ────────────────────────────────────
|
||||
// Stored row-major: m[row][col].
|
||||
|
||||
template <std::floating_point T = float>
|
||||
struct Mat4
|
||||
{
|
||||
std::array<std::array<T, 4>, 4> m{};
|
||||
|
||||
constexpr Mat4() noexcept = default;
|
||||
|
||||
[[nodiscard]] static constexpr Mat4 identity() noexcept
|
||||
{
|
||||
Mat4 r;
|
||||
r.m[0][0] = r.m[1][1] = r.m[2][2] = r.m[3][3] = T{1};
|
||||
return r;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr T& at(int row, int col) noexcept { return m[row][col]; }
|
||||
[[nodiscard]] constexpr T at(int row, int col) const noexcept { return m[row][col]; }
|
||||
|
||||
[[nodiscard]] constexpr bool operator==(const Mat4&) const noexcept = default;
|
||||
|
||||
[[nodiscard]] constexpr Mat4 operator+(const Mat4& o) const noexcept
|
||||
{
|
||||
Mat4 r;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
for (int j = 0; j < 4; ++j)
|
||||
r.m[i][j] = m[i][j] + o.m[i][j];
|
||||
return r;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Mat4 operator*(T s) const noexcept
|
||||
{
|
||||
Mat4 r;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
for (int j = 0; j < 4; ++j)
|
||||
r.m[i][j] = m[i][j] * s;
|
||||
return r;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Mat4 operator*(const Mat4& o) const noexcept
|
||||
{
|
||||
Mat4 r;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
T s{};
|
||||
for (int k = 0; k < 4; ++k) s += m[i][k] * o.m[k][j];
|
||||
r.m[i][j] = s;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Vec4<T> operator*(Vec4<T> v) const noexcept
|
||||
{
|
||||
return {
|
||||
m[0][0]*v.x + m[0][1]*v.y + m[0][2]*v.z + m[0][3]*v.w,
|
||||
m[1][0]*v.x + m[1][1]*v.y + m[1][2]*v.z + m[1][3]*v.w,
|
||||
m[2][0]*v.x + m[2][1]*v.y + m[2][2]*v.z + m[2][3]*v.w,
|
||||
m[3][0]*v.x + m[3][1]*v.y + m[3][2]*v.z + m[3][3]*v.w,
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Mat4 transposed() const noexcept
|
||||
{
|
||||
Mat4 r;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
for (int j = 0; j < 4; ++j)
|
||||
r.m[i][j] = m[j][i];
|
||||
return r;
|
||||
}
|
||||
|
||||
/// Translation matrix (affine, last row [0 0 0 1]).
|
||||
[[nodiscard]] static constexpr Mat4 translation(T tx, T ty, T tz) noexcept
|
||||
{
|
||||
auto r = identity();
|
||||
r.m[0][3] = tx;
|
||||
r.m[1][3] = ty;
|
||||
r.m[2][3] = tz;
|
||||
return r;
|
||||
}
|
||||
|
||||
/// Uniform scale matrix.
|
||||
[[nodiscard]] static constexpr Mat4 scale(T sx, T sy, T sz) noexcept
|
||||
{
|
||||
auto r = identity();
|
||||
r.m[0][0] = sx;
|
||||
r.m[1][1] = sy;
|
||||
r.m[2][2] = sz;
|
||||
return r;
|
||||
}
|
||||
|
||||
/// Rotation around X axis (angle in radians).
|
||||
[[nodiscard]] static Mat4 rotation_x(T angle) noexcept
|
||||
{
|
||||
auto r = identity();
|
||||
const T c = std::cos(angle), s = std::sin(angle);
|
||||
r.m[1][1] = c; r.m[1][2] = -s;
|
||||
r.m[2][1] = s; r.m[2][2] = c;
|
||||
return r;
|
||||
}
|
||||
|
||||
/// Rotation around Y axis.
|
||||
[[nodiscard]] static Mat4 rotation_y(T angle) noexcept
|
||||
{
|
||||
auto r = identity();
|
||||
const T c = std::cos(angle), s = std::sin(angle);
|
||||
r.m[0][0] = c; r.m[0][2] = s;
|
||||
r.m[2][0] = -s; r.m[2][2] = c;
|
||||
return r;
|
||||
}
|
||||
|
||||
/// Rotation around Z axis.
|
||||
[[nodiscard]] static Mat4 rotation_z(T angle) noexcept
|
||||
{
|
||||
auto r = identity();
|
||||
const T c = std::cos(angle), s = std::sin(angle);
|
||||
r.m[0][0] = c; r.m[0][1] = -s;
|
||||
r.m[1][0] = s; r.m[1][1] = c;
|
||||
return r;
|
||||
}
|
||||
};
|
||||
|
||||
using Mat4f = Mat4<float>;
|
||||
using Mat4d = Mat4<double>;
|
||||
|
||||
} // namespace Void::Math
|
||||
@@ -0,0 +1,135 @@
|
||||
#pragma once
|
||||
|
||||
#include <cmath>
|
||||
#include <concepts>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
namespace Void::Math
|
||||
{
|
||||
|
||||
// ── Vec2 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
template <std::floating_point T = float>
|
||||
struct Vec2
|
||||
{
|
||||
T x{}, y{};
|
||||
|
||||
constexpr Vec2() noexcept = default;
|
||||
constexpr Vec2(T x, T y) noexcept : x{x}, y{y} {}
|
||||
|
||||
[[nodiscard]] constexpr bool operator==(const Vec2&) const noexcept = default;
|
||||
|
||||
[[nodiscard]] constexpr Vec2 operator+(Vec2 o) const noexcept { return {x + o.x, y + o.y}; }
|
||||
[[nodiscard]] constexpr Vec2 operator-(Vec2 o) const noexcept { return {x - o.x, y - o.y}; }
|
||||
[[nodiscard]] constexpr Vec2 operator*(T s) const noexcept { return {x * s, y * s}; }
|
||||
[[nodiscard]] constexpr Vec2 operator/(T s) const noexcept { return {x / s, y / s}; }
|
||||
[[nodiscard]] constexpr Vec2 operator-() const noexcept { return {-x, -y}; }
|
||||
|
||||
constexpr Vec2& operator+=(Vec2 o) noexcept { x += o.x; y += o.y; return *this; }
|
||||
constexpr Vec2& operator-=(Vec2 o) noexcept { x -= o.x; y -= o.y; return *this; }
|
||||
constexpr Vec2& operator*=(T s) noexcept { x *= s; y *= s; return *this; }
|
||||
constexpr Vec2& operator/=(T s) noexcept { x /= s; y /= s; return *this; }
|
||||
|
||||
[[nodiscard]] constexpr T dot(Vec2 o) const noexcept { return x * o.x + y * o.y; }
|
||||
[[nodiscard]] constexpr T length_sq() const noexcept { return dot(*this); }
|
||||
[[nodiscard]] T length() const noexcept { return std::sqrt(length_sq()); }
|
||||
[[nodiscard]] Vec2 normalized() const noexcept { return *this / length(); }
|
||||
|
||||
[[nodiscard]] std::string to_string() const
|
||||
{
|
||||
return std::format("({}, {})", x, y);
|
||||
}
|
||||
};
|
||||
|
||||
template <std::floating_point T>
|
||||
[[nodiscard]] constexpr Vec2<T> operator*(T s, Vec2<T> v) noexcept { return v * s; }
|
||||
|
||||
// ── Vec3 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
template <std::floating_point T = float>
|
||||
struct Vec3
|
||||
{
|
||||
T x{}, y{}, z{};
|
||||
|
||||
constexpr Vec3() noexcept = default;
|
||||
constexpr Vec3(T x, T y, T z) noexcept : x{x}, y{y}, z{z} {}
|
||||
|
||||
[[nodiscard]] constexpr bool operator==(const Vec3&) const noexcept = default;
|
||||
|
||||
[[nodiscard]] constexpr Vec3 operator+(Vec3 o) const noexcept { return {x + o.x, y + o.y, z + o.z}; }
|
||||
[[nodiscard]] constexpr Vec3 operator-(Vec3 o) const noexcept { return {x - o.x, y - o.y, z - o.z}; }
|
||||
[[nodiscard]] constexpr Vec3 operator*(T s) const noexcept { return {x * s, y * s, z * s}; }
|
||||
[[nodiscard]] constexpr Vec3 operator/(T s) const noexcept { return {x / s, y / s, z / s}; }
|
||||
[[nodiscard]] constexpr Vec3 operator-() const noexcept { return {-x, -y, -z}; }
|
||||
|
||||
constexpr Vec3& operator+=(Vec3 o) noexcept { x += o.x; y += o.y; z += o.z; return *this; }
|
||||
constexpr Vec3& operator-=(Vec3 o) noexcept { x -= o.x; y -= o.y; z -= o.z; return *this; }
|
||||
constexpr Vec3& operator*=(T s) noexcept { x *= s; y *= s; z *= s; return *this; }
|
||||
constexpr Vec3& operator/=(T s) noexcept { x /= s; y /= s; z /= s; return *this; }
|
||||
|
||||
[[nodiscard]] constexpr T dot(Vec3 o) const noexcept { return x * o.x + y * o.y + z * o.z; }
|
||||
[[nodiscard]] constexpr Vec3 cross(Vec3 o) const noexcept
|
||||
{
|
||||
return {y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x};
|
||||
}
|
||||
[[nodiscard]] constexpr T length_sq() const noexcept { return dot(*this); }
|
||||
[[nodiscard]] T length() const noexcept { return std::sqrt(length_sq()); }
|
||||
[[nodiscard]] Vec3 normalized() const noexcept { return *this / length(); }
|
||||
|
||||
[[nodiscard]] std::string to_string() const
|
||||
{
|
||||
return std::format("({}, {}, {})", x, y, z);
|
||||
}
|
||||
};
|
||||
|
||||
template <std::floating_point T>
|
||||
[[nodiscard]] constexpr Vec3<T> operator*(T s, Vec3<T> v) noexcept { return v * s; }
|
||||
|
||||
// ── Vec4 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
template <std::floating_point T = float>
|
||||
struct Vec4
|
||||
{
|
||||
T x{}, y{}, z{}, w{};
|
||||
|
||||
constexpr Vec4() noexcept = default;
|
||||
constexpr Vec4(T x, T y, T z, T w) noexcept : x{x}, y{y}, z{z}, w{w} {}
|
||||
explicit constexpr Vec4(Vec3<T> v, T w = T{1}) noexcept : x{v.x}, y{v.y}, z{v.z}, w{w} {}
|
||||
|
||||
[[nodiscard]] constexpr bool operator==(const Vec4&) const noexcept = default;
|
||||
|
||||
[[nodiscard]] constexpr Vec4 operator+(Vec4 o) const noexcept { return {x+o.x, y+o.y, z+o.z, w+o.w}; }
|
||||
[[nodiscard]] constexpr Vec4 operator-(Vec4 o) const noexcept { return {x-o.x, y-o.y, z-o.z, w-o.w}; }
|
||||
[[nodiscard]] constexpr Vec4 operator*(T s) const noexcept { return {x*s, y*s, z*s, w*s}; }
|
||||
[[nodiscard]] constexpr Vec4 operator/(T s) const noexcept { return {x/s, y/s, z/s, w/s}; }
|
||||
|
||||
[[nodiscard]] constexpr T dot(Vec4 o) const noexcept { return x*o.x + y*o.y + z*o.z + w*o.w; }
|
||||
[[nodiscard]] constexpr T length_sq() const noexcept { return dot(*this); }
|
||||
[[nodiscard]] T length() const noexcept { return std::sqrt(length_sq()); }
|
||||
[[nodiscard]] constexpr Vec3<T> xyz() const noexcept { return {x, y, z}; }
|
||||
};
|
||||
|
||||
// ── Free functions ────────────────────────────────────────────────────────────
|
||||
|
||||
template <std::floating_point T>
|
||||
[[nodiscard]] constexpr T distance(Vec2<T> a, Vec2<T> b) noexcept { return (a - b).length(); }
|
||||
|
||||
template <std::floating_point T>
|
||||
[[nodiscard]] constexpr T distance(Vec3<T> a, Vec3<T> b) noexcept { return (a - b).length(); }
|
||||
|
||||
template <std::floating_point T>
|
||||
[[nodiscard]] constexpr Vec2<T> lerp(Vec2<T> a, Vec2<T> b, T t) noexcept { return a + (b - a) * t; }
|
||||
|
||||
template <std::floating_point T>
|
||||
[[nodiscard]] constexpr Vec3<T> lerp(Vec3<T> a, Vec3<T> b, T t) noexcept { return a + (b - a) * t; }
|
||||
|
||||
// Convenience aliases
|
||||
using Vec2f = Vec2<float>;
|
||||
using Vec2d = Vec2<double>;
|
||||
using Vec3f = Vec3<float>;
|
||||
using Vec3d = Vec3<double>;
|
||||
using Vec4f = Vec4<float>;
|
||||
using Vec4d = Vec4<double>;
|
||||
|
||||
} // namespace Void::Math
|
||||
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Result/Error.hpp>
|
||||
#include <Void/Result/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#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
|
||||
};
|
||||
|
||||
/// 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});
|
||||
|
||||
/// 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,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
|
||||
@@ -36,7 +36,11 @@ namespace Void::Result::Detail
|
||||
template <typename T> [[nodiscard]] std::string reflect_struct(const T& obj)
|
||||
{
|
||||
std::string out;
|
||||
out += std::meta::identifier_of(^^T);
|
||||
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(
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <concepts>
|
||||
#include <ranges>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::String
|
||||
{
|
||||
|
||||
// ── Views (zero allocation) ───────────────────────────────────────────────
|
||||
|
||||
/// Remove leading whitespace.
|
||||
[[nodiscard]] constexpr std::string_view
|
||||
trim_left(std::string_view s) noexcept
|
||||
{
|
||||
const auto it =
|
||||
std::find_if_not(s.begin(), s.end(),
|
||||
[](unsigned char c) { return std::isspace(c); });
|
||||
s.remove_prefix(static_cast<std::size_t>(it - s.begin()));
|
||||
return s;
|
||||
}
|
||||
|
||||
/// Remove trailing whitespace.
|
||||
[[nodiscard]] constexpr std::string_view
|
||||
trim_right(std::string_view s) noexcept
|
||||
{
|
||||
const auto it =
|
||||
std::find_if_not(s.rbegin(), s.rend(),
|
||||
[](unsigned char c) { return std::isspace(c); });
|
||||
s.remove_suffix(static_cast<std::size_t>(it - s.rbegin()));
|
||||
return s;
|
||||
}
|
||||
|
||||
/// Remove leading and trailing whitespace.
|
||||
[[nodiscard]] constexpr std::string_view trim(std::string_view s) noexcept
|
||||
{
|
||||
return trim_right(trim_left(s));
|
||||
}
|
||||
|
||||
// ── Split ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Split on a single character delimiter. Empty tokens are preserved.
|
||||
/// The returned views point into `s`; `s` must outlive the result.
|
||||
[[nodiscard]] inline std::vector<std::string_view>
|
||||
split(std::string_view s, char delimiter)
|
||||
{
|
||||
std::vector<std::string_view> parts;
|
||||
std::size_t pos = 0;
|
||||
while (true) {
|
||||
const auto end = s.find(delimiter, pos);
|
||||
parts.push_back(s.substr(pos, end - pos));
|
||||
if (end == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = end + 1;
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/// Split on a multi-character delimiter string. Empty tokens are preserved.
|
||||
[[nodiscard]] inline std::vector<std::string_view>
|
||||
split(std::string_view s, std::string_view delimiter)
|
||||
{
|
||||
std::vector<std::string_view> parts;
|
||||
if (delimiter.empty()) {
|
||||
parts.emplace_back(s);
|
||||
return parts;
|
||||
}
|
||||
std::size_t pos = 0;
|
||||
while (true) {
|
||||
const auto end = s.find(delimiter, pos);
|
||||
parts.push_back(s.substr(pos, end - pos));
|
||||
if (end == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = end + delimiter.size();
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
// ── Join ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Join any input range of string-like values with a separator.
|
||||
template <std::ranges::input_range R>
|
||||
requires std::convertible_to<std::ranges::range_value_t<R>, std::string_view>
|
||||
[[nodiscard]] std::string join(R&& parts, std::string_view sep)
|
||||
{
|
||||
std::string out;
|
||||
bool first = true;
|
||||
for (const auto& part : parts) {
|
||||
if (!first) {
|
||||
out += sep;
|
||||
}
|
||||
out += std::string_view{part};
|
||||
first = false;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── Case conversion ───────────────────────────────────────────────────────
|
||||
|
||||
/// Return an ASCII-lowercased copy of `s`.
|
||||
[[nodiscard]] inline std::string to_lower(std::string_view s)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(s.size());
|
||||
for (unsigned char c : s) {
|
||||
out += static_cast<char>(std::tolower(c));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Return an ASCII-uppercased copy of `s`.
|
||||
[[nodiscard]] inline std::string to_upper(std::string_view s)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(s.size());
|
||||
for (unsigned char c : s) {
|
||||
out += static_cast<char>(std::toupper(c));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── Replace ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// Return a copy of `s` with every non-overlapping occurrence of `from`
|
||||
/// replaced by `to`. Returns `s` as-is if `from` is empty.
|
||||
[[nodiscard]] inline std::string
|
||||
replace_all(std::string_view s, std::string_view from, std::string_view to)
|
||||
{
|
||||
if (from.empty()) {
|
||||
return std::string{s};
|
||||
}
|
||||
std::string out;
|
||||
out.reserve(s.size());
|
||||
std::size_t pos = 0;
|
||||
while (true) {
|
||||
const auto hit = s.find(from, pos);
|
||||
out += s.substr(pos, hit - pos);
|
||||
if (hit == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
out += to;
|
||||
pos = hit + from.size();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── Padding ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// Left-pad `s` to at least `width` characters, filling with `fill`.
|
||||
[[nodiscard]] inline std::string
|
||||
pad_left(std::string_view s, std::size_t width, char fill = ' ')
|
||||
{
|
||||
if (s.size() >= width) {
|
||||
return std::string{s};
|
||||
}
|
||||
std::string out(width - s.size(), fill);
|
||||
out += s;
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Right-pad `s` to at least `width` characters, filling with `fill`.
|
||||
[[nodiscard]] inline std::string
|
||||
pad_right(std::string_view s, std::size_t width, char fill = ' ')
|
||||
{
|
||||
std::string out{s};
|
||||
if (out.size() < width) {
|
||||
out.append(width - out.size(), fill);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── Misc ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Repeat `s` exactly `n` times.
|
||||
[[nodiscard]] inline std::string repeat(std::string_view s, std::size_t n)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(s.size() * n);
|
||||
for (std::size_t i = 0; i < n; ++i) {
|
||||
out += s;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Count non-overlapping occurrences of `substr` in `s`.
|
||||
[[nodiscard]] inline std::size_t
|
||||
count_occurrences(std::string_view s, std::string_view substr) noexcept
|
||||
{
|
||||
if (substr.empty()) {
|
||||
return 0;
|
||||
}
|
||||
std::size_t n = 0;
|
||||
std::size_t pos = 0;
|
||||
while ((pos = s.find(substr, pos)) != std::string_view::npos) {
|
||||
++n;
|
||||
pos += substr.size();
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
} // namespace Void::String
|
||||
@@ -86,6 +86,7 @@ namespace Void::Testing
|
||||
bool show_help{false};
|
||||
unsigned repeat{1};
|
||||
unsigned random_seed{0};
|
||||
unsigned parallel_threads{0}; // 0 = sequential
|
||||
};
|
||||
|
||||
} // namespace Void::Testing
|
||||
@@ -1,13 +1,13 @@
|
||||
#pragma once
|
||||
#include <Void/Testing/Reporter.hpp>
|
||||
#include <Void/Stacktrace/Color.hpp>
|
||||
#include <Void/Testing/Detail/Color.hpp>
|
||||
#include <ostream>
|
||||
|
||||
namespace Void::Testing {
|
||||
class ConsoleReporter final : public Reporter {
|
||||
public:
|
||||
explicit ConsoleReporter(std::ostream& os, bool color_enabled = true) : os_(os) {
|
||||
Void::Stacktrace::Color::g_color_enabled = color_enabled;
|
||||
Void::Testing::Detail::Color::g_color_enabled = color_enabled;
|
||||
}
|
||||
void on_run_start(const RunConfig& config, int total_tests) override;
|
||||
void on_suite_start(const std::string& suite_name, int test_count) override;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef VOID_HAS_STACKTRACE
|
||||
#include <Void/Stacktrace/Color.hpp>
|
||||
namespace Void::Testing::Detail {
|
||||
namespace Color = Void::Stacktrace::Color;
|
||||
}
|
||||
#else
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
namespace Void::Testing::Detail::Color {
|
||||
inline bool g_color_enabled{true};
|
||||
constexpr std::string_view reset = "\033[0m";
|
||||
constexpr std::string_view bold = "\033[1m";
|
||||
constexpr std::string_view dim = "\033[2m";
|
||||
constexpr std::string_view bold_red = "\033[1;31m";
|
||||
constexpr std::string_view bold_green = "\033[1;32m";
|
||||
constexpr std::string_view bold_yellow = "\033[1;33m";
|
||||
constexpr std::string_view bold_blue = "\033[1;34m";
|
||||
constexpr std::string_view bold_magenta = "\033[1;35m";
|
||||
constexpr std::string_view bold_cyan = "\033[1;36m";
|
||||
constexpr std::string_view bold_white = "\033[1;37m";
|
||||
constexpr std::string_view red = "\033[31m";
|
||||
constexpr std::string_view green = "\033[32m";
|
||||
constexpr std::string_view yellow = "\033[33m";
|
||||
constexpr std::string_view cyan = "\033[36m";
|
||||
inline std::string apply(std::string_view code, std::string_view text)
|
||||
{
|
||||
if (!g_color_enabled) return std::string{text};
|
||||
return std::string{code} + std::string{text} + std::string{reset};
|
||||
}
|
||||
} // namespace Void::Testing::Detail::Color
|
||||
#endif
|
||||
@@ -3,21 +3,30 @@
|
||||
#include <Void/Testing/Reporter.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace Void::Testing {
|
||||
class Runner {
|
||||
public:
|
||||
static Runner& instance() {
|
||||
static Runner r;
|
||||
return r;
|
||||
}
|
||||
RunConfig parse_args(int argc, char** argv);
|
||||
RunResult run(const RunConfig& config);
|
||||
int main(int argc, char** argv);
|
||||
private:
|
||||
Runner() = default;
|
||||
std::vector<TestCase> filter_tests(const std::vector<TestCase>& tests, const RunConfig& config);
|
||||
std::unique_ptr<Reporter> create_reporter(const RunConfig& config);
|
||||
TestResult execute_test(TestCase& test_case);
|
||||
void run_test_body(TestCase& test_case, TestResult& result);
|
||||
};
|
||||
namespace Void::Testing
|
||||
{
|
||||
class Runner
|
||||
{
|
||||
public:
|
||||
|
||||
static Runner& instance()
|
||||
{
|
||||
static Runner r;
|
||||
return r;
|
||||
}
|
||||
RunConfig parse_args(int argc, char** argv);
|
||||
RunResult run(const RunConfig& config);
|
||||
int main(int argc, char** argv);
|
||||
|
||||
private:
|
||||
|
||||
Runner() = default;
|
||||
std::vector<TestCase>
|
||||
filter_tests(const std::vector<TestCase>& tests,
|
||||
const RunConfig& config);
|
||||
std::unique_ptr<Reporter> create_reporter(const RunConfig& config);
|
||||
TestResult execute_test(TestCase& test_case);
|
||||
TestResult execute_test_parallel(TestCase& test_case);
|
||||
void run_test_body(TestCase& test_case, TestResult& result);
|
||||
};
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,106 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
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
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
/// 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{};
|
||||
#ifdef _WIN32
|
||||
gmtime_s(&tm, &now);
|
||||
#else
|
||||
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 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);
|
||||
#else
|
||||
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());
|
||||
}
|
||||
|
||||
} // namespace Void::Time
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
|
||||
namespace Void::Time
|
||||
{
|
||||
|
||||
/// Minimal RAII wall-clock timer built on std::chrono::steady_clock.
|
||||
///
|
||||
/// Usage:
|
||||
/// Stopwatch sw;
|
||||
/// do_work();
|
||||
/// auto ms = sw.elapsed<std::chrono::milliseconds>();
|
||||
class Stopwatch
|
||||
{
|
||||
public:
|
||||
|
||||
using Clock = std::chrono::steady_clock;
|
||||
using TimePoint = Clock::time_point;
|
||||
using Duration = Clock::duration;
|
||||
|
||||
/// Start the stopwatch at construction time.
|
||||
Stopwatch() noexcept : start_(Clock::now()) {}
|
||||
|
||||
/// Restart from zero.
|
||||
void reset() noexcept { start_ = Clock::now(); }
|
||||
|
||||
/// Elapsed time since construction or last reset().
|
||||
[[nodiscard]] Duration elapsed() const noexcept
|
||||
{
|
||||
return Clock::now() - start_;
|
||||
}
|
||||
|
||||
/// Elapsed time cast to a specific duration type.
|
||||
template <typename D = std::chrono::milliseconds>
|
||||
[[nodiscard]] D elapsed_as() const noexcept
|
||||
{
|
||||
return std::chrono::duration_cast<D>(elapsed());
|
||||
}
|
||||
|
||||
/// Split: return elapsed and reset in one call.
|
||||
[[nodiscard]] Duration split() noexcept
|
||||
{
|
||||
auto d = elapsed();
|
||||
reset();
|
||||
return d;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
TimePoint start_;
|
||||
};
|
||||
|
||||
} // namespace Void::Time
|
||||
@@ -0,0 +1,165 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Random/Random.hpp>
|
||||
#include <Void/Hash/Hash.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Uuid
|
||||
{
|
||||
|
||||
// ── UUID type ─────────────────────────────────────────────────────────────────
|
||||
|
||||
struct Uuid
|
||||
{
|
||||
std::array<std::uint8_t, 16> bytes{};
|
||||
|
||||
[[nodiscard]] bool operator==(const Uuid&) const noexcept = default;
|
||||
[[nodiscard]] auto operator<=>(const Uuid&) const noexcept = default;
|
||||
|
||||
[[nodiscard]] bool is_nil() const noexcept
|
||||
{
|
||||
for (auto b : bytes) {
|
||||
if (b != 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Format as lowercase 8-4-4-4-12 hex string.
|
||||
[[nodiscard]] std::string to_string() const
|
||||
{
|
||||
return std::format(
|
||||
"{:02x}{:02x}{:02x}{:02x}-"
|
||||
"{:02x}{:02x}-"
|
||||
"{:02x}{:02x}-"
|
||||
"{:02x}{:02x}-"
|
||||
"{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
|
||||
bytes[0], bytes[1], bytes[2], bytes[3],
|
||||
bytes[4], bytes[5],
|
||||
bytes[6], bytes[7],
|
||||
bytes[8], bytes[9],
|
||||
bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]);
|
||||
}
|
||||
|
||||
[[nodiscard]] static Uuid nil() noexcept { return {}; }
|
||||
};
|
||||
|
||||
// ── v4 (random) ───────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] inline Uuid v4() noexcept
|
||||
{
|
||||
Uuid u;
|
||||
Random::fill_random(
|
||||
{reinterpret_cast<std::byte*>(u.bytes.data()), u.bytes.size()});
|
||||
// version 4
|
||||
u.bytes[6] = (u.bytes[6] & 0x0F) | 0x40;
|
||||
// variant 10xx (RFC 4122)
|
||||
u.bytes[8] = (u.bytes[8] & 0x3F) | 0x80;
|
||||
return u;
|
||||
}
|
||||
|
||||
// ── v5 (name-based SHA-1 substitute using FNV-1a + CRC-32) ──────────────────
|
||||
// Not cryptographically equivalent to SHA-1, but deterministic and collision-
|
||||
// resistant enough for UUID namespacing without pulling in a crypto library.
|
||||
|
||||
[[nodiscard]] inline Uuid v5_lite(Uuid ns, std::string_view name) noexcept
|
||||
{
|
||||
Uuid u;
|
||||
// Mix namespace bytes + name bytes using two orthogonal hash functions.
|
||||
std::string blob;
|
||||
blob.reserve(16 + name.size());
|
||||
for (auto b : ns.bytes) blob += static_cast<char>(b);
|
||||
blob += name;
|
||||
|
||||
const std::uint64_t h64 = Hash::fnv1a64(blob);
|
||||
const std::uint32_t h32 = Hash::crc32(blob);
|
||||
|
||||
u.bytes[0] = static_cast<std::uint8_t>(h64 >> 56);
|
||||
u.bytes[1] = static_cast<std::uint8_t>(h64 >> 48);
|
||||
u.bytes[2] = static_cast<std::uint8_t>(h64 >> 40);
|
||||
u.bytes[3] = static_cast<std::uint8_t>(h64 >> 32);
|
||||
u.bytes[4] = static_cast<std::uint8_t>(h64 >> 24);
|
||||
u.bytes[5] = static_cast<std::uint8_t>(h64 >> 16);
|
||||
u.bytes[6] = static_cast<std::uint8_t>((h64 >> 8) & 0x0F) | 0x50; // version 5
|
||||
u.bytes[7] = static_cast<std::uint8_t>(h64);
|
||||
u.bytes[8] = static_cast<std::uint8_t>((h32 >> 24) & 0x3F) | 0x80; // variant
|
||||
u.bytes[9] = static_cast<std::uint8_t>(h32 >> 16);
|
||||
u.bytes[10] = static_cast<std::uint8_t>(h32 >> 8);
|
||||
u.bytes[11] = static_cast<std::uint8_t>(h32);
|
||||
// Refill bytes 12-15 by re-hashing
|
||||
const std::uint32_t h32b = Hash::murmur3_32(name, static_cast<std::uint32_t>(h64));
|
||||
u.bytes[12] = static_cast<std::uint8_t>(h32b >> 24);
|
||||
u.bytes[13] = static_cast<std::uint8_t>(h32b >> 16);
|
||||
u.bytes[14] = static_cast<std::uint8_t>(h32b >> 8);
|
||||
u.bytes[15] = static_cast<std::uint8_t>(h32b);
|
||||
return u;
|
||||
}
|
||||
|
||||
// ── Parsing ───────────────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] inline std::optional<Uuid> parse(std::string_view s) noexcept
|
||||
{
|
||||
// Accept "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" (36 chars) or 32 hex chars.
|
||||
if (s.size() == 36 &&
|
||||
s[8] == '-' && s[13] == '-' && s[18] == '-' && s[23] == '-') {
|
||||
std::string flat;
|
||||
flat.reserve(32);
|
||||
for (std::size_t i = 0; i < s.size(); ++i) {
|
||||
if (s[i] != '-') flat += s[i];
|
||||
}
|
||||
s = flat; // rebind for uniform parsing below
|
||||
if (flat.size() != 32) return std::nullopt;
|
||||
Uuid u;
|
||||
for (std::size_t i = 0; i < 16; ++i) {
|
||||
const char hi = flat[i * 2];
|
||||
const char lo = flat[i * 2 + 1];
|
||||
auto hex = [](char c) -> std::optional<std::uint8_t> {
|
||||
if (c >= '0' && c <= '9') return static_cast<std::uint8_t>(c - '0');
|
||||
if (c >= 'a' && c <= 'f') return static_cast<std::uint8_t>(c - 'a' + 10);
|
||||
if (c >= 'A' && c <= 'F') return static_cast<std::uint8_t>(c - 'A' + 10);
|
||||
return std::nullopt;
|
||||
};
|
||||
auto h = hex(hi), l = hex(lo);
|
||||
if (!h || !l) return std::nullopt;
|
||||
u.bytes[i] = static_cast<std::uint8_t>((*h << 4) | *l);
|
||||
}
|
||||
return u;
|
||||
}
|
||||
if (s.size() == 32) {
|
||||
Uuid u;
|
||||
for (std::size_t i = 0; i < 16; ++i) {
|
||||
auto hex = [](char c) -> std::optional<std::uint8_t> {
|
||||
if (c >= '0' && c <= '9') return static_cast<std::uint8_t>(c - '0');
|
||||
if (c >= 'a' && c <= 'f') return static_cast<std::uint8_t>(c - 'a' + 10);
|
||||
if (c >= 'A' && c <= 'F') return static_cast<std::uint8_t>(c - 'A' + 10);
|
||||
return std::nullopt;
|
||||
};
|
||||
auto h = hex(s[i * 2]), l = hex(s[i * 2 + 1]);
|
||||
if (!h || !l) return std::nullopt;
|
||||
u.bytes[i] = static_cast<std::uint8_t>((*h << 4) | *l);
|
||||
}
|
||||
return u;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// ── Well-known namespaces (RFC 4122) ─────────────────────────────────────────
|
||||
|
||||
namespace Namespace
|
||||
{
|
||||
// 6ba7b810-9dad-11d1-80b4-00c04fd430c8
|
||||
inline constexpr Uuid Dns{{
|
||||
0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1,
|
||||
0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}};
|
||||
// 6ba7b811-9dad-11d1-80b4-00c04fd430c8
|
||||
inline constexpr Uuid Url{{
|
||||
0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1,
|
||||
0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}};
|
||||
} // namespace Namespace
|
||||
|
||||
} // namespace Void::Uuid
|
||||
Reference in new issue
Block a user