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
@@ -54,6 +54,8 @@ Format code with `clang-format -i <file>`.
|
||||
| `Stacktrace` | `Void::Stacktrace` | Stack capture + source-snippet rendering via Boost.Stacktrace; ANSI color helpers. |
|
||||
| `Result` | `Void::Result` | Header-only `Result<T,E> = std::expected<T,E>` plus `Error` with cause-chain context, `with_context()` helper, reflection-based struct `repr` (C++26 `<meta>`). |
|
||||
| `FileSystem` | `Void::FileSystem` | Header-only path utilities returning `Result<T,E>`: `read_file`, `write_file`, `atomic_write`, `ensure_directory`, `remove_path`, RAII `TempDir`. |
|
||||
| `Concurrency` | `Void::Concurrency` | Header-only `ThreadPool`, bounded MPMC `Channel<T>`, and `parallel_for` built on the pool. Testing runner uses the pool for `--parallel <n>` mode. |
|
||||
| `Log` | `Void::Log` | Thin global log-sink layer used internally by all modules. Install any callable via `set_sink(fn)`; include `LoggingAdapter.hpp` to bridge to `Void::Logging`. |
|
||||
|
||||
## Adding a module
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(Concurrency
|
||||
INTERNAL_DEPS Log
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(Configuration
|
||||
INTERNAL_DEPS Result FileSystem Log
|
||||
)
|
||||
@@ -1,3 +1,3 @@
|
||||
void_add_module(FileSystem
|
||||
INTERNAL_DEPS Result
|
||||
INTERNAL_DEPS Result Log
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
|
||||
namespace Void::Log
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
Sink g_sink;
|
||||
std::shared_mutex g_mutex;
|
||||
} // namespace
|
||||
|
||||
void set_sink(Sink sink)
|
||||
{
|
||||
std::unique_lock lock{g_mutex};
|
||||
g_sink = std::move(sink);
|
||||
}
|
||||
|
||||
void log(Level level, std::string_view module, std::string_view message)
|
||||
{
|
||||
std::shared_lock lock{g_mutex};
|
||||
if (g_sink) {
|
||||
g_sink(level, module, message);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Void::Log
|
||||
@@ -0,0 +1 @@
|
||||
void_add_module(Log)
|
||||
@@ -1,3 +1,4 @@
|
||||
#include <Void/Detail/Enum.hpp>
|
||||
#include <Void/Logging/ConsoleLogger.hpp>
|
||||
|
||||
#ifdef VOID_HAS_STACKTRACE
|
||||
@@ -19,6 +20,28 @@ namespace Void::Logging
|
||||
std::string_view color_for(Level level)
|
||||
{
|
||||
using namespace Void::Stacktrace::Color;
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
static constexpr auto enumerators =
|
||||
std::define_static_array(std::meta::enumerators_of(^^Level));
|
||||
template for (constexpr auto e : enumerators) {
|
||||
if (level == [:e:]) {
|
||||
if constexpr (std::meta::identifier_of(e) == "Trace")
|
||||
return dim;
|
||||
if constexpr (std::meta::identifier_of(e) == "Debug")
|
||||
return cyan;
|
||||
if constexpr (std::meta::identifier_of(e) == "Info")
|
||||
return bold_cyan;
|
||||
if constexpr (std::meta::identifier_of(e) == "Warning")
|
||||
return bold_yellow;
|
||||
if constexpr (std::meta::identifier_of(e) == "Error")
|
||||
return bold_red;
|
||||
if constexpr (std::meta::identifier_of(e) == "Fatal")
|
||||
return bold_magenta;
|
||||
return reset;
|
||||
}
|
||||
}
|
||||
return reset;
|
||||
#else
|
||||
switch (level) {
|
||||
case Level::Trace:
|
||||
return dim;
|
||||
@@ -35,6 +58,7 @@ namespace Void::Logging
|
||||
default:
|
||||
return reset;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include <Void/Logging/FileLogger.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#include <format>
|
||||
#include <stdexcept>
|
||||
@@ -9,12 +10,17 @@ namespace Void::Logging
|
||||
FileLogger::FileLogger(const std::filesystem::path& path,
|
||||
Mode mode,
|
||||
std::size_t capacity)
|
||||
: Logger(mode, capacity), m_file(path, std::ios::app)
|
||||
: Logger(mode, capacity), m_path(path), m_file(path, std::ios::app)
|
||||
{
|
||||
if (!m_file.is_open()) {
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Warning, "Logging",
|
||||
std::format("FileLogger: cannot open '{}'", path.string()));
|
||||
throw std::runtime_error(
|
||||
std::format("FileLogger: cannot open '{}'", path.string()));
|
||||
}
|
||||
Void::Log::log(Void::Log::Level::Debug, "Logging",
|
||||
std::format("FileLogger: opened '{}'", path.string()));
|
||||
}
|
||||
|
||||
Void::Result::Result<std::unique_ptr<FileLogger>, Void::Result::Error>
|
||||
@@ -30,7 +36,13 @@ namespace Void::Logging
|
||||
}
|
||||
}
|
||||
|
||||
FileLogger::~FileLogger() noexcept { flush(); }
|
||||
FileLogger::~FileLogger() noexcept
|
||||
{
|
||||
flush();
|
||||
Void::Log::log(Void::Log::Level::Debug, "Logging",
|
||||
std::format("FileLogger: closed '{}'",
|
||||
m_path.string()));
|
||||
}
|
||||
|
||||
void FileLogger::write(const Entry& entry)
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
void_add_module(Logging
|
||||
INTERNAL_DEPS Result
|
||||
INTERNAL_DEPS Result Log
|
||||
OPTIONAL_DEPS Stacktrace
|
||||
)
|
||||
@@ -0,0 +1,253 @@
|
||||
#include <Void/Process/Process.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#include <format>
|
||||
|
||||
#ifdef _WIN32
|
||||
|
||||
namespace Void::Process
|
||||
{
|
||||
Void::Result::Result<Output, Void::Result::Error>
|
||||
run(const std::filesystem::path&,
|
||||
std::vector<std::string>,
|
||||
std::string_view,
|
||||
std::chrono::milliseconds)
|
||||
{
|
||||
return Void::Result::fail(
|
||||
"Process::run: not implemented on Windows");
|
||||
}
|
||||
|
||||
Void::Result::Result<Output, Void::Result::Error>
|
||||
shell(std::string_view, std::chrono::milliseconds)
|
||||
{
|
||||
return Void::Result::fail(
|
||||
"Process::shell: not implemented on Windows");
|
||||
}
|
||||
} // namespace Void::Process
|
||||
|
||||
#else // POSIX
|
||||
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <csignal>
|
||||
#include <cstring>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace Void::Process
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
// Read into buf until EAGAIN (no more data right now) or EOF.
|
||||
// Returns true on EOF, false on EAGAIN.
|
||||
bool drain(int fd, std::string& buf)
|
||||
{
|
||||
char tmp[4096];
|
||||
for (;;) {
|
||||
ssize_t n = ::read(fd, tmp, sizeof(tmp));
|
||||
if (n > 0) {
|
||||
buf.append(tmp, static_cast<std::size_t>(n));
|
||||
} else if (n == 0) {
|
||||
return true; // EOF
|
||||
} else {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
// EAGAIN / EWOULDBLOCK: no data right now
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void set_nonblock(int fd)
|
||||
{
|
||||
int flags = ::fcntl(fd, F_GETFL, 0);
|
||||
if (flags >= 0) {
|
||||
::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
|
||||
}
|
||||
}
|
||||
|
||||
// Close an fd if it is >= 0, then set it to -1.
|
||||
void safe_close(int& fd)
|
||||
{
|
||||
if (fd >= 0) {
|
||||
::close(fd);
|
||||
fd = -1;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
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)
|
||||
{
|
||||
// [0] = read end, [1] = write end
|
||||
int stdin_pipe[2] = {-1, -1};
|
||||
int stdout_pipe[2] = {-1, -1};
|
||||
int stderr_pipe[2] = {-1, -1};
|
||||
|
||||
if (::pipe(stdin_pipe) != 0 || ::pipe(stdout_pipe) != 0 ||
|
||||
::pipe(stderr_pipe) != 0) {
|
||||
safe_close(stdin_pipe[0]);
|
||||
safe_close(stdin_pipe[1]);
|
||||
safe_close(stdout_pipe[0]);
|
||||
safe_close(stdout_pipe[1]);
|
||||
safe_close(stderr_pipe[0]);
|
||||
safe_close(stderr_pipe[1]);
|
||||
return Void::Result::fail(std::format("Process::run: pipe() failed: {}",
|
||||
std::strerror(errno)));
|
||||
}
|
||||
|
||||
Void::Log::log(Void::Log::Level::Debug, "Process",
|
||||
std::format("run: '{}'", executable.string()));
|
||||
|
||||
std::vector<const char*> argv;
|
||||
argv.push_back(executable.c_str());
|
||||
for (const auto& a : args) {
|
||||
argv.push_back(a.c_str());
|
||||
}
|
||||
argv.push_back(nullptr);
|
||||
|
||||
pid_t pid = ::fork();
|
||||
if (pid < 0) {
|
||||
safe_close(stdin_pipe[0]);
|
||||
safe_close(stdin_pipe[1]);
|
||||
safe_close(stdout_pipe[0]);
|
||||
safe_close(stdout_pipe[1]);
|
||||
safe_close(stderr_pipe[0]);
|
||||
safe_close(stderr_pipe[1]);
|
||||
return Void::Result::fail(std::format("Process::run: fork() failed: {}",
|
||||
std::strerror(errno)));
|
||||
}
|
||||
|
||||
if (pid == 0) {
|
||||
// Child process
|
||||
::dup2(stdin_pipe[0], STDIN_FILENO);
|
||||
::dup2(stdout_pipe[1], STDOUT_FILENO);
|
||||
::dup2(stderr_pipe[1], STDERR_FILENO);
|
||||
::close(stdin_pipe[0]);
|
||||
::close(stdin_pipe[1]);
|
||||
::close(stdout_pipe[0]);
|
||||
::close(stdout_pipe[1]);
|
||||
::close(stderr_pipe[0]);
|
||||
::close(stderr_pipe[1]);
|
||||
::execvp(executable.c_str(),
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
|
||||
const_cast<char* const*>(argv.data()));
|
||||
// execvp only returns on error; 127 is the POSIX convention
|
||||
::_exit(127);
|
||||
}
|
||||
|
||||
// Parent: close child-side ends
|
||||
safe_close(stdin_pipe[0]);
|
||||
safe_close(stdout_pipe[1]);
|
||||
safe_close(stderr_pipe[1]);
|
||||
|
||||
// Write stdin and close immediately so the child sees EOF
|
||||
if (!stdin_data.empty()) {
|
||||
const char* p = stdin_data.data();
|
||||
std::size_t remaining = stdin_data.size();
|
||||
while (remaining > 0) {
|
||||
ssize_t n = ::write(stdin_pipe[1], p, remaining);
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
break; // child likely closed stdin; ignore
|
||||
}
|
||||
p += static_cast<std::size_t>(n);
|
||||
remaining -= static_cast<std::size_t>(n);
|
||||
}
|
||||
}
|
||||
safe_close(stdin_pipe[1]);
|
||||
|
||||
set_nonblock(stdout_pipe[0]);
|
||||
set_nonblock(stderr_pipe[0]);
|
||||
|
||||
Output output;
|
||||
bool out_done = false;
|
||||
bool err_done = false;
|
||||
|
||||
const bool has_timeout = timeout.count() > 0;
|
||||
const auto deadline =
|
||||
std::chrono::steady_clock::now() +
|
||||
(has_timeout ? timeout : std::chrono::milliseconds{30'000});
|
||||
|
||||
while (!out_done || !err_done) {
|
||||
struct pollfd pfds[2];
|
||||
int nfds = 0;
|
||||
if (!out_done) {
|
||||
pfds[nfds++] = {stdout_pipe[0], POLLIN, 0};
|
||||
}
|
||||
if (!err_done) {
|
||||
pfds[nfds++] = {stderr_pipe[0], POLLIN, 0};
|
||||
}
|
||||
|
||||
auto left_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
deadline - std::chrono::steady_clock::now())
|
||||
.count();
|
||||
if (left_ms <= 0) {
|
||||
::kill(pid, SIGTERM);
|
||||
break;
|
||||
}
|
||||
|
||||
int ret = ::poll(pfds, static_cast<nfds_t>(nfds),
|
||||
static_cast<int>(left_ms));
|
||||
if (ret < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (ret == 0) {
|
||||
// Wall-clock timeout expired
|
||||
::kill(pid, SIGTERM);
|
||||
break;
|
||||
}
|
||||
|
||||
for (int i = 0; i < nfds; ++i) {
|
||||
if ((pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) == 0) {
|
||||
continue;
|
||||
}
|
||||
bool& done =
|
||||
(pfds[i].fd == stdout_pipe[0]) ? out_done : err_done;
|
||||
std::string& buf =
|
||||
(pfds[i].fd == stdout_pipe[0]) ? output.out : output.err;
|
||||
bool eof = drain(pfds[i].fd, buf);
|
||||
// POLLHUP means the write end was closed; no more data will arrive
|
||||
if (eof || (pfds[i].revents & (POLLHUP | POLLERR))) {
|
||||
done = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
safe_close(stdout_pipe[0]);
|
||||
safe_close(stderr_pipe[0]);
|
||||
|
||||
int status = 0;
|
||||
::waitpid(pid, &status, 0);
|
||||
output.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
|
||||
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Debug, "Process",
|
||||
std::format("run: '{}' exited {}", executable.string(),
|
||||
output.exit_code));
|
||||
|
||||
return Void::Result::ok(std::move(output));
|
||||
}
|
||||
|
||||
Void::Result::Result<Output, Void::Result::Error>
|
||||
shell(std::string_view command, std::chrono::milliseconds timeout)
|
||||
{
|
||||
return run("/bin/sh", {"-c", std::string{command}}, {}, timeout);
|
||||
}
|
||||
|
||||
} // namespace Void::Process
|
||||
|
||||
#endif // _WIN32
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(Process
|
||||
INTERNAL_DEPS Result Log
|
||||
)
|
||||
@@ -1,5 +1,6 @@
|
||||
#include <Void/Stacktrace/Stacktrace.hpp>
|
||||
#include <Void/Stacktrace/Color.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
@@ -37,6 +38,8 @@ namespace Void::Stacktrace
|
||||
}
|
||||
} catch (...) {
|
||||
}
|
||||
Void::Log::log(Void::Log::Level::Debug, "Stacktrace",
|
||||
std::format("captured {} frames", result.size()));
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -46,6 +49,9 @@ namespace Void::Stacktrace
|
||||
{
|
||||
std::ifstream ifs{file};
|
||||
if (!ifs.is_open()) {
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Warning, "Stacktrace",
|
||||
std::format("read_source_snippet: cannot open '{}'", file));
|
||||
return Void::Result::fail(
|
||||
std::format("read_source_snippet: cannot open '{}'", file));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
void_add_module(Stacktrace
|
||||
INTERNAL_DEPS Result
|
||||
INTERNAL_DEPS Result Log
|
||||
EXTERNAL_DEPS Boost::stacktrace_backtrace
|
||||
DEPS_WIN32 dbghelp
|
||||
DEPS_UNIX dl
|
||||
|
||||
Whitespace-only changes.
@@ -1,12 +1,11 @@
|
||||
#include <Void/Testing/ConsoleReporter.hpp>
|
||||
#include <Void/Stacktrace/Color.hpp>
|
||||
#include <Void/Testing/Detail/SignalHandler.hpp>
|
||||
#include <format>
|
||||
#include <chrono>
|
||||
#include <algorithm>
|
||||
|
||||
namespace Void::Testing {
|
||||
using namespace Void::Stacktrace::Color;
|
||||
using namespace Void::Testing::Detail::Color;
|
||||
|
||||
void ConsoleReporter::on_run_start(const RunConfig&, int total_tests) {
|
||||
os_ << "\n" << apply(bold_blue, "╭──────────────────────────────────────────────╮") << "\n"
|
||||
|
||||
+351
-97
@@ -1,17 +1,43 @@
|
||||
#include <Void/Testing/Runner.hpp>
|
||||
#include "Void/Testing/Config.hpp"
|
||||
#include <Void/Logging/FileLogger.hpp>
|
||||
#include <Void/Logging/Level.hpp>
|
||||
#include <Void/Detail/Enum.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Testing/Detail/Color.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/ConsoleReporter.hpp>
|
||||
#include <Void/Stacktrace/Color.hpp>
|
||||
|
||||
#ifdef VOID_HAS_STACKTRACE
|
||||
#include <Void/Stacktrace/Stacktrace.hpp>
|
||||
#endif
|
||||
#include <Void/Testing/ConsoleReporter.hpp>
|
||||
#include <Void/Testing/Detail/Registry.hpp>
|
||||
#include <Void/Testing/Detail/SignalHandler.hpp>
|
||||
#include <Void/Testing/JUnitReporter.hpp>
|
||||
#include <Void/Time/Format.hpp>
|
||||
|
||||
#ifdef VOID_HAS_CONCURRENCY
|
||||
#include <Void/Concurrency/ThreadPool.hpp>
|
||||
#include <future>
|
||||
#endif
|
||||
|
||||
#ifdef VOID_HAS_CONFIGURATION
|
||||
#include <Void/Configuration/Env.hpp>
|
||||
#else
|
||||
#include <cstdlib>
|
||||
#endif
|
||||
|
||||
#ifdef VOID_HAS_LOGGING
|
||||
#include <Void/Log/LoggingAdapter.hpp>
|
||||
#include <Void/Logging/ConsoleLogger.hpp>
|
||||
#include <Void/Logging/FileLogger.hpp>
|
||||
#include <Void/Logging/Level.hpp>
|
||||
#endif
|
||||
|
||||
#ifdef VOID_HAS_STRING
|
||||
#include <Void/String/String.hpp>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <csignal>
|
||||
#include <cstdlib>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
@@ -28,9 +54,10 @@ namespace Void::Testing
|
||||
RunConfig config;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
std::string arg = argv[i];
|
||||
if ((arg == "--filter" || arg == "--suite" || arg == "--reporter" ||
|
||||
arg == "--output" || arg == "--tag" || arg == "--seed" ||
|
||||
arg == "--repeat" || arg == "--log-file") &&
|
||||
if ((arg == "--filter" || arg == "--suite" ||
|
||||
arg == "--reporter" || arg == "--output" ||
|
||||
arg == "--tag" || arg == "--seed" || arg == "--repeat" ||
|
||||
arg == "--log-file" || arg == "--parallel") &&
|
||||
i + 1 < argc) {
|
||||
std::string val = argv[++i];
|
||||
if (arg == "--filter") {
|
||||
@@ -47,11 +74,14 @@ namespace Void::Testing
|
||||
config.log_file = val;
|
||||
} else if (arg == "--seed") {
|
||||
config.shuffle = true;
|
||||
config.random_seed = static_cast<unsigned>(std::stoul(val));
|
||||
config.random_seed =
|
||||
static_cast<unsigned>(std::stoul(val));
|
||||
} else if (arg == "--repeat") {
|
||||
config.repeat = static_cast<unsigned>(std::stoul(val));
|
||||
} else if (arg == "--parallel") {
|
||||
config.parallel_threads =
|
||||
static_cast<unsigned>(std::stoul(val));
|
||||
}
|
||||
|
||||
} else if (arg == "--help") {
|
||||
config.show_help = true;
|
||||
} else if (arg == "--list") {
|
||||
@@ -138,10 +168,11 @@ namespace Void::Testing
|
||||
|
||||
int crash_signal = 0;
|
||||
std::string crash_stacktrace;
|
||||
Detail::install_signal_handlers([&](int sig, const std::string& trace) {
|
||||
crash_signal = sig;
|
||||
crash_stacktrace = trace;
|
||||
});
|
||||
Detail::install_signal_handlers(
|
||||
[&](int sig, const std::string& trace) {
|
||||
crash_signal = sig;
|
||||
crash_stacktrace = trace;
|
||||
});
|
||||
auto start = std::chrono::high_resolution_clock::now();
|
||||
|
||||
try {
|
||||
@@ -167,13 +198,17 @@ namespace Void::Testing
|
||||
result.state = TestState::Failed;
|
||||
result.crash_info =
|
||||
std::format("Unhandled exception: {}", e.what());
|
||||
#ifdef VOID_HAS_STACKTRACE
|
||||
result.stacktrace = Void::Stacktrace::format_stacktrace(
|
||||
Void::Stacktrace::capture_stacktrace(1, 8));
|
||||
#endif
|
||||
} catch (...) {
|
||||
result.state = TestState::Failed;
|
||||
result.crash_info = "Unhandled unknown exception";
|
||||
#ifdef VOID_HAS_STACKTRACE
|
||||
result.stacktrace = Void::Stacktrace::format_stacktrace(
|
||||
Void::Stacktrace::capture_stacktrace(1, 8));
|
||||
#endif
|
||||
}
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
@@ -183,9 +218,56 @@ namespace Void::Testing
|
||||
|
||||
if (result.state != TestState::Skipped &&
|
||||
result.state != TestState::Crashed) {
|
||||
bool any =
|
||||
std::any_of(result.assertions.begin(), result.assertions.end(),
|
||||
[](const auto& a) { return !a.passed; });
|
||||
bool any = std::any_of(
|
||||
result.assertions.begin(), result.assertions.end(),
|
||||
[](const auto& a) { return !a.passed; });
|
||||
result.state = any ? TestState::Failed : TestState::Passed;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Like execute_test() but without sigsetjmp/signal-handler installation,
|
||||
// safe to call from multiple threads simultaneously.
|
||||
TestResult Runner::execute_test_parallel(TestCase& test_case)
|
||||
{
|
||||
TestResult result;
|
||||
result.name = test_case.name;
|
||||
result.suite = test_case.suite;
|
||||
result.tags = test_case.tags;
|
||||
if (test_case.disabled) {
|
||||
result.state = TestState::Skipped;
|
||||
result.skip_reason = test_case.skip_reason.empty()
|
||||
? "disabled"
|
||||
: test_case.skip_reason;
|
||||
return result;
|
||||
}
|
||||
Detail::TestContext::current().current_result = &result;
|
||||
Detail::TestContext::current().should_abort = false;
|
||||
|
||||
auto start = std::chrono::high_resolution_clock::now();
|
||||
try {
|
||||
run_test_body(test_case, result);
|
||||
} catch (const Detail::RequireFailure&) {
|
||||
if (result.state != TestState::Skipped) {
|
||||
result.state = TestState::Failed;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
result.state = TestState::Failed;
|
||||
result.crash_info =
|
||||
std::format("Unhandled exception: {}", e.what());
|
||||
} catch (...) {
|
||||
result.state = TestState::Failed;
|
||||
result.crash_info = "Unhandled unknown exception";
|
||||
}
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
result.duration = end - start;
|
||||
Detail::TestContext::current().current_result = nullptr;
|
||||
|
||||
if (result.state != TestState::Skipped &&
|
||||
result.state != TestState::Crashed) {
|
||||
bool any = std::any_of(
|
||||
result.assertions.begin(), result.assertions.end(),
|
||||
[](const auto& a) { return !a.passed; });
|
||||
result.state = any ? TestState::Failed : TestState::Passed;
|
||||
}
|
||||
return result;
|
||||
@@ -215,56 +297,103 @@ namespace Void::Testing
|
||||
|
||||
RunResult Runner::run(const RunConfig& config)
|
||||
{
|
||||
Void::Stacktrace::Color::g_color_enabled = !config.no_color;
|
||||
Void::Testing::Detail::Color::g_color_enabled = !config.no_color;
|
||||
if (config.show_help) {
|
||||
using namespace Void::Stacktrace::Color;
|
||||
using namespace Void::Testing::Detail::Color;
|
||||
|
||||
std::cout
|
||||
<< "\n"
|
||||
<< apply(bold_blue, "╭─────────────────────────────────────────"
|
||||
"─────────────────────────╮")
|
||||
<< apply(bold_blue,
|
||||
"\xe2\x95\xad\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x95\xae")
|
||||
<< "\n"
|
||||
<< apply(bold_blue, "│") << apply(bold_white, " Void Testing")
|
||||
<< apply(dim, " — Command Line Interface")
|
||||
<< std::string(28, ' ') << apply(bold_blue, "│") << "\n"
|
||||
<< apply(bold_blue, "╰─────────────────────────────────────────"
|
||||
"─────────────────────────╯")
|
||||
<< apply(bold_blue, "\xe2\x94\x82")
|
||||
<< apply(bold_white, " Void Testing")
|
||||
<< apply(dim, " \xe2\x80\x94 Command Line Interface")
|
||||
<< std::string(28, ' ') << apply(bold_blue, "\xe2\x94\x82")
|
||||
<< "\n"
|
||||
<< apply(bold_blue,
|
||||
"\xe2\x95\xb0\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x95\xaf")
|
||||
<< "\n"
|
||||
<< "\n"
|
||||
<< " " << apply(bold_white, "USAGE:") << "\n"
|
||||
<< " " << apply(cyan, "<executable>") << " "
|
||||
<< apply(dim, "[options]") << "\n"
|
||||
<< "\n"
|
||||
<< " " << apply(bold_white, "OPTIONS:") << "\n"
|
||||
<< " " << apply(green, "--filter <pattern> ")
|
||||
<< " " << apply(bold_white, "OPTIONS:") << "\n";
|
||||
|
||||
constexpr std::size_t OPT_WIDTH = 23;
|
||||
auto opt = [&](std::string_view name) {
|
||||
#ifdef VOID_HAS_STRING
|
||||
return apply(green, Void::String::pad_right(name, OPT_WIDTH));
|
||||
#else
|
||||
std::string s{name};
|
||||
if (s.size() < OPT_WIDTH) {
|
||||
s.append(OPT_WIDTH - s.size(), ' ');
|
||||
}
|
||||
return apply(green, s);
|
||||
#endif
|
||||
};
|
||||
|
||||
std::cout
|
||||
<< " " << opt("--filter <pattern>")
|
||||
<< apply(dim, "Run tests matching the regex pattern") << "\n"
|
||||
<< " " << apply(green, "--suite <name> ")
|
||||
<< " " << opt("--suite <name>")
|
||||
<< apply(dim, "Run only tests in the specified suite") << "\n"
|
||||
<< " " << apply(green, "--tag <name> ")
|
||||
<< " " << opt("--tag <name>")
|
||||
<< apply(dim, "Run only tests with the specified tag") << "\n"
|
||||
<< " " << apply(green, "--list ")
|
||||
<< " " << opt("--list")
|
||||
<< apply(dim, "List discovered tests without running them")
|
||||
<< "\n"
|
||||
<< " " << apply(green, "--shuffle ")
|
||||
<< " " << opt("--shuffle")
|
||||
<< apply(dim, "Randomize the order of test execution") << "\n"
|
||||
<< " " << apply(green, "--seed <n> ")
|
||||
<< " " << opt("--seed <n>")
|
||||
<< apply(dim, "Set the random seed (implies --shuffle)") << "\n"
|
||||
<< " " << apply(green, "--repeat <n> ")
|
||||
<< " " << opt("--repeat <n>")
|
||||
<< apply(dim, "Repeat the test run n times") << "\n"
|
||||
<< " " << apply(green, "--reporter <type> ")
|
||||
<< " " << opt("--reporter <type>")
|
||||
<< apply(dim, "Choose the output reporter: console, junit")
|
||||
<< "\n"
|
||||
<< " " << apply(green, "--output <file> ")
|
||||
<< " " << opt("--output <file>")
|
||||
<< apply(dim, "Write reporter output to a file") << "\n"
|
||||
<< " " << apply(green, "--log-file <file> ")
|
||||
#ifdef VOID_HAS_LOGGING
|
||||
<< " " << opt("--log-file <file>")
|
||||
<< apply(dim,
|
||||
"Mirror test events to <file> via Void::Logging")
|
||||
<< "\n"
|
||||
<< " " << apply(green, "--verbose ")
|
||||
#endif
|
||||
#ifdef VOID_HAS_CONCURRENCY
|
||||
<< " " << opt("--parallel <n>")
|
||||
<< apply(dim,
|
||||
"Run tests across n threads (no crash detection)")
|
||||
<< "\n"
|
||||
#endif
|
||||
<< " " << opt("--verbose")
|
||||
<< apply(dim, "Enable verbose output") << "\n"
|
||||
<< " " << apply(green, "--no-color ")
|
||||
<< " " << opt("--no-color")
|
||||
<< apply(dim, "Disable colored console output") << "\n"
|
||||
<< " " << apply(green, "--help ")
|
||||
<< " " << opt("--help")
|
||||
<< apply(dim, "Show this help message") << "\n"
|
||||
<< "\n"
|
||||
<< " " << apply(bold_white, "EXAMPLES:") << "\n"
|
||||
@@ -284,6 +413,8 @@ namespace Void::Testing
|
||||
auto tests = filter_tests(all_tests, config);
|
||||
auto reporter = create_reporter(config);
|
||||
|
||||
// ── Optional: file logger sink (requires Void::Logging) ──────────────────
|
||||
#ifdef VOID_HAS_LOGGING
|
||||
std::unique_ptr<Void::Logging::FileLogger> log_sink;
|
||||
if (!config.log_file.empty()) {
|
||||
try {
|
||||
@@ -294,6 +425,45 @@ namespace Void::Testing
|
||||
<< "\n";
|
||||
}
|
||||
}
|
||||
#else
|
||||
if (!config.log_file.empty()) {
|
||||
std::cerr
|
||||
<< "warning: --log-file requires Void::Logging (not linked)\n";
|
||||
}
|
||||
#endif
|
||||
|
||||
// ── Optional: VOID_LOG_LEVEL auto-sink ───────────────────────────────────
|
||||
#ifdef VOID_HAS_LOGGING
|
||||
std::unique_ptr<Void::Logging::ConsoleLogger> env_log;
|
||||
{
|
||||
#ifdef VOID_HAS_CONFIGURATION
|
||||
const auto lvl_str =
|
||||
Void::Configuration::get_env_or("VOID_LOG_LEVEL");
|
||||
#else
|
||||
const char* raw_env =
|
||||
std::getenv("VOID_LOG_LEVEL"); // NOLINT(concurrency-mt-unsafe)
|
||||
const std::string lvl_str = raw_env ? raw_env : "";
|
||||
#endif
|
||||
if (!lvl_str.empty()) {
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
auto level =
|
||||
Void::Detail::enum_parse<Void::Logging::Level>(lvl_str)
|
||||
.value_or(Void::Logging::Level::Info);
|
||||
#else
|
||||
Void::Logging::Level level = Void::Logging::Level::Info;
|
||||
if (lvl_str == "Trace") level = Void::Logging::Level::Trace;
|
||||
else if (lvl_str == "Debug") level = Void::Logging::Level::Debug;
|
||||
else if (lvl_str == "Warning") level = Void::Logging::Level::Warning;
|
||||
else if (lvl_str == "Error") level = Void::Logging::Level::Error;
|
||||
else if (lvl_str == "Fatal") level = Void::Logging::Level::Fatal;
|
||||
#endif
|
||||
env_log =
|
||||
std::make_unique<Void::Logging::ConsoleLogger>(std::cerr);
|
||||
env_log->set_level(level);
|
||||
Void::Log::set_sink(Void::Log::make_sink(*env_log));
|
||||
}
|
||||
}
|
||||
#endif // VOID_HAS_LOGGING
|
||||
|
||||
if (config.list_only) {
|
||||
for (const auto& t : tests) {
|
||||
@@ -304,19 +474,6 @@ namespace Void::Testing
|
||||
}
|
||||
|
||||
RunResult run_result;
|
||||
reporter->on_run_start(config, static_cast<int>(tests.size()));
|
||||
if (log_sink) {
|
||||
log_sink->info(std::format("run start: {} test(s) discovered",
|
||||
tests.size()));
|
||||
}
|
||||
if (config.shuffle) {
|
||||
std::shuffle(tests.begin(), tests.end(),
|
||||
std::mt19937{config.random_seed});
|
||||
if (log_sink) {
|
||||
log_sink->info(std::format("shuffle enabled (seed = {})",
|
||||
config.random_seed));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<SuiteResult> suite_results;
|
||||
std::unordered_map<std::string, size_t> suite_index;
|
||||
@@ -326,58 +483,148 @@ namespace Void::Testing
|
||||
suite_results.push_back({.name = test.suite});
|
||||
}
|
||||
}
|
||||
|
||||
auto log_result = [&](const TestResult& r, const std::string& q) {
|
||||
#ifdef VOID_HAS_LOGGING
|
||||
if (!log_sink) {
|
||||
return;
|
||||
}
|
||||
const auto ts = Void::Time::utc_now_iso8601_ms();
|
||||
const auto dur = Void::Time::format_duration(r.duration);
|
||||
switch (r.state) {
|
||||
case TestState::Passed:
|
||||
log_sink->info(std::format("[{}] test pass: {} ({})", ts,
|
||||
q, dur));
|
||||
break;
|
||||
case TestState::Failed:
|
||||
log_sink->error(std::format(
|
||||
"[{}] test fail: {} ({}) \xe2\x80\x94 {}", ts, q, dur,
|
||||
r.crash_info.empty() ? "assertion failed"
|
||||
: r.crash_info));
|
||||
break;
|
||||
case TestState::Skipped:
|
||||
log_sink->warning(std::format(
|
||||
"[{}] test skip: {} \xe2\x80\x94 {}", ts, q,
|
||||
r.skip_reason.empty() ? "no reason" : r.skip_reason));
|
||||
break;
|
||||
case TestState::Crashed:
|
||||
log_sink->fatal(std::format(
|
||||
"[{}] test crash: {} \xe2\x80\x94 {}", ts, q,
|
||||
r.crash_info));
|
||||
break;
|
||||
}
|
||||
#else
|
||||
(void)r;
|
||||
(void)q;
|
||||
#endif
|
||||
};
|
||||
|
||||
auto start_time = std::chrono::high_resolution_clock::now();
|
||||
|
||||
for (unsigned rep = 0; rep < config.repeat; ++rep) {
|
||||
// ── Optional: parallel execution (requires Void::Concurrency) ────────────
|
||||
bool run_parallel = config.parallel_threads > 0;
|
||||
#ifndef VOID_HAS_CONCURRENCY
|
||||
if (run_parallel) {
|
||||
std::cerr << "warning: --parallel requires Void::Concurrency "
|
||||
"(not linked); running sequentially\n";
|
||||
run_parallel = false;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (run_parallel) {
|
||||
#ifdef VOID_HAS_CONCURRENCY
|
||||
reporter->on_run_start(config, static_cast<int>(tests.size()));
|
||||
#ifdef VOID_HAS_LOGGING
|
||||
if (log_sink) {
|
||||
log_sink->info(std::format(
|
||||
"run start (parallel, {} threads): {} test(s)",
|
||||
config.parallel_threads, tests.size()));
|
||||
}
|
||||
#endif
|
||||
Void::Concurrency::ThreadPool pool{config.parallel_threads};
|
||||
std::vector<std::future<TestResult>> futures;
|
||||
futures.reserve(tests.size());
|
||||
for (auto& test : tests) {
|
||||
auto& suite = suite_results[suite_index[test.suite]];
|
||||
if (rep == 0) {
|
||||
futures.push_back(pool.submit(
|
||||
[this, &test] { return execute_test_parallel(test); }));
|
||||
}
|
||||
std::vector<TestResult> par_results;
|
||||
par_results.reserve(tests.size());
|
||||
for (auto& fut : futures) {
|
||||
par_results.push_back(fut.get());
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, bool> suite_started;
|
||||
for (std::size_t i = 0; i < tests.size(); ++i) {
|
||||
auto& test = tests[i];
|
||||
auto& result = par_results[i];
|
||||
if (!suite_started[test.suite]) {
|
||||
suite_started[test.suite] = true;
|
||||
reporter->on_suite_start(
|
||||
suite.name, std::count_if(tests.begin(), tests.end(),
|
||||
[&](const auto& t) {
|
||||
return t.suite ==
|
||||
suite.name;
|
||||
}));
|
||||
if (log_sink) {
|
||||
log_sink->info(
|
||||
std::format("suite start: {}", suite.name));
|
||||
}
|
||||
test.suite,
|
||||
static_cast<int>(
|
||||
std::count_if(tests.begin(), tests.end(),
|
||||
[&](const auto& t) {
|
||||
return t.suite == test.suite;
|
||||
})));
|
||||
}
|
||||
reporter->on_test_start(test);
|
||||
auto result = execute_test(test);
|
||||
reporter->on_test_end(result);
|
||||
log_result(result, std::format("{}.{}", result.suite,
|
||||
result.name));
|
||||
suite_results[suite_index[test.suite]].tests.push_back(
|
||||
std::move(result));
|
||||
}
|
||||
#endif // VOID_HAS_CONCURRENCY
|
||||
} else {
|
||||
reporter->on_run_start(config, static_cast<int>(tests.size()));
|
||||
#ifdef VOID_HAS_LOGGING
|
||||
if (log_sink) {
|
||||
log_sink->info(std::format("run start: {} test(s) discovered",
|
||||
tests.size()));
|
||||
}
|
||||
#endif
|
||||
if (config.shuffle) {
|
||||
std::shuffle(tests.begin(), tests.end(),
|
||||
std::mt19937{config.random_seed});
|
||||
#ifdef VOID_HAS_LOGGING
|
||||
if (log_sink) {
|
||||
const auto qualified =
|
||||
std::format("{}.{}", result.suite, result.name);
|
||||
switch (result.state) {
|
||||
case TestState::Passed:
|
||||
log_sink->info(
|
||||
std::format("test pass: {}", qualified));
|
||||
break;
|
||||
case TestState::Failed:
|
||||
log_sink->error(std::format(
|
||||
"test fail: {} — {}", qualified,
|
||||
result.crash_info.empty() ? "assertion failed"
|
||||
: result.crash_info));
|
||||
break;
|
||||
case TestState::Skipped:
|
||||
log_sink->warning(std::format(
|
||||
"test skip: {} ({})", qualified,
|
||||
result.skip_reason.empty() ? "no reason"
|
||||
: result.skip_reason));
|
||||
break;
|
||||
case TestState::Crashed:
|
||||
log_sink->fatal(std::format(
|
||||
"test crash: {} — {}", qualified,
|
||||
result.crash_info));
|
||||
break;
|
||||
}
|
||||
log_sink->info(std::format("shuffle enabled (seed = {})",
|
||||
config.random_seed));
|
||||
}
|
||||
if (rep == config.repeat - 1) {
|
||||
suite.tests.push_back(std::move(result));
|
||||
#endif
|
||||
}
|
||||
|
||||
for (unsigned rep = 0; rep < config.repeat; ++rep) {
|
||||
for (auto& test : tests) {
|
||||
auto& suite = suite_results[suite_index[test.suite]];
|
||||
if (rep == 0) {
|
||||
reporter->on_suite_start(
|
||||
suite.name,
|
||||
std::count_if(
|
||||
tests.begin(), tests.end(),
|
||||
[&](const auto& t) {
|
||||
return t.suite == suite.name;
|
||||
}));
|
||||
#ifdef VOID_HAS_LOGGING
|
||||
if (log_sink) {
|
||||
log_sink->info(std::format("suite start: {}",
|
||||
suite.name));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
reporter->on_test_start(test);
|
||||
auto result = execute_test(test);
|
||||
reporter->on_test_end(result);
|
||||
log_result(result, std::format("{}.{}", result.suite,
|
||||
result.name));
|
||||
if (rep == config.repeat - 1) {
|
||||
suite.tests.push_back(std::move(result));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto end_time = std::chrono::high_resolution_clock::now();
|
||||
|
||||
for (auto& suite : suite_results) {
|
||||
@@ -403,12 +650,19 @@ namespace Void::Testing
|
||||
}
|
||||
run_result.total_duration = end_time - start_time;
|
||||
reporter->on_run_end(run_result);
|
||||
#ifdef VOID_HAS_LOGGING
|
||||
if (log_sink) {
|
||||
log_sink->info(std::format(
|
||||
"run end: {} total / {} passed / {} failed / {} skipped / {} crashed",
|
||||
run_result.total, run_result.passed, run_result.failed,
|
||||
run_result.skipped, run_result.crashed));
|
||||
log_sink->info(
|
||||
std::format("run end: {} total / {} passed / {} failed / {} "
|
||||
"skipped / {} crashed",
|
||||
run_result.total, run_result.passed,
|
||||
run_result.failed, run_result.skipped,
|
||||
run_result.crashed));
|
||||
}
|
||||
if (env_log) {
|
||||
Void::Log::set_sink({});
|
||||
}
|
||||
#endif
|
||||
return run_result;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#include <Void/Testing/Detail/SignalHandler.hpp>
|
||||
#ifdef VOID_HAS_STACKTRACE
|
||||
#include <Void/Stacktrace/Stacktrace.hpp>
|
||||
#endif
|
||||
#include <csignal>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
@@ -30,8 +32,12 @@ const char* signal_name(int sig) {
|
||||
|
||||
static void crash_handler(int sig) {
|
||||
g_last_signal = sig;
|
||||
#ifdef VOID_HAS_STACKTRACE
|
||||
auto frames = Void::Stacktrace::capture_stacktrace(1, 16);
|
||||
auto trace = Void::Stacktrace::format_stacktrace(frames);
|
||||
#else
|
||||
std::string trace;
|
||||
#endif
|
||||
if (g_crash_callback) g_crash_callback(sig, trace);
|
||||
#ifndef _WIN32
|
||||
if (g_jump_ready) { g_jump_ready = false; siglongjmp(g_jump_buffer, sig); }
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
void_add_module(Testing INTERNAL_DEPS Stacktrace Logging Result)
|
||||
void_add_module(Testing
|
||||
OPTIONAL_DEPS Stacktrace Logging Concurrency Configuration String
|
||||
)
|
||||
@@ -1,10 +1,12 @@
|
||||
// Cross-module integration tests for the kitchen-sink VoidInternalTests
|
||||
// binary. Exercises Logging + Result + Stacktrace + FileSystem working
|
||||
// binary. Exercises Logging + Result + Stacktrace + FileSystem + Log working
|
||||
// together — the kind of thing the standalone per-module tests can't
|
||||
// reach because they only link one module.
|
||||
|
||||
#include <Void/FileSystem/Path.hpp>
|
||||
#include <Void/FileSystem/TempDir.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Log/LoggingAdapter.hpp>
|
||||
#include <Void/Logging/ConsoleLogger.hpp>
|
||||
#include <Void/Logging/FileLogger.hpp>
|
||||
#include <Void/Logging/Level.hpp>
|
||||
@@ -113,3 +115,57 @@ Void::Testing::Test error_chain_logged_to_file_roundtrip()
|
||||
Void::Testing::expect(content.find("socket closed") != std::string::npos);
|
||||
Void::Testing::expect(content.find("caused by:") != std::string::npos);
|
||||
}
|
||||
|
||||
// Void::Log + Void::Logging: make_sink() bridges the two modules so that
|
||||
// internal library events routed through Void::Log::log() surface in a
|
||||
// Void::Logging::ConsoleLogger captured via a stringstream.
|
||||
Void::Testing::Test log_adapter_routes_to_void_logging()
|
||||
{
|
||||
std::ostringstream out;
|
||||
Void::Logging::ConsoleLogger logger{out};
|
||||
logger.set_level(Void::Logging::Level::Trace);
|
||||
|
||||
Void::Log::set_sink(Void::Log::make_sink(logger));
|
||||
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Info, "TestModule", "hello from Void::Log");
|
||||
Void::Log::log(Void::Log::Level::Warning, "TestModule", "a warning");
|
||||
|
||||
Void::Log::set_sink({});
|
||||
|
||||
const auto text = out.str();
|
||||
Void::Testing::expect(text.find("hello from Void::Log") !=
|
||||
std::string::npos);
|
||||
Void::Testing::expect(text.find("a warning") != std::string::npos);
|
||||
Void::Testing::expect(text.find("[TestModule]") != std::string::npos);
|
||||
}
|
||||
|
||||
// FileSystem operations now emit Void::Log events; verify they reach a sink.
|
||||
Void::Testing::Test filesystem_ops_emit_log_events()
|
||||
{
|
||||
int debug_count = 0;
|
||||
int warning_count = 0;
|
||||
Void::Log::set_sink(
|
||||
[&](Void::Log::Level l, std::string_view, std::string_view) {
|
||||
if (l == Void::Log::Level::Debug) {
|
||||
++debug_count;
|
||||
}
|
||||
if (l == Void::Log::Level::Warning) {
|
||||
++warning_count;
|
||||
}
|
||||
});
|
||||
|
||||
Void::FileSystem::TempDir tmp;
|
||||
auto p = tmp / "test.txt";
|
||||
(void)Void::FileSystem::write_file(p, "data");
|
||||
(void)Void::FileSystem::read_file(p);
|
||||
(void)Void::FileSystem::read_file(tmp / "nonexistent.txt");
|
||||
|
||||
Void::Log::set_sink({});
|
||||
|
||||
// TempDir creation + read success + write (no debug from write_file) = at
|
||||
// least 2
|
||||
Void::Testing::expect(debug_count >= 2);
|
||||
// Missing file read = 1 warning
|
||||
Void::Testing::expect(warning_count >= 1);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
#include <Void/Bits/Bits.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// ── popcount ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test popcount_zero()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::popcount(0u), 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test popcount_all_ones_u8()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::popcount(std::uint8_t{0xFF}), 8);
|
||||
}
|
||||
|
||||
Void::Testing::Test popcount_u32()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::popcount(std::uint32_t{0x0F0F0F0F}), 16);
|
||||
}
|
||||
|
||||
// ── test/set/clear/toggle ────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test test_bit_set()
|
||||
{
|
||||
Void::Testing::expect(Void::Bits::test_bit(std::uint8_t{0b00000100u}, 2));
|
||||
}
|
||||
|
||||
Void::Testing::Test test_bit_clear()
|
||||
{
|
||||
Void::Testing::expect(!Void::Bits::test_bit(std::uint8_t{0b00000100u}, 0));
|
||||
}
|
||||
|
||||
Void::Testing::Test set_bit_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::set_bit(std::uint8_t{0u}, 3),
|
||||
std::uint8_t{0b00001000u});
|
||||
}
|
||||
|
||||
Void::Testing::Test clear_bit_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::clear_bit(std::uint8_t{0xFF}, 3),
|
||||
std::uint8_t{0b11110111u});
|
||||
}
|
||||
|
||||
Void::Testing::Test toggle_bit_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::toggle_bit(std::uint8_t{0u}, 5),
|
||||
std::uint8_t{0b00100000u});
|
||||
}
|
||||
|
||||
// ── extract / deposit ─────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test extract_bits_works()
|
||||
{
|
||||
// bits 4-7 of 0b10110100 = 0b1011
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::extract_bits(std::uint8_t{0b10110100u}, 4, 4),
|
||||
std::uint8_t{0b1011u});
|
||||
}
|
||||
|
||||
Void::Testing::Test deposit_bits_works()
|
||||
{
|
||||
// deposit 0b1010 into bits 4-7 of 0x00
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::deposit_bits(std::uint8_t{0u}, std::uint8_t{0b1010u}, 4, 4),
|
||||
std::uint8_t{0b10100000u});
|
||||
}
|
||||
|
||||
// ── rotation ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test rotl_8()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::rotl(std::uint8_t{0b10000001u}, 1),
|
||||
std::uint8_t{0b00000011u});
|
||||
}
|
||||
|
||||
Void::Testing::Test rotr_8()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::rotr(std::uint8_t{0b10000001u}, 1),
|
||||
std::uint8_t{0b11000000u});
|
||||
}
|
||||
|
||||
// ── pow2 helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test has_single_bit()
|
||||
{
|
||||
Void::Testing::expect(Void::Bits::has_single_bit(64u));
|
||||
Void::Testing::expect(!Void::Bits::has_single_bit(63u));
|
||||
}
|
||||
|
||||
Void::Testing::Test ceil_pow2_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::ceil_pow2(5u), 8u);
|
||||
Void::Testing::expect_eq(Void::Bits::ceil_pow2(8u), 8u);
|
||||
}
|
||||
|
||||
Void::Testing::Test floor_pow2_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::floor_pow2(5u), 4u);
|
||||
}
|
||||
|
||||
// ── align ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test align_up_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::align_up(13u, 8u), 16u);
|
||||
Void::Testing::expect_eq(Void::Bits::align_up(8u, 8u), 8u);
|
||||
}
|
||||
|
||||
Void::Testing::Test align_down_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::align_down(13u, 8u), 8u);
|
||||
}
|
||||
|
||||
// ── masks ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test low_mask_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::low_mask<std::uint8_t>(4),
|
||||
std::uint8_t{0x0F});
|
||||
}
|
||||
|
||||
Void::Testing::Test range_mask_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::range_mask<std::uint8_t>(2, 5),
|
||||
std::uint8_t{0b00111100u});
|
||||
}
|
||||
|
||||
// ── byteswap / endian ────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test byteswap_u32()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::byteswap(std::uint32_t{0x12345678u}),
|
||||
std::uint32_t{0x78563412u});
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
#include <Void/Concurrency/Channel.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
using Void::Concurrency::Channel;
|
||||
|
||||
Void::Testing::Test capacity_is_preserved()
|
||||
{
|
||||
Channel<int> ch{8};
|
||||
Void::Testing::expect_eq(ch.capacity(), std::size_t{8});
|
||||
}
|
||||
|
||||
Void::Testing::Test try_send_and_try_receive_roundtrip()
|
||||
{
|
||||
Channel<int> ch{4};
|
||||
Void::Testing::expect(ch.try_send(10));
|
||||
Void::Testing::expect(ch.try_send(20));
|
||||
Void::Testing::expect_eq(ch.size(), std::size_t{2});
|
||||
auto v1 = ch.try_receive();
|
||||
Void::Testing::expect(v1.has_value());
|
||||
Void::Testing::expect_eq(*v1, 10);
|
||||
auto v2 = ch.try_receive();
|
||||
Void::Testing::expect(v2.has_value());
|
||||
Void::Testing::expect_eq(*v2, 20);
|
||||
auto empty = ch.try_receive();
|
||||
Void::Testing::expect(!empty.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test try_send_fails_when_full()
|
||||
{
|
||||
Channel<int> ch{2};
|
||||
Void::Testing::expect(ch.try_send(1));
|
||||
Void::Testing::expect(ch.try_send(2));
|
||||
Void::Testing::expect(!ch.try_send(3));
|
||||
}
|
||||
|
||||
Void::Testing::Test close_unblocks_receiver()
|
||||
{
|
||||
Channel<int> ch{4};
|
||||
std::thread producer{[&] { ch.close(); }};
|
||||
auto val = ch.receive();
|
||||
producer.join();
|
||||
Void::Testing::expect(!val.has_value());
|
||||
Void::Testing::expect(ch.is_closed());
|
||||
}
|
||||
|
||||
Void::Testing::Test producer_consumer_ordering()
|
||||
{
|
||||
Channel<int> ch{16};
|
||||
constexpr int N = 10;
|
||||
std::thread producer{[&] {
|
||||
for (int i = 0; i < N; ++i) {
|
||||
ch.send(i);
|
||||
}
|
||||
ch.close();
|
||||
}};
|
||||
std::vector<int> received;
|
||||
while (auto v = ch.receive()) {
|
||||
received.push_back(*v);
|
||||
}
|
||||
producer.join();
|
||||
Void::Testing::expect_eq(static_cast<int>(received.size()), N);
|
||||
for (int i = 0; i < N; ++i) {
|
||||
Void::Testing::expect_eq(received[i], i);
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test try_send_fails_after_close()
|
||||
{
|
||||
Channel<int> ch{4};
|
||||
ch.close();
|
||||
Void::Testing::expect(!ch.try_send(1));
|
||||
}
|
||||
|
||||
Void::Testing::Test send_returns_false_when_closed()
|
||||
{
|
||||
Channel<int> ch{1};
|
||||
ch.close();
|
||||
bool ok = ch.send(42);
|
||||
Void::Testing::expect(!ok);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
#include <Void/Concurrency/ParallelFor.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <vector>
|
||||
|
||||
using namespace Void::Concurrency;
|
||||
|
||||
Void::Testing::Test parallel_sum_matches_sequential()
|
||||
{
|
||||
constexpr int N = 1000;
|
||||
std::atomic<long long> total{0};
|
||||
parallel_for(0, N, [&](int i) { total += i; });
|
||||
Void::Testing::expect_eq(total.load(),
|
||||
static_cast<long long>(N) * (N - 1) / 2);
|
||||
}
|
||||
|
||||
Void::Testing::Test empty_range_does_nothing()
|
||||
{
|
||||
std::atomic<int> calls{0};
|
||||
parallel_for(5, 5, [&](int) { ++calls; });
|
||||
Void::Testing::expect_eq(calls.load(), 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test with_explicit_pool()
|
||||
{
|
||||
ThreadPool pool{2};
|
||||
std::atomic<int> count{0};
|
||||
parallel_for(0, 10, [&](int) { ++count; }, pool);
|
||||
Void::Testing::expect_eq(count.load(), 10);
|
||||
}
|
||||
|
||||
Void::Testing::Test results_written_to_indexed_array()
|
||||
{
|
||||
constexpr int N = 64;
|
||||
std::vector<int> out(N, 0);
|
||||
parallel_for(0, N, [&](int i) { out[i] = i * i; });
|
||||
for (int i = 0; i < N; ++i) {
|
||||
Void::Testing::expect_eq(out[i], i * i);
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test exception_propagates()
|
||||
{
|
||||
bool caught = false;
|
||||
try {
|
||||
parallel_for(0, 4, [](int i) {
|
||||
if (i == 2) {
|
||||
throw std::runtime_error("bad index");
|
||||
}
|
||||
});
|
||||
} catch (const std::runtime_error&) {
|
||||
caught = true;
|
||||
}
|
||||
Void::Testing::expect(caught);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
#include <Void/Concurrency/ThreadPool.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
|
||||
using Void::Concurrency::ThreadPool;
|
||||
|
||||
Void::Testing::Test thread_count_matches_requested()
|
||||
{
|
||||
ThreadPool pool{4};
|
||||
Void::Testing::expect_eq(pool.thread_count(), std::size_t{4});
|
||||
}
|
||||
|
||||
Void::Testing::Test defaults_to_hardware_concurrency()
|
||||
{
|
||||
ThreadPool pool;
|
||||
Void::Testing::expect(pool.thread_count() >= 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test submit_returns_correct_value()
|
||||
{
|
||||
ThreadPool pool{2};
|
||||
auto fut = pool.submit([] { return 42; });
|
||||
Void::Testing::expect_eq(fut.get(), 42);
|
||||
}
|
||||
|
||||
Void::Testing::Test tasks_run_concurrently()
|
||||
{
|
||||
constexpr int N = 8;
|
||||
ThreadPool pool{N};
|
||||
std::atomic<int> counter{0};
|
||||
std::vector<std::future<void>> futs;
|
||||
futs.reserve(N);
|
||||
for (int i = 0; i < N; ++i) {
|
||||
futs.push_back(pool.submit([&] {
|
||||
++counter;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
}));
|
||||
}
|
||||
for (auto& f : futs) {
|
||||
f.get();
|
||||
}
|
||||
Void::Testing::expect_eq(counter.load(), N);
|
||||
}
|
||||
|
||||
Void::Testing::Test parallel_sum_is_correct()
|
||||
{
|
||||
ThreadPool pool{4};
|
||||
constexpr int N = 100;
|
||||
std::atomic<long long> total{0};
|
||||
std::vector<std::future<void>> futs;
|
||||
futs.reserve(N);
|
||||
for (int i = 1; i <= N; ++i) {
|
||||
futs.push_back(pool.submit([&, i] { total += i; }));
|
||||
}
|
||||
for (auto& f : futs) {
|
||||
f.get();
|
||||
}
|
||||
Void::Testing::expect_eq(total.load(), 5050LL);
|
||||
}
|
||||
|
||||
Void::Testing::Test exception_propagates_through_future()
|
||||
{
|
||||
ThreadPool pool{1};
|
||||
auto fut = pool.submit([] -> int { throw std::runtime_error("boom"); });
|
||||
bool caught = false;
|
||||
try {
|
||||
fut.get();
|
||||
} catch (const std::runtime_error& e) {
|
||||
caught = (std::string{e.what()} == "boom");
|
||||
}
|
||||
Void::Testing::expect(caught);
|
||||
}
|
||||
|
||||
Void::Testing::Test submit_after_destruction_throws()
|
||||
{
|
||||
std::optional<std::future<int>> fut;
|
||||
{
|
||||
ThreadPool pool{1};
|
||||
fut = pool.submit([] { return 1; });
|
||||
fut->get();
|
||||
}
|
||||
// pool is now destroyed; this just verifies destruction was clean
|
||||
Void::Testing::expect(true);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Configuration/Env.hpp>
|
||||
#include <Void/FileSystem/TempDir.hpp>
|
||||
#include <Void/FileSystem/Path.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
|
||||
Void::Testing::Test get_env_finds_set_variable()
|
||||
{
|
||||
::setenv("VOID_TEST_VAR_A", "hello", 1);
|
||||
auto r = Void::Configuration::get_env("VOID_TEST_VAR_A");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, std::string{"hello"});
|
||||
::unsetenv("VOID_TEST_VAR_A");
|
||||
}
|
||||
|
||||
Void::Testing::Test get_env_returns_error_for_missing()
|
||||
{
|
||||
::unsetenv("VOID_TEST_VAR_MISSING_XYZ");
|
||||
auto r = Void::Configuration::get_env("VOID_TEST_VAR_MISSING_XYZ");
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test get_env_or_returns_fallback_when_absent()
|
||||
{
|
||||
::unsetenv("VOID_TEST_VAR_MISSING_XYZ");
|
||||
auto val = Void::Configuration::get_env_or("VOID_TEST_VAR_MISSING_XYZ", "default");
|
||||
Void::Testing::expect_eq(val, std::string{"default"});
|
||||
}
|
||||
|
||||
Void::Testing::Test get_env_or_returns_value_when_present()
|
||||
{
|
||||
::setenv("VOID_TEST_VAR_B", "world", 1);
|
||||
auto val = Void::Configuration::get_env_or("VOID_TEST_VAR_B", "fallback");
|
||||
Void::Testing::expect_eq(val, std::string{"world"});
|
||||
::unsetenv("VOID_TEST_VAR_B");
|
||||
}
|
||||
|
||||
Void::Testing::Test config_set_and_get()
|
||||
{
|
||||
Void::Configuration::Config cfg;
|
||||
cfg.set("key", "value");
|
||||
auto r = cfg.get("key");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(std::string{*r}, std::string{"value"});
|
||||
}
|
||||
|
||||
Void::Testing::Test config_get_missing_key_fails()
|
||||
{
|
||||
Void::Configuration::Config cfg;
|
||||
auto r = cfg.get("nonexistent");
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test config_get_or_returns_fallback()
|
||||
{
|
||||
Void::Configuration::Config cfg;
|
||||
auto val = cfg.get_or("missing", "fb");
|
||||
Void::Testing::expect_eq(std::string{val}, std::string{"fb"});
|
||||
}
|
||||
|
||||
Void::Testing::Test config_from_env_reads_listed_keys()
|
||||
{
|
||||
::setenv("VOID_TEST_CFG_X", "42", 1);
|
||||
::unsetenv("VOID_TEST_CFG_Y");
|
||||
|
||||
auto cfg = Void::Configuration::Config::from_env({"VOID_TEST_CFG_X", "VOID_TEST_CFG_Y"});
|
||||
Void::Testing::expect_eq(cfg.size(), std::size_t{1});
|
||||
Void::Testing::expect_eq(std::string{cfg.get_or("VOID_TEST_CFG_X")}, std::string{"42"});
|
||||
::unsetenv("VOID_TEST_CFG_X");
|
||||
}
|
||||
|
||||
Void::Testing::Test config_from_file_parses_key_value()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp;
|
||||
auto path = tmp / "cfg.env";
|
||||
(void)Void::FileSystem::write_file(path, "HOST=localhost\nPORT=5432\n");
|
||||
|
||||
auto r = Void::Configuration::Config::from_file(path);
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(std::string{r->get_or("HOST")}, std::string{"localhost"});
|
||||
Void::Testing::expect_eq(std::string{r->get_or("PORT")}, std::string{"5432"});
|
||||
}
|
||||
|
||||
Void::Testing::Test config_from_file_skips_comments_and_blank_lines()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp;
|
||||
auto path = tmp / "cfg.env";
|
||||
(void)Void::FileSystem::write_file(path, "# this is a comment\n\nFOO=bar\n");
|
||||
|
||||
auto r = Void::Configuration::Config::from_file(path);
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(r->size(), std::size_t{1});
|
||||
Void::Testing::expect_eq(std::string{r->get_or("FOO")}, std::string{"bar"});
|
||||
}
|
||||
|
||||
Void::Testing::Test config_overlay_later_wins_on_conflict()
|
||||
{
|
||||
Void::Configuration::Config base;
|
||||
base.set("A", "from_base");
|
||||
base.set("B", "only_base");
|
||||
|
||||
Void::Configuration::Config top;
|
||||
top.set("A", "from_top");
|
||||
top.set("C", "only_top");
|
||||
|
||||
base.overlay(top);
|
||||
|
||||
Void::Testing::expect_eq(std::string{base.get_or("A")}, std::string{"from_top"});
|
||||
Void::Testing::expect_eq(std::string{base.get_or("B")}, std::string{"only_base"});
|
||||
Void::Testing::expect_eq(std::string{base.get_or("C")}, std::string{"only_top"});
|
||||
}
|
||||
|
||||
Void::Testing::Test config_from_file_missing_path_fails()
|
||||
{
|
||||
auto r = Void::Configuration::Config::from_file("/no/such/file.env");
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
#include <Void/Encoding/Base64.hpp>
|
||||
#include <Void/Encoding/Hex.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
// ── Base64 encode ─────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test base64_encode_empty()
|
||||
{
|
||||
Void::Testing::expect(Void::Encoding::Base64::encode("").empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test base64_encode_man()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Man"),
|
||||
std::string{"TWFu"});
|
||||
}
|
||||
|
||||
Void::Testing::Test base64_encode_ma()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Ma"),
|
||||
std::string{"TWE="});
|
||||
}
|
||||
|
||||
Void::Testing::Test base64_encode_m()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Encoding::Base64::encode("M"),
|
||||
std::string{"TQ=="});
|
||||
}
|
||||
|
||||
Void::Testing::Test base64_encode_hello_world()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Hello, World!"),
|
||||
std::string{"SGVsbG8sIFdvcmxkIQ=="});
|
||||
}
|
||||
|
||||
// ── Base64 decode ─────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test base64_decode_empty()
|
||||
{
|
||||
const auto r = Void::Encoding::Base64::decode("");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect(r->empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test base64_decode_man()
|
||||
{
|
||||
const auto r = Void::Encoding::Base64::decode("TWFu");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, std::string{"Man"});
|
||||
}
|
||||
|
||||
Void::Testing::Test base64_decode_with_padding()
|
||||
{
|
||||
const auto r = Void::Encoding::Base64::decode("SGVsbG8sIFdvcmxkIQ==");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, std::string{"Hello, World!"});
|
||||
}
|
||||
|
||||
Void::Testing::Test base64_decode_invalid_returns_nullopt()
|
||||
{
|
||||
const auto r = Void::Encoding::Base64::decode("!!");
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test base64_round_trip()
|
||||
{
|
||||
const std::string original = "The quick brown fox jumps over the lazy dog";
|
||||
const auto encoded = Void::Encoding::Base64::encode(original);
|
||||
const auto decoded = Void::Encoding::Base64::decode(encoded);
|
||||
Void::Testing::expect(decoded.has_value());
|
||||
Void::Testing::expect_eq(*decoded, original);
|
||||
}
|
||||
|
||||
// ── Base64 URL ────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test base64url_no_padding()
|
||||
{
|
||||
const auto s = Void::Encoding::Base64::encode_url("Man");
|
||||
Void::Testing::expect_eq(s, std::string{"TWFu"});
|
||||
Void::Testing::expect(s.find('=') == std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test base64url_no_plus_or_slash()
|
||||
{
|
||||
// encode something that would produce + or / in standard base64
|
||||
const std::string tricky = "\xfb\xff\xfe";
|
||||
const auto s = Void::Encoding::Base64::encode_url(tricky);
|
||||
Void::Testing::expect(s.find('+') == std::string::npos);
|
||||
Void::Testing::expect(s.find('/') == std::string::npos);
|
||||
}
|
||||
|
||||
// ── Hex encode ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test hex_encode_empty()
|
||||
{
|
||||
Void::Testing::expect(Void::Encoding::Hex::encode("").empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test hex_encode_hello()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Encoding::Hex::encode("Hi"),
|
||||
std::string{"4869"});
|
||||
}
|
||||
|
||||
Void::Testing::Test hex_encode_binary()
|
||||
{
|
||||
const std::string bin{'\x00', '\xff', '\xab'};
|
||||
Void::Testing::expect_eq(Void::Encoding::Hex::encode(bin),
|
||||
std::string{"00ffab"});
|
||||
}
|
||||
|
||||
Void::Testing::Test hex_encode_upper()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Encoding::Hex::encode_upper("Hi"),
|
||||
std::string{"4869"});
|
||||
}
|
||||
|
||||
// ── Hex decode ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test hex_decode_empty()
|
||||
{
|
||||
const auto r = Void::Encoding::Hex::decode("");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect(r->empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test hex_decode_hello()
|
||||
{
|
||||
const auto r = Void::Encoding::Hex::decode("4869");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, std::string{"Hi"});
|
||||
}
|
||||
|
||||
Void::Testing::Test hex_decode_uppercase()
|
||||
{
|
||||
const auto r = Void::Encoding::Hex::decode("4869");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, std::string{"Hi"});
|
||||
}
|
||||
|
||||
Void::Testing::Test hex_decode_odd_length_fails()
|
||||
{
|
||||
Void::Testing::expect(!Void::Encoding::Hex::decode("abc").has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test hex_decode_invalid_char_fails()
|
||||
{
|
||||
Void::Testing::expect(!Void::Encoding::Hex::decode("zz").has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test hex_round_trip()
|
||||
{
|
||||
const std::string original = "binary\x00\x01\x02\xff";
|
||||
const auto encoded = Void::Encoding::Hex::encode(original);
|
||||
const auto decoded = Void::Encoding::Hex::decode(encoded);
|
||||
Void::Testing::expect(decoded.has_value());
|
||||
Void::Testing::expect_eq(*decoded, original);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
#include <Void/FileSystem/Path.hpp>
|
||||
#include <Void/FileSystem/Query.hpp>
|
||||
#include <Void/FileSystem/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
|
||||
Void::Testing::Test exists_returns_true_for_existing_file()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp;
|
||||
auto p = tmp / "f.txt";
|
||||
(void)Void::FileSystem::write_file(p, "x");
|
||||
Void::Testing::expect(Void::FileSystem::exists(p));
|
||||
}
|
||||
|
||||
Void::Testing::Test exists_returns_false_for_missing()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp;
|
||||
Void::Testing::expect(!Void::FileSystem::exists(tmp / "no_such.txt"));
|
||||
}
|
||||
|
||||
Void::Testing::Test file_size_returns_correct_byte_count()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp;
|
||||
auto p = tmp / "sized.txt";
|
||||
(void)Void::FileSystem::write_file(p, "hello");
|
||||
auto r = Void::FileSystem::file_size(p);
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(*r, std::uintmax_t{5});
|
||||
}
|
||||
|
||||
Void::Testing::Test file_size_fails_for_missing_path()
|
||||
{
|
||||
auto r = Void::FileSystem::file_size("/no/such/file.txt");
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test last_modified_returns_a_time()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp;
|
||||
auto p = tmp / "ts.txt";
|
||||
(void)Void::FileSystem::write_file(p, "data");
|
||||
auto r = Void::FileSystem::last_modified(p);
|
||||
Void::Testing::expect(r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test last_modified_fails_for_missing_path()
|
||||
{
|
||||
auto r = Void::FileSystem::last_modified("/no/such/file.txt");
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test list_directory_returns_created_entries()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp;
|
||||
(void)Void::FileSystem::write_file(tmp / "a.txt", "");
|
||||
(void)Void::FileSystem::write_file(tmp / "b.txt", "");
|
||||
auto r = Void::FileSystem::list_directory(tmp.path());
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect(r->size() >= 2);
|
||||
const auto has_a = std::any_of(r->begin(), r->end(), [&](const auto& p) {
|
||||
return p.filename() == "a.txt";
|
||||
});
|
||||
const auto has_b = std::any_of(r->begin(), r->end(), [&](const auto& p) {
|
||||
return p.filename() == "b.txt";
|
||||
});
|
||||
Void::Testing::expect(has_a);
|
||||
Void::Testing::expect(has_b);
|
||||
}
|
||||
|
||||
Void::Testing::Test list_directory_fails_for_missing_path()
|
||||
{
|
||||
auto r = Void::FileSystem::list_directory("/no/such/directory");
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test copy_file_creates_duplicate()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp;
|
||||
auto src = tmp / "src.txt";
|
||||
auto dst = tmp / "dst.txt";
|
||||
(void)Void::FileSystem::write_file(src, "contents");
|
||||
auto r = Void::FileSystem::copy_file(src, dst);
|
||||
Void::Testing::expect(r.has_value());
|
||||
auto back = Void::FileSystem::read_file(dst);
|
||||
Void::Testing::expect(back.has_value());
|
||||
Void::Testing::expect_eq(*back, std::string{"contents"});
|
||||
}
|
||||
|
||||
Void::Testing::Test copy_file_fails_without_overwrite_when_dst_exists()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp;
|
||||
auto src = tmp / "src.txt";
|
||||
auto dst = tmp / "dst.txt";
|
||||
(void)Void::FileSystem::write_file(src, "new");
|
||||
(void)Void::FileSystem::write_file(dst, "old");
|
||||
auto r = Void::FileSystem::copy_file(src, dst, /*overwrite=*/false);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test copy_file_with_overwrite_replaces_dst()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp;
|
||||
auto src = tmp / "src.txt";
|
||||
auto dst = tmp / "dst.txt";
|
||||
(void)Void::FileSystem::write_file(src, "new_content");
|
||||
(void)Void::FileSystem::write_file(dst, "old_content");
|
||||
auto r = Void::FileSystem::copy_file(src, dst, /*overwrite=*/true);
|
||||
Void::Testing::expect(r.has_value());
|
||||
auto back = Void::FileSystem::read_file(dst);
|
||||
Void::Testing::expect_eq(*back, std::string{"new_content"});
|
||||
}
|
||||
|
||||
Void::Testing::Test copy_dir_duplicates_tree()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp;
|
||||
auto src = tmp / "src";
|
||||
auto dst = tmp / "dst";
|
||||
(void)Void::FileSystem::ensure_directory(src);
|
||||
(void)Void::FileSystem::write_file(src / "file.txt", "tree");
|
||||
auto r = Void::FileSystem::copy_dir(src, dst);
|
||||
Void::Testing::expect(r.has_value());
|
||||
auto back = Void::FileSystem::read_file(dst / "file.txt");
|
||||
Void::Testing::expect(back.has_value());
|
||||
Void::Testing::expect_eq(*back, std::string{"tree"});
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
#include <Void/Hash/Hash.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using namespace Void::Hash::Literals;
|
||||
|
||||
// ── FNV-1a 32 ────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test fnv1a32_empty_string()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Hash::fnv1a32(""), 2166136261u);
|
||||
}
|
||||
|
||||
Void::Testing::Test fnv1a32_hello_world()
|
||||
{
|
||||
const auto a = Void::Hash::fnv1a32("hello");
|
||||
const auto b = Void::Hash::fnv1a32("world");
|
||||
Void::Testing::expect(a != b);
|
||||
Void::Testing::expect(a != 0u);
|
||||
}
|
||||
|
||||
Void::Testing::Test fnv1a32_deterministic()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Hash::fnv1a32("test"),
|
||||
Void::Hash::fnv1a32("test"));
|
||||
}
|
||||
|
||||
Void::Testing::Test fnv1a32_different_strings_differ()
|
||||
{
|
||||
Void::Testing::expect(Void::Hash::fnv1a32("abc") !=
|
||||
Void::Hash::fnv1a32("abd"));
|
||||
}
|
||||
|
||||
// ── FNV-1a 64 ────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test fnv1a64_empty_basis()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Hash::fnv1a64(""),
|
||||
14695981039346656037ull);
|
||||
}
|
||||
|
||||
Void::Testing::Test fnv1a64_hello_is_stable()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Hash::fnv1a64("hello"),
|
||||
Void::Hash::fnv1a64("hello"));
|
||||
}
|
||||
|
||||
Void::Testing::Test fnv1a64_wider_than_32()
|
||||
{
|
||||
// 64-bit should differ from 32-bit value for same input
|
||||
Void::Testing::expect(Void::Hash::fnv1a64("test") !=
|
||||
static_cast<std::uint64_t>(Void::Hash::fnv1a32("test")));
|
||||
}
|
||||
|
||||
// ── CRC-32 ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test crc32_known_value()
|
||||
{
|
||||
// CRC-32 of "123456789" is a well-known check value: 0xCBF43926
|
||||
Void::Testing::expect_eq(Void::Hash::crc32("123456789"), std::uint32_t{0xCBF43926u});
|
||||
}
|
||||
|
||||
Void::Testing::Test crc32_empty_is_zero()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Hash::crc32(""), std::uint32_t{0u});
|
||||
}
|
||||
|
||||
Void::Testing::Test crc32_deterministic()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Hash::crc32("void"), Void::Hash::crc32("void"));
|
||||
}
|
||||
|
||||
// ── DJB2 ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test djb2_non_zero_for_nonempty()
|
||||
{
|
||||
Void::Testing::expect(Void::Hash::djb2("hello") != 0u);
|
||||
}
|
||||
|
||||
Void::Testing::Test djb2_differs_per_string()
|
||||
{
|
||||
Void::Testing::expect(Void::Hash::djb2("foo") != Void::Hash::djb2("bar"));
|
||||
}
|
||||
|
||||
// ── MurmurHash3 ──────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test murmur3_32_deterministic()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Hash::murmur3_32("hello", 42u),
|
||||
Void::Hash::murmur3_32("hello", 42u));
|
||||
}
|
||||
|
||||
Void::Testing::Test murmur3_32_seed_affects_output()
|
||||
{
|
||||
Void::Testing::expect(Void::Hash::murmur3_32("hello", 0u) !=
|
||||
Void::Hash::murmur3_32("hello", 1u));
|
||||
}
|
||||
|
||||
Void::Testing::Test murmur3_32_empty_with_zero_seed()
|
||||
{
|
||||
// MurmurHash3("", 0) = 0
|
||||
Void::Testing::expect_eq(Void::Hash::murmur3_32("", 0u), std::uint32_t{0u});
|
||||
}
|
||||
|
||||
// ── UDL literals ─────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test udl_fnv32_comptime()
|
||||
{
|
||||
constexpr auto h = "hello"_fnv32;
|
||||
static_assert(h != 0u);
|
||||
Void::Testing::expect_eq(h, Void::Hash::fnv1a32("hello"));
|
||||
}
|
||||
|
||||
Void::Testing::Test udl_fnv64_comptime()
|
||||
{
|
||||
constexpr auto h = "hello"_fnv64;
|
||||
static_assert(h != 0u);
|
||||
Void::Testing::expect_eq(h, Void::Hash::fnv1a64("hello"));
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
// Reset the global sink between tests via a scoped RAII guard.
|
||||
struct SinkGuard {
|
||||
~SinkGuard() { Void::Log::set_sink({}); }
|
||||
};
|
||||
|
||||
Void::Testing::Test no_sink_is_silent()
|
||||
{
|
||||
SinkGuard guard;
|
||||
bool called = false;
|
||||
// No sink installed — this must not crash or invoke anything.
|
||||
Void::Log::log(Void::Log::Level::Info, "test", "silent message");
|
||||
Void::Testing::expect(!called);
|
||||
}
|
||||
|
||||
Void::Testing::Test sink_receives_all_fields()
|
||||
{
|
||||
SinkGuard guard;
|
||||
Void::Log::Level got_level{};
|
||||
std::string got_module;
|
||||
std::string got_message;
|
||||
|
||||
Void::Log::set_sink(
|
||||
[&](Void::Log::Level l, std::string_view mod, std::string_view msg) {
|
||||
got_level = l;
|
||||
got_module = mod;
|
||||
got_message = msg;
|
||||
});
|
||||
|
||||
Void::Log::log(Void::Log::Level::Warning, "MyModule", "something happened");
|
||||
|
||||
Void::Testing::expect(got_level == Void::Log::Level::Warning);
|
||||
Void::Testing::expect(got_module == "MyModule");
|
||||
Void::Testing::expect(got_message == "something happened");
|
||||
}
|
||||
|
||||
Void::Testing::Test set_sink_replaces_previous()
|
||||
{
|
||||
SinkGuard guard;
|
||||
int first_calls = 0;
|
||||
int second_calls = 0;
|
||||
|
||||
Void::Log::set_sink([&](auto, auto, auto) { ++first_calls; });
|
||||
Void::Log::log(Void::Log::Level::Info, "m", "a");
|
||||
|
||||
Void::Log::set_sink([&](auto, auto, auto) { ++second_calls; });
|
||||
Void::Log::log(Void::Log::Level::Info, "m", "b");
|
||||
|
||||
Void::Testing::expect_eq(first_calls, 1);
|
||||
Void::Testing::expect_eq(second_calls, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test clear_sink_silences_output()
|
||||
{
|
||||
SinkGuard guard;
|
||||
int calls = 0;
|
||||
Void::Log::set_sink([&](auto, auto, auto) { ++calls; });
|
||||
Void::Log::log(Void::Log::Level::Info, "m", "before clear");
|
||||
Void::Log::set_sink({});
|
||||
Void::Log::log(Void::Log::Level::Info, "m", "after clear");
|
||||
Void::Testing::expect_eq(calls, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test concurrent_log_calls_are_safe()
|
||||
{
|
||||
SinkGuard guard;
|
||||
std::atomic<int> count{0};
|
||||
Void::Log::set_sink([&](auto, auto, auto) { ++count; });
|
||||
|
||||
constexpr int N = 64;
|
||||
std::vector<std::thread> threads;
|
||||
threads.reserve(N);
|
||||
for (int i = 0; i < N; ++i) {
|
||||
threads.emplace_back([] {
|
||||
Void::Log::log(Void::Log::Level::Debug, "test", "concurrent");
|
||||
});
|
||||
}
|
||||
for (auto& t : threads) {
|
||||
t.join();
|
||||
}
|
||||
|
||||
Void::Testing::expect_eq(count.load(), N);
|
||||
}
|
||||
|
||||
Void::Testing::Test all_levels_are_forwarded()
|
||||
{
|
||||
SinkGuard guard;
|
||||
int calls = 0;
|
||||
Void::Log::set_sink([&](auto, auto, auto) { ++calls; });
|
||||
|
||||
Void::Log::log(Void::Log::Level::Trace, "m", "t");
|
||||
Void::Log::log(Void::Log::Level::Debug, "m", "d");
|
||||
Void::Log::log(Void::Log::Level::Info, "m", "i");
|
||||
Void::Log::log(Void::Log::Level::Warning, "m", "w");
|
||||
Void::Log::log(Void::Log::Level::Error, "m", "e");
|
||||
Void::Log::log(Void::Log::Level::Fatal, "m", "f");
|
||||
|
||||
Void::Testing::expect_eq(calls, 6);
|
||||
}
|
||||
@@ -21,7 +21,7 @@ class ConsoleLoggerTests : public Void::Testing::Fixture
|
||||
const auto content = out.str();
|
||||
Void::Testing::expect(content.find("hello world") !=
|
||||
std::string::npos);
|
||||
Void::Testing::expect(content.find("INFO") != std::string::npos);
|
||||
Void::Testing::expect(content.find("Info") != std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test level_filtering()
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
#include <Void/Math/Mat.hpp>
|
||||
#include <Void/Math/Vec.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <cmath>
|
||||
|
||||
static constexpr float EPS = 1e-5f;
|
||||
|
||||
// ── Vec2 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test vec2_add()
|
||||
{
|
||||
constexpr auto v = Void::Math::Vec2f{1, 2} + Void::Math::Vec2f{3, 4};
|
||||
static_assert(v.x == 4.f && v.y == 6.f);
|
||||
Void::Testing::expect_eq(v.x, 4.f);
|
||||
}
|
||||
|
||||
Void::Testing::Test vec2_subtract()
|
||||
{
|
||||
constexpr auto v = Void::Math::Vec2f{3, 4} - Void::Math::Vec2f{1, 1};
|
||||
Void::Testing::expect_eq(v.x, 2.f);
|
||||
Void::Testing::expect_eq(v.y, 3.f);
|
||||
}
|
||||
|
||||
Void::Testing::Test vec2_scale()
|
||||
{
|
||||
constexpr auto v = Void::Math::Vec2f{2, 3} * 2.f;
|
||||
Void::Testing::expect_eq(v.x, 4.f);
|
||||
Void::Testing::expect_eq(v.y, 6.f);
|
||||
}
|
||||
|
||||
Void::Testing::Test vec2_dot()
|
||||
{
|
||||
constexpr auto d = Void::Math::Vec2f{1, 0}.dot({0, 1});
|
||||
static_assert(d == 0.f);
|
||||
Void::Testing::expect_eq(d, 0.f);
|
||||
}
|
||||
|
||||
Void::Testing::Test vec2_length()
|
||||
{
|
||||
const Void::Math::Vec2f v{3, 4};
|
||||
Void::Testing::expect(std::abs(v.length() - 5.f) < EPS);
|
||||
}
|
||||
|
||||
Void::Testing::Test vec2_normalized()
|
||||
{
|
||||
const Void::Math::Vec2f v = Void::Math::Vec2f{3, 4}.normalized();
|
||||
Void::Testing::expect(std::abs(v.length() - 1.f) < EPS);
|
||||
}
|
||||
|
||||
Void::Testing::Test vec2_lerp()
|
||||
{
|
||||
const auto v = Void::Math::lerp(Void::Math::Vec2f{0, 0},
|
||||
Void::Math::Vec2f{2, 4}, 0.5f);
|
||||
Void::Testing::expect(std::abs(v.x - 1.f) < EPS);
|
||||
Void::Testing::expect(std::abs(v.y - 2.f) < EPS);
|
||||
}
|
||||
|
||||
// ── Vec3 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test vec3_cross_unit_vectors()
|
||||
{
|
||||
constexpr Void::Math::Vec3f x{1, 0, 0};
|
||||
constexpr Void::Math::Vec3f y{0, 1, 0};
|
||||
constexpr Void::Math::Vec3f z = x.cross(y);
|
||||
static_assert(z.x == 0.f && z.y == 0.f && z.z == 1.f);
|
||||
Void::Testing::expect_eq(z.z, 1.f);
|
||||
}
|
||||
|
||||
Void::Testing::Test vec3_length()
|
||||
{
|
||||
const Void::Math::Vec3f v{1, 2, 2};
|
||||
Void::Testing::expect(std::abs(v.length() - 3.f) < EPS);
|
||||
}
|
||||
|
||||
Void::Testing::Test vec3_normalized_unit_length()
|
||||
{
|
||||
const auto v = Void::Math::Vec3f{2, 3, 6}.normalized();
|
||||
Void::Testing::expect(std::abs(v.length() - 1.f) < EPS);
|
||||
}
|
||||
|
||||
// ── Vec4 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test vec4_from_vec3()
|
||||
{
|
||||
constexpr Void::Math::Vec4f v{Void::Math::Vec3f{1, 2, 3}, 1.f};
|
||||
static_assert(v.w == 1.f);
|
||||
Void::Testing::expect_eq(v.z, 3.f);
|
||||
}
|
||||
|
||||
Void::Testing::Test vec4_xyz()
|
||||
{
|
||||
constexpr Void::Math::Vec4f v{1, 2, 3, 4};
|
||||
constexpr auto xyz = v.xyz();
|
||||
static_assert(xyz.x == 1.f && xyz.y == 2.f && xyz.z == 3.f);
|
||||
}
|
||||
|
||||
// ── Mat4 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test mat4_identity_times_vec()
|
||||
{
|
||||
constexpr auto I = Void::Math::Mat4f::identity();
|
||||
constexpr Void::Math::Vec4f v{1, 2, 3, 1};
|
||||
constexpr auto r = I * v;
|
||||
static_assert(r.x == 1.f && r.y == 2.f && r.z == 3.f && r.w == 1.f);
|
||||
}
|
||||
|
||||
Void::Testing::Test mat4_translation()
|
||||
{
|
||||
const auto T = Void::Math::Mat4f::translation(1, 2, 3);
|
||||
const Void::Math::Vec4f v{0, 0, 0, 1};
|
||||
const auto r = T * v;
|
||||
Void::Testing::expect(std::abs(r.x - 1.f) < EPS);
|
||||
Void::Testing::expect(std::abs(r.y - 2.f) < EPS);
|
||||
Void::Testing::expect(std::abs(r.z - 3.f) < EPS);
|
||||
}
|
||||
|
||||
Void::Testing::Test mat4_scale()
|
||||
{
|
||||
const auto S = Void::Math::Mat4f::scale(2, 3, 4);
|
||||
const Void::Math::Vec4f v{1, 1, 1, 1};
|
||||
const auto r = S * v;
|
||||
Void::Testing::expect(std::abs(r.x - 2.f) < EPS);
|
||||
Void::Testing::expect(std::abs(r.y - 3.f) < EPS);
|
||||
Void::Testing::expect(std::abs(r.z - 4.f) < EPS);
|
||||
}
|
||||
|
||||
Void::Testing::Test mat4_rotation_z_90_degrees()
|
||||
{
|
||||
const auto R = Void::Math::Mat4f::rotation_z(
|
||||
static_cast<float>(M_PI) / 2.f);
|
||||
const Void::Math::Vec4f v{1, 0, 0, 0};
|
||||
const auto r = R * v;
|
||||
Void::Testing::expect(std::abs(r.x - 0.f) < EPS);
|
||||
Void::Testing::expect(std::abs(r.y - 1.f) < EPS);
|
||||
}
|
||||
|
||||
Void::Testing::Test mat4_mul_identity_nop()
|
||||
{
|
||||
const auto A = Void::Math::Mat4f::translation(1, 2, 3);
|
||||
const auto I = Void::Math::Mat4f::identity();
|
||||
const auto R = A * I;
|
||||
Void::Testing::expect_eq(R, A);
|
||||
}
|
||||
|
||||
Void::Testing::Test mat4_transpose()
|
||||
{
|
||||
auto M = Void::Math::Mat4f::identity();
|
||||
M.at(0, 1) = 5.f;
|
||||
const auto T = M.transposed();
|
||||
Void::Testing::expect_eq(T.at(1, 0), 5.f);
|
||||
Void::Testing::expect_eq(T.at(0, 1), 0.f);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
#include <Void/Process/Process.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
Void::Testing::Test shell_echo_captures_stdout()
|
||||
{
|
||||
auto r = Void::Process::shell("echo hello");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(r->exit_code, 0);
|
||||
Void::Testing::expect(r->out.find("hello") != std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test shell_exit_code_propagates()
|
||||
{
|
||||
auto r = Void::Process::shell("exit 42");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(r->exit_code, 42);
|
||||
}
|
||||
|
||||
Void::Testing::Test shell_captures_stderr_separately()
|
||||
{
|
||||
auto r = Void::Process::shell("echo err_output >&2");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect(r->err.find("err_output") != std::string::npos);
|
||||
Void::Testing::expect(r->out.find("err_output") == std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test run_with_args_builds_correct_argv()
|
||||
{
|
||||
auto r = Void::Process::run("/bin/echo", {"hello", "world"});
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(r->exit_code, 0);
|
||||
Void::Testing::expect(r->out.find("hello world") != std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test run_stdin_forwarded_to_cat()
|
||||
{
|
||||
auto r = Void::Process::run("/bin/cat", {}, "piped_input");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(r->exit_code, 0);
|
||||
Void::Testing::expect(r->out.find("piped_input") != std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test run_missing_executable_returns_code_127()
|
||||
{
|
||||
auto r = Void::Process::run("/this/binary/does/not/exist");
|
||||
// fork succeeds, execvp fails, child _exits(127)
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(r->exit_code, 127);
|
||||
}
|
||||
|
||||
Void::Testing::Test run_stdout_and_stderr_independent()
|
||||
{
|
||||
auto r = Void::Process::shell(
|
||||
"echo to_stdout; echo to_stderr >&2");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect(r->out.find("to_stdout") != std::string::npos);
|
||||
Void::Testing::expect(r->err.find("to_stderr") != std::string::npos);
|
||||
Void::Testing::expect(r->out.find("to_stderr") == std::string::npos);
|
||||
Void::Testing::expect(r->err.find("to_stdout") == std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test run_large_output_is_captured_fully()
|
||||
{
|
||||
// Generate 10 000 lines; poll-based reader must accumulate them all.
|
||||
auto r = Void::Process::shell("seq 1 10000");
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(r->exit_code, 0);
|
||||
// "10000\n" must be present, and total output must be substantial
|
||||
Void::Testing::expect(r->out.find("10000") != std::string::npos);
|
||||
Void::Testing::expect(r->out.size() > 40000);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
#include <Void/Random/Random.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
|
||||
// ── Xoshiro256 ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test xoshiro_produces_output()
|
||||
{
|
||||
Void::Random::Xoshiro256 rng{42};
|
||||
const auto a = rng();
|
||||
const auto b = rng();
|
||||
Void::Testing::expect(a != b);
|
||||
}
|
||||
|
||||
Void::Testing::Test xoshiro_same_seed_same_sequence()
|
||||
{
|
||||
Void::Random::Xoshiro256 r1{12345};
|
||||
Void::Random::Xoshiro256 r2{12345};
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
Void::Testing::expect_eq(r1(), r2());
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test xoshiro_different_seeds_differ()
|
||||
{
|
||||
Void::Random::Xoshiro256 r1{1};
|
||||
Void::Random::Xoshiro256 r2{2};
|
||||
Void::Testing::expect(r1() != r2());
|
||||
}
|
||||
|
||||
// ── uniform_int ──────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test uniform_int_in_range()
|
||||
{
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
const auto v = Void::Random::uniform_int(1, 6);
|
||||
Void::Testing::expect(v >= 1);
|
||||
Void::Testing::expect(v <= 6);
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test uniform_int_single_value()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Random::uniform_int(7, 7), 7);
|
||||
}
|
||||
|
||||
// ── uniform_real ─────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test uniform_real_in_range()
|
||||
{
|
||||
for (int i = 0; i < 50; ++i) {
|
||||
const double v = Void::Random::uniform_real(0.0, 1.0);
|
||||
Void::Testing::expect(v >= 0.0);
|
||||
Void::Testing::expect(v < 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
// ── coin_flip ────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test coin_flip_always_true()
|
||||
{
|
||||
Void::Testing::expect(Void::Random::coin_flip(1.0));
|
||||
}
|
||||
|
||||
Void::Testing::Test coin_flip_always_false()
|
||||
{
|
||||
Void::Testing::expect(!Void::Random::coin_flip(0.0));
|
||||
}
|
||||
|
||||
// ── shuffle ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test shuffle_preserves_elements()
|
||||
{
|
||||
std::vector<int> v{1, 2, 3, 4, 5};
|
||||
const auto orig = v;
|
||||
Void::Random::shuffle(v);
|
||||
auto sorted = v;
|
||||
std::sort(sorted.begin(), sorted.end());
|
||||
Void::Testing::expect_eq(sorted, orig);
|
||||
}
|
||||
|
||||
// ── random_string ────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test random_string_correct_length()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Random::random_string(10).size(),
|
||||
std::size_t{10});
|
||||
}
|
||||
|
||||
Void::Testing::Test random_string_empty()
|
||||
{
|
||||
Void::Testing::expect(Void::Random::random_string(0).empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test random_string_varies()
|
||||
{
|
||||
// Extremely unlikely to produce identical 16-char strings twice
|
||||
const auto a = Void::Random::random_string(16);
|
||||
const auto b = Void::Random::random_string(16);
|
||||
Void::Testing::expect(a != b);
|
||||
}
|
||||
|
||||
// ── sample_indices ───────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test sample_indices_correct_count()
|
||||
{
|
||||
const auto idxs = Void::Random::sample_indices(20, 5);
|
||||
Void::Testing::expect_eq(idxs.size(), std::size_t{5});
|
||||
}
|
||||
|
||||
Void::Testing::Test sample_indices_in_range()
|
||||
{
|
||||
const auto idxs = Void::Random::sample_indices(10, 10);
|
||||
for (auto i : idxs) {
|
||||
Void::Testing::expect(i < std::size_t{10});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
#include <Void/String/String.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
// ── trim ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test trim_removes_leading_and_trailing_spaces()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
std::string{Void::String::trim(" hello ")},
|
||||
std::string{"hello"});
|
||||
}
|
||||
|
||||
Void::Testing::Test trim_leaves_interior_whitespace()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
std::string{Void::String::trim(" a b ")},
|
||||
std::string{"a b"});
|
||||
}
|
||||
|
||||
Void::Testing::Test trim_empty_string_stays_empty()
|
||||
{
|
||||
Void::Testing::expect(Void::String::trim("").empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test trim_only_whitespace_returns_empty()
|
||||
{
|
||||
Void::Testing::expect(Void::String::trim(" \t\n ").empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test trim_left_only_removes_prefix()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
std::string{Void::String::trim_left(" hi ")},
|
||||
std::string{"hi "});
|
||||
}
|
||||
|
||||
Void::Testing::Test trim_right_only_removes_suffix()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
std::string{Void::String::trim_right(" hi ")},
|
||||
std::string{" hi"});
|
||||
}
|
||||
|
||||
// ── split ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test split_char_produces_correct_parts()
|
||||
{
|
||||
const auto parts = Void::String::split("a,b,c", ',');
|
||||
Void::Testing::expect_eq(parts.size(), std::size_t{3});
|
||||
Void::Testing::expect_eq(std::string{parts[0]}, std::string{"a"});
|
||||
Void::Testing::expect_eq(std::string{parts[1]}, std::string{"b"});
|
||||
Void::Testing::expect_eq(std::string{parts[2]}, std::string{"c"});
|
||||
}
|
||||
|
||||
Void::Testing::Test split_char_preserves_empty_tokens()
|
||||
{
|
||||
const auto parts = Void::String::split("a,,b", ',');
|
||||
Void::Testing::expect_eq(parts.size(), std::size_t{3});
|
||||
Void::Testing::expect(parts[1].empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test split_char_no_delimiter_returns_whole_string()
|
||||
{
|
||||
const auto parts = Void::String::split("hello", ',');
|
||||
Void::Testing::expect_eq(parts.size(), std::size_t{1});
|
||||
Void::Testing::expect_eq(std::string{parts[0]}, std::string{"hello"});
|
||||
}
|
||||
|
||||
Void::Testing::Test split_string_delimiter_works()
|
||||
{
|
||||
const auto parts = Void::String::split("a::b::c", "::");
|
||||
Void::Testing::expect_eq(parts.size(), std::size_t{3});
|
||||
Void::Testing::expect_eq(std::string{parts[1]}, std::string{"b"});
|
||||
}
|
||||
|
||||
Void::Testing::Test split_empty_delimiter_returns_whole()
|
||||
{
|
||||
const auto parts = Void::String::split("abc", "");
|
||||
Void::Testing::expect_eq(parts.size(), std::size_t{1});
|
||||
}
|
||||
|
||||
// ── join ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test join_vector_of_string_view()
|
||||
{
|
||||
const std::vector<std::string_view> parts{"a", "b", "c"};
|
||||
Void::Testing::expect_eq(Void::String::join(parts, ", "),
|
||||
std::string{"a, b, c"});
|
||||
}
|
||||
|
||||
Void::Testing::Test join_single_element_no_separator()
|
||||
{
|
||||
const std::vector<std::string_view> parts{"only"};
|
||||
Void::Testing::expect_eq(Void::String::join(parts, "-"),
|
||||
std::string{"only"});
|
||||
}
|
||||
|
||||
Void::Testing::Test join_empty_range_returns_empty()
|
||||
{
|
||||
const std::vector<std::string_view> parts;
|
||||
Void::Testing::expect(Void::String::join(parts, ",").empty());
|
||||
}
|
||||
|
||||
// ── case ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test to_lower_converts_ascii()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::String::to_lower("Hello World"),
|
||||
std::string{"hello world"});
|
||||
}
|
||||
|
||||
Void::Testing::Test to_upper_converts_ascii()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::String::to_upper("Hello World"),
|
||||
std::string{"HELLO WORLD"});
|
||||
}
|
||||
|
||||
// ── replace_all ───────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test replace_all_replaces_all_occurrences()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::String::replace_all("aXbXc", "X", "--"),
|
||||
std::string{"a--b--c"});
|
||||
}
|
||||
|
||||
Void::Testing::Test replace_all_with_empty_from_returns_original()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::String::replace_all("abc", "", "x"),
|
||||
std::string{"abc"});
|
||||
}
|
||||
|
||||
Void::Testing::Test replace_all_no_match_returns_original()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::String::replace_all("abc", "z", "x"),
|
||||
std::string{"abc"});
|
||||
}
|
||||
|
||||
// ── pad ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test pad_right_pads_to_width()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::String::pad_right("hi", 5),
|
||||
std::string{"hi "});
|
||||
}
|
||||
|
||||
Void::Testing::Test pad_right_no_op_when_already_wide()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::String::pad_right("hello", 3),
|
||||
std::string{"hello"});
|
||||
}
|
||||
|
||||
Void::Testing::Test pad_left_pads_to_width()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::String::pad_left("hi", 5),
|
||||
std::string{" hi"});
|
||||
}
|
||||
|
||||
// ── misc ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test repeat_produces_correct_output()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::String::repeat("ab", 3),
|
||||
std::string{"ababab"});
|
||||
}
|
||||
|
||||
Void::Testing::Test repeat_zero_returns_empty()
|
||||
{
|
||||
Void::Testing::expect(Void::String::repeat("ab", 0).empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test count_occurrences_finds_all()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::String::count_occurrences("abab", "ab"),
|
||||
std::size_t{2});
|
||||
}
|
||||
|
||||
Void::Testing::Test count_occurrences_no_match_returns_zero()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::String::count_occurrences("abc", "x"),
|
||||
std::size_t{0});
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
#include <Void/Time/Format.hpp>
|
||||
#include <Void/Time/Stopwatch.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
// ── Stopwatch ─────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test stopwatch_elapsed_is_non_negative()
|
||||
{
|
||||
Void::Time::Stopwatch sw;
|
||||
Void::Testing::expect(sw.elapsed().count() >= 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test stopwatch_elapsed_as_milliseconds()
|
||||
{
|
||||
Void::Time::Stopwatch sw;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
const auto ms = sw.elapsed_as<std::chrono::milliseconds>().count();
|
||||
Void::Testing::expect(ms >= 4);
|
||||
Void::Testing::expect(ms < 500);
|
||||
}
|
||||
|
||||
Void::Testing::Test stopwatch_reset_restarts_from_zero()
|
||||
{
|
||||
Void::Time::Stopwatch sw;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
sw.reset();
|
||||
const auto ns = sw.elapsed().count();
|
||||
Void::Testing::expect(ns < 5'000'000); // < 5ms since reset
|
||||
}
|
||||
|
||||
Void::Testing::Test stopwatch_split_returns_elapsed_and_resets()
|
||||
{
|
||||
Void::Time::Stopwatch sw;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
const auto d = sw.split();
|
||||
const auto after = sw.elapsed().count();
|
||||
Void::Testing::expect(d.count() >= 0);
|
||||
Void::Testing::expect(after < d.count()); // after reset < before reset
|
||||
}
|
||||
|
||||
// ── format_duration ───────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test format_duration_nanoseconds()
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
Void::Testing::expect_eq(Void::Time::format_duration(500ns),
|
||||
std::string{"500ns"});
|
||||
}
|
||||
|
||||
Void::Testing::Test format_duration_microseconds()
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
Void::Testing::expect(
|
||||
Void::Time::format_duration(4500ns).find("\xc2\xb5s") !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test format_duration_milliseconds()
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
Void::Testing::expect(
|
||||
Void::Time::format_duration(2'300'000ns).find("ms") !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test format_duration_seconds()
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
Void::Testing::expect(
|
||||
Void::Time::format_duration(1'500'000'000ns).find('s') !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test format_duration_minutes()
|
||||
{
|
||||
Void::Testing::expect(
|
||||
Void::Time::format_duration(std::chrono::seconds{90}).find('m') !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test format_duration_hours()
|
||||
{
|
||||
Void::Testing::expect(
|
||||
Void::Time::format_duration(std::chrono::seconds{3700}).find('h') !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test format_duration_works_with_chrono_milliseconds()
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
const auto s = Void::Time::format_duration(15ms);
|
||||
Void::Testing::expect(s.find("ms") != std::string::npos);
|
||||
}
|
||||
|
||||
// ── utc timestamps ────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test utc_now_iso8601_has_correct_format()
|
||||
{
|
||||
const auto s = Void::Time::utc_now_iso8601();
|
||||
// "2026-05-14T10:30:00Z"
|
||||
Void::Testing::expect_eq(s.size(), std::size_t{20});
|
||||
Void::Testing::expect_eq(s[4], '-');
|
||||
Void::Testing::expect_eq(s[7], '-');
|
||||
Void::Testing::expect_eq(s[10], 'T');
|
||||
Void::Testing::expect_eq(s.back(), 'Z');
|
||||
}
|
||||
|
||||
Void::Testing::Test utc_now_iso8601_ms_has_correct_format()
|
||||
{
|
||||
const auto s = Void::Time::utc_now_iso8601_ms();
|
||||
// "2026-05-14T10:30:00.123Z"
|
||||
Void::Testing::expect_eq(s.size(), std::size_t{24});
|
||||
Void::Testing::expect_eq(s[10], 'T');
|
||||
Void::Testing::expect_eq(s[19], '.');
|
||||
Void::Testing::expect_eq(s.back(), 'Z');
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
#include <Void/Uuid/Uuid.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
// ── v4 ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test v4_not_nil()
|
||||
{
|
||||
Void::Testing::expect(!Void::Uuid::v4().is_nil());
|
||||
}
|
||||
|
||||
Void::Testing::Test v4_version_nibble()
|
||||
{
|
||||
const auto u = Void::Uuid::v4();
|
||||
Void::Testing::expect_eq(u.bytes[6] >> 4, std::uint8_t{4});
|
||||
}
|
||||
|
||||
Void::Testing::Test v4_variant_bits()
|
||||
{
|
||||
const auto u = Void::Uuid::v4();
|
||||
// top two bits of byte 8 must be 10
|
||||
Void::Testing::expect_eq(u.bytes[8] >> 6, std::uint8_t{2});
|
||||
}
|
||||
|
||||
Void::Testing::Test v4_unique()
|
||||
{
|
||||
Void::Testing::expect(Void::Uuid::v4() != Void::Uuid::v4());
|
||||
}
|
||||
|
||||
Void::Testing::Test v4_string_length()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Uuid::v4().to_string().size(),
|
||||
std::size_t{36});
|
||||
}
|
||||
|
||||
Void::Testing::Test v4_string_has_dashes()
|
||||
{
|
||||
const auto s = Void::Uuid::v4().to_string();
|
||||
Void::Testing::expect_eq(s[8], '-');
|
||||
Void::Testing::expect_eq(s[13], '-');
|
||||
Void::Testing::expect_eq(s[18], '-');
|
||||
Void::Testing::expect_eq(s[23], '-');
|
||||
}
|
||||
|
||||
// ── v5_lite ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test v5_lite_deterministic()
|
||||
{
|
||||
const auto a = Void::Uuid::v5_lite(Void::Uuid::Namespace::Dns, "example.com");
|
||||
const auto b = Void::Uuid::v5_lite(Void::Uuid::Namespace::Dns, "example.com");
|
||||
Void::Testing::expect_eq(a, b);
|
||||
}
|
||||
|
||||
Void::Testing::Test v5_lite_different_names()
|
||||
{
|
||||
const auto a = Void::Uuid::v5_lite(Void::Uuid::Namespace::Dns, "foo.com");
|
||||
const auto b = Void::Uuid::v5_lite(Void::Uuid::Namespace::Dns, "bar.com");
|
||||
Void::Testing::expect(a != b);
|
||||
}
|
||||
|
||||
Void::Testing::Test v5_lite_different_namespaces()
|
||||
{
|
||||
const auto a = Void::Uuid::v5_lite(Void::Uuid::Namespace::Dns, "example");
|
||||
const auto b = Void::Uuid::v5_lite(Void::Uuid::Namespace::Url, "example");
|
||||
Void::Testing::expect(a != b);
|
||||
}
|
||||
|
||||
Void::Testing::Test v5_lite_version_nibble()
|
||||
{
|
||||
const auto u = Void::Uuid::v5_lite(Void::Uuid::Namespace::Dns, "test");
|
||||
Void::Testing::expect_eq(u.bytes[6] >> 4, std::uint8_t{5});
|
||||
}
|
||||
|
||||
// ── parse ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test parse_round_trip()
|
||||
{
|
||||
const auto u = Void::Uuid::v4();
|
||||
const auto s = u.to_string();
|
||||
const auto parsed = Void::Uuid::parse(s);
|
||||
Void::Testing::expect(parsed.has_value());
|
||||
Void::Testing::expect_eq(*parsed, u);
|
||||
}
|
||||
|
||||
Void::Testing::Test parse_uppercase()
|
||||
{
|
||||
const auto opt = Void::Uuid::parse(
|
||||
"550E8400-E29B-41D4-A716-446655440000");
|
||||
Void::Testing::expect(opt.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test parse_invalid_returns_nullopt()
|
||||
{
|
||||
Void::Testing::expect(!Void::Uuid::parse("not-a-uuid").has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test parse_32_char_hex()
|
||||
{
|
||||
const auto opt = Void::Uuid::parse("550e8400e29b41d4a716446655440000");
|
||||
Void::Testing::expect(opt.has_value());
|
||||
}
|
||||
|
||||
// ── nil ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test nil_uuid_is_nil()
|
||||
{
|
||||
Void::Testing::expect(Void::Uuid::Uuid::nil().is_nil());
|
||||
}
|
||||
|
||||
Void::Testing::Test v4_not_nil_check()
|
||||
{
|
||||
Void::Testing::expect(!Void::Uuid::v4().is_nil());
|
||||
}
|
||||
Reference in new issue
Block a user