This commit is contained in:
Jorijn van der Graaf 2026-10-31 20:50:57 +01:00
commit 367c19386c
17 changed files with 561 additions and 166 deletions

View file

@ -0,0 +1,69 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro:Utils;
import std;
namespace fs = std::filesystem;
export namespace Nostro {
constexpr std::string EscB(std::string_view s) {
std::string out;
out.reserve(s.size() + 8);
for (const char c : s) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (static_cast<unsigned char>(c) < 0x20) {
out += std::format("\\u{:04x}", static_cast<unsigned char>(c));
} else {
out += c;
}
}
}
return out;
}
constexpr std::chrono::system_clock::time_point ParseTimestamp(std::string_view text) {
const auto field = [text](std::size_t offset, std::size_t length) {
std::uint32_t value = 0;
const char* const first = text.data() + offset;
if(offset + length > text.size()) {
throw std::runtime_error(std::format("malformed timestamp '{}'", text));
}
const std::from_chars_result result = std::from_chars(first, first + length, value);
if(result.ec != std::errc() || result.ptr != first + length) {
throw std::runtime_error(std::format("malformed timestamp '{}'", text));
}
return value;
};
if(text.size() < 19 || text[4] != '-' || text[7] != '-' || text[10] != ' ' || text[13] != ':' || text[16] != ':') {
throw std::runtime_error(std::format("malformed timestamp '{}'", text));
}
std::uint32_t micros = 0;
if(text.size() > 19) {
const std::size_t digits = text.size() - 20;
if(text[19] != '.' || digits == 0 || digits > 6) {
throw std::runtime_error(std::format("malformed timestamp '{}'", text));
}
micros = field(20, digits);
for(std::size_t i = digits; i < 6; i++) {
micros *= 10;
}
}
const std::chrono::year_month_day date(std::chrono::year(static_cast<std::int32_t>(field(0, 4))), std::chrono::month(field(5, 2)), std::chrono::day(field(8, 2)));
if(!date.ok()) {
throw std::runtime_error(std::format("malformed timestamp '{}'", text));
}
return std::chrono::sys_days(date) + std::chrono::hours(field(11, 2)) + std::chrono::minutes(field(14, 2)) + std::chrono::seconds(field(17, 2)) + std::chrono::microseconds(micros);
}
}