diff --git a/docs/mkdocs/docs/api/basic_json/dump_canonical.md b/docs/mkdocs/docs/api/basic_json/dump_canonical.md new file mode 100644 index 0000000000..af585a7f89 --- /dev/null +++ b/docs/mkdocs/docs/api/basic_json/dump_canonical.md @@ -0,0 +1,103 @@ +# nlohmann::basic_json::dump_canonical + +```cpp +// (1) +string_t dump_canonical() const; + +// (2) +static void dump_canonical(const basic_json& j, detail::output_adapter o); +``` + +Serialization function for JSON values according to the +**JSON Canonicalization Scheme (JCS, [RFC 8785](https://datatracker.ietf.org/doc/html/rfc8785))**. + +Canonical JSON serialization produces a deterministic, byte-for-byte identical +representation of a JSON document across implementations. This is crucial for +digital signatures, hashing, blockchain protocols, and cryptographic checksums. + +1. Member function: Returns a string containing the canonical serialization + of the JSON value. +2. Static function: Writes the canonical serialization of JSON value `j` directly + into the given output adapter `o` (e.g. `std::string`, `std::ostream`, or + custom output adapter). + +## Parameters + +`j` (in) +: The JSON value to serialize (for overload 2). + +`o` (out) +: The output adapter to write into (for overload 2). + +## Return value + +(1) `string_t` containing the canonical serialization of the JSON value. +(2) none. + +## Exceptions + +- Throws [`out_of_range.406`](../../home/exceptions.md#jsonexceptionout_of_range406) + if a floating-point number is not finite (`NaN` or `Infinity`). +- Throws [`type_error.316`](../../home/exceptions.md#jsonexceptiontype_error316) + if a string is not valid UTF-8. +- Throws [`type_error.317`](../../home/exceptions.md#jsonexceptiontype_error317) + if called on unsupported types (such as binary or discarded). + +## Complexity + +Linear in the size of the JSON document ($O(N \log K)$ where $K$ is the number of +keys in each object due to key sorting). + +## Notes + +The canonical serialization strictly adheres to [RFC 8785](https://datatracker.ietf.org/doc/html/rfc8785): + +- **Whitespace**: No whitespace is added around separators (`:`, `,`). +- **Object Keys**: Object keys are sorted lexicographically by their UTF-16 code units + (RFC 8785 Section 3.2.3). +- **Strings**: Only characters `\"`, `\\`, and control characters `\u0000` through `\u001F` + (`\b`, `\f`, `\n`, `\r`, `\t`, or `\u00XX`) are escaped. Characters U+0020 and above + (including Unicode characters and `/`) are emitted as raw UTF-8 without escaping. +- **Numbers**: Numbers are formatted according to ECMAScript 2019 `Number::toString` + (RFC 8785 Section 3.2.2.3): + - Negative zero (`-0.0`) is formatted as `"0"`. + - No trailing `.0` is emitted for integer values. + - Exponents have no leading zeros (e.g. `1e+21` or `1e-7`). + - Values in range $10^{-6} \le |x| < 10^{21}$ are formatted in plain decimal notation. +- **Unsupported Types**: Non-finite numbers (`NaN`, `Infinity`, `-Infinity`), binary + values, and discarded values cannot be serialized in canonical JSON. + +## Examples + +??? example + + The following example shows the usage of `dump_canonical()`. + + ```cpp + #include + #include + + using json = nlohmann::json; + + int main() + { + // Object keys are automatically sorted deterministically + json j = {{"banana", 2}, {"apple", 1}, {"cherry", 3}}; + std::cout << j.dump_canonical() << '\n'; + // Output: {"apple":1,"banana":2,"cherry":3} + + // Float without trailing .0 + json j_num = {{"value", 42.0}}; + std::cout << j_num.dump_canonical() << '\n'; + // Output: {"value":42} + } + ``` + +## See also + +- [dump](dump.md) - standard configurable JSON serialization +- [RFC 8785](https://datatracker.ietf.org/doc/html/rfc8785) - JSON Canonicalization Scheme (JCS) specification + +## Version history + +- Added in version 3.13.0. diff --git a/docs/mkdocs/docs/api/basic_json/index.md b/docs/mkdocs/docs/api/basic_json/index.md index 8d945de9bc..93a4f913dd 100644 --- a/docs/mkdocs/docs/api/basic_json/index.md +++ b/docs/mkdocs/docs/api/basic_json/index.md @@ -264,6 +264,7 @@ Access to the JSON value ### Serialization / Dumping - [**dump**](dump.md) - serialization +- [**dump_canonical**](dump_canonical.md) - serialization using JSON Canonicalization Scheme (RFC 8785) ### Deserialization / Parsing diff --git a/docs/mkdocs/docs/features/serialization.md b/docs/mkdocs/docs/features/serialization.md index 5e1aedac0d..706e44b958 100644 --- a/docs/mkdocs/docs/features/serialization.md +++ b/docs/mkdocs/docs/features/serialization.md @@ -123,6 +123,7 @@ Besides JSON text, a value can also be serialized to the more compact [binary fo ## See also - [`dump`](../api/basic_json/dump.md) - serialize to a JSON-formatted string +- [`dump_canonical`](../api/basic_json/dump_canonical.md) - serialize using JSON Canonicalization Scheme (RFC 8785) - [`operator<<`](../api/operator_ltlt.md) - serialize to a stream - [`to_string`](../api/basic_json/to_string.md) - user-defined-conversion helper - [`std::formatter`](../api/basic_json/std_formatter.md) - use JSON values with `std::format` and `std::print` diff --git a/docs/mkdocs/mkdocs.yml b/docs/mkdocs/mkdocs.yml index 90393ff0d6..547435aeae 100644 --- a/docs/mkdocs/mkdocs.yml +++ b/docs/mkdocs/mkdocs.yml @@ -136,6 +136,7 @@ nav: - 'default_object_comparator_t': api/basic_json/default_object_comparator_t.md - 'diff': api/basic_json/diff.md - 'dump': api/basic_json/dump.md + - 'dump_canonical': api/basic_json/dump_canonical.md - 'emplace': api/basic_json/emplace.md - 'emplace_back': api/basic_json/emplace_back.md - 'empty': api/basic_json/empty.md diff --git a/include/nlohmann/detail/output/serializer.hpp b/include/nlohmann/detail/output/serializer.hpp index 5eb9906a1b..04000c4052 100644 --- a/include/nlohmann/detail/output/serializer.hpp +++ b/include/nlohmann/detail/output/serializer.hpp @@ -38,6 +38,231 @@ NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { +///////////////////////////////////////////////////////// +// JSON Canonicalization Scheme (RFC 8785) helpers // +///////////////////////////////////////////////////////// + +// Note: next_utf16_code_unit decodes code units for ordering without validating +// continuation bytes; strict validation is performed during dump_escaped(). +inline bool next_utf16_code_unit(const char*& p, const char* end, std::uint16_t& pending_surrogate, std::uint16_t& out_code_unit) noexcept +{ + if (pending_surrogate != 0) + { + out_code_unit = pending_surrogate; + pending_surrogate = 0; + return true; + } + if (p >= end) + { + return false; + } + + const auto b0 = static_cast(*p++); + if (b0 < 0x80) + { + out_code_unit = static_cast(b0); + return true; + } + if ((b0 & 0xE0) == 0xC0) + { + if (p < end) + { + const auto b1 = static_cast(*p++); + out_code_unit = static_cast(((b0 & 0x1F) << 6) | (b1 & 0x3F)); + return true; + } + } + else if ((b0 & 0xF0) == 0xE0) + { + if (p + 1 < end) + { + const auto b1 = static_cast(*p++); + const auto b2 = static_cast(*p++); + out_code_unit = static_cast(((b0 & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F)); + return true; + } + } + else if ((b0 & 0xF8) == 0xF0) + { + if (p + 2 < end) + { + const auto b1 = static_cast(*p++); + const auto b2 = static_cast(*p++); + const auto b3 = static_cast(*p++); + std::uint32_t cp = ((static_cast(b0 & 0x07)) << 18) | + ((static_cast(b1 & 0x3F)) << 12) | + ((static_cast(b2 & 0x3F)) << 6) | + static_cast(b3 & 0x3F); + if (cp >= 0x10000 && cp <= 0x10FFFF) + { + cp -= 0x10000; + out_code_unit = static_cast(0xD800 + (cp >> 10)); + pending_surrogate = static_cast(0xDC00 + (cp & 0x3FF)); + return true; + } + } + } + out_code_unit = static_cast(b0); + return true; +} + +struct utf16_code_unit_less +{ + template + bool operator()(const StringType& a, const StringType& b) const noexcept + { + const char* p1 = a.data(); + const char* const end1 = p1 + a.size(); + const char* p2 = b.data(); + const char* const end2 = p2 + b.size(); + + std::uint16_t pending1 = 0; + std::uint16_t pending2 = 0; + std::uint16_t cu1 = 0; + std::uint16_t cu2 = 0; + + while (true) + { + const bool has1 = next_utf16_code_unit(p1, end1, pending1, cu1); + const bool has2 = next_utf16_code_unit(p2, end2, pending2, cu2); + + if (!has1) + { + return has2; + } + if (!has2) + { + return false; + } + if (cu1 != cu2) + { + return cu1 < cu2; + } + } + } +}; + +// Note: pos is passed by value and returned as a scalar for performance +// (avoiding reference aliasing overhead in tight loops). +inline std::size_t append_exponent_ecmascript(std::array& buf, std::size_t pos, int e) noexcept +{ + if (e < 0) + { + buf[pos++] = '-'; + e = -e; + } + else + { + buf[pos++] = '+'; + } + + std::array temp{{}}; + std::size_t idx = 0; + auto val = static_cast(e); + if (val == 0) + { + buf[pos++] = '0'; + return pos; + } + while (val > 0) + { + temp[idx++] = static_cast('0' + (val % 10)); + val /= 10; + } + while (idx > 0) + { + buf[pos++] = temp[--idx]; + } + return pos; +} + +inline std::size_t format_buffer_ecmascript(std::array& buf, std::size_t len, int decimal_exponent) noexcept +{ + const auto k = static_cast(len); + const int n = k + decimal_exponent; + + if (k <= n && n <= 21) + { + std::memset(buf.data() + k, '0', static_cast(n - k)); + return static_cast(n); + } + + if (0 < n && n <= 21) + { + std::memmove(buf.data() + (n + 1), buf.data() + n, static_cast(k - n)); + buf[static_cast(n)] = '.'; + return static_cast(k + 1); + } + + if (-6 < n && n <= 0) + { + const auto zeros = static_cast(-n); + std::memmove(buf.data() + (2 + zeros), buf.data(), static_cast(k)); + buf[0] = '0'; + buf[1] = '.'; + std::memset(buf.data() + 2, '0', zeros); + return 2 + zeros + static_cast(k); + } + + std::size_t pos = 0; + if (k == 1) + { + pos = 1; + } + else + { + std::memmove(buf.data() + 2, buf.data() + 1, static_cast(k - 1)); + buf[1] = '.'; + pos = 1 + static_cast(k); + } + + buf[pos++] = 'e'; + return append_exponent_ecmascript(buf, pos, n - 1); +} + +template +inline void get_shortest_digits(FloatType x, std::array& buf, std::size_t& len, int& decimal_exponent, std::true_type /*is_binary64*/) +{ + std::uint64_t bits = 0; + std::memcpy(&bits, &x, sizeof(bits)); + const zmij::shortest_decimal sd = zmij::to_shortest(bits); + std::uint64_t significand = sd.has_digit ? (sd.integral * 10) + sd.digit : sd.integral; + decimal_exponent = sd.has_digit ? sd.exponent : sd.exponent + 1; + + std::array temp{{}}; + std::size_t temp_idx = 0; + while (significand > 0) + { + temp[temp_idx++] = static_cast('0' + (significand % 10)); + significand /= 10; + } + if (temp_idx == 0) + { + buf[len++] = '0'; + } + else + { + while (temp_idx > 0) + { + buf[len++] = temp[--temp_idx]; + } + } + + while (len > 1 && buf[len - 1] == '0') + { + --len; + ++decimal_exponent; + } +} + +template +inline void get_shortest_digits(FloatType x, std::array& buf, std::size_t& len, int& decimal_exponent, std::false_type /*is_binary64*/) +{ + int l = 0; + ::nlohmann::detail::dtoa_impl::grisu2(buf.data(), l, decimal_exponent, x); + len = static_cast(l); +} + /////////////////// // serialization // /////////////////// @@ -122,6 +347,360 @@ class serializer flush(); } + /*! + @brief serialization using JSON Canonicalization Scheme (RFC 8785) + + @param[in] val value to serialize + */ + void dump_canonical(const BasicJsonType& val) + { + dump_canonical_internal(val, 0); + flush(); + } + + JSON_PRIVATE_UNLESS_TESTED: + using value_type = typename BasicJsonType::object_t::value_type; + + static std::vector sort_canonical_object_elements(const typename BasicJsonType::object_t& obj) + { + std::vector sorted_elements; + sorted_elements.reserve(obj.size()); + for (const auto& el : obj) + { + sorted_elements.push_back(&el); + } + std::sort(sorted_elements.begin(), sorted_elements.end(), + [](const value_type * a, const value_type * b) + { + return utf16_code_unit_less{}(a->first, b->first); + }); + return sorted_elements; + } + + /// @brief a container that has been opened for iterative canonical dump + struct canonical_dump_frame + { + const BasicJsonType* container; + std::vector sorted_elements{}; + std::size_t current_idx = 0; + + explicit canonical_dump_frame(const BasicJsonType* c) + : container(c) + { + if (c->is_object()) + { + sorted_elements = sort_canonical_object_elements(*c->m_data.m_value.object); + } + } + }; + + /*! + @brief serialize scalar values according to RFC 8785 + */ + void dump_canonical_scalar(const BasicJsonType& val) + { + switch (val.m_data.m_type) + { + case value_t::string: + { + put_char('"'); + dump_escaped(*val.m_data.m_value.string); + put_char('"'); + return; + } + + case value_t::boolean: + { + if (val.m_data.m_value.boolean) + { + put_literal("true"); + } + else + { + put_literal("false"); + } + return; + } + + case value_t::number_integer: + { + dump_float_canonical(static_cast(val.m_data.m_value.number_integer), &val); + return; + } + + case value_t::number_unsigned: + { + dump_float_canonical(static_cast(val.m_data.m_value.number_unsigned), &val); + return; + } + + case value_t::number_float: + { + dump_float_canonical(static_cast(val.m_data.m_value.number_float), &val); + return; + } + + case value_t::null: + { + put_literal("null"); + return; + } + + case value_t::object: + case value_t::array: + { + JSON_ASSERT(false); + JSON_THROW(type_error::create(exception_id::type_not_serializable, concat("containers cannot be serialized by dump_canonical_scalar(): ", val.type_name()), &val)); + } + + case value_t::binary: + case value_t::discarded: + default: + { + JSON_THROW(type_error::create(exception_id::type_not_serializable, concat("type cannot be serialized in canonical JSON (RFC 8785): ", val.type_name()), &val)); + } + } + } + + /*! + @brief write out @a val canonically without the call stack + */ + void dump_canonical_iteratively(const BasicJsonType& val) + { + if (val.is_object()) + { + if (val.m_data.m_value.object->empty()) + { + put_literal("{}"); + return; + } + put_char('{'); + } + else if (val.is_array()) + { + if (val.m_data.m_value.array->empty()) + { + put_literal("[]"); + return; + } + put_char('['); + } + else + { + dump_canonical_scalar(val); + return; + } + + std::vector stack; + stack.emplace_back(&val); + + auto push_or_dump_child = [this, &stack](const BasicJsonType& child) + { + if (child.is_object()) + { + if (child.m_data.m_value.object->empty()) + { + put_literal("{}"); + } + else + { + put_char('{'); + stack.emplace_back(&child); + } + } + else if (child.is_array()) + { + if (child.m_data.m_value.array->empty()) + { + put_literal("[]"); + } + else + { + put_char('['); + stack.emplace_back(&child); + } + } + else + { + dump_canonical_scalar(child); + } + }; + + while (!stack.empty()) + { + if (stack.back().container->is_object()) + { + if (stack.back().current_idx < stack.back().sorted_elements.size()) + { + if (stack.back().current_idx > 0) + { + put_char(','); + } + + const auto* elem = stack.back().sorted_elements[stack.back().current_idx]; + ++stack.back().current_idx; + + put_char('"'); + dump_escaped(elem->first); + put_literal("\":"); + + push_or_dump_child(elem->second); + } + else + { + put_char('}'); + stack.pop_back(); + } + } + else // is_array + { + const auto* arr = stack.back().container->m_data.m_value.array; + if (stack.back().current_idx < arr->size()) + { + if (stack.back().current_idx > 0) + { + put_char(','); + } + + const BasicJsonType& child = (*arr)[stack.back().current_idx]; + ++stack.back().current_idx; + + push_or_dump_child(child); + } + else + { + put_char(']'); + stack.pop_back(); + } + } + } + } + + /*! + @brief worker for @ref dump_canonical + */ + void dump_canonical_internal(const BasicJsonType& val, const std::size_t depth = 0) + { + switch (val.m_data.m_type) + { + case value_t::object: + { + if (JSON_HEDLEY_UNLIKELY(depth >= recursion_depth_limit())) + { + dump_canonical_iteratively(val); + return; + } + + const auto* obj = val.m_data.m_value.object; + if (obj->empty()) + { + put_literal("{}"); + return; + } + + put_char('{'); + + const auto sorted_elements = sort_canonical_object_elements(*obj); + for (std::size_t i = 0; i < sorted_elements.size(); ++i) + { + if (i > 0) + { + put_char(','); + } + put_char('"'); + dump_escaped(sorted_elements[i]->first); + put_literal("\":"); + dump_canonical_internal(sorted_elements[i]->second, depth + 1); + } + + put_char('}'); + return; + } + + case value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(depth >= recursion_depth_limit())) + { + dump_canonical_iteratively(val); + return; + } + + const auto* arr = val.m_data.m_value.array; + if (arr->empty()) + { + put_literal("[]"); + return; + } + + put_char('['); + for (std::size_t i = 0; i < arr->size(); ++i) + { + if (i > 0) + { + put_char(','); + } + dump_canonical_internal((*arr)[i], depth + 1); + } + put_char(']'); + return; + } + + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::null: + case value_t::binary: + case value_t::discarded: + default: + { + dump_canonical_scalar(val); + return; + } + } + } + + /*! + @brief dump a number according to RFC 8785 (ECMAScript Number::toString modeled as IEEE 754 binary64 double) + */ + void dump_float_canonical(double x, const BasicJsonType* context) + { + if (!std::isfinite(x)) + { + JSON_THROW(out_of_range::create(exception_id::number_overflow, "cannot serialize non-finite numbers in canonical mode", context)); + } + +#if defined(__GNUC__) || defined(__clang__) + JSON_HEDLEY_DIAGNOSTIC_PUSH + JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") +#endif + const bool is_zero = (x == 0.0); +#if defined(__GNUC__) || defined(__clang__) + JSON_HEDLEY_DIAGNOSTIC_POP +#endif + + if (is_zero) + { + put_char('0'); + return; + } + + if (std::signbit(x)) + { + put_char('-'); + x = -x; + } + + std::array buf{{}}; + std::size_t len = 0; + int decimal_exponent = 0; + get_shortest_digits(x, buf, len, decimal_exponent, std::true_type{}); + + const std::size_t str_len = format_buffer_ecmascript(buf, len, decimal_exponent); + put_buffer(buf, str_len); + } + JSON_PRIVATE_UNLESS_TESTED: /*! @brief serialize the object or array @a val diff --git a/include/nlohmann/json.hpp b/include/nlohmann/json.hpp index 6bfb26771c..fc44c26212 100644 --- a/include/nlohmann/json.hpp +++ b/include/nlohmann/json.hpp @@ -2796,6 +2796,28 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec return result; } + /// @brief serialization using JSON Canonicalization Scheme (RFC 8785) + /// @return canonical JSON representation + /// @sa https://datatracker.ietf.org/doc/html/rfc8785 + JSON_HEDLEY_WARN_UNUSED_RESULT + string_t dump_canonical() const + { + string_t result; + detail::output_string_adapter string_adapter(result); + serializer s(string_adapter, ' ', false, false, 0, error_handler_t::strict); + s.dump_canonical(*this); + return result; + } + + /// @brief serialization using JSON Canonicalization Scheme (RFC 8785) + /// @sa https://datatracker.ietf.org/doc/html/rfc8785 + static void dump_canonical(const basic_json& j, detail::output_adapter o) + { + const detail::output_adapter_t adapter = o; + serializer s(*adapter, ' ', false, false, 0, error_handler_t::strict); + s.dump_canonical(j); + } + /// @brief return the type of the JSON value (explicit) /// @sa https://json.nlohmann.me/api/basic_json/type/ JSON_HEDLEY_WARN_UNUSED_RESULT diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index f53ebbbf9d..391dd028ce 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -32299,6 +32299,231 @@ NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { +///////////////////////////////////////////////////////// +// JSON Canonicalization Scheme (RFC 8785) helpers // +///////////////////////////////////////////////////////// + +// Note: next_utf16_code_unit decodes code units for ordering without validating +// continuation bytes; strict validation is performed during dump_escaped(). +inline bool next_utf16_code_unit(const char*& p, const char* end, std::uint16_t& pending_surrogate, std::uint16_t& out_code_unit) noexcept +{ + if (pending_surrogate != 0) + { + out_code_unit = pending_surrogate; + pending_surrogate = 0; + return true; + } + if (p >= end) + { + return false; + } + + const auto b0 = static_cast(*p++); + if (b0 < 0x80) + { + out_code_unit = static_cast(b0); + return true; + } + if ((b0 & 0xE0) == 0xC0) + { + if (p < end) + { + const auto b1 = static_cast(*p++); + out_code_unit = static_cast(((b0 & 0x1F) << 6) | (b1 & 0x3F)); + return true; + } + } + else if ((b0 & 0xF0) == 0xE0) + { + if (p + 1 < end) + { + const auto b1 = static_cast(*p++); + const auto b2 = static_cast(*p++); + out_code_unit = static_cast(((b0 & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F)); + return true; + } + } + else if ((b0 & 0xF8) == 0xF0) + { + if (p + 2 < end) + { + const auto b1 = static_cast(*p++); + const auto b2 = static_cast(*p++); + const auto b3 = static_cast(*p++); + std::uint32_t cp = ((static_cast(b0 & 0x07)) << 18) | + ((static_cast(b1 & 0x3F)) << 12) | + ((static_cast(b2 & 0x3F)) << 6) | + static_cast(b3 & 0x3F); + if (cp >= 0x10000 && cp <= 0x10FFFF) + { + cp -= 0x10000; + out_code_unit = static_cast(0xD800 + (cp >> 10)); + pending_surrogate = static_cast(0xDC00 + (cp & 0x3FF)); + return true; + } + } + } + out_code_unit = static_cast(b0); + return true; +} + +struct utf16_code_unit_less +{ + template + bool operator()(const StringType& a, const StringType& b) const noexcept + { + const char* p1 = a.data(); + const char* const end1 = p1 + a.size(); + const char* p2 = b.data(); + const char* const end2 = p2 + b.size(); + + std::uint16_t pending1 = 0; + std::uint16_t pending2 = 0; + std::uint16_t cu1 = 0; + std::uint16_t cu2 = 0; + + while (true) + { + const bool has1 = next_utf16_code_unit(p1, end1, pending1, cu1); + const bool has2 = next_utf16_code_unit(p2, end2, pending2, cu2); + + if (!has1) + { + return has2; + } + if (!has2) + { + return false; + } + if (cu1 != cu2) + { + return cu1 < cu2; + } + } + } +}; + +// Note: pos is passed by value and returned as a scalar for performance +// (avoiding reference aliasing overhead in tight loops). +inline std::size_t append_exponent_ecmascript(std::array& buf, std::size_t pos, int e) noexcept +{ + if (e < 0) + { + buf[pos++] = '-'; + e = -e; + } + else + { + buf[pos++] = '+'; + } + + std::array temp{{}}; + std::size_t idx = 0; + auto val = static_cast(e); + if (val == 0) + { + buf[pos++] = '0'; + return pos; + } + while (val > 0) + { + temp[idx++] = static_cast('0' + (val % 10)); + val /= 10; + } + while (idx > 0) + { + buf[pos++] = temp[--idx]; + } + return pos; +} + +inline std::size_t format_buffer_ecmascript(std::array& buf, std::size_t len, int decimal_exponent) noexcept +{ + const auto k = static_cast(len); + const int n = k + decimal_exponent; + + if (k <= n && n <= 21) + { + std::memset(buf.data() + k, '0', static_cast(n - k)); + return static_cast(n); + } + + if (0 < n && n <= 21) + { + std::memmove(buf.data() + (n + 1), buf.data() + n, static_cast(k - n)); + buf[static_cast(n)] = '.'; + return static_cast(k + 1); + } + + if (-6 < n && n <= 0) + { + const auto zeros = static_cast(-n); + std::memmove(buf.data() + (2 + zeros), buf.data(), static_cast(k)); + buf[0] = '0'; + buf[1] = '.'; + std::memset(buf.data() + 2, '0', zeros); + return 2 + zeros + static_cast(k); + } + + std::size_t pos = 0; + if (k == 1) + { + pos = 1; + } + else + { + std::memmove(buf.data() + 2, buf.data() + 1, static_cast(k - 1)); + buf[1] = '.'; + pos = 1 + static_cast(k); + } + + buf[pos++] = 'e'; + return append_exponent_ecmascript(buf, pos, n - 1); +} + +template +inline void get_shortest_digits(FloatType x, std::array& buf, std::size_t& len, int& decimal_exponent, std::true_type /*is_binary64*/) +{ + std::uint64_t bits = 0; + std::memcpy(&bits, &x, sizeof(bits)); + const zmij::shortest_decimal sd = zmij::to_shortest(bits); + std::uint64_t significand = sd.has_digit ? (sd.integral * 10) + sd.digit : sd.integral; + decimal_exponent = sd.has_digit ? sd.exponent : sd.exponent + 1; + + std::array temp{{}}; + std::size_t temp_idx = 0; + while (significand > 0) + { + temp[temp_idx++] = static_cast('0' + (significand % 10)); + significand /= 10; + } + if (temp_idx == 0) + { + buf[len++] = '0'; + } + else + { + while (temp_idx > 0) + { + buf[len++] = temp[--temp_idx]; + } + } + + while (len > 1 && buf[len - 1] == '0') + { + --len; + ++decimal_exponent; + } +} + +template +inline void get_shortest_digits(FloatType x, std::array& buf, std::size_t& len, int& decimal_exponent, std::false_type /*is_binary64*/) +{ + int l = 0; + ::nlohmann::detail::dtoa_impl::grisu2(buf.data(), l, decimal_exponent, x); + len = static_cast(l); +} + /////////////////// // serialization // /////////////////// @@ -32383,6 +32608,360 @@ class serializer flush(); } + /*! + @brief serialization using JSON Canonicalization Scheme (RFC 8785) + + @param[in] val value to serialize + */ + void dump_canonical(const BasicJsonType& val) + { + dump_canonical_internal(val, 0); + flush(); + } + + JSON_PRIVATE_UNLESS_TESTED: + using value_type = typename BasicJsonType::object_t::value_type; + + static std::vector sort_canonical_object_elements(const typename BasicJsonType::object_t& obj) + { + std::vector sorted_elements; + sorted_elements.reserve(obj.size()); + for (const auto& el : obj) + { + sorted_elements.push_back(&el); + } + std::sort(sorted_elements.begin(), sorted_elements.end(), + [](const value_type * a, const value_type * b) + { + return utf16_code_unit_less{}(a->first, b->first); + }); + return sorted_elements; + } + + /// @brief a container that has been opened for iterative canonical dump + struct canonical_dump_frame + { + const BasicJsonType* container; + std::vector sorted_elements{}; + std::size_t current_idx = 0; + + explicit canonical_dump_frame(const BasicJsonType* c) + : container(c) + { + if (c->is_object()) + { + sorted_elements = sort_canonical_object_elements(*c->m_data.m_value.object); + } + } + }; + + /*! + @brief serialize scalar values according to RFC 8785 + */ + void dump_canonical_scalar(const BasicJsonType& val) + { + switch (val.m_data.m_type) + { + case value_t::string: + { + put_char('"'); + dump_escaped(*val.m_data.m_value.string); + put_char('"'); + return; + } + + case value_t::boolean: + { + if (val.m_data.m_value.boolean) + { + put_literal("true"); + } + else + { + put_literal("false"); + } + return; + } + + case value_t::number_integer: + { + dump_float_canonical(static_cast(val.m_data.m_value.number_integer), &val); + return; + } + + case value_t::number_unsigned: + { + dump_float_canonical(static_cast(val.m_data.m_value.number_unsigned), &val); + return; + } + + case value_t::number_float: + { + dump_float_canonical(static_cast(val.m_data.m_value.number_float), &val); + return; + } + + case value_t::null: + { + put_literal("null"); + return; + } + + case value_t::object: + case value_t::array: + { + JSON_ASSERT(false); + JSON_THROW(type_error::create(exception_id::type_not_serializable, concat("containers cannot be serialized by dump_canonical_scalar(): ", val.type_name()), &val)); + } + + case value_t::binary: + case value_t::discarded: + default: + { + JSON_THROW(type_error::create(exception_id::type_not_serializable, concat("type cannot be serialized in canonical JSON (RFC 8785): ", val.type_name()), &val)); + } + } + } + + /*! + @brief write out @a val canonically without the call stack + */ + void dump_canonical_iteratively(const BasicJsonType& val) + { + if (val.is_object()) + { + if (val.m_data.m_value.object->empty()) + { + put_literal("{}"); + return; + } + put_char('{'); + } + else if (val.is_array()) + { + if (val.m_data.m_value.array->empty()) + { + put_literal("[]"); + return; + } + put_char('['); + } + else + { + dump_canonical_scalar(val); + return; + } + + std::vector stack; + stack.emplace_back(&val); + + auto push_or_dump_child = [this, &stack](const BasicJsonType& child) + { + if (child.is_object()) + { + if (child.m_data.m_value.object->empty()) + { + put_literal("{}"); + } + else + { + put_char('{'); + stack.emplace_back(&child); + } + } + else if (child.is_array()) + { + if (child.m_data.m_value.array->empty()) + { + put_literal("[]"); + } + else + { + put_char('['); + stack.emplace_back(&child); + } + } + else + { + dump_canonical_scalar(child); + } + }; + + while (!stack.empty()) + { + if (stack.back().container->is_object()) + { + if (stack.back().current_idx < stack.back().sorted_elements.size()) + { + if (stack.back().current_idx > 0) + { + put_char(','); + } + + const auto* elem = stack.back().sorted_elements[stack.back().current_idx]; + ++stack.back().current_idx; + + put_char('"'); + dump_escaped(elem->first); + put_literal("\":"); + + push_or_dump_child(elem->second); + } + else + { + put_char('}'); + stack.pop_back(); + } + } + else // is_array + { + const auto* arr = stack.back().container->m_data.m_value.array; + if (stack.back().current_idx < arr->size()) + { + if (stack.back().current_idx > 0) + { + put_char(','); + } + + const BasicJsonType& child = (*arr)[stack.back().current_idx]; + ++stack.back().current_idx; + + push_or_dump_child(child); + } + else + { + put_char(']'); + stack.pop_back(); + } + } + } + } + + /*! + @brief worker for @ref dump_canonical + */ + void dump_canonical_internal(const BasicJsonType& val, const std::size_t depth = 0) + { + switch (val.m_data.m_type) + { + case value_t::object: + { + if (JSON_HEDLEY_UNLIKELY(depth >= recursion_depth_limit())) + { + dump_canonical_iteratively(val); + return; + } + + const auto* obj = val.m_data.m_value.object; + if (obj->empty()) + { + put_literal("{}"); + return; + } + + put_char('{'); + + const auto sorted_elements = sort_canonical_object_elements(*obj); + for (std::size_t i = 0; i < sorted_elements.size(); ++i) + { + if (i > 0) + { + put_char(','); + } + put_char('"'); + dump_escaped(sorted_elements[i]->first); + put_literal("\":"); + dump_canonical_internal(sorted_elements[i]->second, depth + 1); + } + + put_char('}'); + return; + } + + case value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(depth >= recursion_depth_limit())) + { + dump_canonical_iteratively(val); + return; + } + + const auto* arr = val.m_data.m_value.array; + if (arr->empty()) + { + put_literal("[]"); + return; + } + + put_char('['); + for (std::size_t i = 0; i < arr->size(); ++i) + { + if (i > 0) + { + put_char(','); + } + dump_canonical_internal((*arr)[i], depth + 1); + } + put_char(']'); + return; + } + + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::null: + case value_t::binary: + case value_t::discarded: + default: + { + dump_canonical_scalar(val); + return; + } + } + } + + /*! + @brief dump a number according to RFC 8785 (ECMAScript Number::toString modeled as IEEE 754 binary64 double) + */ + void dump_float_canonical(double x, const BasicJsonType* context) + { + if (!std::isfinite(x)) + { + JSON_THROW(out_of_range::create(exception_id::number_overflow, "cannot serialize non-finite numbers in canonical mode", context)); + } + +#if defined(__GNUC__) || defined(__clang__) + JSON_HEDLEY_DIAGNOSTIC_PUSH + JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") +#endif + const bool is_zero = (x == 0.0); +#if defined(__GNUC__) || defined(__clang__) + JSON_HEDLEY_DIAGNOSTIC_POP +#endif + + if (is_zero) + { + put_char('0'); + return; + } + + if (std::signbit(x)) + { + put_char('-'); + x = -x; + } + + std::array buf{{}}; + std::size_t len = 0; + int decimal_exponent = 0; + get_shortest_digits(x, buf, len, decimal_exponent, std::true_type{}); + + const std::size_t str_len = format_buffer_ecmascript(buf, len, decimal_exponent); + put_buffer(buf, str_len); + } + JSON_PRIVATE_UNLESS_TESTED: /*! @brief serialize the object or array @a val @@ -37632,6 +38211,28 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec return result; } + /// @brief serialization using JSON Canonicalization Scheme (RFC 8785) + /// @return canonical JSON representation + /// @sa https://datatracker.ietf.org/doc/html/rfc8785 + JSON_HEDLEY_WARN_UNUSED_RESULT + string_t dump_canonical() const + { + string_t result; + detail::output_string_adapter string_adapter(result); + serializer s(string_adapter, ' ', false, false, 0, error_handler_t::strict); + s.dump_canonical(*this); + return result; + } + + /// @brief serialization using JSON Canonicalization Scheme (RFC 8785) + /// @sa https://datatracker.ietf.org/doc/html/rfc8785 + static void dump_canonical(const basic_json& j, detail::output_adapter o) + { + const detail::output_adapter_t adapter = o; + serializer s(*adapter, ' ', false, false, 0, error_handler_t::strict); + s.dump_canonical(j); + } + /// @brief return the type of the JSON value (explicit) /// @sa https://json.nlohmann.me/api/basic_json/type/ JSON_HEDLEY_WARN_UNUSED_RESULT diff --git a/tests/src/unit-canonical_json.cpp b/tests/src/unit-canonical_json.cpp new file mode 100644 index 0000000000..d0b4de052c --- /dev/null +++ b/tests/src/unit-canonical_json.cpp @@ -0,0 +1,292 @@ +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ (supporting code) +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann +// SPDX-License-Identifier: MIT + +#include "doctest_compatibility.h" + +#include +#include +#include +#include +#include + +using nlohmann::json; +using nlohmann::ordered_json; + +TEST_CASE("canonical JSON serialization (RFC 8785 / JCS)") +{ + SECTION("primitives and literals") + { + CHECK(json(nullptr).dump_canonical() == "null"); + CHECK(json(true).dump_canonical() == "true"); + CHECK(json(false).dump_canonical() == "false"); + CHECK(json(0).dump_canonical() == "0"); + CHECK(json(42).dump_canonical() == "42"); + CHECK(json(-42).dump_canonical() == "-42"); + CHECK(json("").dump_canonical() == "\"\""); + CHECK(json("hello").dump_canonical() == "\"hello\""); + } + + SECTION("empty containers") + { + CHECK(json::object().dump_canonical() == "{}"); + CHECK(json::array().dump_canonical() == "[]"); + CHECK(json({{"empty_obj", json::object()}, {"empty_arr", json::array()}}).dump_canonical() + == "{\"empty_arr\":[],\"empty_obj\":{}}"); + } + + SECTION("string escaping according to RFC 8785") + { + // Minimal escapes: \", \\, \b, \f, \n, \r, \t, and \u0000..\u001f + CHECK(json("\"").dump_canonical() == "\"\\\"\""); + CHECK(json("\\").dump_canonical() == "\"\\\\\""); + CHECK(json("\b").dump_canonical() == "\"\\b\""); + CHECK(json("\f").dump_canonical() == "\"\\f\""); + CHECK(json("\n").dump_canonical() == "\"\\n\""); + CHECK(json("\r").dump_canonical() == "\"\\r\""); + CHECK(json("\t").dump_canonical() == "\"\\t\""); + CHECK(json("\x01").dump_canonical() == "\"\\u0001\""); + CHECK(json("\x1F").dump_canonical() == "\"\\u001f\""); + + // Forward slash MUST NOT be escaped + CHECK(json("/").dump_canonical() == "\"/\""); + CHECK(json("http://example.com/api").dump_canonical() == "\"http://example.com/api\""); + + // Unicode >= 0x20 MUST NOT be escaped (emitted as raw UTF-8) + CHECK(json("€").dump_canonical() == "\"€\""); + CHECK(json("ö").dump_canonical() == "\"ö\""); + CHECK(json("Å").dump_canonical() == "\"Å\""); + } + + SECTION("key sorting by UTF-16 code units") + { + // BMP characters sort by code point = code unit + json j1 = {{"b", 2}, {"a", 1}, {"c", 3}}; + CHECK(j1.dump_canonical() == "{\"a\":1,\"b\":2,\"c\":3}"); + + // Empty string sorts before non-empty + json j2 = {{"a", 1}, {"", 0}}; + CHECK(j2.dump_canonical() == "{\"\":0,\"a\":1}"); + + // Numeric string keys + json j3 = {{"111", 3}, {"1", 1}, {"10", 2}}; + CHECK(j3.dump_canonical() == "{\"1\":1,\"10\":2,\"111\":3}"); + + // UTF-16 surrogate pairs sort before U+E000..U+FFFF BMP characters + // 😂 (U+1F602, UTF-16: D83D DE02) vs דּ (U+FB33, UTF-16: FB33) + // In UTF-8 bytes: דּ (EF AC B3) < 😂 (F0 9F 98 82) + // In UTF-16 code units: 😂 (0xD83D) < דּ (0xFB33) + json j_surrogate = {{"\xEF\xAC\xB3", "Hebrew"}, {"\xF0\x9F\x98\x82", "Smiley"}}; + CHECK(j_surrogate.dump_canonical() == "{\"😂\":\"Smiley\",\"דּ\":\"Hebrew\"}"); + + // Works equally on ordered_json + ordered_json oj = {{"z", 1}, {"a", 2}, {"m", 3}}; + CHECK(oj.dump_canonical() == "{\"a\":2,\"m\":3,\"z\":1}"); + } + + SECTION("number formatting (RFC 8785 Appendix B)") + { + // Zero and minus zero + CHECK(json(0.0).dump_canonical() == "0"); + CHECK(json(-0.0).dump_canonical() == "0"); + + // Integers stored as float without trailing .0 + CHECK(json(56.0).dump_canonical() == "56"); + CHECK(json(-42.0).dump_canonical() == "-42"); + + // Plain decimal range: 1e-6 <= |x| < 1e21 + CHECK(json(4.5).dump_canonical() == "4.5"); + CHECK(json(0.002).dump_canonical() == "0.002"); + CHECK(json(0.000001).dump_canonical() == "0.000001"); + CHECK(json(333333333.3333333).dump_canonical() == "333333333.3333333"); + CHECK(json(9007199254740992.0).dump_canonical() == "9007199254740992"); + CHECK(json(-9007199254740992.0).dump_canonical() == "-9007199254740992"); + + // 64-bit integer values formatted according to IEEE 754 binary64 rules + CHECK(json(9007199254740992LL).dump_canonical() == "9007199254740992"); + CHECK(json(9007199254740993LL).dump_canonical() == "9007199254740992"); + CHECK(json(-9007199254740993LL).dump_canonical() == "-9007199254740992"); + CHECK(json(18446744073709551615ULL).dump_canonical() == "18446744073709552000"); + + // Single-precision float formatted according to IEEE 754 double value + CHECK(json(0.1f).dump_canonical() == "0.10000000149011612"); + + // Exponential range: |x| < 1e-6 or |x| >= 1e21 + CHECK(json(9.999999999999997e-7).dump_canonical() == "9.999999999999997e-7"); + CHECK(json(1e21).dump_canonical() == "1e+21"); + CHECK(json(1e30).dump_canonical() == "1e+30"); + CHECK(json(1e-27).dump_canonical() == "1e-27"); + CHECK(json(5e-324).dump_canonical() == "5e-324"); + CHECK(json(-5e-324).dump_canonical() == "-5e-324"); + CHECK(json(1.7976931348623157e+308).dump_canonical() == "1.7976931348623157e+308"); + CHECK(json(-1.7976931348623157e+308).dump_canonical() == "-1.7976931348623157e+308"); + } + + SECTION("reproducible byte-identical output across different key insertion orders") + { + ordered_json doc1 = + { + {"user", {{"id", 101}, {"name", "Alice"}, {"role", "admin"}}}, + {"active", true}, + {"tags", {"security", "audit"}} + }; + + ordered_json doc2 = + { + {"tags", {"security", "audit"}}, + {"active", true}, + {"user", {{"role", "admin"}, {"id", 101}, {"name", "Alice"}}} + }; + + CHECK(doc1.dump_canonical() == doc2.dump_canonical()); + } + + SECTION("official RFC 8785 test vectors") + { + struct TestVector + { + const char* name; + const char* input; + const char* expected; + }; + + const std::vector test_vectors = + { + { + "arrays", + "[\n 56,\n {\n \"d\": true,\n \"10\": null,\n \"1\": [ ]\n }\n]\n", + "[56,{\"1\":[],\"10\":null,\"d\":true}]" + }, + { + "french", + "{\n \"peach\": \"This sorting order\",\n \"p\xC3\xA9\x63\x68\xC3\xA9\": \"is wrong according to French\",\n \"p\xC3\xAA\x63\x68\x65\": \"but canonicalization MUST\",\n \"sin\": \"ignore locale\"\n}\n", + "{\"peach\":\"This sorting order\",\"p\xC3\xA9\x63\x68\xC3\xA9\":\"is wrong according to French\",\"p\xC3\xAA\x63\x68\x65\":\"but canonicalization MUST\",\"sin\":\"ignore locale\"}" + }, + { + "structures", + "{\n \"1\": {\"f\": {\"f\": \"hi\",\"F\": 5} ,\"\\n\": 56.0},\n \"10\": { },\n \"\": \"empty\",\n \"a\": { },\n \"111\": [ {\"e\": \"yes\",\"E\": \"no\" } ],\n \"A\": { }\n}", + "{\"\":\"empty\",\"1\":{\"\\n\":56,\"f\":{\"F\":5,\"f\":\"hi\"}},\"10\":{},\"111\":[{\"E\":\"no\",\"e\":\"yes\"}],\"A\":{},\"a\":{}}" + }, + { + "unicode", + "{\n \"Unnormalized Unicode\":\"A\\u030a\"\n}\n", + "{\"Unnormalized Unicode\":\"A\xCC\x8A\"}" + }, + { + "values", + "{\n \"numbers\": [333333333.33333329, 1E30, 4.50, 2e-3, 0.000000000000000000000000001],\n \"string\": \"\\u20ac$\\u000F\\u000aA'\\u0042\\u0022\\u005c\\\\\\\"\\/\",\n \"literals\": [null, true, false]\n}", + "{\"literals\":[null,true,false],\"numbers\":[333333333.3333333,1e+30,4.5,0.002,1e-27],\"string\":\"\xE2\x82\xAC$\\u000f\\nA'B\\\"\\\\\\\\\\\"/\"}" + }, + { + "weird", + "{\n \"\\u20ac\": \"Euro Sign\",\n \"\\r\": \"Carriage Return\",\n \"\\u000a\": \"Newline\",\n \"1\": \"One\",\n \"\\u0080\": \"Control\\u007f\",\n \"\\ud83d\\ude02\": \"Smiley\",\n \"\\u00f6\": \"Latin Small Letter O With Diaeresis\",\n \"\\ufb33\": \"Hebrew Letter Dalet With Dagesh\",\n \"\": \"Browser Challenge\"\n}\n", + "{\"\\n\":\"Newline\",\"\\r\":\"Carriage Return\",\"1\":\"One\",\"\":\"Browser Challenge\",\"\xC2\x80\":\"Control\x7F\",\"\xC3\xB6\":\"Latin Small Letter O With Diaeresis\",\"\xE2\x82\xAC\":\"Euro Sign\",\"\xF0\x9F\x98\x82\":\"Smiley\",\"\xEF\xAC\xB3\":\"Hebrew Letter Dalet With Dagesh\"}" + } + }; + + for (const auto& vec : test_vectors) + { + CAPTURE(vec.name) + json j = json::parse(vec.input); + CHECK(j.dump_canonical() == vec.expected); + + ordered_json oj = ordered_json::parse(vec.input); + CHECK(oj.dump_canonical() == vec.expected); + } + } + + SECTION("error handling") + { + // NaN is rejected + json j_nan = std::numeric_limits::quiet_NaN(); + CHECK_THROWS_WITH_AS(static_cast(j_nan.dump_canonical()), + "[json.exception.out_of_range.406] cannot serialize non-finite numbers in canonical mode", + json::out_of_range&); + + // Infinity is rejected + json j_inf = std::numeric_limits::infinity(); + CHECK_THROWS_WITH_AS(static_cast(j_inf.dump_canonical()), + "[json.exception.out_of_range.406] cannot serialize non-finite numbers in canonical mode", + json::out_of_range&); + + json j_neg_inf = -std::numeric_limits::infinity(); + CHECK_THROWS_WITH_AS(static_cast(j_neg_inf.dump_canonical()), + "[json.exception.out_of_range.406] cannot serialize non-finite numbers in canonical mode", + json::out_of_range&); + + // Binary types are rejected + json j_bin = json::binary({0x01, 0x02, 0x03}); + CHECK_THROWS_WITH_AS(static_cast(j_bin.dump_canonical()), + "[json.exception.type_error.317] type cannot be serialized in canonical JSON (RFC 8785): binary", + json::type_error&); + + // Discarded values are rejected + json j_disc = json::value_t::discarded; + CHECK_THROWS_WITH_AS(static_cast(j_disc.dump_canonical()), + "[json.exception.type_error.317] type cannot be serialized in canonical JSON (RFC 8785): discarded", + json::type_error&); + + // Lone surrogates are rejected (RFC 8785 Section 3.2.2.2) + json j_high_surrogate = "\xED\xA0\x80"; + CHECK_THROWS_AS(static_cast(j_high_surrogate.dump_canonical()), json::type_error&); + + json j_low_surrogate = "\xED\xBF\xBF"; + CHECK_THROWS_AS(static_cast(j_low_surrogate.dump_canonical()), json::type_error&); + + json j_surrogate_key = {{"\xED\xA0\x80", 1}}; + CHECK_THROWS_AS(static_cast(j_surrogate_key.dump_canonical()), json::type_error&); + } + + SECTION("static dump_canonical with output adapter") + { + json j = {{"b", 2}, {"a", 1}}; + std::string result; + json::dump_canonical(j, result); + CHECK(result == "{\"a\":1,\"b\":2}"); + + std::ostringstream ss; + json::dump_canonical(j, ss); + CHECK(ss.str() == "{\"a\":1,\"b\":2}"); + } + + SECTION("deep nesting beyond recursion_depth_limit (#5387)") + { + // Recursion limit in recursion_depth_limit.hpp is 512 + constexpr std::size_t depth = 600; + + // 1. Deeply nested arrays: [[[[... 42 ...]]]] + json nested_array = 42; + for (std::size_t i = 0; i < depth; ++i) + { + nested_array = json::array({nested_array}); + } + std::string expected_arr; + expected_arr.reserve(depth * 2 + 3); + expected_arr.append(depth, '['); + expected_arr.append("42"); + expected_arr.append(depth, ']'); + CHECK(nested_array.dump_canonical() == expected_arr); + + // 2. Deeply nested objects with sorted keys: {"b":1,"a":{"b":1,"a":...}} + json nested_obj = 42; + for (std::size_t i = 0; i < depth; ++i) + { + nested_obj = json{{"b", 1}, {"a", nested_obj}}; + } + std::string expected_obj; + for (std::size_t i = 0; i < depth; ++i) + { + expected_obj.append("{\"a\":"); + } + expected_obj.append("42"); + for (std::size_t i = 0; i < depth; ++i) + { + expected_obj.append(",\"b\":1}"); + } + CHECK(nested_obj.dump_canonical() == expected_obj); + } +}