feat(Data): add exact 64-bit signed/unsigned JSON numbers and checked conversion (M-DATA-02)

This commit is contained in:
faumaray committed 2026-11-24 03:25:17 +03:00
1 parent eacb8a4602
commit 692f5ba5b2
6 files changed
+530 -47

No files matched your search

+9 -1
View File
@@ -14,6 +14,7 @@
#include <cctype>
#include <charconv>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <filesystem>
#include <format>
@@ -404,9 +405,16 @@ namespace Void::Configuration
} else if (v.is_bool()) {
cfg.values_.insert_or_assign(prefix, v.as_bool() ? "true"
: "false");
} else if (v.is_int()) {
cfg.values_.insert_or_assign(
prefix, std::to_string(v.as_int()));
} else if (v.is_uint()) {
cfg.values_.insert_or_assign(
prefix, std::to_string(v.as_uint()));
} else if (v.is_number()) {
const double d = v.as_number();
if (d == static_cast<double>(static_cast<long long>(d))) {
if (std::isfinite(d) && !(d == 0.0 && std::signbit(d)) &&
std::floor(d) == d && std::abs(d) < 1e15) {
cfg.values_.insert_or_assign(
prefix, std::to_string(static_cast<long long>(d)));
} else {
+329 -39
View File
@@ -1,10 +1,14 @@
#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>
@@ -23,6 +27,18 @@ namespace Void::Json
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;
@@ -40,7 +56,9 @@ namespace Void::Json
using Data =
std::variant<std::monostate, // null
bool, // bool
double, // number
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
@@ -74,9 +92,14 @@ namespace Void::Json
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)} {}
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}} {}
@@ -101,27 +124,50 @@ namespace Void::Json
// ────────────────────────────────────────────────────────────
[[nodiscard]] bool is_null() const noexcept
{
return data_.index() == 0;
return std::holds_alternative<std::monostate>(data_);
}
[[nodiscard]] bool is_bool() const noexcept
{
return data_.index() == 1;
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 data_.index() == 2;
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 data_.index() == 3;
return std::holds_alternative<std::string>(data_);
}
[[nodiscard]] bool is_array() const noexcept
{
return data_.index() == 4;
return std::holds_alternative<std::unique_ptr<Array_t>>(data_);
}
[[nodiscard]] bool is_object() const noexcept
{
return data_.index() == 5;
return std::holds_alternative<std::unique_ptr<Object_t>>(data_);
}
// ── typed access (throws std::bad_variant_access on wrong type)
@@ -129,12 +175,35 @@ namespace Void::Json
[[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
{
return static_cast<std::int64_t>(as_number());
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_);
@@ -172,6 +241,42 @@ namespace Void::Json
}
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
{
@@ -357,8 +462,40 @@ namespace Void::Json
}
[[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;
}
@@ -368,23 +505,49 @@ namespace Void::Json
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_);
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 = {})
@@ -497,43 +660,90 @@ namespace Void::Json
std::expected<Value, ParseError> parse_number()
{
const std::size_t start = pos;
if (peek() == '-') {
const bool neg = (peek() == '-');
if (neg) {
advance();
}
if (peek() == '0') {
advance();
} else {
while (peek() >= '1' && peek() <= '9') {
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);
double val = 0.0;
const auto [ptr, ec] = std::from_chars(
raw.data(), raw.data() + raw.size(), val);
if (ec != std::errc{}) {
if (raw.size() > Void::Numeric::kMaxNumericTokenBytes) {
return std::unexpected{
err("invalid number: " + std::string{raw})};
err("numeric literal exceeds 256 bytes")};
}
return Value{val};
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()
@@ -780,6 +990,8 @@ namespace Void::Json
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
@@ -846,7 +1058,11 @@ namespace Void::Json
if (!v) {
return v.error();
}
if (h.on_number) {
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;
@@ -1016,9 +1232,30 @@ namespace Void::Json
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) {
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];
@@ -1086,6 +1323,49 @@ namespace Void::Json
} // 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 = {})
{
@@ -1094,4 +1374,14 @@ namespace Void::Json
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
+27 -6
View File
@@ -144,7 +144,9 @@ namespace Void::Json
return Value{static_cast<double>(
static_cast<std::underlying_type_t<T>>(v))};
#endif
} else if constexpr (std::is_arithmetic_v<T>) {
} else if constexpr (std::integral<T>) {
return Value{v};
} else if constexpr (std::floating_point<T>) {
return Value{static_cast<double>(v)};
} else if constexpr (std::same_as<T, std::string>) {
return Value{v};
@@ -287,14 +289,27 @@ namespace Void::Json
return std::unexpected{
ReflectError{"", "expected enum number"}};
}
return static_cast<T>(
static_cast<std::underlying_type_t<T>>(j.as_number()));
auto raw = Void::Json::number_as<std::underlying_type_t<T>>(j);
if (!raw) {
return std::unexpected{
ReflectError{"", std::move(raw.error().message)}};
}
return static_cast<T>(*raw);
#endif
} else if constexpr (std::is_arithmetic_v<T>) {
if (!j.is_number()) {
return std::unexpected{ReflectError{"", "expected number"}};
}
return static_cast<T>(j.as_number());
const auto mode =
(std::floating_point<T> && j.is_double())
? Void::Numeric::Rounding::nearest_even
: Void::Numeric::Rounding::exact;
auto converted = Void::Json::number_as<T>(j, mode);
if (!converted) {
return std::unexpected{
ReflectError{"", std::move(converted.error().message)}};
}
return *converted;
} else if constexpr (std::same_as<T, std::string>) {
if (!j.is_string()) {
return std::unexpected{ReflectError{"", "expected string"}};
@@ -584,7 +599,7 @@ namespace Void::Json
{
auto envelope = object();
envelope.as_object().emplace_back(
"__version", Value{static_cast<double>(StateTraits<T>::version)});
"__version", Value{StateTraits<T>::version});
envelope.as_object().emplace_back("data", to_json(v));
return envelope;
}
@@ -604,7 +619,13 @@ namespace Void::Json
return std::unexpected{
ReflectError{"__version", "malformed versioned envelope"}};
}
const auto from = static_cast<std::uint32_t>(version->as_number());
const auto from_expected =
Void::Json::number_as<std::uint32_t>(*version);
if (!from_expected) {
return std::unexpected{
ReflectError{"__version", "malformed versioned envelope"}};
}
const auto from = *from_expected;
constexpr auto to = StateTraits<T>::version;
if (from > to) {
return std::unexpected{ReflectError{