Update
CI / GCC 16 / C++26 / werror (push) Failing after 3m9s
CI / GCC 16 / C++26 / sanitizers (push) Failing after 10m15s
CI / GCC 16 / C++26 / default (push) Failing after 13m1s

Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-20 01:18:53 +03:00
1 parent 8583a479dd
commit 3851aeb703
42 files changed
+6948 -759

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
namespace Void::Archive
{
struct ExtractionOptions {
std::size_t maxEntries{10'000};
std::uint64_t maxFileBytes{512ULL * 1024 * 1024};
std::uint64_t maxTotalBytes{2ULL * 1024 * 1024 * 1024};
bool overwriteExisting{false};
};
struct ExtractionResult {
std::size_t entries{0};
std::uint64_t bytes{0};
};
/// Extract a tar/tar.zst archive without invoking an external process.
/// Only regular files and directories are accepted. Absolute/traversal
/// paths, links, special files, duplicates and configured size/count
/// overages fail the whole operation.
[[nodiscard]] Void::Result::Result<ExtractionResult>
extract(const std::filesystem::path& archivePath,
const std::filesystem::path& destination,
const ExtractionOptions& options = {});
} // namespace Void::Archive
+156
View File
@@ -0,0 +1,156 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <algorithm>
#include <array>
#include <bit>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <format>
#include <span>
#include <string>
namespace Void::Binary
{
/// Bounds-checked, non-owning reader for binary formats.
class Reader
{
public:
explicit constexpr Reader(std::span<const std::byte> bytes) noexcept
: m_bytes(bytes)
{
}
[[nodiscard]] constexpr std::size_t position() const noexcept
{
return m_position;
}
[[nodiscard]] constexpr std::size_t size() const noexcept
{
return m_bytes.size();
}
[[nodiscard]] constexpr std::size_t remaining() const noexcept
{
return m_bytes.size() - m_position;
}
[[nodiscard]] constexpr bool empty() const noexcept
{
return remaining() == 0;
}
[[nodiscard]] Void::Result::Result<void> seek(std::size_t position)
{
if (position > m_bytes.size()) {
return Void::Result::fail(std::format(
"Binary::Reader::seek: offset {} exceeds size {}",
position, m_bytes.size()));
}
m_position = position;
return {};
}
[[nodiscard]] Void::Result::Result<void> skip(std::size_t count)
{
if (count > remaining()) {
return truncated("skip", count);
}
m_position += count;
return {};
}
[[nodiscard]] Void::Result::Result<std::span<const std::byte>>
readBytes(std::size_t count)
{
if (count > remaining()) {
return std::unexpected{truncatedError("readBytes", count)};
}
const auto result = m_bytes.subspan(m_position, count);
m_position += count;
return result;
}
[[nodiscard]] Void::Result::Result<std::span<const std::byte>>
peekBytes(std::size_t count) const
{
if (count > remaining()) {
return std::unexpected{truncatedError("peekBytes", count)};
}
return m_bytes.subspan(m_position, count);
}
template <std::integral T>
requires(!std::same_as<T, bool>)
[[nodiscard]] Void::Result::Result<T>
read(std::endian byteOrder = std::endian::native)
{
auto bytes = readBytes(sizeof(T));
if (!bytes) {
return std::unexpected{bytes.error()};
}
std::array<std::byte, sizeof(T)> storage{};
std::ranges::copy(*bytes, storage.begin());
T value = std::bit_cast<T>(storage);
if constexpr (std::endian::native != std::endian::little &&
std::endian::native != std::endian::big) {
return Void::Result::fail(
"Binary::Reader::read: mixed-endian targets are "
"unsupported");
} else if (byteOrder != std::endian::native) {
value = std::byteswap(value);
}
return value;
}
[[nodiscard]] Void::Result::Result<std::string>
readString(std::size_t count)
{
auto bytes = readBytes(count);
if (!bytes) {
return std::unexpected{bytes.error()};
}
return std::string{reinterpret_cast<const char*>(bytes->data()),
bytes->size()};
}
[[nodiscard]] Void::Result::Result<Reader>
subreader(std::size_t count)
{
auto bytes = readBytes(count);
if (!bytes) {
return std::unexpected{bytes.error()};
}
return Reader{*bytes};
}
private:
std::span<const std::byte> m_bytes;
std::size_t m_position{0};
[[nodiscard]] Void::Result::Error
truncatedError(std::string_view operation,
std::size_t requested) const
{
return Void::Result::Error{
std::format("Binary::Reader::{}: requested {} bytes at "
"offset {}, only {} "
"remain",
operation, requested, m_position, remaining())};
}
[[nodiscard]] Void::Result::Result<void>
truncated(std::string_view operation,
std::size_t requested) const
{
return std::unexpected{truncatedError(operation, requested)};
}
};
} // namespace Void::Binary
+78
View File
@@ -0,0 +1,78 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <filesystem>
#include <memory>
#include <span>
#include <string_view>
#include <vector>
namespace Void::Crypto
{
enum class HashAlgorithm { Sha1, Sha256, Sha512 };
using Digest = std::vector<std::byte>;
class Hasher
{
public:
[[nodiscard]] static Void::Result::Result<Hasher>
create(HashAlgorithm algorithm);
~Hasher();
Hasher(Hasher&&) noexcept;
Hasher& operator=(Hasher&&) noexcept;
Hasher(const Hasher&) = delete;
Hasher& operator=(const Hasher&) = delete;
[[nodiscard]] Void::Result::Result<void>
update(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<void>
update(std::string_view data);
/// Finalize this hash. Calling finalize or update again is an
/// error.
[[nodiscard]] Void::Result::Result<Digest> finalize();
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit Hasher(std::unique_ptr<Impl> impl) noexcept;
};
[[nodiscard]] Void::Result::Result<Digest>
hash(HashAlgorithm algorithm, std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> hash(HashAlgorithm algorithm,
std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha1(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> sha1(std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
sha256(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> sha256(std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
sha512(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> sha512(std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
sha1File(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha256File(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha512File(const std::filesystem::path& path);
inline constexpr std::size_t Ed25519PublicKeySize = 32;
inline constexpr std::size_t Ed25519SignatureSize = 64;
/// Verify an Ed25519 detached signature over the exact message bytes.
/// Invalid key/signature sizes are errors; a well-formed but invalid
/// signature returns false.
[[nodiscard]] Void::Result::Result<bool>
verifyEd25519(std::span<const std::byte> message,
std::span<const std::byte> signature,
std::span<const std::byte> publicKey);
} // namespace Void::Crypto
+80 -65
View File
@@ -9,82 +9,97 @@
namespace Void::Plugin
{
enum class LoadError {
FileNotFound,
DlopenFailed,
SymbolMissing,
AbiMismatch,
CreateFailed,
NotSupported, // platform does not support dlopen
StateRejected, // new instance refused the serialized state
ActivationFailed, // on_load threw or readiness validation failed
UnknownPlugin, // PluginManager: no plugin registered under that name
};
enum class LoadError {
FileNotFound,
DlopenFailed,
SymbolMissing,
AbiMismatch,
CreateFailed,
NotSupported, // platform does not support dlopen
StateRejected, // new instance refused the serialized state
ActivationFailed, // on_load threw or readiness validation failed
UnknownPlugin, // PluginManager: no plugin registered under that name
NameMismatch, // replacement reports a different registry name
};
[[nodiscard]] std::string_view to_string(LoadError e) noexcept;
[[nodiscard]] std::string_view to_string(LoadError e) noexcept;
// ── PluginLoader ──────────────────────────────────────────────────────────────
// Owns one plugin instance loaded from a shared library.
//
// Hot-reload protocol:
// 1. The new .so (at the same canonical path) is copied to a temp file so
// dlopen gets a fresh inode even if the path was already cached.
// 2. New instance is created and optional transfer_state() called (both
// old and new instances are alive simultaneously at this point).
// 3. Old instance is destroyed and old handle is closed.
//
// Thread safety: not thread-safe. Protect with external locking if needed.
// ── PluginLoader
// ────────────────────────────────────────────────────────────── Owns one
// plugin instance loaded from a shared library.
//
// Hot-reload protocol:
// 1. The new .so (at the same canonical path) is copied to a temp file so
// dlopen gets a fresh inode even if the path was already cached.
// 2. New instance is created and optional transfer_state() called (both
// old and new instances are alive simultaneously at this point).
// 3. Old instance is destroyed and old handle is closed.
//
// Thread safety: not thread-safe. Protect with external locking if needed.
class PluginLoader {
public:
[[nodiscard]] static std::expected<PluginLoader, LoadError>
load(std::filesystem::path path);
class PluginLoader
{
public:
~PluginLoader();
PluginLoader(PluginLoader&&) noexcept;
PluginLoader& operator=(PluginLoader&&) noexcept;
PluginLoader(const PluginLoader&) = delete;
PluginLoader& operator=(const PluginLoader&) = delete;
[[nodiscard]] static std::expected<PluginLoader, LoadError>
load(std::filesystem::path path);
[[nodiscard]] IPlugin* plugin() noexcept { return plugin_; }
[[nodiscard]] const IPlugin* plugin() const noexcept { return plugin_; }
[[nodiscard]] const PluginInfo& info() const noexcept { return info_; }
[[nodiscard]] bool loaded() const noexcept { return handle_ != nullptr; }
~PluginLoader();
PluginLoader(PluginLoader&&) noexcept;
PluginLoader& operator=(PluginLoader&&) noexcept;
PluginLoader(const PluginLoader&) = delete;
PluginLoader& operator=(const PluginLoader&) = delete;
IPlugin* operator->() noexcept { return plugin_; }
[[nodiscard]] IPlugin* plugin() noexcept { return plugin_; }
[[nodiscard]] const IPlugin* plugin() const noexcept
{
return plugin_;
}
[[nodiscard]] const PluginInfo& info() const noexcept
{
return info_;
}
[[nodiscard]] bool loaded() const noexcept
{
return handle_ != nullptr;
}
// Hot-reload: copies current .so to a temp file (fresh inode), loads
// it, transfers state, then destroys old instance and swaps handles.
// State transfer prefers the v2 serialize/deserialize protocol (old
// serializes, new deserializes with the old schema version); falls
// back to void_plugin_transfer_state; else no transfer.
[[nodiscard]] std::expected<void, LoadError> reload();
IPlugin* operator->() noexcept { return plugin_; }
private:
PluginLoader() = default;
// Hot-reload: copies current .so to a temp file (fresh inode),
// loads it, transfers state, then destroys old instance and swaps
// handles. State transfer prefers the v2 serialize/deserialize
// protocol (old serializes, new deserializes with the old schema
// version); falls back to void_plugin_transfer_state; else no
// transfer.
[[nodiscard]] std::expected<void, LoadError> reload();
// Moves plugin state old -> new during a reload (v2 serialize/
// deserialize, else transfer_state). Returns false only if the new
// instance rejects the state.
friend bool transfer_plugin_state(const PluginLoader& from,
PluginLoader& to);
private:
void* handle_ {};
IPlugin* plugin_ {};
destroy_fn destroy_ {};
transfer_fn transfer_ {};
ready_fn ready_ {};
state_version_fn state_version_{};
serialize_fn serialize_ {};
free_string_fn free_string_ {};
deserialize_fn deserialize_ {};
PluginInfo info_ {};
std::filesystem::path path_;
PluginLoader() = default;
[[nodiscard]] std::expected<void, LoadError>
load_from(const std::filesystem::path& path);
// Moves plugin state old -> new during a reload (v2 serialize/
// deserialize, else transfer_state). Returns false only if the new
// instance rejects the state.
friend bool transfer_plugin_state(const PluginLoader& from,
PluginLoader& to);
void destroy_current() noexcept;
};
void* handle_{};
IPlugin* plugin_{};
destroy_fn destroy_{};
transfer_fn transfer_{};
ready_fn ready_{};
state_version_fn state_version_{};
serialize_fn serialize_{};
free_string_fn free_string_{};
deserialize_fn deserialize_{};
PluginInfo info_{};
std::filesystem::path path_;
[[nodiscard]] std::expected<void, LoadError>
load_from(const std::filesystem::path& path);
void destroy_current() noexcept;
};
} // namespace Void::Plugin
+16 -3
View File
@@ -87,7 +87,8 @@ namespace Void::Plugin
std::function<std::string(std::string_view plugin_name)>
config_provider;
// Host-specific contract checked after plugin activation and before
// publication. A failed validation aborts load/reload transactionally.
// publication. A failed validation aborts load/reload
// transactionally.
std::function<bool(IPlugin&, const PluginInfo&)> instance_validator;
};
@@ -140,6 +141,16 @@ namespace Void::Plugin
/// it alive until they drop.
std::expected<void, LoadError> reload(std::string_view name);
/// Replace `name` from an immutable new library path. The candidate
/// must report the same plugin name. It is configured, receives the
/// old state, activates and passes host validation before one
/// atomic publication. On any error the current instance, source
/// path and watcher remain unchanged. Pinned old handles remain
/// valid.
std::expected<void, LoadError>
replace(std::string_view name,
const std::filesystem::path& newPath);
/// Begin watching the plugin's file; reload automatically when
/// it changes (debounced). Reload failures are logged and the
/// old instance is kept.
@@ -191,11 +202,13 @@ namespace Void::Plugin
struct Entry {
std::filesystem::path path;
std::atomic<std::shared_ptr<detail::Instance>> current;
bool watched{false};
};
Entry* find(std::string_view name) const;
std::expected<void, LoadError> reload_locked(Entry& entry,
std::string_view name);
std::expected<void, LoadError>
reload_locked(Entry& entry, std::string_view name,
const std::filesystem::path& sourcePath);
std::vector<std::function<void(std::string_view)>>
reload_callbacks_locked() const;
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <memory>
#include <optional>
#include <vector>
namespace Void::Process
{
/// Converts process signals into synchronous, deterministic waits.
/// Construct this before worker threads so the selected signals inherit a
/// blocked mask. A watcher must be destroyed on the thread that created it.
class SignalWatcher
{
public:
/// An empty signal list watches SIGINT and SIGTERM.
[[nodiscard]] static Void::Result::Result<SignalWatcher>
create(std::vector<int> signals = {});
~SignalWatcher();
SignalWatcher(SignalWatcher&&) noexcept;
SignalWatcher& operator=(SignalWatcher&&) noexcept;
SignalWatcher(const SignalWatcher&) = delete;
SignalWatcher& operator=(const SignalWatcher&) = delete;
/// Wait for a configured signal. A zero timeout performs a poll;
/// milliseconds::max() waits indefinitely.
[[nodiscard]] Void::Result::Result<std::optional<int>>
wait(std::chrono::milliseconds timeout =
std::chrono::milliseconds::max());
[[nodiscard]] Void::Result::Result<std::optional<int>> poll();
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit SignalWatcher(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::Process
+201 -106
View File
@@ -6,121 +6,216 @@
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Encoding::Base64
{
namespace Detail
{
constexpr std::string_view alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
namespace Detail
{
constexpr std::string_view alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
constexpr std::string_view alphabet_url =
"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
[[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 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 an unsigned-byte view without forcing callers to reinterpret
/// their binary buffers as text.
[[nodiscard]] inline std::string encode(std::span<const std::uint8_t> data)
{
return encode(std::as_bytes(data));
}
/// 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;
}
/// 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()}));
}
/// 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;
}
/// 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 canonical URL-safe Base64 without padding. Returns nullopt for
/// padding, invalid characters, impossible lengths, or non-zero trailing
/// bits.
[[nodiscard]] inline std::optional<std::string>
decode_url(std::string_view s)
{
static constexpr auto table =
Detail::make_decode_table(Detail::alphabet_url);
if (s.size() % 4 == 1 || s.find('=') != std::string_view::npos) {
return std::nullopt;
}
std::string out;
out.reserve((s.size() * 3) / 4);
std::uint32_t buffer = 0;
int bits = 0;
for (const char encoded : s) {
const auto character = static_cast<unsigned char>(encoded);
const std::int8_t value = table[character];
if (value < 0) {
return std::nullopt;
}
buffer = (buffer << 6) | static_cast<std::uint32_t>(value);
bits += 6;
if (bits >= 8) {
bits -= 8;
out += static_cast<char>((buffer >> bits) & 0xFFU);
buffer &= bits == 0 ? 0U : ((1U << bits) - 1U);
}
}
if (bits != 0 && buffer != 0) {
return std::nullopt;
}
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);
std::uint32_t buffer = 0;
int bits = 0;
std::size_t symbols = 0;
std::size_t padding = 0;
bool saw_padding = false;
for (const char encoded : s) {
const auto character = static_cast<unsigned char>(encoded);
if (character == ' ' || character == '\n' || character == '\r' ||
character == '\t') {
continue;
}
if (character == '=') {
saw_padding = true;
if (++padding > 2) {
return std::nullopt;
}
continue;
}
if (saw_padding) {
return std::nullopt;
}
const std::int8_t value = table[character];
if (value < 0) {
return std::nullopt;
}
buffer = (buffer << 6) | static_cast<std::uint32_t>(value);
++symbols;
bits += 6;
if (bits >= 8) {
bits -= 8;
out += static_cast<char>((buffer >> bits) & 0xFFU);
buffer &= bits == 0 ? 0U : ((1U << bits) - 1U);
}
}
const std::size_t remainder = symbols % 4;
if (remainder == 1) {
return std::nullopt;
}
const std::size_t expected_padding = remainder == 0 ? 0 : 4 - remainder;
if (padding != 0 && padding != expected_padding) {
return std::nullopt;
}
if (bits != 0 && buffer != 0) {
return std::nullopt;
}
return out;
}
/// Decode standard Base64 into an explicitly binary buffer. This is the
/// preferred overload for protocol, cryptographic, and file-format data.
[[nodiscard]] inline std::optional<std::vector<std::byte>>
decode_bytes(std::string_view s)
{
const auto decoded = decode(s);
if (!decoded) {
return std::nullopt;
}
const auto bytes =
std::as_bytes(std::span{decoded->data(), decoded->size()});
return std::vector<std::byte>{bytes.begin(), bytes.end()};
}
} // namespace Void::Encoding::Base64
+86 -54
View File
@@ -5,67 +5,99 @@
#include <span>
#include <string>
#include <string_view>
#include <vector>
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;
}
/// 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()}));
}
/// Encode an unsigned-byte view without treating binary data as text.
[[nodiscard]] inline std::string encode(std::span<const std::uint8_t> data)
{
return encode(std::as_bytes(data));
}
/// 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;
}
[[nodiscard]] inline std::string encode(std::string_view s)
{
return encode(std::as_bytes(std::span{s.data(), s.size()}));
}
/// 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;
}
/// 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;
}
[[nodiscard]] inline std::string encode_upper(std::string_view s)
{
return encode_upper(std::as_bytes(std::span{s.data(), s.size()}));
}
/// Decode hexadecimal text into an explicitly binary buffer.
[[nodiscard]] inline std::optional<std::vector<std::byte>>
decode_bytes(std::string_view s)
{
const auto decoded = decode(s);
if (!decoded) {
return std::nullopt;
}
const auto bytes =
std::as_bytes(std::span{decoded->data(), decoded->size()});
return std::vector<std::byte>{bytes.begin(), bytes.end()};
}
/// 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
+571 -101
View File
@@ -1,132 +1,602 @@
#pragma once
#include <charconv>
#include <compare>
#include <cstdlib>
#include <format>
#include <limits>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Semver
{
// ── Version ───────────────────────────────────────────────────────────────────
namespace Detail
{
[[nodiscard]] constexpr bool is_digit(char value) noexcept
{
return value >= '0' && value <= '9';
}
struct Version
{
unsigned major{0};
unsigned minor{0};
unsigned patch{0};
std::string pre_release; // e.g. "alpha.1"
std::string build; // e.g. "20240101"
[[nodiscard]] constexpr bool
is_identifier_character(char value) noexcept
{
return is_digit(value) || (value >= 'A' && value <= 'Z') ||
(value >= 'a' && value <= 'z') || value == '-';
}
[[nodiscard]] std::string to_string() const
{
std::string s = std::format("{}.{}.{}", major, minor, patch);
if (!pre_release.empty()) { s += '-'; s += pre_release; }
if (!build.empty()) { s += '+'; s += build; }
return s;
}
[[nodiscard]] inline bool
is_numeric(std::string_view identifier) noexcept
{
if (identifier.empty()) {
return false;
}
for (const char value : identifier) {
if (!is_digit(value)) {
return false;
}
}
return true;
}
// Precedence comparison per semver spec (build metadata ignored).
[[nodiscard]] std::strong_ordering
operator<=>(const Version& o) const noexcept
{
if (auto c = major <=> o.major; c != 0) return c;
if (auto c = minor <=> o.minor; c != 0) return c;
if (auto c = patch <=> o.patch; c != 0) return c;
// No pre-release > has pre-release
const bool l_pre = !pre_release.empty();
const bool r_pre = !o.pre_release.empty();
if (!l_pre && r_pre) return std::strong_ordering::greater;
if (l_pre && !r_pre) return std::strong_ordering::less;
// Both have pre-release — lexicographic (simplified)
if (auto c = pre_release <=> o.pre_release; c != 0) {
return c < 0 ? std::strong_ordering::less
: std::strong_ordering::greater;
}
return std::strong_ordering::equal;
}
[[nodiscard]] inline std::strong_ordering
compare_identifier(std::string_view left,
std::string_view right) noexcept
{
const bool left_numeric = is_numeric(left);
const bool right_numeric = is_numeric(right);
if (left_numeric && right_numeric) {
if (left.size() != right.size()) {
return left.size() < right.size()
? std::strong_ordering::less
: std::strong_ordering::greater;
}
return left <=> right;
}
if (left_numeric != right_numeric) {
return left_numeric ? std::strong_ordering::less
: std::strong_ordering::greater;
}
return left <=> right;
}
[[nodiscard]] bool operator==(const Version& o) const noexcept
{
return major == o.major && minor == o.minor && patch == o.patch &&
pre_release == o.pre_release;
}
[[nodiscard]] inline std::strong_ordering
compare_prerelease(std::string_view left,
std::string_view right) noexcept
{
std::size_t left_begin = 0;
std::size_t right_begin = 0;
for (;;) {
const auto left_end = left.find('.', left_begin);
const auto right_end = right.find('.', right_begin);
const auto left_id =
left.substr(left_begin, left_end == std::string_view::npos
? std::string_view::npos
: left_end - left_begin);
const auto right_id = right.substr(
right_begin, right_end == std::string_view::npos
? std::string_view::npos
: right_end - right_begin);
if (const auto comparison =
compare_identifier(left_id, right_id);
comparison != 0) {
return comparison;
}
const bool left_done = left_end == std::string_view::npos;
const bool right_done = right_end == std::string_view::npos;
if (left_done || right_done) {
if (left_done == right_done) {
return std::strong_ordering::equal;
}
return left_done ? std::strong_ordering::less
: std::strong_ordering::greater;
}
left_begin = left_end + 1;
right_begin = right_end + 1;
}
}
// Is this version compatible with `required`? (same major, >= minor.patch)
[[nodiscard]] bool compatible_with(const Version& required) const noexcept
{
if (major != required.major) return false;
return (*this <=> required) >= 0;
}
[[nodiscard]] inline bool
valid_identifiers(std::string_view value,
bool reject_numeric_leading_zero) noexcept
{
if (value.empty()) {
return false;
}
std::size_t begin = 0;
for (;;) {
const auto end = value.find('.', begin);
const auto identifier =
value.substr(begin, end == std::string_view::npos
? std::string_view::npos
: end - begin);
if (identifier.empty()) {
return false;
}
for (const char character : identifier) {
if (!is_identifier_character(character)) {
return false;
}
}
if (reject_numeric_leading_zero && identifier.size() > 1 &&
identifier.front() == '0' && is_numeric(identifier)) {
return false;
}
if (end == std::string_view::npos) {
return true;
}
begin = end + 1;
}
}
[[nodiscard]] bool is_stable() const noexcept
{
return major >= 1 && pre_release.empty();
}
[[nodiscard]] inline bool parse_component(std::string_view value,
unsigned& output) noexcept
{
if (value.empty() || (value.size() > 1 && value.front() == '0')) {
return false;
}
unsigned long long parsed = 0;
const auto [end, error] = std::from_chars(
value.data(), value.data() + value.size(), parsed);
if (error != std::errc{} || end != value.data() + value.size() ||
parsed > std::numeric_limits<unsigned>::max()) {
return false;
}
output = static_cast<unsigned>(parsed);
return true;
}
[[nodiscard]] Version bumped_major() const noexcept
{
return {major + 1, 0, 0};
}
[[nodiscard]] constexpr std::string_view
trim(std::string_view value) noexcept
{
while (!value.empty() &&
(value.front() == ' ' || value.front() == '\t' ||
value.front() == '\r' || value.front() == '\n')) {
value.remove_prefix(1);
}
while (!value.empty() &&
(value.back() == ' ' || value.back() == '\t' ||
value.back() == '\r' || value.back() == '\n')) {
value.remove_suffix(1);
}
return value;
}
} // namespace Detail
[[nodiscard]] Version bumped_minor() const noexcept
{
return {major, minor + 1, 0};
}
struct Version {
unsigned major{0};
unsigned minor{0};
unsigned patch{0};
std::string pre_release;
std::string build;
[[nodiscard]] Version bumped_patch() const noexcept
{
return {major, minor, patch + 1};
}
};
[[nodiscard]] std::string to_string() const
{
std::string value =
std::format("{}.{}.{}", major, minor, patch);
if (!pre_release.empty()) {
value += '-';
value += pre_release;
}
if (!build.empty()) {
value += '+';
value += build;
}
return value;
}
// ── Parsing ───────────────────────────────────────────────────────────────────
[[nodiscard]] std::strong_ordering
operator<=>(const Version& other) const noexcept
{
if (const auto comparison = major <=> other.major;
comparison != 0) {
return comparison;
}
if (const auto comparison = minor <=> other.minor;
comparison != 0) {
return comparison;
}
if (const auto comparison = patch <=> other.patch;
comparison != 0) {
return comparison;
}
if (pre_release.empty() != other.pre_release.empty()) {
return pre_release.empty() ? std::strong_ordering::greater
: std::strong_ordering::less;
}
if (pre_release.empty()) {
return std::strong_ordering::equal;
}
return Detail::compare_prerelease(pre_release,
other.pre_release);
}
[[nodiscard]] inline std::optional<Version> parse(std::string_view s)
{
Version v;
[[nodiscard]] bool operator==(const Version& other) const noexcept
{
return major == other.major && minor == other.minor &&
patch == other.patch && pre_release == other.pre_release;
}
auto parse_uint = [](std::string_view sv, unsigned& out) -> bool {
if (sv.empty()) return false;
out = 0;
for (char c : sv) {
if (c < '0' || c > '9') return false;
out = out * 10 + static_cast<unsigned>(c - '0');
}
return true;
};
[[nodiscard]] bool
compatible_with(const Version& required) const noexcept
{
return major == required.major && (*this <=> required) >= 0;
}
// Optional leading 'v'
if (!s.empty() && (s[0] == 'v' || s[0] == 'V')) s.remove_prefix(1);
[[nodiscard]] bool is_stable() const noexcept
{
return major >= 1 && pre_release.empty();
}
// Split build metadata first
const auto plus = s.find('+');
if (plus != std::string_view::npos) {
v.build = std::string{s.substr(plus + 1)};
s = s.substr(0, plus);
}
[[nodiscard]] Version bumped_major() const noexcept
{
return Version{.major = major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}};
}
// Split pre-release
const auto dash = s.find('-');
if (dash != std::string_view::npos) {
v.pre_release = std::string{s.substr(dash + 1)};
s = s.substr(0, dash);
}
[[nodiscard]] Version bumped_minor() const noexcept
{
return Version{.major = major,
.minor = minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
}
// Major.minor.patch
const auto d1 = s.find('.');
if (d1 == std::string_view::npos) return std::nullopt;
if (!parse_uint(s.substr(0, d1), v.major)) return std::nullopt;
s = s.substr(d1 + 1);
[[nodiscard]] Version bumped_patch() const noexcept
{
return Version{.major = major,
.minor = minor,
.patch = patch + 1,
.pre_release = {},
.build = {}};
}
};
const auto d2 = s.find('.');
if (d2 == std::string_view::npos) return std::nullopt;
if (!parse_uint(s.substr(0, d2), v.minor)) return std::nullopt;
if (!parse_uint(s.substr(d2 + 1), v.patch)) return std::nullopt;
namespace Detail
{
[[nodiscard]] inline std::optional<Version>
parse_version(std::string_view value, bool allow_v_prefix)
{
if (allow_v_prefix && !value.empty() &&
(value.front() == 'v' || value.front() == 'V')) {
value.remove_prefix(1);
}
if (value.empty()) {
return std::nullopt;
}
return v;
}
Version version;
const auto plus = value.find('+');
if (plus != std::string_view::npos) {
if (value.find('+', plus + 1) != std::string_view::npos) {
return std::nullopt;
}
const auto metadata = value.substr(plus + 1);
if (!valid_identifiers(metadata, false)) {
return std::nullopt;
}
version.build = std::string{metadata};
value = value.substr(0, plus);
}
const auto dash = value.find('-');
if (dash != std::string_view::npos) {
const auto prerelease = value.substr(dash + 1);
if (!valid_identifiers(prerelease, true)) {
return std::nullopt;
}
version.pre_release = std::string{prerelease};
value = value.substr(0, dash);
}
const auto first_dot = value.find('.');
if (first_dot == std::string_view::npos) {
return std::nullopt;
}
const auto second_dot = value.find('.', first_dot + 1);
if (second_dot == std::string_view::npos ||
value.find('.', second_dot + 1) != std::string_view::npos) {
return std::nullopt;
}
if (!parse_component(value.substr(0, first_dot), version.major) ||
!parse_component(
value.substr(first_dot + 1, second_dot - first_dot - 1),
version.minor) ||
!parse_component(value.substr(second_dot + 1), version.patch)) {
return std::nullopt;
}
return version;
}
} // namespace Detail
/// Parse SemVer while retaining the historic optional `v` prefix.
[[nodiscard]] inline std::optional<Version> parse(std::string_view value)
{
return Detail::parse_version(value, true);
}
/// Parse exactly according to SemVer 2.0.0 (no leading `v`).
[[nodiscard]] inline std::optional<Version>
parse_strict(std::string_view value)
{
return Detail::parse_version(value, false);
}
class VersionRange
{
public:
[[nodiscard]] static std::optional<VersionRange>
parse(std::string_view expression)
{
VersionRange result;
expression = Detail::trim(expression);
if (expression.empty() || expression == "*") {
result.m_alternatives.emplace_back();
return result;
}
std::size_t clause_begin = 0;
for (;;) {
const auto separator = expression.find("||", clause_begin);
const auto clause_text = Detail::trim(expression.substr(
clause_begin, separator == std::string_view::npos
? std::string_view::npos
: separator - clause_begin));
if (clause_text.empty()) {
return std::nullopt;
}
Clause clause;
std::size_t token_begin = 0;
while (token_begin < clause_text.size()) {
while (token_begin < clause_text.size() &&
(clause_text[token_begin] == ' ' ||
clause_text[token_begin] == '\t')) {
++token_begin;
}
if (token_begin == clause_text.size()) {
break;
}
auto token_end =
clause_text.find_first_of(" \t", token_begin);
if (token_end == std::string_view::npos) {
token_end = clause_text.size();
}
if (!append_token(
clause,
clause_text.substr(token_begin,
token_end - token_begin))) {
return std::nullopt;
}
token_begin = token_end;
}
result.m_alternatives.push_back(std::move(clause));
if (separator == std::string_view::npos) {
break;
}
clause_begin = separator + 2;
}
return result;
}
[[nodiscard]] bool contains(const Version& version) const noexcept
{
for (const auto& clause : m_alternatives) {
bool matches = true;
for (const auto& comparator : clause) {
if (!comparator.matches(version)) {
matches = false;
break;
}
}
if (matches) {
return true;
}
}
return false;
}
private:
enum class Operation {
Equal,
Greater,
GreaterEqual,
Less,
LessEqual
};
struct Comparator {
Operation operation{Operation::Equal};
Version version;
[[nodiscard]] bool
matches(const Version& candidate) const noexcept
{
const auto comparison = candidate <=> version;
switch (operation) {
case Operation::Equal:
return comparison == 0;
case Operation::Greater:
return comparison > 0;
case Operation::GreaterEqual:
return comparison >= 0;
case Operation::Less:
return comparison < 0;
case Operation::LessEqual:
return comparison <= 0;
}
return false;
}
};
using Clause = std::vector<Comparator>;
std::vector<Clause> m_alternatives;
[[nodiscard]] static bool append_token(Clause& clause,
std::string_view token)
{
if (token == "*") {
return true;
}
if (token.starts_with('^') || token.starts_with('~')) {
const char kind = token.front();
token.remove_prefix(1);
const auto lower = parse_strict(token);
if (!lower) {
return false;
}
Version upper;
if (kind == '~') {
if (lower->minor ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower->major,
.minor = lower->minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
} else if (lower->major > 0) {
if (lower->major ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower->major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}};
} else if (lower->minor > 0) {
if (lower->minor ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = 0,
.minor = lower->minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
} else {
if (lower->patch ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = 0,
.minor = 0,
.patch = lower->patch + 1,
.pre_release = {},
.build = {}};
}
clause.push_back({Operation::GreaterEqual, *lower});
clause.push_back({Operation::Less, std::move(upper)});
return true;
}
if (token.find_first_of("xX*") != std::string_view::npos) {
return append_wildcard(clause, token);
}
Operation operation = Operation::Equal;
if (token.starts_with(">=")) {
operation = Operation::GreaterEqual;
token.remove_prefix(2);
} else if (token.starts_with("<=")) {
operation = Operation::LessEqual;
token.remove_prefix(2);
} else if (token.starts_with('>')) {
operation = Operation::Greater;
token.remove_prefix(1);
} else if (token.starts_with('<')) {
operation = Operation::Less;
token.remove_prefix(1);
} else if (token.starts_with('=')) {
token.remove_prefix(1);
}
const auto version = parse_strict(token);
if (!version) {
return false;
}
clause.push_back({operation, *version});
return true;
}
[[nodiscard]] static bool append_wildcard(Clause& clause,
std::string_view token)
{
const auto first_dot = token.find('.');
if (first_dot == std::string_view::npos) {
return token == "x" || token == "X" || token == "*";
}
const auto second_dot = token.find('.', first_dot + 1);
unsigned major = 0;
if (!Detail::parse_component(token.substr(0, first_dot),
major)) {
return false;
}
const auto minor_text = token.substr(
first_dot + 1, second_dot == std::string_view::npos
? std::string_view::npos
: second_dot - first_dot - 1);
if (minor_text == "x" || minor_text == "X" ||
minor_text == "*") {
if (second_dot != std::string_view::npos) {
return false;
}
if (major == std::numeric_limits<unsigned>::max()) {
return false;
}
clause.push_back(
{Operation::GreaterEqual, Version{.major = major,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}}});
clause.push_back(
{Operation::Less, Version{.major = major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}}});
return true;
}
unsigned minor = 0;
if (!Detail::parse_component(minor_text, minor) ||
second_dot == std::string_view::npos) {
return false;
}
const auto patch_text = token.substr(second_dot + 1);
if (patch_text != "x" && patch_text != "X" &&
patch_text != "*") {
return false;
}
if (minor == std::numeric_limits<unsigned>::max()) {
return false;
}
clause.push_back(
{Operation::GreaterEqual, Version{.major = major,
.minor = minor,
.patch = 0,
.pre_release = {},
.build = {}}});
clause.push_back({Operation::Less, Version{.major = major,
.minor = minor + 1,
.patch = 0,
.pre_release = {},
.build = {}}});
return true;
}
};
[[nodiscard]] inline std::optional<VersionRange>
parse_range(std::string_view expression)
{
return VersionRange::parse(expression);
}
} // namespace Void::Semver
+111
View File
@@ -0,0 +1,111 @@
#pragma once
#include <Void/Crypto/Crypto.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Text/Semver.hpp>
#include <array>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
namespace Void::Update
{
struct Compatibility {
std::unordered_map<std::string, Semver::VersionRange>
versionContracts;
std::unordered_map<std::string, std::string> exactContracts;
};
struct Release {
std::string component;
std::string artifactId;
std::string channel;
Semver::Version version;
std::string cohort;
std::string platform;
std::string architecture;
std::string url;
std::uint64_t size{0};
std::string sha256;
std::string packageType;
Compatibility compatibility;
std::string releaseManifestSha256;
};
struct Feed {
std::uint32_t schemaVersion{1};
std::string feedId;
std::uint64_t sequence{0};
std::chrono::system_clock::time_point generatedAt;
std::chrono::system_clock::time_point expiresAt;
std::vector<Release> releases;
};
struct FeedEnvelope {
std::uint32_t schemaVersion{1};
std::string keyId;
std::string payload;
Crypto::Digest signature;
};
using Ed25519PublicKey =
std::array<std::byte, Crypto::Ed25519PublicKeySize>;
using Keyring = std::unordered_map<std::string, Ed25519PublicKey>;
struct VerificationPolicy {
std::size_t maxEnvelopeBytes{5 * 1024 * 1024};
std::size_t maxPayloadBytes{4 * 1024 * 1024};
std::size_t maxReleases{10'000};
std::optional<std::uint64_t> minimumSequence;
std::chrono::system_clock::time_point now{
std::chrono::system_clock::now()};
bool requireUnexpired{true};
};
struct VerifiedFeed {
Feed feed;
std::string keyId;
std::string signedPayload;
};
struct Environment {
std::unordered_map<std::string, Semver::Version> versionContracts;
std::unordered_map<std::string, std::string> exactContracts;
std::string platform;
std::string architecture;
};
struct SelectionRequest {
std::string component;
std::string artifactId;
std::string channel;
Environment environment;
std::optional<Semver::Version> currentVersion;
std::optional<std::string> requiredCohort;
bool allowDowngrade{false};
bool includeCurrent{false};
};
/// Parse and validate an unsigned payload. Trust and activation policy is a
/// caller concern; all structural, size, expiry and replay checks still
/// run.
[[nodiscard]] Void::Result::Result<Feed>
parseFeedPayload(std::string_view payload,
const VerificationPolicy& policy = {});
/// Verify the envelope signature before parsing the signed payload.
[[nodiscard]] Void::Result::Result<VerifiedFeed>
verifyFeedEnvelope(std::string_view envelopeJson, const Keyring& keys,
const VerificationPolicy& policy = {});
/// Select the greatest compatible version, independent of feed order.
[[nodiscard]] std::optional<Release>
selectRelease(const Feed& feed, const SelectionRequest& request);
} // namespace Void::Update
+4
View File
@@ -0,0 +1,4 @@
#pragma once
#include <Void/Update/Feed.hpp>
#include <Void/Update/VersionStore.hpp>
+102
View File
@@ -0,0 +1,102 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Text/Semver.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <optional>
#include <vector>
namespace Void::Update
{
struct PendingActivation {
std::optional<Semver::Version> previousVersion;
Semver::Version candidateVersion;
/// Health-log generation observed before activation. A later
/// healthy event for the candidate is the durable commit marker
/// used to reconcile an activation journal left behind by a
/// post-commit cleanup failure.
std::uint64_t healthGeneration{};
};
/// Immutable version directory store with a relative `current` symlink and
/// a durable activation journal. An uncommitted activation is rolled back
/// by reconcile(), making candidate health checks an explicit commit
/// boundary.
///
/// The crash-durability and cross-process locking guarantees are provided
/// by the POSIX implementation. The current Windows fallback is functional
/// but does not yet provide equivalent crash durability or process locking.
class VersionStore
{
public:
explicit VersionStore(std::filesystem::path root);
[[nodiscard]] Void::Result::Result<void> initialize();
[[nodiscard]] Void::Result::Result<std::filesystem::path>
prepare(const Semver::Version& version);
[[nodiscard]] Void::Result::Result<void>
publish(const Semver::Version& version,
const std::filesystem::path& stagingDirectory);
[[nodiscard]] Void::Result::Result<void>
activate(const Semver::Version& version);
/// Idempotently accept the candidate. A durable healthy-history
/// event is the commit point; activation-journal cleanup after that
/// point cannot be reported as a reversible failure.
[[nodiscard]] Void::Result::Result<void> commit();
/// Idempotently restore the previous version. The journal is
/// retained until restoration succeeds. A candidate whose commit
/// marker is newer than the journal baseline is finalized instead
/// of rolled back.
[[nodiscard]] Void::Result::Result<void> rollback();
[[nodiscard]] Void::Result::Result<void> reconcile();
/// Record a successful activation performed by an external
/// lifecycle owner. The published version must be a real immediate
/// directory. Every call appends a durable healthy event and
/// refreshes retention order. It rejects stores with an internal
/// activation journal so it cannot implicitly commit activate().
/// This method does not initialize the store or create staging.
[[nodiscard]] Void::Result::Result<void>
recordHealthy(const Semver::Version& version);
/// Record a failed external activation unless this version's
/// current publication lifecycle is already known healthy. A
/// retired and later republished SemVer starts a new lifecycle.
/// This method does not initialize the store or create staging.
[[nodiscard]] Void::Result::Result<void>
recordFailed(const Semver::Version& version);
/// Return real, currently published versions whose current
/// lifecycle is known healthy, newest durable healthy event first.
/// Missing, symlinked, failed, retired, and unknown publications
/// are excluded.
[[nodiscard]]
Void::Result::Result<std::vector<Semver::Version>>
healthyPublishedVersions() const;
/// Remove structurally valid, published version directories except
/// the active version, an in-flight activation's candidate and
/// previous version, and the requested number of most recently
/// committed healthy versions. Unknown publication state is
/// retained conservatively. Symlinks and the staging tree are never
/// traversed or removed. Returns the versions that were quarantined
/// and removed.
[[nodiscard]]
Void::Result::Result<std::vector<Semver::Version>>
prune(std::size_t retainedPreviousVersions);
[[nodiscard]] Void::Result::Result<std::optional<Semver::Version>>
currentVersion() const;
[[nodiscard]] Void::Result::Result<std::optional<PendingActivation>>
pendingActivation() const;
[[nodiscard]] const std::filesystem::path& root() const noexcept;
[[nodiscard]] std::filesystem::path
versionPath(const Semver::Version& version) const;
private:
std::filesystem::path m_root;
};
} // namespace Void::Update