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