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
968 lines
26 KiB
C++
968 lines
26 KiB
C++
#pragma once
|
|
|
|
#include <array>
|
|
#include <charconv>
|
|
#include <cmath>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <expected>
|
|
#include <limits>
|
|
#include <map>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <utility>
|
|
#include <variant>
|
|
#include <vector>
|
|
|
|
namespace Void::Json::Strict
|
|
{
|
|
inline constexpr std::size_t default_maximum_depth{64U};
|
|
|
|
struct ParseOptions {
|
|
std::size_t maximumDepth{default_maximum_depth};
|
|
bool allowDecimals{true};
|
|
};
|
|
|
|
struct ParseError {
|
|
std::size_t offset{};
|
|
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, 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 {
|
|
ParseError error;
|
|
};
|
|
|
|
[[nodiscard]] constexpr std::size_t
|
|
validate_utf8_at(const std::string_view input,
|
|
const std::size_t pos) noexcept
|
|
{
|
|
if (pos >= input.size()) {
|
|
return 0U;
|
|
}
|
|
const auto b0 = static_cast<unsigned char>(input[pos]);
|
|
if (b0 <= 0x7FU) {
|
|
return 1U;
|
|
}
|
|
if (b0 >= 0xC2U && b0 <= 0xDFU) {
|
|
if (pos + 1U >= input.size()) {
|
|
return 0U;
|
|
}
|
|
const auto b1 = static_cast<unsigned char>(input[pos + 1U]);
|
|
return (b1 >= 0x80U && b1 <= 0xBFU) ? 2U : 0U;
|
|
}
|
|
if (b0 >= 0xE0U && b0 <= 0xEFU) {
|
|
if (pos + 2U >= input.size()) {
|
|
return 0U;
|
|
}
|
|
const auto b1 = static_cast<unsigned char>(input[pos + 1U]);
|
|
const auto b2 = static_cast<unsigned char>(input[pos + 2U]);
|
|
const unsigned char lo = (b0 == 0xE0U) ? 0xA0U : 0x80U;
|
|
const unsigned char hi = (b0 == 0xEDU) ? 0x9FU : 0xBFU;
|
|
if (b1 < lo || b1 > hi || b2 < 0x80U || b2 > 0xBFU) {
|
|
return 0U;
|
|
}
|
|
return 3U;
|
|
}
|
|
if (b0 >= 0xF0U && b0 <= 0xF4U) {
|
|
if (pos + 3U >= input.size()) {
|
|
return 0U;
|
|
}
|
|
const auto b1 = static_cast<unsigned char>(input[pos + 1U]);
|
|
const auto b2 = static_cast<unsigned char>(input[pos + 2U]);
|
|
const auto b3 = static_cast<unsigned char>(input[pos + 3U]);
|
|
const unsigned char lo = (b0 == 0xF0U) ? 0x90U : 0x80U;
|
|
const unsigned char hi = (b0 == 0xF4U) ? 0x8FU : 0xBFU;
|
|
if (b1 < lo || b1 > hi || b2 < 0x80U || b2 > 0xBFU ||
|
|
b3 < 0x80U || b3 > 0xBFU) {
|
|
return 0U;
|
|
}
|
|
return 4U;
|
|
}
|
|
return 0U;
|
|
}
|
|
|
|
[[nodiscard]] inline std::expected<void, ParseError>
|
|
validate_utf8_bytes(const std::string_view input)
|
|
{
|
|
std::size_t pos = 0U;
|
|
while (pos < input.size()) {
|
|
const std::size_t len = validate_utf8_at(input, pos);
|
|
if (len == 0U) {
|
|
return std::unexpected{ParseError{
|
|
.offset = pos,
|
|
.message = "invalid UTF-8 sequence",
|
|
}};
|
|
}
|
|
pos += len;
|
|
}
|
|
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:
|
|
|
|
explicit Parser(const std::string_view input,
|
|
const ParseOptions options)
|
|
: input_{input}, options_{options}
|
|
{
|
|
}
|
|
|
|
[[nodiscard]] Value parse()
|
|
{
|
|
skipWhitespace();
|
|
Value result = parseValue(0U);
|
|
skipWhitespace();
|
|
if (position_ != input_.size()) {
|
|
fail("trailing data");
|
|
}
|
|
return result;
|
|
}
|
|
|
|
private:
|
|
|
|
[[noreturn]] void fail(const std::string_view message) const
|
|
{
|
|
throw ParseFailure{
|
|
.error =
|
|
{
|
|
.offset = position_,
|
|
.message = std::string{message},
|
|
},
|
|
};
|
|
}
|
|
|
|
void skipWhitespace()
|
|
{
|
|
while (position_ < input_.size() &&
|
|
(input_[position_] == ' ' ||
|
|
input_[position_] == '\t' ||
|
|
input_[position_] == '\r' ||
|
|
input_[position_] == '\n')) {
|
|
++position_;
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] char take()
|
|
{
|
|
if (position_ >= input_.size()) {
|
|
fail("unexpected end of input");
|
|
}
|
|
return input_[position_++];
|
|
}
|
|
|
|
void expect(const char expected)
|
|
{
|
|
if (take() != expected) {
|
|
fail("unexpected character");
|
|
}
|
|
}
|
|
|
|
void expectLiteral(const std::string_view literal)
|
|
{
|
|
if (input_.substr(position_, literal.size()) != literal) {
|
|
fail("invalid literal");
|
|
}
|
|
position_ += literal.size();
|
|
}
|
|
|
|
[[nodiscard]] static int hexValue(const char value)
|
|
{
|
|
if (value >= '0' && value <= '9') {
|
|
return value - '0';
|
|
}
|
|
if (value >= 'a' && value <= 'f') {
|
|
return value - 'a' + 10;
|
|
}
|
|
if (value >= 'A' && value <= 'F') {
|
|
return value - 'A' + 10;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
[[nodiscard]] std::uint32_t unicodeEscape()
|
|
{
|
|
std::uint32_t value{};
|
|
for (int index{}; index < 4; ++index) {
|
|
const int digit = hexValue(take());
|
|
if (digit < 0) {
|
|
fail("invalid unicode escape");
|
|
}
|
|
value = value * 16U + static_cast<std::uint32_t>(digit);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
static void appendUtf8(std::string& output,
|
|
const std::uint32_t codepoint)
|
|
{
|
|
if (codepoint <= 0x7FU) {
|
|
output.push_back(static_cast<char>(codepoint));
|
|
} else if (codepoint <= 0x7FFU) {
|
|
output.push_back(
|
|
static_cast<char>(0xC0U | (codepoint >> 6U)));
|
|
output.push_back(
|
|
static_cast<char>(0x80U | (codepoint & 0x3FU)));
|
|
} else if (codepoint <= 0xFFFFU) {
|
|
output.push_back(
|
|
static_cast<char>(0xE0U | (codepoint >> 12U)));
|
|
output.push_back(static_cast<char>(
|
|
0x80U | ((codepoint >> 6U) & 0x3FU)));
|
|
output.push_back(
|
|
static_cast<char>(0x80U | (codepoint & 0x3FU)));
|
|
} else {
|
|
output.push_back(
|
|
static_cast<char>(0xF0U | (codepoint >> 18U)));
|
|
output.push_back(static_cast<char>(
|
|
0x80U | ((codepoint >> 12U) & 0x3FU)));
|
|
output.push_back(static_cast<char>(
|
|
0x80U | ((codepoint >> 6U) & 0x3FU)));
|
|
output.push_back(
|
|
static_cast<char>(0x80U | (codepoint & 0x3FU)));
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] std::string parseString()
|
|
{
|
|
expect('"');
|
|
std::string output;
|
|
while (true) {
|
|
const unsigned char value =
|
|
static_cast<unsigned char>(take());
|
|
if (value == '"') {
|
|
return output;
|
|
}
|
|
if (value < 0x20U) {
|
|
fail("control character in string");
|
|
}
|
|
if (value != '\\') {
|
|
if (value >= 0x80U) {
|
|
const std::size_t seq_start = position_ - 1U;
|
|
const std::size_t len =
|
|
validate_utf8_at(input_, seq_start);
|
|
if (len == 0U) {
|
|
position_ = seq_start;
|
|
fail("invalid UTF-8 sequence");
|
|
}
|
|
output.append(input_.substr(seq_start, len));
|
|
position_ = seq_start + len;
|
|
continue;
|
|
}
|
|
output.push_back(static_cast<char>(value));
|
|
continue;
|
|
}
|
|
switch (take()) {
|
|
case '"':
|
|
output.push_back('"');
|
|
break;
|
|
case '\\':
|
|
output.push_back('\\');
|
|
break;
|
|
case '/':
|
|
output.push_back('/');
|
|
break;
|
|
case 'b':
|
|
output.push_back('\b');
|
|
break;
|
|
case 'f':
|
|
output.push_back('\f');
|
|
break;
|
|
case 'n':
|
|
output.push_back('\n');
|
|
break;
|
|
case 'r':
|
|
output.push_back('\r');
|
|
break;
|
|
case 't':
|
|
output.push_back('\t');
|
|
break;
|
|
case 'u':
|
|
{
|
|
std::uint32_t codepoint = unicodeEscape();
|
|
if (codepoint >= 0xD800U &&
|
|
codepoint <= 0xDBFFU) {
|
|
if (take() != '\\' || take() != 'u') {
|
|
fail("missing low surrogate");
|
|
}
|
|
const std::uint32_t low =
|
|
unicodeEscape();
|
|
if (low < 0xDC00U || low > 0xDFFFU) {
|
|
fail("invalid low surrogate");
|
|
}
|
|
codepoint =
|
|
0x10000U +
|
|
((codepoint - 0xD800U) << 10U) +
|
|
low - 0xDC00U;
|
|
} else if (codepoint >= 0xDC00U &&
|
|
codepoint <= 0xDFFFU) {
|
|
fail("unexpected low surrogate");
|
|
}
|
|
appendUtf8(output, codepoint);
|
|
break;
|
|
}
|
|
default:
|
|
fail("invalid string escape");
|
|
}
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] static bool isDigit(const char ch) noexcept
|
|
{
|
|
return ch >= '0' && ch <= '9';
|
|
}
|
|
|
|
[[nodiscard]] std::size_t consumeDigits() noexcept
|
|
{
|
|
const std::size_t begin = position_;
|
|
while (position_ < input_.size() &&
|
|
isDigit(input_[position_])) {
|
|
++position_;
|
|
}
|
|
return position_ - begin;
|
|
}
|
|
|
|
[[nodiscard]] Value parseNumber()
|
|
{
|
|
const std::size_t start = position_;
|
|
if (input_[position_] == '-') {
|
|
++position_;
|
|
}
|
|
if (position_ >= input_.size()) {
|
|
fail("incomplete number");
|
|
}
|
|
if (input_[position_] == '0') {
|
|
++position_;
|
|
if (position_ < input_.size() &&
|
|
isDigit(input_[position_])) {
|
|
fail("leading zero in number");
|
|
}
|
|
} else {
|
|
if (input_[position_] < '1' ||
|
|
input_[position_] > '9') {
|
|
fail("invalid number");
|
|
}
|
|
static_cast<void>(consumeDigits());
|
|
}
|
|
bool isDecimal = false;
|
|
if (position_ < input_.size() && input_[position_] == '.') {
|
|
isDecimal = true;
|
|
++position_;
|
|
if (consumeDigits() == 0U) {
|
|
fail("incomplete fractional part");
|
|
}
|
|
}
|
|
if (position_ < input_.size() &&
|
|
(input_[position_] == 'e' || input_[position_] == 'E')) {
|
|
isDecimal = true;
|
|
++position_;
|
|
if (position_ < input_.size() &&
|
|
(input_[position_] == '+' ||
|
|
input_[position_] == '-')) {
|
|
++position_;
|
|
}
|
|
if (consumeDigits() == 0U) {
|
|
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");
|
|
}
|
|
double value{};
|
|
const auto result = std::from_chars(
|
|
input_.data() + start, input_.data() + position_,
|
|
value, std::chars_format::general);
|
|
// 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_) {
|
|
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)
|
|
{
|
|
expect('[');
|
|
skipWhitespace();
|
|
Value::Array result;
|
|
if (position_ < input_.size() && input_[position_] == ']') {
|
|
++position_;
|
|
return Value{std::move(result)};
|
|
}
|
|
while (true) {
|
|
result.push_back(parseValue(depth + 1U));
|
|
skipWhitespace();
|
|
const char separator = take();
|
|
if (separator == ']') {
|
|
return Value{std::move(result)};
|
|
}
|
|
if (separator != ',') {
|
|
fail("array requires comma or closing bracket");
|
|
}
|
|
skipWhitespace();
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] Value parseObject(const std::size_t depth)
|
|
{
|
|
expect('{');
|
|
skipWhitespace();
|
|
Value::Object result;
|
|
if (position_ < input_.size() && input_[position_] == '}') {
|
|
++position_;
|
|
return Value{std::move(result)};
|
|
}
|
|
while (true) {
|
|
if (position_ >= input_.size() ||
|
|
input_[position_] != '"') {
|
|
fail("object key must be a string");
|
|
}
|
|
std::string key = parseString();
|
|
skipWhitespace();
|
|
expect(':');
|
|
skipWhitespace();
|
|
auto [iterator, inserted] = result.emplace(
|
|
std::move(key), parseValue(depth + 1U));
|
|
static_cast<void>(iterator);
|
|
if (!inserted) {
|
|
fail("duplicate object key");
|
|
}
|
|
skipWhitespace();
|
|
const char separator = take();
|
|
if (separator == '}') {
|
|
return Value{std::move(result)};
|
|
}
|
|
if (separator != ',') {
|
|
fail("object requires comma or closing brace");
|
|
}
|
|
skipWhitespace();
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] Value parseValue(const std::size_t depth)
|
|
{
|
|
if (depth > options_.maximumDepth ||
|
|
position_ >= input_.size()) {
|
|
fail("nesting limit or unexpected end of input");
|
|
}
|
|
switch (input_[position_]) {
|
|
case '{':
|
|
return parseObject(depth);
|
|
case '[':
|
|
return parseArray(depth);
|
|
case '"':
|
|
return Value{parseString()};
|
|
case 't':
|
|
expectLiteral("true");
|
|
return Value{true};
|
|
case 'f':
|
|
expectLiteral("false");
|
|
return Value{false};
|
|
case 'n':
|
|
expectLiteral("null");
|
|
return Value{nullptr};
|
|
default:
|
|
if (input_[position_] == '-' ||
|
|
isDigit(input_[position_])) {
|
|
return parseNumber();
|
|
}
|
|
fail("invalid value");
|
|
}
|
|
}
|
|
|
|
std::string_view input_;
|
|
ParseOptions options_;
|
|
std::size_t position_{};
|
|
};
|
|
} // namespace Detail
|
|
|
|
[[nodiscard]] inline std::expected<Value, ParseError>
|
|
parse(const std::string_view input, const ParseOptions options)
|
|
{
|
|
try {
|
|
return Detail::Parser{input, options}.parse();
|
|
} catch (const Detail::ParseFailure& failure) {
|
|
return std::unexpected{failure.error};
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] inline std::expected<Value, ParseError>
|
|
parse(const std::string_view input,
|
|
const std::size_t maximumDepth = default_maximum_depth)
|
|
{
|
|
return parse(input, ParseOptions{.maximumDepth = maximumDepth,
|
|
.allowDecimals = true});
|
|
}
|
|
|
|
[[nodiscard]] inline bool is_valid_utf8(const std::string_view input) noexcept
|
|
{
|
|
std::size_t pos = 0U;
|
|
while (pos < input.size()) {
|
|
const std::size_t len = Detail::validate_utf8_at(input, pos);
|
|
if (len == 0U) {
|
|
return false;
|
|
}
|
|
pos += len;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
[[nodiscard]] inline std::expected<void, ParseError>
|
|
validate_utf8(const std::string_view input)
|
|
{
|
|
return Detail::validate_utf8_bytes(input);
|
|
}
|
|
|
|
namespace Detail
|
|
{
|
|
inline void append_escaped_string(std::string& out,
|
|
const std::string_view text)
|
|
{
|
|
const auto utf8 = validate_utf8_bytes(text);
|
|
if (!utf8.has_value()) {
|
|
throw ParseFailure{.error = utf8.error()};
|
|
}
|
|
out.push_back('"');
|
|
std::size_t pos = 0U;
|
|
while (pos < text.size()) {
|
|
const auto ch = static_cast<unsigned char>(text[pos]);
|
|
switch (ch) {
|
|
case '"':
|
|
out += "\\\"";
|
|
++pos;
|
|
break;
|
|
case '\\':
|
|
out += "\\\\";
|
|
++pos;
|
|
break;
|
|
case '\b':
|
|
out += "\\b";
|
|
++pos;
|
|
break;
|
|
case '\f':
|
|
out += "\\f";
|
|
++pos;
|
|
break;
|
|
case '\n':
|
|
out += "\\n";
|
|
++pos;
|
|
break;
|
|
case '\r':
|
|
out += "\\r";
|
|
++pos;
|
|
break;
|
|
case '\t':
|
|
out += "\\t";
|
|
++pos;
|
|
break;
|
|
default:
|
|
if (ch < 0x20U) {
|
|
static constexpr char kHex[] = "0123456789abcdef";
|
|
out += "\\u00";
|
|
out.push_back(kHex[(ch >> 4U) & 0x0FU]);
|
|
out.push_back(kHex[ch & 0x0FU]);
|
|
++pos;
|
|
} else if (ch >= 0x80U) {
|
|
const std::size_t len = validate_utf8_at(text, pos);
|
|
out.append(text.substr(pos, len));
|
|
pos += len;
|
|
} else {
|
|
out.push_back(static_cast<char>(ch));
|
|
++pos;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
out.push_back('"');
|
|
}
|
|
|
|
inline void serialize_value(std::string& out, const Value& val,
|
|
const std::size_t depth,
|
|
const std::size_t maximumDepth)
|
|
{
|
|
if (depth > maximumDepth) {
|
|
throw ParseFailure{
|
|
.error =
|
|
{
|
|
.offset = out.size(),
|
|
.message = "nesting limit exceeded during serialize",
|
|
},
|
|
};
|
|
}
|
|
std::visit(
|
|
[&](const auto& node) {
|
|
using T = std::decay_t<decltype(node)>;
|
|
if constexpr (std::same_as<T, std::nullptr_t>) {
|
|
out += "null";
|
|
} else if constexpr (std::same_as<T, bool>) {
|
|
out += (node ? "true" : "false");
|
|
} else if constexpr (std::same_as<T, std::int64_t>) {
|
|
std::array<char, 32> buf{};
|
|
const auto res = std::to_chars(
|
|
buf.data(), buf.data() + buf.size(), node);
|
|
out.append(buf.data(), res.ptr);
|
|
} else if constexpr (std::same_as<T, double>) {
|
|
if (!std::isfinite(node)) {
|
|
throw ParseFailure{
|
|
.error =
|
|
{
|
|
.offset = out.size(),
|
|
.message =
|
|
"non-finite double is not valid JSON",
|
|
},
|
|
};
|
|
}
|
|
std::array<char, 64> buf{};
|
|
const auto res = std::to_chars(
|
|
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>) {
|
|
out.push_back('[');
|
|
for (std::size_t i = 0; i < node.size(); ++i) {
|
|
if (i > 0U) {
|
|
out.push_back(',');
|
|
}
|
|
serialize_value(out, node[i], depth + 1U,
|
|
maximumDepth);
|
|
}
|
|
out.push_back(']');
|
|
} else if constexpr (std::same_as<T, Value::Object>) {
|
|
out.push_back('{');
|
|
bool first = true;
|
|
for (const auto& [k, v] : node) {
|
|
if (!first) {
|
|
out.push_back(',');
|
|
}
|
|
first = false;
|
|
append_escaped_string(out, k);
|
|
out.push_back(':');
|
|
serialize_value(out, v, depth + 1U, maximumDepth);
|
|
}
|
|
out.push_back('}');
|
|
}
|
|
},
|
|
val.value);
|
|
}
|
|
} // namespace Detail
|
|
|
|
[[nodiscard]] inline std::expected<std::string, ParseError>
|
|
serialize(const Value& value,
|
|
const std::size_t maximumDepth = default_maximum_depth)
|
|
{
|
|
try {
|
|
std::string out;
|
|
Detail::serialize_value(out, value, 0U, maximumDepth);
|
|
return out;
|
|
} catch (const Detail::ParseFailure& failure) {
|
|
return std::unexpected{failure.error};
|
|
}
|
|
}
|
|
|
|
} // namespace Void::Json::Strict
|