Restructure into umbrella modules (~55 -> 16 targets)
Headers move, CMake targets merge, C++ namespaces stay unchanged: - Core: Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant - Functional: Pipeline, Either, Result, Retry - Containers: Ring, Pool, PriorityQueue, LRU, Trie, Graph, DisjointSet, Bitset, Interval - Math: +Matrix, Numeric, Random, Histogram - Text: Str, Format, Tokenizer, Diff, Encoding, Semver - Data: Json, Csv, Ini - Async: Coro, Concurrency, EventBus, Observable - Time: +Bench - Log: Log facade + Logging framework (facade now header-only, breaking the Stacktrace<->Log link cycle the merge would have created) - System: FileSystem + Process - Configuration: +Argparse - Unchanged: Stacktrace, Plugin, StateMachine, Testing, TestingMock, Detail Module system fixes: - OPTIONAL_DEPS resolution deferred to void_finalize_modules() so it no longer depends on the alphabetical discovery order of src/ subdirs (Testing -> Text would have been silently dropped). - Every header-only module now has a tracked module.cmake; previously the empty src/<Name> marker dirs were untracked, so a fresh clone would have silently skipped those modules. - VOID_HAS_LOGGING/CONCURRENCY/STR consumers renamed to LOG/ASYNC/TEXT. Tests move to tests/standalone/<Umbrella>/<Feature>.cpp (Result suite files prefixed: ResultBasic etc.). Test count verified identical (831) before and after. README/CLAUDE.md module tables updated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
da2e93c405
commit
28b94883fd
156 files changed
+278
-220
No files matched your search
@@ -0,0 +1,138 @@
|
||||
#pragma once
|
||||
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Csv
|
||||
{
|
||||
|
||||
using Row = std::vector<std::string>;
|
||||
using Table = std::vector<Row>;
|
||||
|
||||
// ── parse ─────────────────────────────────────────────────────────────────────
|
||||
// RFC 4180-compatible parser. Fields may be quoted ("..."). CRLF and LF
|
||||
// both accepted as row terminators.
|
||||
|
||||
[[nodiscard]] inline Table parse(std::string_view text, char delim = ',')
|
||||
{
|
||||
Table result;
|
||||
Row row;
|
||||
std::string field;
|
||||
bool in_quote = false;
|
||||
|
||||
for (std::size_t i = 0; i < text.size(); ++i) {
|
||||
const char c = text[i];
|
||||
|
||||
if (in_quote) {
|
||||
if (c == '"') {
|
||||
// Peek for doubled quote
|
||||
if (i + 1 < text.size() && text[i + 1] == '"') {
|
||||
field += '"'; ++i;
|
||||
} else {
|
||||
in_quote = false;
|
||||
}
|
||||
} else {
|
||||
field += c;
|
||||
}
|
||||
} else {
|
||||
if (c == '"') {
|
||||
in_quote = true;
|
||||
} else if (c == delim) {
|
||||
row.push_back(std::move(field));
|
||||
field.clear();
|
||||
} else if (c == '\n') {
|
||||
row.push_back(std::move(field));
|
||||
field.clear();
|
||||
result.push_back(std::move(row));
|
||||
row.clear();
|
||||
} else if (c == '\r') {
|
||||
// skip CR in CRLF
|
||||
} else {
|
||||
field += c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Flush last field/row
|
||||
row.push_back(std::move(field));
|
||||
if (!row.empty() && !(row.size() == 1 && row[0].empty())) {
|
||||
result.push_back(std::move(row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── serialize ─────────────────────────────────────────────────────────────────
|
||||
// Produces RFC 4180 CSV. Fields that contain the delimiter, quote, or newline
|
||||
// are wrapped in double quotes; embedded quotes are doubled.
|
||||
|
||||
[[nodiscard]] inline std::string serialize(const Table& table,
|
||||
char delim = ',')
|
||||
{
|
||||
std::string out;
|
||||
for (const auto& row : table) {
|
||||
for (std::size_t i = 0; i < row.size(); ++i) {
|
||||
const auto& field = row[i];
|
||||
const bool needs_quote =
|
||||
field.find(delim) != std::string::npos ||
|
||||
field.find('"') != std::string::npos ||
|
||||
field.find('\n') != std::string::npos ||
|
||||
field.find('\r') != std::string::npos;
|
||||
if (needs_quote) {
|
||||
out += '"';
|
||||
for (char c : field) {
|
||||
if (c == '"') out += '"';
|
||||
out += c;
|
||||
}
|
||||
out += '"';
|
||||
} else {
|
||||
out += field;
|
||||
}
|
||||
if (i + 1 < row.size()) out += delim;
|
||||
}
|
||||
out += '\n';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── with_header convenience ───────────────────────────────────────────────────
|
||||
|
||||
struct CsvWithHeader
|
||||
{
|
||||
Row header;
|
||||
Table rows;
|
||||
|
||||
[[nodiscard]] std::optional<std::size_t>
|
||||
col_index(std::string_view name) const
|
||||
{
|
||||
for (std::size_t i = 0; i < header.size(); ++i) {
|
||||
if (header[i] == name) return i;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
get(const Row& row, std::string_view name) const
|
||||
{
|
||||
auto idx = col_index(name);
|
||||
if (!idx || *idx >= row.size()) return std::nullopt;
|
||||
return row[*idx];
|
||||
}
|
||||
};
|
||||
|
||||
[[nodiscard]] inline std::optional<CsvWithHeader>
|
||||
parse_with_header(std::string_view text, char delim = ',')
|
||||
{
|
||||
auto table = parse(text, delim);
|
||||
if (table.empty()) return std::nullopt;
|
||||
CsvWithHeader result;
|
||||
result.header = std::move(table[0]);
|
||||
result.rows.assign(std::make_move_iterator(table.begin() + 1),
|
||||
std::make_move_iterator(table.end()));
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace Void::Csv
|
||||
@@ -0,0 +1,163 @@
|
||||
#pragma once
|
||||
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Ini
|
||||
{
|
||||
|
||||
// ── IniFile ───────────────────────────────────────────────────────────────────
|
||||
// Parses .ini / .cfg files with sections ([section]) and key=value pairs.
|
||||
// Comments start with ';' or '#'. Inline comments are NOT stripped.
|
||||
// Values may be quoted ("hello world") — quotes are stripped.
|
||||
|
||||
class IniFile
|
||||
{
|
||||
public:
|
||||
using Section = std::unordered_map<std::string, std::string>;
|
||||
|
||||
struct ParseError
|
||||
{
|
||||
std::size_t line;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
// Parse from a string. Returns error on malformed input.
|
||||
[[nodiscard]] static std::optional<ParseError>
|
||||
parse(IniFile& out, std::string_view text)
|
||||
{
|
||||
out.data_.clear();
|
||||
std::string current_section;
|
||||
std::size_t lineno = 0;
|
||||
|
||||
auto sv_trim = [](std::string_view s) {
|
||||
while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) s.remove_prefix(1);
|
||||
while (!s.empty() && (s.back() == ' ' || s.back() == '\t' ||
|
||||
s.back() == '\r')) s.remove_suffix(1);
|
||||
return s;
|
||||
};
|
||||
|
||||
std::string_view remaining = text;
|
||||
while (!remaining.empty()) {
|
||||
++lineno;
|
||||
const auto nl = remaining.find('\n');
|
||||
std::string_view line = sv_trim(
|
||||
nl == std::string_view::npos ? remaining
|
||||
: remaining.substr(0, nl));
|
||||
remaining = nl == std::string_view::npos
|
||||
? std::string_view{}
|
||||
: remaining.substr(nl + 1);
|
||||
|
||||
if (line.empty() || line[0] == ';' || line[0] == '#') continue;
|
||||
|
||||
if (line[0] == '[') {
|
||||
const auto close = line.find(']');
|
||||
if (close == std::string_view::npos) {
|
||||
return ParseError{lineno, "unclosed '['"};
|
||||
}
|
||||
current_section = std::string{line.substr(1, close - 1)};
|
||||
out.data_[current_section]; // ensure section exists
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto eq = line.find('=');
|
||||
if (eq == std::string_view::npos) {
|
||||
if (!line.empty()) {
|
||||
return ParseError{lineno, std::string{"expected '=' in: "} + std::string{line}};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
std::string key{sv_trim(line.substr(0, eq))};
|
||||
std::string_view val_sv = sv_trim(line.substr(eq + 1));
|
||||
|
||||
// Strip optional quotes
|
||||
std::string val;
|
||||
if (val_sv.size() >= 2 && val_sv.front() == '"' && val_sv.back() == '"') {
|
||||
val = std::string{val_sv.substr(1, val_sv.size() - 2)};
|
||||
} else {
|
||||
val = std::string{val_sv};
|
||||
}
|
||||
|
||||
out.data_[current_section][std::move(key)] = std::move(val);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]] static IniFile from_string(std::string_view text)
|
||||
{
|
||||
IniFile f;
|
||||
parse(f, text);
|
||||
return f;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
get(std::string_view section, std::string_view key) const
|
||||
{
|
||||
auto sec_it = data_.find(std::string{section});
|
||||
if (sec_it == data_.end()) return std::nullopt;
|
||||
auto key_it = sec_it->second.find(std::string{key});
|
||||
if (key_it == sec_it->second.end()) return std::nullopt;
|
||||
return key_it->second;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string
|
||||
get_or(std::string_view section, std::string_view key,
|
||||
std::string_view fallback) const
|
||||
{
|
||||
return get(section, key).value_or(std::string{fallback});
|
||||
}
|
||||
|
||||
void set(std::string_view section, std::string_view key, std::string value)
|
||||
{
|
||||
data_[std::string{section}][std::string{key}] = std::move(value);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool has_section(std::string_view section) const
|
||||
{
|
||||
return data_.contains(std::string{section});
|
||||
}
|
||||
|
||||
[[nodiscard]] bool has_key(std::string_view section,
|
||||
std::string_view key) const
|
||||
{
|
||||
return get(section, key).has_value();
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<std::string> sections() const
|
||||
{
|
||||
std::vector<std::string> result;
|
||||
result.reserve(data_.size());
|
||||
for (const auto& [k, _] : data_) result.push_back(k);
|
||||
return result;
|
||||
}
|
||||
|
||||
[[nodiscard]] const Section* section(std::string_view name) const
|
||||
{
|
||||
auto it = data_.find(std::string{name});
|
||||
return it == data_.end() ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
// Serialize back to INI text.
|
||||
[[nodiscard]] std::string serialize() const
|
||||
{
|
||||
std::string out;
|
||||
for (const auto& [sec, kv] : data_) {
|
||||
out += '['; out += sec; out += "]\n";
|
||||
for (const auto& [k, v] : kv) {
|
||||
out += k; out += " = "; out += v; out += '\n';
|
||||
}
|
||||
out += '\n';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
std::unordered_map<std::string, Section> data_;
|
||||
};
|
||||
|
||||
} // namespace Void::Ini
|
||||
@@ -0,0 +1,444 @@
|
||||
#pragma once
|
||||
|
||||
#include <charconv>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Json
|
||||
{
|
||||
|
||||
// ── Value ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
class Value;
|
||||
|
||||
struct ParseError {
|
||||
std::size_t line{1}, col{1};
|
||||
std::string message;
|
||||
};
|
||||
|
||||
class Value
|
||||
{
|
||||
public:
|
||||
using Array_t = std::vector<Value>;
|
||||
using Object_t = std::vector<std::pair<std::string, Value>>;
|
||||
|
||||
private:
|
||||
using Data = std::variant<
|
||||
std::monostate, // null
|
||||
bool, // bool
|
||||
double, // number
|
||||
std::string, // string
|
||||
std::unique_ptr<Array_t>, // array (boxed to avoid incomplete-type issues)
|
||||
std::unique_ptr<Object_t> // object (same)
|
||||
>;
|
||||
Data data_{};
|
||||
|
||||
static Data clone(const Data& src)
|
||||
{
|
||||
return std::visit([](const auto& v) -> Data {
|
||||
using T = std::decay_t<decltype(v)>;
|
||||
if constexpr (std::is_same_v<T, std::unique_ptr<Array_t>>)
|
||||
return std::make_unique<Array_t>(*v);
|
||||
else if constexpr (std::is_same_v<T, std::unique_ptr<Object_t>>)
|
||||
return std::make_unique<Object_t>(*v);
|
||||
else
|
||||
return v;
|
||||
}, src);
|
||||
}
|
||||
|
||||
public:
|
||||
// ── construction ──────────────────────────────────────────────────────────
|
||||
Value() noexcept = default;
|
||||
Value(std::nullptr_t) noexcept {}
|
||||
Value(bool b) noexcept : data_{b} {}
|
||||
Value(double n) noexcept : data_{n} {}
|
||||
Value(int n) noexcept : data_{static_cast<double>(n)} {}
|
||||
Value(long long n) noexcept : data_{static_cast<double>(n)} {}
|
||||
Value(std::string s) : data_{std::move(s)} {}
|
||||
Value(std::string_view s) : data_{std::string{s}} {}
|
||||
Value(const char* s) : data_{std::string{s}} {}
|
||||
Value(Array_t a) : data_{std::make_unique<Array_t>(std::move(a))} {}
|
||||
Value(Object_t o) : data_{std::make_unique<Object_t>(std::move(o))} {}
|
||||
|
||||
Value(const Value& o) : data_{clone(o.data_)} {}
|
||||
Value& operator=(const Value& o) { if (this != &o) data_ = clone(o.data_); return *this; }
|
||||
Value(Value&&) noexcept = default;
|
||||
Value& operator=(Value&&) noexcept = default;
|
||||
~Value() = default;
|
||||
|
||||
// ── type query ────────────────────────────────────────────────────────────
|
||||
[[nodiscard]] bool is_null() const noexcept { return data_.index() == 0; }
|
||||
[[nodiscard]] bool is_bool() const noexcept { return data_.index() == 1; }
|
||||
[[nodiscard]] bool is_number() const noexcept { return data_.index() == 2; }
|
||||
[[nodiscard]] bool is_string() const noexcept { return data_.index() == 3; }
|
||||
[[nodiscard]] bool is_array() const noexcept { return data_.index() == 4; }
|
||||
[[nodiscard]] bool is_object() const noexcept { return data_.index() == 5; }
|
||||
|
||||
// ── typed access (throws std::bad_variant_access on wrong type) ───────────
|
||||
[[nodiscard]] bool as_bool() const { return std::get<bool>(data_); }
|
||||
[[nodiscard]] double as_number() const { return std::get<double>(data_); }
|
||||
[[nodiscard]] std::int64_t as_int() const { return static_cast<std::int64_t>(as_number()); }
|
||||
[[nodiscard]] const std::string& as_string() const { return std::get<std::string>(data_); }
|
||||
[[nodiscard]] const Array_t& as_array() const { return *std::get<std::unique_ptr<Array_t>>(data_); }
|
||||
[[nodiscard]] const Object_t& as_object() const { return *std::get<std::unique_ptr<Object_t>>(data_); }
|
||||
[[nodiscard]] Array_t& as_array() { return *std::get<std::unique_ptr<Array_t>>(data_); }
|
||||
[[nodiscard]] Object_t& as_object() { return *std::get<std::unique_ptr<Object_t>>(data_); }
|
||||
|
||||
// ── optional access ───────────────────────────────────────────────────────
|
||||
[[nodiscard]] std::optional<bool> get_bool() const noexcept { if (!is_bool()) return {}; return as_bool(); }
|
||||
[[nodiscard]] std::optional<double> get_number() const noexcept { if (!is_number()) return {}; return as_number(); }
|
||||
[[nodiscard]] std::optional<std::string_view> get_string() const noexcept { if (!is_string()) return {}; return as_string(); }
|
||||
|
||||
// ── subscript (array by index, object by key) ─────────────────────────────
|
||||
[[nodiscard]] const Value& operator[](std::size_t i) const { return as_array().at(i); }
|
||||
[[nodiscard]] Value& operator[](std::size_t i) { return as_array().at(i); }
|
||||
|
||||
[[nodiscard]] const Value* find(std::string_view key) const noexcept
|
||||
{
|
||||
if (!is_object()) return nullptr;
|
||||
for (const auto& [k, v] : as_object())
|
||||
if (k == key) return &v;
|
||||
return nullptr;
|
||||
}
|
||||
[[nodiscard]] Value* find(std::string_view key) noexcept
|
||||
{
|
||||
if (!is_object()) return nullptr;
|
||||
for (auto& [k, v] : as_object())
|
||||
if (k == key) return &v;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
[[nodiscard]] const Value& operator[](std::string_view key) const
|
||||
{
|
||||
const auto* p = find(key);
|
||||
if (!p) throw std::out_of_range{std::string{"key not found: "} + std::string{key}};
|
||||
return *p;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept
|
||||
{
|
||||
if (is_array()) return as_array().size();
|
||||
if (is_object()) return as_object().size();
|
||||
if (is_string()) return as_string().size();
|
||||
return 0;
|
||||
}
|
||||
[[nodiscard]] bool empty() const noexcept { return size() == 0; }
|
||||
|
||||
[[nodiscard]] bool operator==(const Value& o) const noexcept
|
||||
{
|
||||
if (data_.index() != o.data_.index()) return false;
|
||||
if (is_array()) return as_array() == o.as_array();
|
||||
if (is_object()) return as_object() == o.as_object();
|
||||
// For monostate, bool, double, string — variant equality works
|
||||
return std::visit([&](const auto& lhs) -> bool {
|
||||
using T = std::decay_t<decltype(lhs)>;
|
||||
if constexpr (std::is_same_v<T, std::unique_ptr<Array_t>> ||
|
||||
std::is_same_v<T, std::unique_ptr<Object_t>>)
|
||||
return false; // unreachable (handled above)
|
||||
else
|
||||
return lhs == std::get<T>(o.data_);
|
||||
}, data_);
|
||||
}
|
||||
};
|
||||
|
||||
// ── static factories ──────────────────────────────────────────────────────────
|
||||
[[nodiscard]] inline Value array(Value::Array_t a = {}) { return Value{std::move(a)}; }
|
||||
[[nodiscard]] inline Value object(Value::Object_t o = {}) { return Value{std::move(o)}; }
|
||||
|
||||
// ── parse ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
|
||||
struct Parser
|
||||
{
|
||||
std::string_view src;
|
||||
std::size_t pos{0}, line{1}, col{1};
|
||||
|
||||
[[nodiscard]] char peek() const noexcept { return pos < src.size() ? src[pos] : '\0'; }
|
||||
|
||||
char advance() noexcept
|
||||
{
|
||||
const char c = src[pos++];
|
||||
if (c == '\n') { ++line; col = 1; } else ++col;
|
||||
return c;
|
||||
}
|
||||
|
||||
bool at_end() const noexcept { return pos >= src.size(); }
|
||||
|
||||
void skip_ws() noexcept
|
||||
{
|
||||
while (!at_end() && (peek() == ' ' || peek() == '\t' || peek() == '\n' || peek() == '\r'))
|
||||
advance();
|
||||
}
|
||||
|
||||
ParseError err(std::string msg) const { return {line, col, std::move(msg)}; }
|
||||
|
||||
bool match(std::string_view lit) noexcept
|
||||
{
|
||||
if (pos + lit.size() > src.size()) return false;
|
||||
if (src.substr(pos, lit.size()) != lit) return false;
|
||||
for (std::size_t i = 0; i < lit.size(); ++i) advance();
|
||||
return true;
|
||||
}
|
||||
|
||||
std::expected<Value, ParseError> parse_value()
|
||||
{
|
||||
skip_ws();
|
||||
if (at_end()) return std::unexpected{err("unexpected end of input")};
|
||||
const char c = peek();
|
||||
if (c == 'n') return parse_literal("null", Value{nullptr});
|
||||
if (c == 't') return parse_literal("true", Value{true});
|
||||
if (c == 'f') return parse_literal("false", Value{false});
|
||||
if (c == '"') return parse_string();
|
||||
if (c == '[') return parse_array();
|
||||
if (c == '{') return parse_object();
|
||||
if (c == '-' || (c >= '0' && c <= '9')) return parse_number();
|
||||
return std::unexpected{err(std::string{"unexpected character '"} + c + "'")};
|
||||
}
|
||||
|
||||
std::expected<Value, ParseError> parse_literal(std::string_view lit, Value v)
|
||||
{
|
||||
if (!match(lit))
|
||||
return std::unexpected{err(std::string{"expected '"} + std::string{lit} + "'")};
|
||||
return v;
|
||||
}
|
||||
|
||||
std::expected<Value, ParseError> parse_number()
|
||||
{
|
||||
const std::size_t start = pos;
|
||||
if (peek() == '-') advance();
|
||||
if (peek() == '0') { advance(); }
|
||||
else { while (peek() >= '1' && peek() <= '9') advance(); while (peek() >= '0' && peek() <= '9') advance(); }
|
||||
bool is_float = false;
|
||||
if (peek() == '.') { is_float = true; advance(); while (peek() >= '0' && peek() <= '9') advance(); }
|
||||
if (peek() == 'e' || peek() == 'E') {
|
||||
is_float = true; advance();
|
||||
if (peek() == '+' || peek() == '-') advance();
|
||||
while (peek() >= '0' && peek() <= '9') advance();
|
||||
}
|
||||
const std::string_view raw = src.substr(start, pos - start);
|
||||
double val = 0.0;
|
||||
const auto [ptr, ec] = std::from_chars(raw.data(), raw.data() + raw.size(), val);
|
||||
if (ec != std::errc{})
|
||||
return std::unexpected{err("invalid number: " + std::string{raw})};
|
||||
return Value{val};
|
||||
}
|
||||
|
||||
std::expected<std::string, ParseError> parse_string_raw()
|
||||
{
|
||||
if (peek() != '"') return std::unexpected{err("expected '\"'")};
|
||||
advance(); // consume opening quote
|
||||
std::string out;
|
||||
while (!at_end() && peek() != '"') {
|
||||
const char c = advance();
|
||||
if (c != '\\') { out += c; continue; }
|
||||
if (at_end()) return std::unexpected{err("unterminated escape")};
|
||||
const char esc = advance();
|
||||
switch (esc) {
|
||||
case '"': out += '"'; break;
|
||||
case '\\': out += '\\'; break;
|
||||
case '/': out += '/'; break;
|
||||
case 'b': out += '\b'; break;
|
||||
case 'f': out += '\f'; break;
|
||||
case 'n': out += '\n'; break;
|
||||
case 'r': out += '\r'; break;
|
||||
case 't': out += '\t'; break;
|
||||
case 'u': {
|
||||
if (pos + 4 > src.size()) return std::unexpected{err("incomplete \\uXXXX")};
|
||||
const auto hex = src.substr(pos, 4);
|
||||
unsigned cp = 0;
|
||||
const auto [p, e] = std::from_chars(hex.data(), hex.data() + 4, cp, 16);
|
||||
if (e != std::errc{} || p != hex.data() + 4)
|
||||
return std::unexpected{err("invalid \\uXXXX escape")};
|
||||
for (std::size_t i = 0; i < 4; ++i) advance();
|
||||
// Encode as UTF-8
|
||||
if (cp < 0x80) {
|
||||
out += static_cast<char>(cp);
|
||||
} else if (cp < 0x800) {
|
||||
out += static_cast<char>(0xC0 | (cp >> 6));
|
||||
out += static_cast<char>(0x80 | (cp & 0x3F));
|
||||
} else {
|
||||
out += static_cast<char>(0xE0 | (cp >> 12));
|
||||
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
|
||||
out += static_cast<char>(0x80 | (cp & 0x3F));
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: return std::unexpected{err(std::string{"unknown escape '\\"} + esc + "'")};
|
||||
}
|
||||
}
|
||||
if (at_end()) return std::unexpected{err("unterminated string")};
|
||||
advance(); // consume closing quote
|
||||
return out;
|
||||
}
|
||||
|
||||
std::expected<Value, ParseError> parse_string()
|
||||
{
|
||||
auto r = parse_string_raw();
|
||||
if (!r) return std::unexpected{r.error()};
|
||||
return Value{std::move(*r)};
|
||||
}
|
||||
|
||||
std::expected<Value, ParseError> parse_array()
|
||||
{
|
||||
advance(); // '['
|
||||
Value::Array_t arr;
|
||||
skip_ws();
|
||||
if (peek() == ']') { advance(); return Value{std::move(arr)}; }
|
||||
while (true) {
|
||||
auto v = parse_value();
|
||||
if (!v) return v;
|
||||
arr.push_back(std::move(*v));
|
||||
skip_ws();
|
||||
if (peek() == ']') { advance(); break; }
|
||||
if (peek() != ',') return std::unexpected{err("expected ',' or ']' in array")};
|
||||
advance();
|
||||
}
|
||||
return Value{std::move(arr)};
|
||||
}
|
||||
|
||||
std::expected<Value, ParseError> parse_object()
|
||||
{
|
||||
advance(); // '{'
|
||||
Value::Object_t obj;
|
||||
skip_ws();
|
||||
if (peek() == '}') { advance(); return Value{std::move(obj)}; }
|
||||
while (true) {
|
||||
skip_ws();
|
||||
auto key = parse_string_raw();
|
||||
if (!key) return std::unexpected{key.error()};
|
||||
skip_ws();
|
||||
if (peek() != ':') return std::unexpected{err("expected ':' after object key")};
|
||||
advance();
|
||||
auto val = parse_value();
|
||||
if (!val) return val;
|
||||
obj.emplace_back(std::move(*key), std::move(*val));
|
||||
skip_ws();
|
||||
if (peek() == '}') { advance(); break; }
|
||||
if (peek() != ',') return std::unexpected{err("expected ',' or '}' in object")};
|
||||
advance();
|
||||
}
|
||||
return Value{std::move(obj)};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Detail
|
||||
|
||||
[[nodiscard]] inline std::expected<Value, ParseError> parse(std::string_view json)
|
||||
{
|
||||
Detail::Parser p{json};
|
||||
auto r = p.parse_value();
|
||||
if (!r) return r;
|
||||
p.skip_ws();
|
||||
if (!p.at_end())
|
||||
return std::unexpected{p.err("trailing characters after JSON value")};
|
||||
return r;
|
||||
}
|
||||
|
||||
// ── serialize ─────────────────────────────────────────────────────────────────
|
||||
|
||||
struct SerializeOptions {
|
||||
bool pretty{false};
|
||||
int indent_width{2};
|
||||
};
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
|
||||
inline void escape_string(std::string& out, std::string_view s)
|
||||
{
|
||||
out += '"';
|
||||
for (const unsigned 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;
|
||||
case '\b': out += "\\b"; break;
|
||||
case '\f': out += "\\f"; break;
|
||||
default:
|
||||
if (c < 0x20) {
|
||||
out += "\\u00";
|
||||
const char hex[] = "0123456789abcdef";
|
||||
out += hex[c >> 4];
|
||||
out += hex[c & 0xF];
|
||||
} else {
|
||||
out += static_cast<char>(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
out += '"';
|
||||
}
|
||||
|
||||
inline void serialize_impl(std::string& out, const Value& v, const SerializeOptions& opts, int depth)
|
||||
{
|
||||
if (v.is_null()) { out += "null"; return; }
|
||||
if (v.is_bool()) { out += v.as_bool() ? "true" : "false"; return; }
|
||||
if (v.is_number()) {
|
||||
const double n = v.as_number();
|
||||
if (std::floor(n) == n && std::abs(n) < 1e15) {
|
||||
out += std::to_string(static_cast<std::int64_t>(n));
|
||||
} else {
|
||||
char buf[32];
|
||||
const auto [ptr, ec] = std::to_chars(buf, buf + sizeof(buf), n,
|
||||
std::chars_format::general, 17);
|
||||
if (ec == std::errc{}) out.append(buf, ptr);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (v.is_string()) { escape_string(out, v.as_string()); return; }
|
||||
|
||||
const std::string nl = opts.pretty ? "\n" : "";
|
||||
const std::string sep = opts.pretty ? " " : "";
|
||||
auto indent = [&](int d) {
|
||||
if (opts.pretty) out.append(static_cast<std::size_t>(d * opts.indent_width), ' ');
|
||||
};
|
||||
|
||||
if (v.is_array()) {
|
||||
out += '[';
|
||||
const auto& arr = v.as_array();
|
||||
for (std::size_t i = 0; i < arr.size(); ++i) {
|
||||
out += nl; indent(depth + 1);
|
||||
serialize_impl(out, arr[i], opts, depth + 1);
|
||||
if (i + 1 < arr.size()) out += ',';
|
||||
}
|
||||
if (!arr.empty()) { out += nl; indent(depth); }
|
||||
out += ']';
|
||||
return;
|
||||
}
|
||||
// object
|
||||
out += '{';
|
||||
const auto& obj = v.as_object();
|
||||
for (std::size_t i = 0; i < obj.size(); ++i) {
|
||||
out += nl; indent(depth + 1);
|
||||
escape_string(out, obj[i].first);
|
||||
out += ':'; out += sep;
|
||||
serialize_impl(out, obj[i].second, opts, depth + 1);
|
||||
if (i + 1 < obj.size()) out += ',';
|
||||
}
|
||||
if (!obj.empty()) { out += nl; indent(depth); }
|
||||
out += '}';
|
||||
}
|
||||
|
||||
} // namespace Detail
|
||||
|
||||
[[nodiscard]] inline std::string serialize(const Value& v, SerializeOptions opts = {})
|
||||
{
|
||||
std::string out;
|
||||
Detail::serialize_impl(out, v, opts, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Void::Json
|
||||
Reference in new issue
Block a user