Data: keep exact JSON number lexemes and accept out-of-range numbers
StrictJson now preserves numbers that cannot be represented exactly as int64 or double in a Number alternative holding the exact lexeme, integrality, int64 fit and double range state. Grammar-valid numbers such as 2^63, 1e309 and 1e-400 parse instead of failing, decimals such as 1.0000000000000001 no longer collapse to double 1.0, and serialization round-trips the lexeme. Expose as_number/is_integral/is_finite_number and keep allowDecimals for consumers that reject decimals. Closes #60
This commit is contained in:
1 parent
e6745ac8cb
commit
9cb86f8f97
2 files changed
+396
-17
No files matched your search
@@ -6,6 +6,7 @@
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <limits>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
@@ -28,14 +29,71 @@ namespace Void::Json::Strict
|
||||
std::string message;
|
||||
};
|
||||
|
||||
/// A JSON number that cannot be represented exactly as `int64` or
|
||||
/// `double` (out of range, or a decimal whose value is not the shortest
|
||||
/// round-trip form of its `double`). The exact lexeme is preserved so
|
||||
/// integrality, `int64` fit and range can be decided without rounding.
|
||||
struct Number {
|
||||
enum class Range : std::uint8_t {
|
||||
in_range = 0,
|
||||
overflow = 1,
|
||||
underflow = 2
|
||||
};
|
||||
|
||||
std::string lexeme; ///< exact JSON number text
|
||||
bool isInteger{false}; ///< mathematically integral (exact)
|
||||
bool fitsInt64{false}; ///< integer that fits std::int64_t
|
||||
std::int64_t int64Value{0}; ///< valid when fitsInt64
|
||||
Range range{Range::in_range}; ///< double conversion range
|
||||
double approximate{0.0}; ///< nearest double (may be inf/0)
|
||||
};
|
||||
|
||||
struct Value {
|
||||
using Array = std::vector<Value>;
|
||||
using Object = std::map<std::string, Value, std::less<>>;
|
||||
std::variant<std::nullptr_t, bool, std::int64_t, double,
|
||||
std::variant<std::nullptr_t, bool, std::int64_t, double, Number,
|
||||
std::string, Array, Object>
|
||||
value;
|
||||
};
|
||||
|
||||
/// The exact-lexeme alternative, if this value uses it.
|
||||
[[nodiscard]] inline const Number*
|
||||
as_number(const Value& value) noexcept
|
||||
{
|
||||
return std::get_if<Number>(&value.value);
|
||||
}
|
||||
|
||||
/// True when the number is mathematically an integer, decided exactly
|
||||
/// (integers and exact doubles by value, inexact decimals by lexeme).
|
||||
[[nodiscard]] inline bool is_integral(const Value& value) noexcept
|
||||
{
|
||||
if (std::holds_alternative<std::int64_t>(value.value)) {
|
||||
return true;
|
||||
}
|
||||
if (const auto* real = std::get_if<double>(&value.value)) {
|
||||
return std::isfinite(*real) && std::trunc(*real) == *real;
|
||||
}
|
||||
if (const auto* number = std::get_if<Number>(&value.value)) {
|
||||
return number->isInteger;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// True for numbers whose double conversion is finite and in range.
|
||||
[[nodiscard]] inline bool is_finite_number(const Value& value) noexcept
|
||||
{
|
||||
if (std::holds_alternative<std::int64_t>(value.value)) {
|
||||
return true;
|
||||
}
|
||||
if (const auto* real = std::get_if<double>(&value.value)) {
|
||||
return std::isfinite(*real);
|
||||
}
|
||||
if (const auto* number = std::get_if<Number>(&value.value)) {
|
||||
return number->range == Number::Range::in_range;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
struct ParseFailure {
|
||||
@@ -108,6 +166,220 @@ namespace Void::Json::Strict
|
||||
return {};
|
||||
}
|
||||
|
||||
// ── Exact decimal analysis ───────────────────────────────────────────
|
||||
// A JSON number lexeme is normalized to (sign, significant digits,
|
||||
// power-of-ten exponent) so two lexemes can be compared exactly without
|
||||
// converting through a binary floating point value.
|
||||
|
||||
struct NormalizedDecimal {
|
||||
bool negative{false};
|
||||
bool zero{true};
|
||||
std::string digits; ///< no leading or trailing zeros
|
||||
std::int64_t exponent{0}; ///< value = digits * 10^exponent
|
||||
};
|
||||
|
||||
[[nodiscard]] inline std::int64_t
|
||||
saturating_add(const std::int64_t lhs, const std::int64_t rhs) noexcept
|
||||
{
|
||||
constexpr std::int64_t kMax =
|
||||
std::numeric_limits<std::int64_t>::max();
|
||||
constexpr std::int64_t kMin =
|
||||
std::numeric_limits<std::int64_t>::min();
|
||||
if (rhs > 0 && lhs > kMax - rhs) {
|
||||
return kMax;
|
||||
}
|
||||
if (rhs < 0 && lhs < kMin - rhs) {
|
||||
return kMin;
|
||||
}
|
||||
return lhs + rhs;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline NormalizedDecimal
|
||||
normalize_decimal(const std::string_view text)
|
||||
{
|
||||
NormalizedDecimal result;
|
||||
std::size_t pos = 0U;
|
||||
if (pos < text.size() && text[pos] == '-') {
|
||||
result.negative = true;
|
||||
++pos;
|
||||
}
|
||||
std::string digits;
|
||||
std::int64_t exponent = 0;
|
||||
while (pos < text.size() && text[pos] >= '0' && text[pos] <= '9') {
|
||||
digits.push_back(text[pos++]);
|
||||
}
|
||||
if (pos < text.size() && text[pos] == '.') {
|
||||
++pos;
|
||||
const std::size_t fraction_begin = digits.size();
|
||||
while (pos < text.size() && text[pos] >= '0' &&
|
||||
text[pos] <= '9') {
|
||||
digits.push_back(text[pos++]);
|
||||
}
|
||||
const std::size_t fraction_length =
|
||||
digits.size() - fraction_begin;
|
||||
const std::int64_t delta =
|
||||
fraction_length >
|
||||
static_cast<std::size_t>(
|
||||
std::numeric_limits<std::int64_t>::max())
|
||||
? std::numeric_limits<std::int64_t>::min()
|
||||
: -static_cast<std::int64_t>(fraction_length);
|
||||
exponent = saturating_add(exponent, delta);
|
||||
}
|
||||
if (pos < text.size() &&
|
||||
(text[pos] == 'e' || text[pos] == 'E')) {
|
||||
++pos;
|
||||
bool negative_exponent = false;
|
||||
if (pos < text.size() &&
|
||||
(text[pos] == '+' || text[pos] == '-')) {
|
||||
negative_exponent = text[pos] == '-';
|
||||
++pos;
|
||||
}
|
||||
constexpr std::int64_t kExponentCap{1000000000};
|
||||
std::int64_t value = 0;
|
||||
while (pos < text.size() && text[pos] >= '0' &&
|
||||
text[pos] <= '9') {
|
||||
if (value < kExponentCap) {
|
||||
value = value * 10 + (text[pos] - '0');
|
||||
}
|
||||
++pos;
|
||||
}
|
||||
exponent = saturating_add(
|
||||
exponent, negative_exponent ? -value : value);
|
||||
}
|
||||
const std::size_t first = digits.find_first_not_of('0');
|
||||
if (first == std::string::npos) {
|
||||
result.zero = true;
|
||||
return result;
|
||||
}
|
||||
digits.erase(0U, first);
|
||||
const std::size_t last = digits.find_last_not_of('0');
|
||||
const std::int64_t trailing =
|
||||
static_cast<std::int64_t>(digits.size() - 1U - last);
|
||||
digits.erase(last + 1U);
|
||||
exponent = saturating_add(exponent, trailing);
|
||||
result.zero = false;
|
||||
result.digits = std::move(digits);
|
||||
result.exponent = exponent;
|
||||
return result;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline bool
|
||||
same_decimal(const NormalizedDecimal& lhs,
|
||||
const NormalizedDecimal& rhs) noexcept
|
||||
{
|
||||
if (lhs.zero || rhs.zero) {
|
||||
return lhs.zero == rhs.zero;
|
||||
}
|
||||
return lhs.negative == rhs.negative &&
|
||||
lhs.exponent == rhs.exponent && lhs.digits == rhs.digits;
|
||||
}
|
||||
|
||||
// True when `value` is exactly the number spelled by `lexeme` (the
|
||||
// shortest round-trip form comparison).
|
||||
[[nodiscard]] inline bool
|
||||
double_matches_lexeme(const double value,
|
||||
const std::string_view lexeme)
|
||||
{
|
||||
std::array<char, 64> buffer{};
|
||||
const auto result = std::to_chars(
|
||||
buffer.data(), buffer.data() + buffer.size(), value,
|
||||
std::chars_format::general);
|
||||
if (result.ec != std::errc{}) {
|
||||
return false;
|
||||
}
|
||||
const std::string_view text{
|
||||
buffer.data(),
|
||||
static_cast<std::size_t>(result.ptr - buffer.data())};
|
||||
return same_decimal(normalize_decimal(text),
|
||||
normalize_decimal(lexeme));
|
||||
}
|
||||
|
||||
[[nodiscard]] inline bool compute_int64(const NormalizedDecimal& number,
|
||||
std::int64_t& output) noexcept
|
||||
{
|
||||
if (number.zero) {
|
||||
output = 0;
|
||||
return true;
|
||||
}
|
||||
if (number.exponent < 0) {
|
||||
return false;
|
||||
}
|
||||
constexpr std::uint64_t kPositiveLimit = static_cast<std::uint64_t>(
|
||||
std::numeric_limits<std::int64_t>::max());
|
||||
constexpr std::uint64_t kNegativeLimit = kPositiveLimit + 1U;
|
||||
const std::uint64_t limit =
|
||||
number.negative ? kNegativeLimit : kPositiveLimit;
|
||||
std::uint64_t magnitude = 0;
|
||||
for (const char digit : number.digits) {
|
||||
const auto value = static_cast<std::uint64_t>(digit - '0');
|
||||
if (magnitude > (std::numeric_limits<std::uint64_t>::max() -
|
||||
value) /
|
||||
10U) {
|
||||
return false;
|
||||
}
|
||||
magnitude = magnitude * 10U + value;
|
||||
if (magnitude > limit) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (std::int64_t index = 0; index < number.exponent; ++index) {
|
||||
if (magnitude > limit / 10U) {
|
||||
return false;
|
||||
}
|
||||
magnitude *= 10U;
|
||||
if (magnitude > limit) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (number.negative) {
|
||||
output =
|
||||
magnitude == kNegativeLimit
|
||||
? std::numeric_limits<std::int64_t>::min()
|
||||
: -static_cast<std::int64_t>(magnitude);
|
||||
} else {
|
||||
output = static_cast<std::int64_t>(magnitude);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline Number make_number(const std::string_view lexeme)
|
||||
{
|
||||
Number number;
|
||||
number.lexeme = std::string{lexeme};
|
||||
const NormalizedDecimal normalized = normalize_decimal(lexeme);
|
||||
number.isInteger = normalized.zero || normalized.exponent >= 0;
|
||||
number.fitsInt64 = compute_int64(normalized, number.int64Value);
|
||||
|
||||
double approximate{};
|
||||
const auto result = std::from_chars(
|
||||
lexeme.data(), lexeme.data() + lexeme.size(), approximate,
|
||||
std::chars_format::general);
|
||||
if (result.ec == std::errc{} &&
|
||||
result.ptr == lexeme.data() + lexeme.size() &&
|
||||
std::isfinite(approximate)) {
|
||||
number.range = Number::Range::in_range;
|
||||
number.approximate = approximate;
|
||||
return number;
|
||||
}
|
||||
const std::int64_t magnitude_digits = saturating_add(
|
||||
normalized.exponent,
|
||||
static_cast<std::int64_t>(normalized.digits.size()));
|
||||
const bool magnitude_at_least_one =
|
||||
normalized.zero || magnitude_digits > 0;
|
||||
number.range = magnitude_at_least_one
|
||||
? Number::Range::overflow
|
||||
: Number::Range::underflow;
|
||||
if (magnitude_at_least_one) {
|
||||
number.approximate =
|
||||
normalized.negative
|
||||
? -std::numeric_limits<double>::infinity()
|
||||
: std::numeric_limits<double>::infinity();
|
||||
} else {
|
||||
number.approximate = normalized.negative ? -0.0 : 0.0;
|
||||
}
|
||||
return number;
|
||||
}
|
||||
|
||||
class Parser final
|
||||
{
|
||||
public:
|
||||
@@ -374,6 +646,8 @@ namespace Void::Json::Strict
|
||||
fail("incomplete exponent");
|
||||
}
|
||||
}
|
||||
const std::string_view lexeme =
|
||||
input_.substr(start, position_ - start);
|
||||
if (isDecimal) {
|
||||
if (!options_.allowDecimals) {
|
||||
fail("floating-point numbers are not supported");
|
||||
@@ -382,23 +656,28 @@ namespace Void::Json::Strict
|
||||
const auto result = std::from_chars(
|
||||
input_.data() + start, input_.data() + position_,
|
||||
value, std::chars_format::general);
|
||||
if (result.ec != std::errc{} ||
|
||||
result.ptr != input_.data() + position_ ||
|
||||
!std::isfinite(value)) {
|
||||
fail("number is out of range");
|
||||
}
|
||||
// Exact shortest-round-trip decimals stay `double`;
|
||||
// anything the binary value cannot represent exactly
|
||||
// (including overflow and underflow) keeps its lexeme.
|
||||
if (result.ec == std::errc{} &&
|
||||
result.ptr == input_.data() + position_ &&
|
||||
std::isfinite(value) &&
|
||||
double_matches_lexeme(value, lexeme)) {
|
||||
return Value{value};
|
||||
}
|
||||
return Value{make_number(lexeme)};
|
||||
}
|
||||
std::int64_t value{};
|
||||
const auto result =
|
||||
std::from_chars(input_.data() + start,
|
||||
input_.data() + position_, value);
|
||||
if (result.ec != std::errc{} ||
|
||||
result.ptr != input_.data() + position_) {
|
||||
fail("integer is out of range");
|
||||
}
|
||||
if (result.ec == std::errc{} &&
|
||||
result.ptr == input_.data() + position_) {
|
||||
return Value{value};
|
||||
}
|
||||
// Out-of-int64 integers are valid JSON: keep the lexeme.
|
||||
return Value{make_number(lexeme)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Value parseArray(const std::size_t depth)
|
||||
{
|
||||
@@ -637,6 +916,10 @@ namespace Void::Json::Strict
|
||||
buf.data(), buf.data() + buf.size(), node,
|
||||
std::chars_format::general);
|
||||
out.append(buf.data(), res.ptr);
|
||||
} else if constexpr (std::same_as<T, Number>) {
|
||||
// The lexeme was validated by the parser and is always
|
||||
// valid JSON.
|
||||
out += node.lexeme;
|
||||
} else if constexpr (std::same_as<T, std::string>) {
|
||||
append_escaped_string(out, node);
|
||||
} else if constexpr (std::same_as<T, Value::Array>) {
|
||||
|
||||
@@ -39,10 +39,105 @@ Void::Testing::Test strict_json_preserves_signed_64_bit_integers()
|
||||
Void::Testing::expect_eq(
|
||||
std::get<std::int64_t>(object->at("answer").value), std::int64_t{42});
|
||||
|
||||
}
|
||||
|
||||
Void::Testing::Test strict_json_keeps_out_of_int64_integers_as_exact_numbers()
|
||||
{
|
||||
const auto positive = Void::Json::Strict::parse("9223372036854775808");
|
||||
Void::Testing::require(positive.has_value());
|
||||
const auto* number = Void::Json::Strict::as_number(*positive);
|
||||
Void::Testing::require(number != nullptr);
|
||||
Void::Testing::expect_eq(number->lexeme, std::string{"9223372036854775808"});
|
||||
Void::Testing::expect(number->isInteger);
|
||||
Void::Testing::expect(!number->fitsInt64);
|
||||
Void::Testing::expect(number->range == Void::Json::Strict::Number::Range::in_range);
|
||||
Void::Testing::expect(Void::Json::Strict::is_integral(*positive));
|
||||
|
||||
const auto negative = Void::Json::Strict::parse("-9223372036854775809");
|
||||
Void::Testing::require(negative.has_value());
|
||||
const auto* negative_number = Void::Json::Strict::as_number(*negative);
|
||||
Void::Testing::require(negative_number != nullptr);
|
||||
Void::Testing::expect(negative_number->isInteger);
|
||||
Void::Testing::expect(!negative_number->fitsInt64);
|
||||
}
|
||||
|
||||
Void::Testing::Test strict_json_accepts_out_of_double_range_numbers()
|
||||
{
|
||||
const auto tiny = Void::Json::Strict::parse(R"({"n":1e-400})");
|
||||
Void::Testing::require(tiny.has_value());
|
||||
const auto* tiny_object =
|
||||
std::get_if<Void::Json::Strict::Value::Object>(&tiny->value);
|
||||
Void::Testing::require(tiny_object != nullptr);
|
||||
const auto* tiny_number =
|
||||
Void::Json::Strict::as_number(tiny_object->at("n"));
|
||||
Void::Testing::require(tiny_number != nullptr);
|
||||
Void::Testing::expect_eq(tiny_number->lexeme, std::string{"1e-400"});
|
||||
Void::Testing::expect(!tiny_number->isInteger);
|
||||
Void::Testing::expect(tiny_number->range ==
|
||||
Void::Json::Strict::Number::Range::underflow);
|
||||
Void::Testing::expect(
|
||||
!Void::Json::Strict::parse("9223372036854775808").has_value());
|
||||
!Void::Json::Strict::is_finite_number(tiny_object->at("n")));
|
||||
|
||||
for (const std::string_view input : {"1e309", "-1e309"}) {
|
||||
const auto parsed = Void::Json::Strict::parse(input);
|
||||
Void::Testing::require(parsed.has_value());
|
||||
const auto* huge = Void::Json::Strict::as_number(*parsed);
|
||||
Void::Testing::require(huge != nullptr);
|
||||
Void::Testing::expect_eq(huge->lexeme, std::string{input});
|
||||
Void::Testing::expect(huge->range ==
|
||||
Void::Json::Strict::Number::Range::overflow);
|
||||
}
|
||||
|
||||
// allowDecimals still rejects decimal lexemes, in range or not.
|
||||
constexpr Void::Json::Strict::ParseOptions noDecimals{
|
||||
.allowDecimals = false,
|
||||
};
|
||||
Void::Testing::expect(
|
||||
!Void::Json::Strict::parse("-9223372036854775809").has_value());
|
||||
!Void::Json::Strict::parse("1e309", noDecimals).has_value());
|
||||
Void::Testing::expect(
|
||||
!Void::Json::Strict::parse("1e-400", noDecimals).has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test strict_json_decimal_lexemes_keep_exactness()
|
||||
{
|
||||
// A rounded fractional id must not become the integral id 1.
|
||||
const auto rounded = Void::Json::Strict::parse("1.0000000000000001");
|
||||
Void::Testing::require(rounded.has_value());
|
||||
const auto* number = Void::Json::Strict::as_number(*rounded);
|
||||
Void::Testing::require(number != nullptr);
|
||||
Void::Testing::expect_eq(number->lexeme, std::string{"1.0000000000000001"});
|
||||
Void::Testing::expect(!number->isInteger);
|
||||
Void::Testing::expect(!Void::Json::Strict::is_integral(*rounded));
|
||||
|
||||
// Exactly representable decimals stay doubles and are still integral
|
||||
// only when their value is integral.
|
||||
const auto exact = Void::Json::Strict::parse("1.0");
|
||||
Void::Testing::require(exact.has_value());
|
||||
Void::Testing::expect(
|
||||
std::holds_alternative<double>(exact->value));
|
||||
Void::Testing::expect(Void::Json::Strict::is_integral(*exact));
|
||||
|
||||
const auto exponent = Void::Json::Strict::parse("1e2");
|
||||
Void::Testing::require(exponent.has_value());
|
||||
Void::Testing::expect(Void::Json::Strict::is_integral(*exponent));
|
||||
|
||||
const auto fractional = Void::Json::Strict::parse("0.5");
|
||||
Void::Testing::require(fractional.has_value());
|
||||
Void::Testing::expect(!Void::Json::Strict::is_integral(*fractional));
|
||||
}
|
||||
|
||||
Void::Testing::Test strict_json_exact_numbers_round_trip_through_serialize()
|
||||
{
|
||||
constexpr std::array<std::string_view, 4> kInputs{
|
||||
"9223372036854775808", "1e309", "1e-400", "1.0000000000000001",
|
||||
};
|
||||
for (const std::string_view input : kInputs) {
|
||||
const auto parsed = Void::Json::Strict::parse(input);
|
||||
Void::Testing::require(parsed.has_value());
|
||||
const auto serialized = Void::Json::Strict::serialize(*parsed);
|
||||
Void::Testing::require(serialized.has_value());
|
||||
Void::Testing::expect_eq(*serialized, std::string{input});
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test strict_json_rejects_duplicates_floats_when_disabled_and_deep_inputs()
|
||||
@@ -108,11 +203,12 @@ Void::Testing::Test strict_json_parses_lsp_decimals_and_exponents()
|
||||
|
||||
Void::Testing::Test strict_json_rejects_malformed_numbers()
|
||||
{
|
||||
constexpr std::array<std::string_view, 20> kMalformed{
|
||||
"1.", "-0.", ".5", "-.5", "1.e5",
|
||||
"1e", "1e+", "1E-", "1.5e", "01",
|
||||
"01.5", "-01.5", "+1", "+1.5", "1e309",
|
||||
"-1e309", "1e-400", "NaN", "Infinity", "-Infinity",
|
||||
// Out-of-range numbers (1e309, 1e-400) are grammar-valid and accepted;
|
||||
// see strict_json_accepts_out_of_double_range_numbers.
|
||||
constexpr std::array<std::string_view, 17> kMalformed{
|
||||
"1.", "-0.", ".5", "-.5", "1.e5", "1e", "1e+",
|
||||
"1E-", "1.5e", "01", "01.5", "-01.5", "+1", "+1.5",
|
||||
"NaN", "Infinity", "-Infinity",
|
||||
};
|
||||
for (const std::string_view input : kMalformed) {
|
||||
Void::Testing::expect(!Void::Json::Strict::parse(input).has_value());
|
||||
|
||||
Reference in new issue
Block a user