1388 lines
35 KiB
C++
1388 lines
35 KiB
C++
#pragma once
|
|
|
|
#include <Void/Math/Numeric.hpp>
|
|
|
|
#include <charconv>
|
|
#include <cmath>
|
|
#include <concepts>
|
|
#include <cstdint>
|
|
#include <expected>
|
|
#include <functional>
|
|
#include <limits>
|
|
#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;
|
|
|
|
enum class NumberKind : std::uint8_t {
|
|
signed_integer,
|
|
unsigned_integer,
|
|
real
|
|
};
|
|
|
|
struct ConversionError {
|
|
Void::Numeric::Error numeric_error{Void::Numeric::Error::InvalidInput};
|
|
std::string path;
|
|
std::string message;
|
|
};
|
|
|
|
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
|
|
std::int64_t, // signed integer
|
|
std::uint64_t, // unsigned integer
|
|
double, // real
|
|
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} {}
|
|
template <std::signed_integral T>
|
|
requires(!std::same_as<std::remove_cv_t<T>, bool>)
|
|
Value(T n) noexcept : data_{static_cast<std::int64_t>(n)} {}
|
|
template <std::unsigned_integral T>
|
|
requires(!std::same_as<std::remove_cv_t<T>, bool>)
|
|
Value(T n) noexcept : data_{static_cast<std::uint64_t>(n)} {}
|
|
template <std::floating_point T>
|
|
Value(T 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 std::holds_alternative<std::monostate>(data_);
|
|
}
|
|
[[nodiscard]] bool is_bool() const noexcept
|
|
{
|
|
return std::holds_alternative<bool>(data_);
|
|
}
|
|
[[nodiscard]] bool is_int() const noexcept
|
|
{
|
|
return std::holds_alternative<std::int64_t>(data_);
|
|
}
|
|
[[nodiscard]] bool is_uint() const noexcept
|
|
{
|
|
return std::holds_alternative<std::uint64_t>(data_);
|
|
}
|
|
[[nodiscard]] bool is_double() const noexcept
|
|
{
|
|
return std::holds_alternative<double>(data_);
|
|
}
|
|
[[nodiscard]] bool is_integer() const noexcept
|
|
{
|
|
return is_int() || is_uint();
|
|
}
|
|
[[nodiscard]] bool is_number() const noexcept
|
|
{
|
|
return is_int() || is_uint() || is_double();
|
|
}
|
|
[[nodiscard]] std::optional<NumberKind> number_kind() const noexcept
|
|
{
|
|
if (is_int()) return NumberKind::signed_integer;
|
|
if (is_uint()) return NumberKind::unsigned_integer;
|
|
if (is_double()) return NumberKind::real;
|
|
return std::nullopt;
|
|
}
|
|
[[nodiscard]] bool is_string() const noexcept
|
|
{
|
|
return std::holds_alternative<std::string>(data_);
|
|
}
|
|
[[nodiscard]] bool is_array() const noexcept
|
|
{
|
|
return std::holds_alternative<std::unique_ptr<Array_t>>(data_);
|
|
}
|
|
[[nodiscard]] bool is_object() const noexcept
|
|
{
|
|
return std::holds_alternative<std::unique_ptr<Object_t>>(data_);
|
|
}
|
|
|
|
// ── 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
|
|
{
|
|
if (const auto* i = std::get_if<std::int64_t>(&data_)) {
|
|
return static_cast<double>(*i);
|
|
}
|
|
if (const auto* u = std::get_if<std::uint64_t>(&data_)) {
|
|
return static_cast<double>(*u);
|
|
}
|
|
return std::get<double>(data_);
|
|
}
|
|
[[nodiscard]] std::int64_t as_int() const
|
|
{
|
|
if (const auto* i = std::get_if<std::int64_t>(&data_)) {
|
|
return *i;
|
|
}
|
|
if (const auto* u = std::get_if<std::uint64_t>(&data_)) {
|
|
return static_cast<std::int64_t>(*u);
|
|
}
|
|
return static_cast<std::int64_t>(std::get<double>(data_));
|
|
}
|
|
[[nodiscard]] std::uint64_t as_uint() const
|
|
{
|
|
if (const auto* u = std::get_if<std::uint64_t>(&data_)) {
|
|
return *u;
|
|
}
|
|
if (const auto* i = std::get_if<std::int64_t>(&data_)) {
|
|
return static_cast<std::uint64_t>(*i);
|
|
}
|
|
return static_cast<std::uint64_t>(std::get<double>(data_));
|
|
}
|
|
[[nodiscard]] double as_double() const { return 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::int64_t> get_int() const noexcept
|
|
{
|
|
if (const auto* i = std::get_if<std::int64_t>(&data_)) {
|
|
return *i;
|
|
}
|
|
if (const auto* u = std::get_if<std::uint64_t>(&data_)) {
|
|
auto c = Void::Numeric::checked_cast<std::int64_t>(*u);
|
|
return c ? std::optional<std::int64_t>{*c} : std::nullopt;
|
|
}
|
|
if (const auto* d = std::get_if<double>(&data_)) {
|
|
auto c = Void::Numeric::checked_cast<std::int64_t>(
|
|
*d, Void::Numeric::Rounding::exact);
|
|
return c ? std::optional<std::int64_t>{*c} : std::nullopt;
|
|
}
|
|
return {};
|
|
}
|
|
[[nodiscard]] std::optional<std::uint64_t> get_uint() const noexcept
|
|
{
|
|
if (const auto* u = std::get_if<std::uint64_t>(&data_)) {
|
|
return *u;
|
|
}
|
|
if (const auto* i = std::get_if<std::int64_t>(&data_)) {
|
|
auto c = Void::Numeric::checked_cast<std::uint64_t>(*i);
|
|
return c ? std::optional<std::uint64_t>{*c} : std::nullopt;
|
|
}
|
|
if (const auto* d = std::get_if<double>(&data_)) {
|
|
auto c = Void::Numeric::checked_cast<std::uint64_t>(
|
|
*d, Void::Numeric::Rounding::exact);
|
|
return c ? std::optional<std::uint64_t>{*c} : std::nullopt;
|
|
}
|
|
return {};
|
|
}
|
|
[[nodiscard]] std::optional<double> get_double() const noexcept
|
|
{
|
|
return get_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;
|
|
}
|
|
|
|
// ── typed member accessors (safe navigation) ──────────────────
|
|
// Convenience getters for walking dynamic JSON without manual
|
|
// find()+type-check chains. A missing key, or a present key of the
|
|
// wrong type, yields the supplied default (scalars) or nullptr
|
|
// (object/array children) — never throws.
|
|
|
|
[[nodiscard]] bool has(std::string_view key) const noexcept
|
|
{
|
|
return find(key) != nullptr;
|
|
}
|
|
|
|
[[nodiscard]] std::string
|
|
get_str(std::string_view key,
|
|
std::string_view fallback = {}) const
|
|
{
|
|
const Value* c = find(key);
|
|
return (c && c->is_string()) ? c->as_string()
|
|
: std::string{fallback};
|
|
}
|
|
|
|
[[nodiscard]] double get_num(std::string_view key,
|
|
double fallback = 0.0) const noexcept
|
|
{
|
|
const Value* c = find(key);
|
|
return (c && c->is_number()) ? c->as_number() : fallback;
|
|
}
|
|
|
|
[[nodiscard]] bool get_bool(std::string_view key,
|
|
bool fallback = false) const noexcept
|
|
{
|
|
const Value* c = find(key);
|
|
return (c && c->is_bool()) ? c->as_bool() : fallback;
|
|
}
|
|
|
|
// Child only when it exists and is an object; else nullptr.
|
|
[[nodiscard]] const Value*
|
|
child_object(std::string_view key) const noexcept
|
|
{
|
|
const Value* c = find(key);
|
|
return (c && c->is_object()) ? c : nullptr;
|
|
}
|
|
|
|
// Child only when it exists and is an array; else nullptr.
|
|
[[nodiscard]] const Value*
|
|
child_array(std::string_view key) const noexcept
|
|
{
|
|
const Value* c = find(key);
|
|
return (c && c->is_array()) ? c : nullptr;
|
|
}
|
|
|
|
// ── JSON Pointer (RFC 6901) query
|
|
// ───────────────────────────────────────── at("/a/b/0") walks
|
|
// object keys and array indices. Returns nullptr if any step is
|
|
// missing or type-mismatched. The empty pointer "" yields the whole
|
|
// document. Tokens unescape "~1" -> '/' and "~0" -> '~'.
|
|
[[nodiscard]] const Value*
|
|
at(std::string_view pointer) const noexcept
|
|
{
|
|
const Value* cur = this;
|
|
if (pointer.empty()) {
|
|
return cur;
|
|
}
|
|
if (pointer.front() != '/') {
|
|
return nullptr;
|
|
}
|
|
std::size_t pos = 1;
|
|
for (;;) {
|
|
const std::size_t slash = pointer.find('/', pos);
|
|
const std::string_view raw =
|
|
pointer.substr(pos, slash == std::string_view::npos
|
|
? std::string_view::npos
|
|
: slash - pos);
|
|
std::string token;
|
|
token.reserve(raw.size());
|
|
for (std::size_t i = 0; i < raw.size(); ++i) {
|
|
if (raw[i] == '~' && i + 1 < raw.size()) {
|
|
if (raw[i + 1] == '1') {
|
|
token += '/';
|
|
++i;
|
|
continue;
|
|
}
|
|
if (raw[i + 1] == '0') {
|
|
token += '~';
|
|
++i;
|
|
continue;
|
|
}
|
|
}
|
|
token += raw[i];
|
|
}
|
|
if (cur->is_object()) {
|
|
cur = cur->find(token);
|
|
if (!cur) {
|
|
return nullptr;
|
|
}
|
|
} else if (cur->is_array()) {
|
|
std::size_t idx = 0;
|
|
const char* b = token.data();
|
|
const char* e = b + token.size();
|
|
const auto [p, ec] = std::from_chars(b, e, idx);
|
|
if (ec != std::errc{} || p != e ||
|
|
idx >= cur->as_array().size()) {
|
|
return nullptr;
|
|
}
|
|
cur = &cur->as_array()[idx];
|
|
} else {
|
|
return nullptr;
|
|
}
|
|
if (slash == std::string_view::npos) {
|
|
break;
|
|
}
|
|
pos = slash + 1;
|
|
}
|
|
return cur;
|
|
}
|
|
|
|
[[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; }
|
|
|
|
private:
|
|
|
|
static bool numeric_equals(const Value& a, const Value& b) noexcept
|
|
{
|
|
if (a.is_int()) {
|
|
if (b.is_int()) return a.as_int() == b.as_int();
|
|
if (b.is_uint()) {
|
|
return a.as_int() >= 0 &&
|
|
static_cast<std::uint64_t>(a.as_int()) == b.as_uint();
|
|
}
|
|
const auto c = Void::Numeric::checked_cast<std::int64_t>(
|
|
b.as_double(), Void::Numeric::Rounding::exact);
|
|
return c.has_value() && *c == a.as_int();
|
|
}
|
|
if (a.is_uint()) {
|
|
if (b.is_uint()) return a.as_uint() == b.as_uint();
|
|
if (b.is_int()) return numeric_equals(b, a);
|
|
const auto c = Void::Numeric::checked_cast<std::uint64_t>(
|
|
b.as_double(), Void::Numeric::Rounding::exact);
|
|
return c.has_value() && *c == a.as_uint();
|
|
}
|
|
if (b.is_double()) {
|
|
return a.as_double() == b.as_double();
|
|
}
|
|
return numeric_equals(b, a);
|
|
}
|
|
|
|
public:
|
|
|
|
[[nodiscard]] bool operator==(const Value& o) const noexcept
|
|
{
|
|
if (is_number() && o.is_number()) {
|
|
return numeric_equals(*this, o);
|
|
}
|
|
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();
|
|
}
|
|
if (is_null()) {
|
|
return true;
|
|
}
|
|
if (is_bool()) {
|
|
return as_bool() == o.as_bool();
|
|
}
|
|
if (is_string()) {
|
|
return as_string() == o.as_string();
|
|
}
|
|
return false;
|
|
}
|
|
};
|
|
|
|
template <Void::Numeric::ArithmeticScalar T>
|
|
[[nodiscard]] inline std::expected<T, ConversionError>
|
|
number_as(const Value& v,
|
|
Void::Numeric::Rounding mode = Void::Numeric::Rounding::exact,
|
|
std::string_view path = {})
|
|
{
|
|
auto make_conv_err = [&](Void::Numeric::Error e) {
|
|
return std::unexpected{ConversionError{
|
|
e,
|
|
std::string{path},
|
|
"Json::number_as: " + std::string{Void::Numeric::to_string(e)}}};
|
|
};
|
|
if (v.is_int()) {
|
|
auto r = Void::Numeric::checked_cast<T>(v.as_int(), mode);
|
|
if (!r) return make_conv_err(r.error());
|
|
return *r;
|
|
}
|
|
if (v.is_uint()) {
|
|
auto r = Void::Numeric::checked_cast<T>(v.as_uint(), mode);
|
|
if (!r) return make_conv_err(r.error());
|
|
return *r;
|
|
}
|
|
if (v.is_double()) {
|
|
auto r = Void::Numeric::checked_cast<T>(v.as_double(), mode);
|
|
if (!r) return make_conv_err(r.error());
|
|
return *r;
|
|
}
|
|
return make_conv_err(Void::Numeric::Error::InvalidInput);
|
|
}
|
|
|
|
// ── 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;
|
|
const bool neg = (peek() == '-');
|
|
if (neg) {
|
|
advance();
|
|
}
|
|
if (peek() == '0') {
|
|
advance();
|
|
if (peek() >= '0' && peek() <= '9') {
|
|
return std::unexpected{
|
|
err("leading zero in numeric literal")};
|
|
}
|
|
} else if (peek() >= '1' && peek() <= '9') {
|
|
advance();
|
|
while (peek() >= '0' && peek() <= '9') {
|
|
advance();
|
|
}
|
|
} else {
|
|
return std::unexpected{err("expected digit in number")};
|
|
}
|
|
|
|
bool is_real = false;
|
|
if (peek() == '.') {
|
|
is_real = true;
|
|
advance();
|
|
if (!(peek() >= '0' && peek() <= '9')) {
|
|
return std::unexpected{
|
|
err("expected digits after '.'")};
|
|
}
|
|
while (peek() >= '0' && peek() <= '9') {
|
|
advance();
|
|
}
|
|
}
|
|
if (peek() == 'e' || peek() == 'E') {
|
|
is_real = true;
|
|
advance();
|
|
if (peek() == '+' || peek() == '-') {
|
|
advance();
|
|
}
|
|
if (!(peek() >= '0' && peek() <= '9')) {
|
|
return std::unexpected{
|
|
err("expected exponent digits")};
|
|
}
|
|
while (peek() >= '0' && peek() <= '9') {
|
|
advance();
|
|
}
|
|
}
|
|
|
|
const std::string_view raw = src.substr(start, pos - start);
|
|
if (raw.size() > Void::Numeric::kMaxNumericTokenBytes) {
|
|
return std::unexpected{
|
|
err("numeric literal exceeds 256 bytes")};
|
|
}
|
|
if (is_real) {
|
|
const auto r = Void::Numeric::parse_real<double>(raw);
|
|
if (!r) {
|
|
return std::unexpected{
|
|
err("invalid or out-of-range real: " +
|
|
std::string{raw})};
|
|
}
|
|
return Value{*r};
|
|
}
|
|
if (neg) {
|
|
if (raw == "-0") {
|
|
return Value{std::int64_t{0}};
|
|
}
|
|
const auto r =
|
|
Void::Numeric::parse_integer<std::int64_t>(raw);
|
|
if (!r) {
|
|
return std::unexpected{
|
|
err("signed integer out of range: " +
|
|
std::string{raw})};
|
|
}
|
|
return Value{*r};
|
|
}
|
|
if (const auto s =
|
|
Void::Numeric::parse_integer<std::int64_t>(raw)) {
|
|
return Value{*s};
|
|
}
|
|
if (const auto u =
|
|
Void::Numeric::parse_integer<std::uint64_t>(raw)) {
|
|
return Value{*u};
|
|
}
|
|
return std::unexpected{
|
|
err("unsigned integer out of range: " +
|
|
std::string{raw})};
|
|
}
|
|
|
|
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':
|
|
{
|
|
auto read_hex4 =
|
|
[&](std::size_t at,
|
|
unsigned& out_cp) -> bool {
|
|
if (at + 4 > src.size()) {
|
|
return false;
|
|
}
|
|
const auto h = src.substr(at, 4);
|
|
const auto [p, e] = std::from_chars(
|
|
h.data(), h.data() + 4, out_cp, 16);
|
|
return e == std::errc{} &&
|
|
p == h.data() + 4;
|
|
};
|
|
|
|
unsigned cp = 0;
|
|
if (!read_hex4(pos, cp)) {
|
|
return std::unexpected{
|
|
err("invalid \\uXXXX escape")};
|
|
}
|
|
for (std::size_t i = 0; i < 4; ++i) {
|
|
advance();
|
|
}
|
|
|
|
// Combine a UTF-16 surrogate pair
|
|
// (\uD800-\uDBFF followed by \uDC00-\uDFFF)
|
|
// into one code point, so astral characters
|
|
// (emoji, …) become valid 4-byte UTF-8
|
|
// instead of two invalid encoded
|
|
// surrogates.
|
|
if (cp >= 0xD800 && cp <= 0xDBFF) {
|
|
unsigned lo = 0;
|
|
if (pos + 1 < src.size() &&
|
|
src[pos] == '\\' &&
|
|
src[pos + 1] == 'u' &&
|
|
read_hex4(pos + 2, lo) &&
|
|
lo >= 0xDC00 && lo <= 0xDFFF) {
|
|
cp = 0x10000u +
|
|
((cp - 0xD800u) << 10) +
|
|
(lo - 0xDC00u);
|
|
for (std::size_t i = 0; i < 6;
|
|
++i) {
|
|
advance();
|
|
}
|
|
}
|
|
// A lone surrogate falls through and is
|
|
// encoded as-is.
|
|
}
|
|
|
|
// 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 if (cp < 0x10000) {
|
|
out += static_cast<char>(0xE0 |
|
|
(cp >> 12));
|
|
out += static_cast<char>(
|
|
0x80 | ((cp >> 6) & 0x3F));
|
|
out += static_cast<char>(0x80 |
|
|
(cp & 0x3F));
|
|
} else {
|
|
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));
|
|
}
|
|
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;
|
|
}
|
|
|
|
// ── streaming (SAX) parse
|
|
// ────────────────────────────────────────────────────── Event-callback
|
|
// parser for large inputs: fires callbacks as tokens are scanned rather
|
|
// than building a DOM. Any unset callback is skipped. Returns a ParseError
|
|
// on malformed input, or nullopt on success.
|
|
|
|
struct SaxHandler {
|
|
std::function<void()> on_null;
|
|
std::function<void(bool)> on_bool;
|
|
std::function<void(double)> on_number;
|
|
std::function<void(std::string_view)> on_string;
|
|
std::function<void(std::string_view)> on_key;
|
|
std::function<void()> on_object_begin;
|
|
std::function<void()> on_object_end;
|
|
std::function<void()> on_array_begin;
|
|
std::function<void()> on_array_end;
|
|
std::function<void(std::int64_t)> on_int{};
|
|
std::function<void(std::uint64_t)> on_uint{};
|
|
};
|
|
|
|
namespace Detail
|
|
{
|
|
|
|
// Drives the existing Parser's primitives, emitting events instead of a
|
|
// Value.
|
|
struct SaxDriver {
|
|
Parser p;
|
|
const SaxHandler& h;
|
|
|
|
std::optional<ParseError> value()
|
|
{
|
|
p.skip_ws();
|
|
if (p.at_end()) {
|
|
return p.err("unexpected end of input");
|
|
}
|
|
const char c = p.peek();
|
|
if (c == '{') {
|
|
return object();
|
|
}
|
|
if (c == '[') {
|
|
return array();
|
|
}
|
|
if (c == '"') {
|
|
auto s = p.parse_string_raw();
|
|
if (!s) {
|
|
return s.error();
|
|
}
|
|
if (h.on_string) {
|
|
h.on_string(*s);
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
if (c == 'n') {
|
|
if (!p.match("null")) {
|
|
return p.err("expected 'null'");
|
|
}
|
|
if (h.on_null) {
|
|
h.on_null();
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
if (c == 't') {
|
|
if (!p.match("true")) {
|
|
return p.err("expected 'true'");
|
|
}
|
|
if (h.on_bool) {
|
|
h.on_bool(true);
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
if (c == 'f') {
|
|
if (!p.match("false")) {
|
|
return p.err("expected 'false'");
|
|
}
|
|
if (h.on_bool) {
|
|
h.on_bool(false);
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
if (c == '-' || (c >= '0' && c <= '9')) {
|
|
auto v = p.parse_number();
|
|
if (!v) {
|
|
return v.error();
|
|
}
|
|
if (v->is_int() && h.on_int) {
|
|
h.on_int(v->as_int());
|
|
} else if (v->is_uint() && h.on_uint) {
|
|
h.on_uint(v->as_uint());
|
|
} else if (h.on_number) {
|
|
h.on_number(v->as_number());
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
return p.err(std::string{"unexpected character '"} + c +
|
|
"'");
|
|
}
|
|
|
|
std::optional<ParseError> array()
|
|
{
|
|
p.advance(); // '['
|
|
if (h.on_array_begin) {
|
|
h.on_array_begin();
|
|
}
|
|
p.skip_ws();
|
|
if (p.peek() == ']') {
|
|
p.advance();
|
|
if (h.on_array_end) {
|
|
h.on_array_end();
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
for (;;) {
|
|
if (auto e = value()) {
|
|
return e;
|
|
}
|
|
p.skip_ws();
|
|
if (p.peek() == ']') {
|
|
p.advance();
|
|
break;
|
|
}
|
|
if (p.peek() != ',') {
|
|
return p.err("expected ',' or ']' in array");
|
|
}
|
|
p.advance();
|
|
}
|
|
if (h.on_array_end) {
|
|
h.on_array_end();
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
|
|
std::optional<ParseError> object()
|
|
{
|
|
p.advance(); // '{'
|
|
if (h.on_object_begin) {
|
|
h.on_object_begin();
|
|
}
|
|
p.skip_ws();
|
|
if (p.peek() == '}') {
|
|
p.advance();
|
|
if (h.on_object_end) {
|
|
h.on_object_end();
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
for (;;) {
|
|
p.skip_ws();
|
|
auto key = p.parse_string_raw();
|
|
if (!key) {
|
|
return key.error();
|
|
}
|
|
if (h.on_key) {
|
|
h.on_key(*key);
|
|
}
|
|
p.skip_ws();
|
|
if (p.peek() != ':') {
|
|
return p.err("expected ':' after object key");
|
|
}
|
|
p.advance();
|
|
if (auto e = value()) {
|
|
return e;
|
|
}
|
|
p.skip_ws();
|
|
if (p.peek() == '}') {
|
|
p.advance();
|
|
break;
|
|
}
|
|
if (p.peek() != ',') {
|
|
return p.err("expected ',' or '}' in object");
|
|
}
|
|
p.advance();
|
|
}
|
|
if (h.on_object_end) {
|
|
h.on_object_end();
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
};
|
|
|
|
} // namespace Detail
|
|
|
|
[[nodiscard]] inline std::optional<ParseError>
|
|
parse_sax(std::string_view json, const SaxHandler& handler)
|
|
{
|
|
Detail::SaxDriver d{Detail::Parser{json}, handler};
|
|
if (auto e = d.value()) {
|
|
return e;
|
|
}
|
|
d.p.skip_ws();
|
|
if (!d.p.at_end()) {
|
|
return d.p.err("trailing characters after JSON value");
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
|
|
// ── 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 char value : s) {
|
|
const auto c = static_cast<unsigned char>(value);
|
|
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_int()) {
|
|
char buf[32];
|
|
const auto [ptr, ec] =
|
|
std::to_chars(buf, buf + sizeof(buf), v.as_int());
|
|
if (ec == std::errc{}) {
|
|
out.append(buf, ptr);
|
|
}
|
|
return;
|
|
}
|
|
if (v.is_uint()) {
|
|
char buf[32];
|
|
const auto [ptr, ec] =
|
|
std::to_chars(buf, buf + sizeof(buf), v.as_uint());
|
|
if (ec == std::errc{}) {
|
|
out.append(buf, ptr);
|
|
}
|
|
return;
|
|
}
|
|
if (v.is_double()) {
|
|
const double n = v.as_double();
|
|
if (n == 0.0 && std::signbit(n)) {
|
|
out += "-0.0";
|
|
} else if (std::isfinite(n) && 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
|
|
|
|
namespace Detail
|
|
{
|
|
inline std::optional<ConversionError>
|
|
validate_finite(const Value& v, std::string& path)
|
|
{
|
|
if (v.is_double() && !std::isfinite(v.as_double())) {
|
|
return ConversionError{
|
|
Void::Numeric::Error::NonFinite,
|
|
path,
|
|
"Json::try_serialize: non-finite floating value"};
|
|
}
|
|
if (v.is_array()) {
|
|
const auto& arr = v.as_array();
|
|
const std::size_t saved = path.size();
|
|
for (std::size_t i = 0; i < arr.size(); ++i) {
|
|
path.resize(saved);
|
|
path += '[';
|
|
path += std::to_string(i);
|
|
path += ']';
|
|
if (auto e = validate_finite(arr[i], path)) {
|
|
return e;
|
|
}
|
|
}
|
|
path.resize(saved);
|
|
} else if (v.is_object()) {
|
|
const auto& obj = v.as_object();
|
|
const std::size_t saved = path.size();
|
|
for (const auto& [k, val] : obj) {
|
|
path.resize(saved);
|
|
if (!path.empty()) {
|
|
path += '.';
|
|
}
|
|
path += k;
|
|
if (auto e = validate_finite(val, path)) {
|
|
return e;
|
|
}
|
|
}
|
|
path.resize(saved);
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
} // namespace Detail
|
|
|
|
[[nodiscard]] inline std::string serialize(const Value& v,
|
|
SerializeOptions opts = {})
|
|
{
|
|
std::string out;
|
|
Detail::serialize_impl(out, v, opts, 0);
|
|
return out;
|
|
}
|
|
|
|
[[nodiscard]] inline std::expected<std::string, ConversionError>
|
|
try_serialize(const Value& v, SerializeOptions opts = {})
|
|
{
|
|
std::string path;
|
|
if (auto err = Detail::validate_finite(v, path)) {
|
|
return std::unexpected{std::move(*err)};
|
|
}
|
|
return serialize(v, opts);
|
|
}
|
|
|
|
} // namespace Void::Json
|