Files
Library/include/Void/Time/Format.hpp
T
faumarayandClaude Opus 4.8 fb0506581f 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>
2026-06-22 16:15:01 +03:00

280 lines
8.1 KiB
C++

#pragma once
#include <charconv>
#include <chrono>
#include <ctime>
#include <format>
#include <optional>
#include <ratio>
#include <string>
#include <string_view>
#include <type_traits>
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));
}
/// Parse a single-unit duration string into nanoseconds.
///
/// Grammar: a number (integer or floating) followed by one of the suffixes
/// `ns`, `us`, `ms`, `s`, `m`, `h`. An empty suffix is treated as seconds.
/// Returns nullopt on any malformed input. This is the one source of truth
/// for duration parsing — Configuration and Json reflection both route
/// through it.
[[nodiscard]] inline std::optional<std::chrono::nanoseconds>
parse_duration(std::string_view raw)
{
double number = 0;
const char* begin = raw.data();
const char* end = raw.data() + raw.size();
const auto [ptr, ec] = std::from_chars(begin, end, number);
if (ec != std::errc{} || ptr == begin) {
return std::nullopt;
}
const std::string_view suffix{ptr, end};
using namespace std::chrono;
const auto as_ns = [&](auto unit) {
return std::optional{duration_cast<nanoseconds>(
duration<double, typename decltype(unit)::period>{number})};
};
if (suffix == "ns") {
return as_ns(nanoseconds{});
}
if (suffix == "us") {
return as_ns(microseconds{});
}
if (suffix == "ms") {
return as_ns(milliseconds{});
}
if (suffix == "s" || suffix.empty()) {
return as_ns(seconds{});
}
if (suffix == "m") {
return as_ns(minutes{});
}
if (suffix == "h") {
return as_ns(hours{});
}
return std::nullopt;
}
namespace Detail
{
/// The parse_duration suffix for a duration period, when it maps to a
/// known single unit; nullopt for non-standard periods.
template <class Period>
[[nodiscard]] constexpr std::optional<std::string_view>
duration_suffix()
{
if constexpr (std::is_same_v<Period, std::nano>) {
return "ns";
} else if constexpr (std::is_same_v<Period, std::micro>) {
return "us";
} else if constexpr (std::is_same_v<Period, std::milli>) {
return "ms";
} else if constexpr (std::is_same_v<Period, std::ratio<1>>) {
return "s";
} else if constexpr (std::is_same_v<Period, std::ratio<60>>) {
return "m";
} else if constexpr (std::is_same_v<Period, std::ratio<3600>>) {
return "h";
} else {
return std::nullopt;
}
}
} // namespace Detail
/// Emit a duration as a canonical, round-trippable single-unit string that
/// parse_duration accepts (e.g. milliseconds{250} -> "250ms"). The
/// duration's own period is used when it is one of the standard chrono
/// aliases; any other period falls back to a nanosecond count ("<n>ns"),
/// which is exact for the realistic cases. The inverse of parse_duration
/// for the standard aliases.
template <class Rep, class Period>
[[nodiscard]] std::string
duration_to_string(std::chrono::duration<Rep, Period> d)
{
constexpr auto suffix = Detail::duration_suffix<Period>();
if constexpr (suffix.has_value()) {
return std::format("{}{}", d.count(), *suffix);
} else {
const auto ns =
std::chrono::duration_cast<std::chrono::nanoseconds>(d);
return std::format("{}ns", ns.count());
}
}
/// 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());
}
/// 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