Add Url/Html encoding, ISO-8601 interval parse, TempFile, random_string charset

Universal additions (all generic, header-only, tested; full suite 1127 pass):
- Void::Encoding::Url — RFC 3986 percent encode/decode + query_encode.
- Void::Text::html_unescape — numeric + common named HTML entities -> UTF-8.
- Void::Time::parse_iso8601_interval — parse PT#H#M#S / P#DT#H#M#S durations
  (distinct from the unit-suffix parse_duration).
- Void::FileSystem::TempFile — RAII unique temp file (alongside TempDir),
  with keep() to persist.
- Void::Random::random_string(n, charset) overload.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-22 16:15:01 +03:00
1 parent 80293ee56f
commit fb0506581f
9 files changed
+645 -6

No files matched your search

+14 -6
View File
@@ -134,6 +134,19 @@ inline void fill_random(std::span<std::byte> buf) noexcept
}
}
/// Generate a random string of length n drawn from `charset`.
[[nodiscard]] inline std::string random_string(std::size_t n,
std::string_view charset)
{
std::string s;
if (charset.empty()) return s;
s.reserve(n);
for (std::size_t i = 0; i < n; ++i) {
s += charset[uniform_int<std::size_t>(0, charset.size() - 1)];
}
return s;
}
/// Generate a random alphanumeric string of length n.
[[nodiscard]] inline std::string random_string(std::size_t n)
{
@@ -141,12 +154,7 @@ inline void fill_random(std::span<std::byte> buf) noexcept
"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;
return random_string(n, chars);
}
/// Sample k distinct indices from [0, n).
+136
View File
@@ -0,0 +1,136 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <format>
#include <fstream>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <utility>
namespace Void::FileSystem
{
/// RAII scoped *file* under `std::filesystem::temp_directory_path()`.
///
/// A uniquely-named empty file is created on construction and removed on
/// destruction, unless `keep()` was called. Move-only. Useful for staging
/// downloads, copying a shared library to a fresh inode, etc.
///
/// Construction throws `std::system_error` if the file cannot be created;
/// use `TempFile::open(prefix, ext)` for a non-throwing factory.
class TempFile
{
public:
explicit TempFile(std::string_view prefix = "void_",
std::string_view extension = "")
: m_path(make_unique_file(prefix, extension))
{
}
~TempFile() noexcept
{
if (!m_path.empty() && !m_keep) {
std::error_code ignore;
std::filesystem::remove(m_path, ignore);
Void::Log::debug("FileSystem", "TempFile: removed '{}'",
m_path.string());
}
}
TempFile(const TempFile&) = delete;
TempFile& operator=(const TempFile&) = delete;
TempFile(TempFile&& other) noexcept
: m_path(std::exchange(other.m_path, {})),
m_keep(std::exchange(other.m_keep, true))
{
}
TempFile& operator=(TempFile&& other) noexcept
{
if (this != &other) {
if (!m_path.empty() && !m_keep) {
std::error_code ignore;
std::filesystem::remove(m_path, ignore);
}
m_path = std::exchange(other.m_path, {});
m_keep = std::exchange(other.m_keep, true);
}
return *this;
}
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
}
/// Persist the file beyond this object's lifetime (no removal on
/// destruction). Returns the path for convenience.
std::filesystem::path keep() noexcept
{
m_keep = true;
return m_path;
}
/// Non-throwing factory.
[[nodiscard]] static Void::Result::Result<TempFile,
Void::Result::Error>
open(std::string_view prefix = "void_",
std::string_view extension = "")
{
try {
return Void::Result::ok(TempFile{prefix, extension});
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
}
}
private:
std::filesystem::path m_path;
bool m_keep = false;
static std::filesystem::path
make_unique_file(std::string_view prefix,
std::string_view extension)
{
static std::atomic<std::uint64_t> counter{0};
const auto base = std::filesystem::temp_directory_path();
for (int attempt = 0; attempt < 16; ++attempt) {
const auto seed =
static_cast<std::uint64_t>(
std::chrono::steady_clock::now()
.time_since_epoch()
.count()) ^
(counter.fetch_add(1, std::memory_order_relaxed) << 16) ^
static_cast<std::uint64_t>(
std::hash<std::thread::id>{}(
std::this_thread::get_id()));
auto candidate =
base / std::format("{}{:016x}{}", prefix, seed, extension);
std::error_code ec;
if (!std::filesystem::exists(candidate, ec)) {
std::ofstream f(candidate);
if (f) {
Void::Log::debug("FileSystem",
"TempFile: created '{}'",
candidate.string());
return candidate;
}
}
}
throw std::system_error(
std::make_error_code(std::errc::file_exists),
"TempFile: failed to create unique file after 16 attempts");
}
};
} // namespace Void::FileSystem
+113
View File
@@ -0,0 +1,113 @@
#pragma once
#include <array>
#include <cstdint>
#include <string>
#include <string_view>
namespace Void::Text
{
namespace Detail
{
// Append `cp` as UTF-8 to `out`.
inline void append_utf8(std::string& out, std::uint32_t cp)
{
if (cp <= 0x7F) {
out += static_cast<char>(cp);
} else if (cp <= 0x7FF) {
out += static_cast<char>(0xC0 | (cp >> 6));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else if (cp <= 0xFFFF) {
out += static_cast<char>(0xE0 | (cp >> 12));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else if (cp <= 0x10FFFF) {
out += static_cast<char>(0xF0 | (cp >> 18));
out += static_cast<char>(0x80 | ((cp >> 12) & 0x3F));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(0x80 | (cp & 0x3F));
}
}
// The common named HTML entities. Numeric entities cover everything else.
struct NamedEntity {
std::string_view name;
std::uint32_t cp;
};
inline constexpr std::array<NamedEntity, 12> named_entities{{
{"amp", '&'}, {"lt", '<'}, {"gt", '>'}, {"quot", '"'},
{"apos", '\''}, {"nbsp", 0xA0}, {"copy", 0xA9}, {"reg", 0xAE},
{"hellip", 0x2026}, {"mdash", 0x2014}, {"ndash", 0x2013}, {"trade", 0x2122},
}};
} // namespace Detail
/// Decode HTML character references in `s` to UTF-8: numeric (`&#1234;`,
/// `&#x1F600;`) and the common named entities (&amp; &lt; &gt; &quot; &apos;
/// &nbsp; &copy; …). Unknown or malformed references are left verbatim.
/// Generic — no markup parsing, just entity substitution.
[[nodiscard]] inline std::string html_unescape(std::string_view s)
{
std::string out;
out.reserve(s.size());
for (std::size_t i = 0; i < s.size();) {
if (s[i] != '&') {
out += s[i++];
continue;
}
// Find the terminating ';' within a small window.
const std::size_t semi = s.find(';', i + 1);
if (semi == std::string_view::npos || semi - i > 12) {
out += s[i++];
continue;
}
const std::string_view body = s.substr(i + 1, semi - i - 1);
bool handled = false;
if (!body.empty() && body[0] == '#') {
// Numeric reference (decimal or hex).
std::uint32_t cp = 0;
bool ok = false;
if (body.size() > 1 && (body[1] == 'x' || body[1] == 'X')) {
for (std::size_t k = 2; k < body.size(); ++k) {
const char c = body[k];
int v;
if (c >= '0' && c <= '9') v = c - '0';
else if (c >= 'a' && c <= 'f') v = c - 'a' + 10;
else if (c >= 'A' && c <= 'F') v = c - 'A' + 10;
else { ok = false; break; }
cp = cp * 16 + static_cast<std::uint32_t>(v);
ok = true;
}
} else {
for (std::size_t k = 1; k < body.size(); ++k) {
const char c = body[k];
if (c < '0' || c > '9') { ok = false; break; }
cp = cp * 10 + static_cast<std::uint32_t>(c - '0');
ok = true;
}
}
if (ok && cp <= 0x10FFFF) {
Detail::append_utf8(out, cp);
handled = true;
}
} else {
for (const auto& e : Detail::named_entities) {
if (e.name == body) {
Detail::append_utf8(out, e.cp);
handled = true;
break;
}
}
}
if (handled) {
i = semi + 1;
} else {
out += s[i++]; // leave the '&' as-is
}
}
return out;
}
} // namespace Void::Text
+92
View File
@@ -0,0 +1,92 @@
#pragma once
#include <array>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
namespace Void::Encoding::Url
{
namespace Detail
{
// RFC 3986 unreserved characters: ALPHA / DIGIT / "-" / "." / "_" / "~".
[[nodiscard]] constexpr std::array<bool, 256> make_unreserved() noexcept
{
std::array<bool, 256> t{};
for (char c = 'A'; c <= 'Z'; ++c) t[static_cast<unsigned char>(c)] = true;
for (char c = 'a'; c <= 'z'; ++c) t[static_cast<unsigned char>(c)] = true;
for (char c = '0'; c <= '9'; ++c) t[static_cast<unsigned char>(c)] = true;
for (char c : {'-', '.', '_', '~'}) t[static_cast<unsigned char>(c)] = true;
return t;
}
inline constexpr std::array<bool, 256> unreserved = make_unreserved();
inline constexpr std::string_view hex_upper = "0123456789ABCDEF";
[[nodiscard]] constexpr int hex_value(unsigned char c) noexcept
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
} // namespace Detail
/// Percent-encode `s` per RFC 3986. Unreserved characters pass through; every
/// other byte becomes %XX (uppercase hex). When `space_as_plus` is true a space
/// is emitted as '+' (application/x-www-form-urlencoded form encoding) instead
/// of %20.
[[nodiscard]] inline std::string encode(std::string_view s,
bool space_as_plus = false)
{
std::string out;
out.reserve(s.size() * 3);
for (unsigned char c : s) {
if (Detail::unreserved[c]) {
out += static_cast<char>(c);
} else if (space_as_plus && c == ' ') {
out += '+';
} else {
out += '%';
out += Detail::hex_upper[c >> 4];
out += Detail::hex_upper[c & 0x0F];
}
}
return out;
}
/// Encode for a query-string value: form encoding with spaces as '+'.
[[nodiscard]] inline std::string query_encode(std::string_view s)
{
return encode(s, /*space_as_plus=*/true);
}
/// Decode a percent-encoded string. '+' is treated as a space when
/// `plus_as_space` is true (form decoding). Returns nullopt on a malformed
/// escape (a '%' not followed by two hex digits).
[[nodiscard]] inline std::optional<std::string>
decode(std::string_view s, bool plus_as_space = false)
{
std::string out;
out.reserve(s.size());
for (std::size_t i = 0; i < s.size(); ++i) {
const unsigned char c = static_cast<unsigned char>(s[i]);
if (c == '%') {
if (i + 2 >= s.size()) return std::nullopt;
const int hi = Detail::hex_value(static_cast<unsigned char>(s[i + 1]));
const int lo = Detail::hex_value(static_cast<unsigned char>(s[i + 2]));
if (hi < 0 || lo < 0) return std::nullopt;
out += static_cast<char>((hi << 4) | lo);
i += 2;
} else if (plus_as_space && c == '+') {
out += ' ';
} else {
out += static_cast<char>(c);
}
}
return out;
}
} // namespace Void::Encoding::Url
+78
View File
@@ -198,4 +198,82 @@ namespace Void::Time
tm.tm_hour, tm.tm_min, tm.tm_sec, ms.count());
}
/// Parse an ISO 8601 *duration/interval* of the form
/// `[-]P[nD]T[nH][nM][n[.n]S]` (also accepts week form `PnW`) into a
/// std::chrono::seconds. Examples: "PT1H30M" -> 5400s, "P1DT2H" -> 93600s,
/// "PT45S" -> 45s, "PT0S" -> 0s. Fractional seconds are truncated.
/// Returns nullopt on malformed input. Distinct from parse_duration, which
/// handles unit-suffixed values like "250ms".
[[nodiscard]] inline std::optional<std::chrono::seconds>
parse_iso8601_interval(std::string_view s)
{
if (s.empty()) {
return std::nullopt;
}
bool negative = false;
std::size_t i = 0;
if (s[i] == '+' || s[i] == '-') {
negative = (s[i] == '-');
++i;
}
if (i >= s.size() || s[i] != 'P') {
return std::nullopt;
}
++i; // consume 'P'
long long total = 0;
bool in_time = false; // past the 'T' separator
bool any_field = false;
while (i < s.size()) {
if (s[i] == 'T') {
in_time = true;
++i;
continue;
}
// Read a (optionally fractional) number.
const std::size_t start = i;
while (i < s.size() &&
((s[i] >= '0' && s[i] <= '9') || s[i] == '.')) {
++i;
}
if (i == start || i >= s.size()) {
return std::nullopt; // number without a unit
}
double value = 0.0;
{
// from_chars on the [start, i) numeric span.
const auto* b = s.data() + start;
const auto* e = s.data() + i;
const auto [ptr, ec] = std::from_chars(b, e, value);
if (ec != std::errc{} || ptr != e) {
return std::nullopt;
}
}
const char unit = s[i++];
long long secs = 0;
if (!in_time) {
switch (unit) {
case 'W': secs = static_cast<long long>(value) * 604800; break;
case 'D': secs = static_cast<long long>(value) * 86400; break;
default: return std::nullopt; // Y/M (calendar) unsupported
}
} else {
switch (unit) {
case 'H': secs = static_cast<long long>(value) * 3600; break;
case 'M': secs = static_cast<long long>(value) * 60; break;
case 'S': secs = static_cast<long long>(value); break;
default: return std::nullopt;
}
}
total += secs;
any_field = true;
}
if (!any_field) {
return std::nullopt;
}
return std::chrono::seconds{negative ? -total : total};
}
} // namespace Void::Time
+28
View File
@@ -5,6 +5,34 @@
#include <algorithm>
#include <vector>
// ── random_string charset ────────────────────────────────────────────────────
Void::Testing::Test random_string_length_and_charset()
{
const std::string charset = "ABC";
const auto s = Void::Random::random_string(64, charset);
Void::Testing::expect_eq(s.size(), std::size_t{64});
for (char c : s) {
Void::Testing::expect(charset.find(c) != std::string::npos);
}
}
Void::Testing::Test random_string_default_alphanumeric()
{
const auto s = Void::Random::random_string(32);
Void::Testing::expect_eq(s.size(), std::size_t{32});
for (char c : s) {
const bool alnum = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9');
Void::Testing::expect(alnum);
}
}
Void::Testing::Test random_string_empty_charset_is_empty()
{
Void::Testing::expect(Void::Random::random_string(10, "").empty());
}
// ── Xoshiro256 ───────────────────────────────────────────────────────────────
Void::Testing::Test xoshiro_produces_output()
+60
View File
@@ -0,0 +1,60 @@
#include <Void/System/TempFile.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <filesystem>
#include <fstream>
#include <utility>
Void::Testing::Test temp_file_creates_under_temp_and_removes()
{
std::filesystem::path captured;
{
Void::FileSystem::TempFile tmp;
captured = tmp.path();
Void::Testing::expect(std::filesystem::is_regular_file(captured));
Void::Testing::expect(captured.parent_path() ==
std::filesystem::temp_directory_path());
}
Void::Testing::expect(!std::filesystem::exists(captured));
}
Void::Testing::Test temp_file_honors_extension()
{
Void::FileSystem::TempFile tmp{"void_", ".so"};
Void::Testing::expect_eq(tmp.path().extension().string(),
std::string{".so"});
}
Void::Testing::Test temp_file_keep_persists()
{
std::filesystem::path captured;
{
Void::FileSystem::TempFile tmp;
captured = tmp.keep();
}
Void::Testing::expect(std::filesystem::exists(captured));
std::error_code ec;
std::filesystem::remove(captured, ec); // manual cleanup
}
Void::Testing::Test temp_file_move_transfers_ownership()
{
std::filesystem::path captured;
{
Void::FileSystem::TempFile a;
captured = a.path();
Void::FileSystem::TempFile b = std::move(a);
Void::Testing::expect_eq(b.path(), captured);
Void::Testing::expect(a.path().empty());
}
// Removed once (by b); no double-remove crash.
Void::Testing::expect(!std::filesystem::exists(captured));
}
Void::Testing::Test temp_files_are_unique()
{
Void::FileSystem::TempFile a;
Void::FileSystem::TempFile b;
Void::Testing::expect(a.path() != b.path());
}
+81
View File
@@ -1,5 +1,7 @@
#include <Void/Text/Base64.hpp>
#include <Void/Text/Hex.hpp>
#include <Void/Text/Html.hpp>
#include <Void/Text/Url.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
@@ -157,3 +159,82 @@ Void::Testing::Test hex_round_trip()
Void::Testing::expect(decoded.has_value());
Void::Testing::expect_eq(*decoded, original);
}
// ── URL / percent encoding ─────────────────────────────────────────────────────
Void::Testing::Test url_encode_unreserved_passthrough()
{
Void::Testing::expect_eq(Void::Encoding::Url::encode("AZaz09-._~"),
std::string{"AZaz09-._~"});
}
Void::Testing::Test url_encode_reserved()
{
Void::Testing::expect_eq(Void::Encoding::Url::encode("a b/c?d=e&f"),
std::string{"a%20b%2Fc%3Fd%3De%26f"});
}
Void::Testing::Test url_query_encode_space_as_plus()
{
Void::Testing::expect_eq(Void::Encoding::Url::query_encode("a b c"),
std::string{"a+b+c"});
}
Void::Testing::Test url_decode_basic()
{
const auto r = Void::Encoding::Url::decode("a%20b%2Fc");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"a b/c"});
}
Void::Testing::Test url_decode_plus_as_space()
{
const auto r = Void::Encoding::Url::decode("a+b", /*plus_as_space=*/true);
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"a b"});
}
Void::Testing::Test url_decode_malformed_fails()
{
Void::Testing::expect(!Void::Encoding::Url::decode("a%2").has_value());
Void::Testing::expect(!Void::Encoding::Url::decode("a%zz").has_value());
}
Void::Testing::Test url_round_trip_utf8()
{
const std::string original = "café/naïve?x=1 2";
const auto enc = Void::Encoding::Url::encode(original);
const auto dec = Void::Encoding::Url::decode(enc);
Void::Testing::expect(dec.has_value());
Void::Testing::expect_eq(*dec, original);
}
// ── HTML entity decoding ───────────────────────────────────────────────────────
Void::Testing::Test html_named_entities()
{
Void::Testing::expect_eq(
Void::Text::html_unescape("a &amp; b &lt; c &gt; d &quot;e&quot;"),
std::string{"a & b < c > d \"e\""});
}
Void::Testing::Test html_numeric_decimal()
{
Void::Testing::expect_eq(Void::Text::html_unescape("&#65;&#66;&#67;"),
std::string{"ABC"});
}
Void::Testing::Test html_numeric_hex_utf8()
{
// U+1F600 grinning face -> 4-byte UTF-8
const auto r = Void::Text::html_unescape("&#x1F600;");
Void::Testing::expect_eq(r.size(), std::size_t{4});
}
Void::Testing::Test html_unknown_left_verbatim()
{
Void::Testing::expect_eq(Void::Text::html_unescape("a &bogus; b"),
std::string{"a &bogus; b"});
Void::Testing::expect_eq(Void::Text::html_unescape("plain & text"),
std::string{"plain & text"});
}
+43
View File
@@ -9,6 +9,49 @@
// ── Stopwatch ─────────────────────────────────────────────────────────────
// ── ISO 8601 interval parsing ─────────────────────────────────────────────
Void::Testing::Test iso8601_interval_hours_minutes()
{
const auto r = Void::Time::parse_iso8601_interval("PT1H30M");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(r->count(), static_cast<long long>(5400));
}
Void::Testing::Test iso8601_interval_days_and_time()
{
const auto r = Void::Time::parse_iso8601_interval("P1DT2H");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(r->count(), static_cast<long long>(93600));
}
Void::Testing::Test iso8601_interval_seconds_only()
{
const auto r = Void::Time::parse_iso8601_interval("PT45S");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(r->count(), static_cast<long long>(45));
}
Void::Testing::Test iso8601_interval_zero_and_negative()
{
const auto z = Void::Time::parse_iso8601_interval("PT0S");
Void::Testing::expect(z.has_value());
Void::Testing::expect_eq(z->count(), static_cast<long long>(0));
const auto n = Void::Time::parse_iso8601_interval("-PT1M");
Void::Testing::expect(n.has_value());
Void::Testing::expect_eq(n->count(), static_cast<long long>(-60));
}
Void::Testing::Test iso8601_interval_malformed()
{
Void::Testing::expect(!Void::Time::parse_iso8601_interval("").has_value());
Void::Testing::expect(
!Void::Time::parse_iso8601_interval("1H30M").has_value());
Void::Testing::expect(!Void::Time::parse_iso8601_interval("PT").has_value());
Void::Testing::expect(
!Void::Time::parse_iso8601_interval("PT5X").has_value());
}
Void::Testing::Test stopwatch_elapsed_is_non_negative()
{
auto sw = Void::Time::Stopwatch::started();