From afc8f2efe6b63cfeda7a3baf833b3d7a20bf393d Mon Sep 17 00:00:00 2001 From: Saurabh Tiwari Date: Tue, 20 Oct 2026 12:08:15 +0530 Subject: [PATCH 1/6] Add canonical JSON serialization adhering to RFC 8785 (JCS) This adds support for JSON Canonicalization Scheme (JCS) as defined in RFC 8785, providing deterministic, byte-for-byte identical serialization of JSON documents across platforms and implementations. Key implementation details: - Lexicographical object key sorting based on UTF-16 code units (RFC 8785 Section 3.2.3), ensuring characters with supplementary plane code points (>= U+10000) sort before BMP characters in the range U+E000..U+FFFF. - ECMAScript 2019 / RFC 8785 Section 3.2.2.3 number formatting: - Round float numbers serialized without trailing `.0` - Exponents formatted without leading zeros (e.g. 1e+21, 1e-7) - Negative zero (-0.0) normalized to "0" - Numbers in range 1e-6 <= |x| < 1e21 formatted in plain decimal notation - Strict UTF-8 validation and minimal escaping per RFC 8785 Section 3.2.2.2: emits only \", \\, \b, \f, \n, \r, \t, and \u0000..\u001f escaped, leaving all code points >= 0x20 and '/' unescaped. - Throws out_of_range.406 for non-finite numbers (NaN/Infinity) and type_error.317 for unsupported types (binary, discarded). - Member and static overloads dump_canonical on basic_json. - Comprehensive unit test suite in tests/src/unit-canonical_json.cpp covering all edge cases and the 6 official RFC 8785 test suites across C++14, C++17, and C++20. - Documentation added in MkDocs and single-header amalgamation updated. Closes #5297 Signed-off-by: Saurabh Tiwari --- .../docs/api/basic_json/dump_canonical.md | 88 +++++ docs/mkdocs/docs/api/basic_json/index.md | 1 + docs/mkdocs/docs/features/serialization.md | 1 + docs/mkdocs/mkdocs.yml | 1 + include/nlohmann/detail/output/serializer.hpp | 351 +++++++++++++++++ include/nlohmann/json.hpp | 22 ++ single_include/nlohmann/json.hpp | 369 ++++++++++++++++++ tests/src/unit-canonical_json.cpp | 233 +++++++++++ 8 files changed, 1066 insertions(+) create mode 100644 docs/mkdocs/docs/api/basic_json/dump_canonical.md create mode 100644 tests/src/unit-canonical_json.cpp 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..6240f4fc82 --- /dev/null +++ b/docs/mkdocs/docs/api/basic_json/dump_canonical.md @@ -0,0 +1,88 @@ +# 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. + +## Rules of RFC 8785 Canonical JSON + +The 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 without exponents. +- **Unsupported Types**: Non-finite numbers (`NaN`, `Infinity`, `-Infinity`), binary values, and discarded values cannot be serialized in canonical JSON. + +## 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). + +## 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.12.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..c4d8db4532 100644 --- a/include/nlohmann/detail/output/serializer.hpp +++ b/include/nlohmann/detail/output/serializer.hpp @@ -38,6 +38,183 @@ NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { +///////////////////////////////////////////////////////// +// JSON Canonicalization Scheme (RFC 8785) helpers // +///////////////////////////////////////////////////////// + +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; + } + } + } +}; + +inline char* append_exponent_ecmascript(char* buf, int e) noexcept +{ + if (e < 0) + { + *buf++ = '-'; + e = -e; + } + else + { + *buf++ = '+'; + } + + char temp[16]; + int idx = 0; + auto val = static_cast(e); + if (val == 0) + { + *buf++ = '0'; + return buf; + } + while (val > 0) + { + temp[idx++] = static_cast('0' + (val % 10)); + val /= 10; + } + while (idx > 0) + { + *buf++ = temp[--idx]; + } + return buf; +} + +inline char* format_buffer_ecmascript(char* buf, int len, int decimal_exponent) noexcept +{ + const int k = len; + const int n = len + decimal_exponent; + + if (k <= n && n <= 21) + { + std::memset(buf + k, '0', static_cast(n - k)); + return buf + n; + } + + if (0 < n && n <= 21) + { + std::memmove(buf + (n + 1), buf + n, static_cast(k - n)); + buf[n] = '.'; + return buf + (k + 1); + } + + if (-6 < n && n <= 0) + { + const auto zeros = static_cast(-n); + std::memmove(buf + (2 + zeros), buf, static_cast(k)); + buf[0] = '0'; + buf[1] = '.'; + std::memset(buf + 2, '0', zeros); + return buf + (2 + zeros + static_cast(k)); + } + + if (k == 1) + { + buf += 1; + } + else + { + std::memmove(buf + 2, buf + 1, static_cast(k - 1)); + buf[1] = '.'; + buf += 1 + static_cast(k); + } + + *buf++ = 'e'; + return append_exponent_ecmascript(buf, n - 1); +} + /////////////////// // serialization // /////////////////// @@ -122,6 +299,180 @@ 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); + flush(); + } + + JSON_PRIVATE_UNLESS_TESTED: + /*! + @brief worker for @ref dump_canonical + */ + void dump_canonical_internal(const BasicJsonType& val) + { + switch (val.m_data.m_type) + { + case value_t::object: + { + const auto* obj = val.m_data.m_value.object; + if (obj->empty()) + { + put_literal("{}"); + return; + } + + put_char('{'); + + using value_type = typename BasicJsonType::object_t::value_type; + 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); + }); + + 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_char('"'); + put_char(':'); + dump_canonical_internal(sorted_elements[i]->second); + } + + put_char('}'); + return; + } + + case value_t::array: + { + 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]); + } + put_char(']'); + return; + } + + 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_integer(val.m_data.m_value.number_integer); + return; + } + + case value_t::number_unsigned: + { + dump_integer(val.m_data.m_value.number_unsigned); + return; + } + + case value_t::number_float: + { + dump_float_canonical(val.m_data.m_value.number_float, &val); + return; + } + + case value_t::null: + { + put_literal("null"); + return; + } + + 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 dump a floating-point number according to RFC 8785 (ECMAScript Number::toString) + */ + void dump_float_canonical(number_float_t 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 (x == 0) + { + put_char('0'); + return; + } + + if (std::signbit(x)) + { + put_char('-'); + x = -x; + } + + char buf[128]; + int len = 0; + int decimal_exponent = 0; + ::nlohmann::detail::dtoa_impl::grisu2(buf, len, decimal_exponent, x); + + char* const end = format_buffer_ecmascript(buf, len, decimal_exponent); + const auto str_len = static_cast(end - buf); + + if (JSON_HEDLEY_UNLIKELY(write_buffer_pos + str_len > write_buffer.size())) + { + flush(); + } + std::memcpy(write_buffer.data() + write_buffer_pos, buf, str_len); + write_buffer_pos += 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..57a6800521 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -32299,6 +32299,179 @@ NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { +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++); + const auto cp = static_cast(((b0 & 0x1F) << 6) | (b1 & 0x3F)); + out_code_unit = static_cast(cp); + return true; + } + } + else if ((b0 & 0xF0) == 0xE0) + { + if (p + 1 < end) + { + const auto b1 = static_cast(*p++); + const auto b2 = static_cast(*p++); + const auto cp = static_cast(((b0 & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F)); + out_code_unit = static_cast(cp); + 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++); + const auto cp = static_cast(((b0 & 0x07) << 18) | ((b1 & 0x3F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F)); + if (cp >= 0x10000 && cp <= 0x10FFFF) + { + const auto u = cp - 0x10000; + out_code_unit = static_cast(0xD800 + (u >> 10)); + pending_surrogate = static_cast(0xDC00 + (u & 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; + } + } + } +}; + +inline char* append_exponent_ecmascript(char* buf, int e) noexcept +{ + if (e < 0) + { + *buf++ = '-'; + e = -e; + } + else + { + *buf++ = '+'; + } + + char temp[16]; + int idx = 0; + auto val = static_cast(e); + if (val == 0) + { + *buf++ = '0'; + return buf; + } + while (val > 0) + { + temp[idx++] = static_cast('0' + (val % 10)); + val /= 10; + } + while (idx > 0) + { + *buf++ = temp[--idx]; + } + return buf; +} + +inline char* format_buffer_ecmascript(char* buf, int len, int decimal_exponent) noexcept +{ + const int k = len; + const int n = len + decimal_exponent; + + if (k <= n && n <= 21) + { + std::memset(buf + k, '0', static_cast(n - k)); + return buf + n; + } + + if (0 < n && n <= 21) + { + std::memmove(buf + (n + 1), buf + n, static_cast(k - n)); + buf[n] = '.'; + return buf + (k + 1); + } + + if (-6 < n && n <= 0) + { + const auto zeros = static_cast(-n); + std::memmove(buf + (2 + zeros), buf, static_cast(k)); + buf[0] = '0'; + buf[1] = '.'; + std::memset(buf + 2, '0', zeros); + return buf + (2 + zeros + static_cast(k)); + } + + if (k == 1) + { + buf += 1; + } + else + { + std::memmove(buf + 2, buf + 1, static_cast(k - 1)); + buf[1] = '.'; + buf += 1 + static_cast(k); + } + + *buf++ = 'e'; + return append_exponent_ecmascript(buf, n - 1); +} + /////////////////// // serialization // /////////////////// @@ -32383,6 +32556,180 @@ 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); + flush(); + } + + JSON_PRIVATE_UNLESS_TESTED: + /*! + @brief worker for @ref dump_canonical + */ + void dump_canonical_internal(const BasicJsonType& val) + { + switch (val.m_data.m_type) + { + case value_t::object: + { + const auto* obj = val.m_data.m_value.object; + if (obj->empty()) + { + put_literal("{}"); + return; + } + + put_char('{'); + + using value_type = typename BasicJsonType::object_t::value_type; + 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); + }); + + 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_char('"'); + put_char(':'); + dump_canonical_internal(sorted_elements[i]->second); + } + + put_char('}'); + return; + } + + case value_t::array: + { + 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]); + } + put_char(']'); + return; + } + + 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_integer(val.m_data.m_value.number_integer); + return; + } + + case value_t::number_unsigned: + { + dump_integer(val.m_data.m_value.number_unsigned); + return; + } + + case value_t::number_float: + { + dump_float_canonical(val.m_data.m_value.number_float, &val); + return; + } + + case value_t::null: + { + put_literal("null"); + return; + } + + 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 dump a floating-point number according to RFC 8785 (ECMAScript Number::toString) + */ + void dump_float_canonical(number_float_t 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 (x == 0) + { + put_char('0'); + return; + } + + if (std::signbit(x)) + { + put_char('-'); + x = -x; + } + + char buf[128]; + int len = 0; + int decimal_exponent = 0; + ::nlohmann::detail::dtoa_impl::grisu2(buf, len, decimal_exponent, x); + + char* const end = format_buffer_ecmascript(buf, len, decimal_exponent); + const auto str_len = static_cast(end - buf); + + if (JSON_HEDLEY_UNLIKELY(write_buffer_pos + str_len > write_buffer.size())) + { + flush(); + } + std::memcpy(write_buffer.data() + write_buffer_pos, buf, str_len); + write_buffer_pos += str_len; + } + JSON_PRIVATE_UNLESS_TESTED: /*! @brief serialize the object or array @a val @@ -37632,6 +37979,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..c4ad0fa9af --- /dev/null +++ b/tests/src/unit-canonical_json.cpp @@ -0,0 +1,233 @@ +// __ _____ _____ _____ +// __| | __| | | | 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"); + + // 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(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(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(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(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(j_disc.dump_canonical(), + "[json.exception.type_error.317] type cannot be serialized in canonical JSON (RFC 8785): discarded", + 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}"); + } +} From 655f11081020c5657f9e0c9aa9a1f0f881093b65 Mon Sep 17 00:00:00 2001 From: Saurabh Tiwari Date: Wed, 21 Oct 2026 10:06:24 +0530 Subject: [PATCH 2/6] Address review feedback on canonical dump depth and float formatting - Bound dump_canonical_internal recursion with recursion_depth_limit() and fall back to dump_canonical_iteratively to avoid stack overflow on deeply nested documents (#5387). - Route double canonical serialization through Zmij (to_shortest) to guarantee shortest decimal representation per RFC 8785 section 3.2.2.3. - Add regression test for nesting depth beyond 512 levels. - Update amalgamated header single_include/nlohmann/json.hpp. Signed-off-by: Saurabh Tiwari --- include/nlohmann/detail/output/serializer.hpp | 334 +++++++++++++++--- single_include/nlohmann/json.hpp | 334 +++++++++++++++--- tests/src/unit-canonical_json.cpp | 37 ++ 3 files changed, 615 insertions(+), 90 deletions(-) diff --git a/include/nlohmann/detail/output/serializer.hpp b/include/nlohmann/detail/output/serializer.hpp index c4d8db4532..1b76cf150a 100644 --- a/include/nlohmann/detail/output/serializer.hpp +++ b/include/nlohmann/detail/output/serializer.hpp @@ -215,6 +215,47 @@ inline char* format_buffer_ecmascript(char* buf, int len, int decimal_exponent) return append_exponent_ecmascript(buf, n - 1); } +template +inline void get_shortest_digits(FloatType x, char* buf, int& 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; + + char temp[24]; + int 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, char* buf, int& len, int& decimal_exponent, std::false_type /*is_binary64*/) +{ + ::nlohmann::detail::dtoa_impl::grisu2(buf, len, decimal_exponent, x); +} + /////////////////// // serialization // /////////////////// @@ -306,20 +347,255 @@ class serializer */ void dump_canonical(const BasicJsonType& val) { - dump_canonical_internal(val); + dump_canonical_internal(val, 0); flush(); } JSON_PRIVATE_UNLESS_TESTED: + /// @brief a container that has been opened for iterative canonical dump + struct canonical_dump_frame + { + using value_type = typename BasicJsonType::object_t::value_type; + + 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()) + { + const auto* obj = c->m_data.m_value.object; + 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); + }); + } + } + }; + + /*! + @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_integer(val.m_data.m_value.number_integer); + return; + } + + case value_t::number_unsigned: + { + dump_integer(val.m_data.m_value.number_unsigned); + return; + } + + case value_t::number_float: + { + dump_float_canonical(val.m_data.m_value.number_float, &val); + return; + } + + case value_t::null: + { + put_literal("null"); + return; + } + + 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); + + while (!stack.empty()) + { + canonical_dump_frame& frame = stack.back(); + + if (frame.container->is_object()) + { + if (frame.current_idx < frame.sorted_elements.size()) + { + if (frame.current_idx > 0) + { + put_char(','); + } + + const auto* elem = frame.sorted_elements[frame.current_idx]; + ++frame.current_idx; + + put_char('"'); + dump_escaped(elem->first); + put_char('"'); + put_char(':'); + + const BasicJsonType& child = elem->second; + 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); + } + } + else + { + put_char('}'); + stack.pop_back(); + } + } + else // is_array + { + const auto* arr = frame.container->m_data.m_value.array; + if (frame.current_idx < arr->size()) + { + if (frame.current_idx > 0) + { + put_char(','); + } + + const BasicJsonType& child = (*arr)[frame.current_idx]; + ++frame.current_idx; + + 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); + } + } + else + { + put_char(']'); + stack.pop_back(); + } + } + } + } + /*! @brief worker for @ref dump_canonical */ - void dump_canonical_internal(const BasicJsonType& val) + 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()) { @@ -352,7 +628,7 @@ class serializer dump_escaped(sorted_elements[i]->first); put_char('"'); put_char(':'); - dump_canonical_internal(sorted_elements[i]->second); + dump_canonical_internal(sorted_elements[i]->second, depth + 1); } put_char('}'); @@ -361,6 +637,12 @@ class serializer 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()) { @@ -375,62 +657,24 @@ class serializer { put_char(','); } - dump_canonical_internal((*arr)[i]); + dump_canonical_internal((*arr)[i], depth + 1); } put_char(']'); return; } 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_integer(val.m_data.m_value.number_integer); - return; - } - case value_t::number_unsigned: - { - dump_integer(val.m_data.m_value.number_unsigned); - return; - } - case value_t::number_float: - { - dump_float_canonical(val.m_data.m_value.number_float, &val); - return; - } - case value_t::null: - { - put_literal("null"); - return; - } - 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)); + dump_canonical_scalar(val); + return; } } } @@ -460,7 +704,7 @@ class serializer char buf[128]; int len = 0; int decimal_exponent = 0; - ::nlohmann::detail::dtoa_impl::grisu2(buf, len, decimal_exponent, x); + get_shortest_digits(x, buf, len, decimal_exponent, typename dtoa_impl::is_binary64::type{}); char* const end = format_buffer_ecmascript(buf, len, decimal_exponent); const auto str_len = static_cast(end - buf); diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 57a6800521..0b9eefe86f 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -32472,6 +32472,47 @@ inline char* format_buffer_ecmascript(char* buf, int len, int decimal_exponent) return append_exponent_ecmascript(buf, n - 1); } +template +inline void get_shortest_digits(FloatType x, char* buf, int& 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; + + char temp[24]; + int 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, char* buf, int& len, int& decimal_exponent, std::false_type /*is_binary64*/) +{ + ::nlohmann::detail::dtoa_impl::grisu2(buf, len, decimal_exponent, x); +} + /////////////////// // serialization // /////////////////// @@ -32563,20 +32604,255 @@ class serializer */ void dump_canonical(const BasicJsonType& val) { - dump_canonical_internal(val); + dump_canonical_internal(val, 0); flush(); } JSON_PRIVATE_UNLESS_TESTED: + /// @brief a container that has been opened for iterative canonical dump + struct canonical_dump_frame + { + using value_type = typename BasicJsonType::object_t::value_type; + + 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()) + { + const auto* obj = c->m_data.m_value.object; + 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); + }); + } + } + }; + + /*! + @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_integer(val.m_data.m_value.number_integer); + return; + } + + case value_t::number_unsigned: + { + dump_integer(val.m_data.m_value.number_unsigned); + return; + } + + case value_t::number_float: + { + dump_float_canonical(val.m_data.m_value.number_float, &val); + return; + } + + case value_t::null: + { + put_literal("null"); + return; + } + + 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); + + while (!stack.empty()) + { + canonical_dump_frame& frame = stack.back(); + + if (frame.container->is_object()) + { + if (frame.current_idx < frame.sorted_elements.size()) + { + if (frame.current_idx > 0) + { + put_char(','); + } + + const auto* elem = frame.sorted_elements[frame.current_idx]; + ++frame.current_idx; + + put_char('"'); + dump_escaped(elem->first); + put_char('"'); + put_char(':'); + + const BasicJsonType& child = elem->second; + 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); + } + } + else + { + put_char('}'); + stack.pop_back(); + } + } + else // is_array + { + const auto* arr = frame.container->m_data.m_value.array; + if (frame.current_idx < arr->size()) + { + if (frame.current_idx > 0) + { + put_char(','); + } + + const BasicJsonType& child = (*arr)[frame.current_idx]; + ++frame.current_idx; + + 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); + } + } + else + { + put_char(']'); + stack.pop_back(); + } + } + } + } + /*! @brief worker for @ref dump_canonical */ - void dump_canonical_internal(const BasicJsonType& val) + 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()) { @@ -32609,7 +32885,7 @@ class serializer dump_escaped(sorted_elements[i]->first); put_char('"'); put_char(':'); - dump_canonical_internal(sorted_elements[i]->second); + dump_canonical_internal(sorted_elements[i]->second, depth + 1); } put_char('}'); @@ -32618,6 +32894,12 @@ class serializer 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()) { @@ -32632,62 +32914,24 @@ class serializer { put_char(','); } - dump_canonical_internal((*arr)[i]); + dump_canonical_internal((*arr)[i], depth + 1); } put_char(']'); return; } 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_integer(val.m_data.m_value.number_integer); - return; - } - case value_t::number_unsigned: - { - dump_integer(val.m_data.m_value.number_unsigned); - return; - } - case value_t::number_float: - { - dump_float_canonical(val.m_data.m_value.number_float, &val); - return; - } - case value_t::null: - { - put_literal("null"); - return; - } - 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)); + dump_canonical_scalar(val); + return; } } } @@ -32717,7 +32961,7 @@ class serializer char buf[128]; int len = 0; int decimal_exponent = 0; - ::nlohmann::detail::dtoa_impl::grisu2(buf, len, decimal_exponent, x); + get_shortest_digits(x, buf, len, decimal_exponent, typename dtoa_impl::is_binary64::type{}); char* const end = format_buffer_ecmascript(buf, len, decimal_exponent); const auto str_len = static_cast(end - buf); diff --git a/tests/src/unit-canonical_json.cpp b/tests/src/unit-canonical_json.cpp index c4ad0fa9af..aaf69de1a9 100644 --- a/tests/src/unit-canonical_json.cpp +++ b/tests/src/unit-canonical_json.cpp @@ -230,4 +230,41 @@ TEST_CASE("canonical JSON serialization (RFC 8785 / JCS)") 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); + } } From b925e70495bcedbc57776022c13ae65dde864c22 Mon Sep 17 00:00:00 2001 From: Saurabh Tiwari Date: Wed, 21 Oct 2026 12:11:12 +0530 Subject: [PATCH 3/6] Fix lint, code-scanning alerts, and format canonical serialization - Replace statically-sized C arrays with std::array in serializer helpers to satisfy clang-tidy (modernize-avoid-c-arrays) and resolve Flawfinder CWE-119/CWE-120 alerts. - Use serializer's put_buffer() for bounded, checked writes in dump_float_canonical() instead of manual memcpy. - Add const-correctness to format_buffer_ecmascript end pointer. - Reformat dump_canonical.md to conform to documentation linter rules (wrap lines to <= 160 chars and nest specification rules under Notes section). - Apply astyle formatting to lambda sorting and tests/src/unit-canonical_json.cpp. - Update amalgamated header single_include/nlohmann/json.hpp. Signed-off-by: Saurabh Tiwari --- .../docs/api/basic_json/dump_canonical.md | 57 +++++++++++------- include/nlohmann/detail/output/serializer.hpp | 37 ++++++------ single_include/nlohmann/json.hpp | 59 ++++++++++--------- tests/src/unit-canonical_json.cpp | 11 ++-- 4 files changed, 90 insertions(+), 74 deletions(-) diff --git a/docs/mkdocs/docs/api/basic_json/dump_canonical.md b/docs/mkdocs/docs/api/basic_json/dump_canonical.md index 6240f4fc82..1db1c60c05 100644 --- a/docs/mkdocs/docs/api/basic_json/dump_canonical.md +++ b/docs/mkdocs/docs/api/basic_json/dump_canonical.md @@ -8,12 +8,18 @@ string_t dump_canonical() const; 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))**. +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. +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). +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 @@ -28,29 +34,38 @@ Canonical JSON serialization produces a deterministic, byte-for-byte identical r (1) `string_t` containing the canonical serialization of the JSON value. (2) none. -## Rules of RFC 8785 Canonical JSON +## Exceptions -The serialization strictly adheres to [RFC 8785](https://datatracker.ietf.org/doc/html/rfc8785): +- 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). -- **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 without exponents. -- **Unsupported Types**: Non-finite numbers (`NaN`, `Infinity`, `-Infinity`), binary values, and discarded values cannot be serialized in canonical JSON. +## Complexity -## Exceptions +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). -- 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). +## Notes -## Complexity +The canonical serialization strictly adheres to [RFC 8785](https://datatracker.ietf.org/doc/html/rfc8785): -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). +- **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 diff --git a/include/nlohmann/detail/output/serializer.hpp b/include/nlohmann/detail/output/serializer.hpp index 1b76cf150a..3248f07474 100644 --- a/include/nlohmann/detail/output/serializer.hpp +++ b/include/nlohmann/detail/output/serializer.hpp @@ -152,8 +152,8 @@ inline char* append_exponent_ecmascript(char* buf, int e) noexcept *buf++ = '+'; } - char temp[16]; - int idx = 0; + std::array temp{{}}; + std::size_t idx = 0; auto val = static_cast(e); if (val == 0) { @@ -224,8 +224,8 @@ inline void get_shortest_digits(FloatType x, char* buf, int& len, int& decimal_e std::uint64_t significand = sd.has_digit ? (sd.integral * 10) + sd.digit : sd.integral; decimal_exponent = sd.has_digit ? sd.exponent : sd.exponent + 1; - char temp[24]; - int temp_idx = 0; + std::array temp{{}}; + std::size_t temp_idx = 0; while (significand > 0) { temp[temp_idx++] = static_cast('0' + (significand % 10)); @@ -373,9 +373,10 @@ class serializer 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); - }); + [](const value_type * a, const value_type * b) + { + return utf16_code_unit_less{}(a->first, b->first); + }); } } }; @@ -614,9 +615,10 @@ class serializer } 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); - }); + [](const value_type * a, const value_type * b) + { + return utf16_code_unit_less{}(a->first, b->first); + }); for (std::size_t i = 0; i < sorted_elements.size(); ++i) { @@ -701,20 +703,15 @@ class serializer x = -x; } - char buf[128]; + std::array buf{{}}; int len = 0; int decimal_exponent = 0; - get_shortest_digits(x, buf, len, decimal_exponent, typename dtoa_impl::is_binary64::type{}); + get_shortest_digits(x, buf.data(), len, decimal_exponent, typename dtoa_impl::is_binary64::type{}); - char* const end = format_buffer_ecmascript(buf, len, decimal_exponent); - const auto str_len = static_cast(end - buf); + const char* const end = format_buffer_ecmascript(buf.data(), len, decimal_exponent); + const auto str_len = static_cast(end - buf.data()); - if (JSON_HEDLEY_UNLIKELY(write_buffer_pos + str_len > write_buffer.size())) - { - flush(); - } - std::memcpy(write_buffer.data() + write_buffer_pos, buf, str_len); - write_buffer_pos += str_len; + put_buffer(buf, str_len); } JSON_PRIVATE_UNLESS_TESTED: diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 0b9eefe86f..96e09d2f4b 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -32299,6 +32299,10 @@ NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { +///////////////////////////////////////////////////////// +// JSON Canonicalization Scheme (RFC 8785) helpers // +///////////////////////////////////////////////////////// + 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) @@ -32307,7 +32311,6 @@ inline bool next_utf16_code_unit(const char*& p, const char* end, std::uint16_t& pending_surrogate = 0; return true; } - if (p >= end) { return false; @@ -32324,8 +32327,7 @@ inline bool next_utf16_code_unit(const char*& p, const char* end, std::uint16_t& if (p < end) { const auto b1 = static_cast(*p++); - const auto cp = static_cast(((b0 & 0x1F) << 6) | (b1 & 0x3F)); - out_code_unit = static_cast(cp); + out_code_unit = static_cast(((b0 & 0x1F) << 6) | (b1 & 0x3F)); return true; } } @@ -32335,8 +32337,7 @@ inline bool next_utf16_code_unit(const char*& p, const char* end, std::uint16_t& { const auto b1 = static_cast(*p++); const auto b2 = static_cast(*p++); - const auto cp = static_cast(((b0 & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F)); - out_code_unit = static_cast(cp); + out_code_unit = static_cast(((b0 & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F)); return true; } } @@ -32347,12 +32348,15 @@ inline bool next_utf16_code_unit(const char*& p, const char* end, std::uint16_t& const auto b1 = static_cast(*p++); const auto b2 = static_cast(*p++); const auto b3 = static_cast(*p++); - const auto cp = static_cast(((b0 & 0x07) << 18) | ((b1 & 0x3F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F)); + 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) { - const auto u = cp - 0x10000; - out_code_unit = static_cast(0xD800 + (u >> 10)); - pending_surrogate = static_cast(0xDC00 + (u & 0x3FF)); + cp -= 0x10000; + out_code_unit = static_cast(0xD800 + (cp >> 10)); + pending_surrogate = static_cast(0xDC00 + (cp & 0x3FF)); return true; } } @@ -32409,8 +32413,8 @@ inline char* append_exponent_ecmascript(char* buf, int e) noexcept *buf++ = '+'; } - char temp[16]; - int idx = 0; + std::array temp{{}}; + std::size_t idx = 0; auto val = static_cast(e); if (val == 0) { @@ -32481,8 +32485,8 @@ inline void get_shortest_digits(FloatType x, char* buf, int& len, int& decimal_e std::uint64_t significand = sd.has_digit ? (sd.integral * 10) + sd.digit : sd.integral; decimal_exponent = sd.has_digit ? sd.exponent : sd.exponent + 1; - char temp[24]; - int temp_idx = 0; + std::array temp{{}}; + std::size_t temp_idx = 0; while (significand > 0) { temp[temp_idx++] = static_cast('0' + (significand % 10)); @@ -32630,9 +32634,10 @@ class serializer 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); - }); + [](const value_type * a, const value_type * b) + { + return utf16_code_unit_less{}(a->first, b->first); + }); } } }; @@ -32871,9 +32876,10 @@ class serializer } 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); - }); + [](const value_type * a, const value_type * b) + { + return utf16_code_unit_less{}(a->first, b->first); + }); for (std::size_t i = 0; i < sorted_elements.size(); ++i) { @@ -32958,20 +32964,15 @@ class serializer x = -x; } - char buf[128]; + std::array buf{{}}; int len = 0; int decimal_exponent = 0; - get_shortest_digits(x, buf, len, decimal_exponent, typename dtoa_impl::is_binary64::type{}); + get_shortest_digits(x, buf.data(), len, decimal_exponent, typename dtoa_impl::is_binary64::type{}); - char* const end = format_buffer_ecmascript(buf, len, decimal_exponent); - const auto str_len = static_cast(end - buf); + const char* const end = format_buffer_ecmascript(buf.data(), len, decimal_exponent); + const auto str_len = static_cast(end - buf.data()); - if (JSON_HEDLEY_UNLIKELY(write_buffer_pos + str_len > write_buffer.size())) - { - flush(); - } - std::memcpy(write_buffer.data() + write_buffer_pos, buf, str_len); - write_buffer_pos += str_len; + put_buffer(buf, str_len); } JSON_PRIVATE_UNLESS_TESTED: diff --git a/tests/src/unit-canonical_json.cpp b/tests/src/unit-canonical_json.cpp index aaf69de1a9..ef70c84fb8 100644 --- a/tests/src/unit-canonical_json.cpp +++ b/tests/src/unit-canonical_json.cpp @@ -36,7 +36,7 @@ TEST_CASE("canonical JSON serialization (RFC 8785 / JCS)") 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\":{}}"); + == "{\"empty_arr\":[],\"empty_obj\":{}}"); } SECTION("string escaping according to RFC 8785") @@ -119,13 +119,15 @@ TEST_CASE("canonical JSON serialization (RFC 8785 / JCS)") SECTION("reproducible byte-identical output across different key insertion orders") { - ordered_json doc1 = { + ordered_json doc1 = + { {"user", {{"id", 101}, {"name", "Alice"}, {"role", "admin"}}}, {"active", true}, {"tags", {"security", "audit"}} }; - ordered_json doc2 = { + ordered_json doc2 = + { {"tags", {"security", "audit"}}, {"active", true}, {"user", {{"role", "admin"}, {"id", 101}, {"name", "Alice"}}} @@ -143,7 +145,8 @@ TEST_CASE("canonical JSON serialization (RFC 8785 / JCS)") const char* expected; }; - const std::vector test_vectors = { + const std::vector test_vectors = + { { "arrays", "[\n 56,\n {\n \"d\": true,\n \"10\": null,\n \"1\": [ ]\n }\n]\n", From d7751cdb0c41d18a79809106522a3d43c9018b25 Mon Sep 17 00:00:00 2001 From: Saurabh Tiwari Date: Wed, 21 Oct 2026 17:45:07 +0530 Subject: [PATCH 4/6] Fix compiler warnings on GCC and Clang matrix builds - tests/src/unit-canonical_json.cpp: Cast dump_canonical() calls in CHECK_THROWS_WITH_AS to void to satisfy -Werror=unused-result. - tests/src/unit-canonical_json.cpp: Remove trailing semicolon after CAPTURE macro to satisfy -Wextra-semi-stmt. - include/nlohmann/detail/output/serializer.hpp & single_include: Add explicit object and array cases in dump_canonical_scalar switch to satisfy -Wswitch-enum. - include/nlohmann/detail/output/serializer.hpp & single_include: Suppress -Wfloat-equal for zero comparison in dump_float_canonical. Signed-off-by: Saurabh Tiwari --- include/nlohmann/detail/output/serializer.hpp | 13 ++++++++++++- single_include/nlohmann/json.hpp | 13 ++++++++++++- tests/src/unit-canonical_json.cpp | 12 ++++++------ 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/include/nlohmann/detail/output/serializer.hpp b/include/nlohmann/detail/output/serializer.hpp index 3248f07474..2dfe450dce 100644 --- a/include/nlohmann/detail/output/serializer.hpp +++ b/include/nlohmann/detail/output/serializer.hpp @@ -433,6 +433,8 @@ class serializer return; } + case value_t::object: + case value_t::array: case value_t::binary: case value_t::discarded: default: @@ -691,7 +693,16 @@ class serializer JSON_THROW(out_of_range::create(exception_id::number_overflow, "cannot serialize non-finite numbers in canonical mode", context)); } - if (x == 0) +#ifdef __GNUC__ + JSON_HEDLEY_DIAGNOSTIC_PUSH + JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") +#endif + const bool is_zero = (x == 0); +#ifdef __GNUC__ + JSON_HEDLEY_DIAGNOSTIC_POP +#endif + + if (is_zero) { put_char('0'); return; diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 96e09d2f4b..715ecbf5ce 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -32694,6 +32694,8 @@ class serializer return; } + case value_t::object: + case value_t::array: case value_t::binary: case value_t::discarded: default: @@ -32952,7 +32954,16 @@ class serializer JSON_THROW(out_of_range::create(exception_id::number_overflow, "cannot serialize non-finite numbers in canonical mode", context)); } - if (x == 0) +#ifdef __GNUC__ + JSON_HEDLEY_DIAGNOSTIC_PUSH + JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") +#endif + const bool is_zero = (x == 0); +#ifdef __GNUC__ + JSON_HEDLEY_DIAGNOSTIC_POP +#endif + + if (is_zero) { put_char('0'); return; diff --git a/tests/src/unit-canonical_json.cpp b/tests/src/unit-canonical_json.cpp index ef70c84fb8..63f743971d 100644 --- a/tests/src/unit-canonical_json.cpp +++ b/tests/src/unit-canonical_json.cpp @@ -181,7 +181,7 @@ TEST_CASE("canonical JSON serialization (RFC 8785 / JCS)") for (const auto& vec : test_vectors) { - CAPTURE(vec.name); + CAPTURE(vec.name) json j = json::parse(vec.input); CHECK(j.dump_canonical() == vec.expected); @@ -194,30 +194,30 @@ TEST_CASE("canonical JSON serialization (RFC 8785 / JCS)") { // NaN is rejected json j_nan = std::numeric_limits::quiet_NaN(); - CHECK_THROWS_WITH_AS(j_nan.dump_canonical(), + 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(j_inf.dump_canonical(), + 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(j_neg_inf.dump_canonical(), + 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(j_bin.dump_canonical(), + 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(j_disc.dump_canonical(), + 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&); } From 07f22f8eb32a1b815507b3677bf2d6651faa7cfa Mon Sep 17 00:00:00 2001 From: Saurabh Tiwari Date: Thu, 22 Oct 2026 17:40:42 +0530 Subject: [PATCH 5/6] Address review comments on canonical JSON serialization - serializer.hpp & single_include: Avoid potential dangling reference or reallocation invalidation in dump_canonical_iteratively by using direct indexing on stack.back(). - serializer.hpp & single_include: Extract push_or_dump_child lambda to deduplicate child handling in dump_canonical_iteratively. - serializer.hpp & single_include: Extract sort_canonical_object_elements static helper to eliminate duplicate UTF-16 code unit sorting logic. - serializer.hpp & single_include: Merge put_char('"') and put_char(':') into put_literal("\":"). - serializer.hpp & single_include: Assert and throw type_error on container types in dump_canonical_scalar instead of silent break. - serializer.hpp & single_include: Pass std::array& by reference and return std::size_t len in format_buffer_ecmascript, append_exponent_ecmascript, and get_shortest_digits to prevent raw pointer decay. - serializer.hpp & single_include: Suppress -Wfloat-equal warning around zero comparison in dump_float_canonical. - dump_canonical.md: Update @since version tag to 3.13.0. Signed-off-by: Saurabh Tiwari --- .../docs/api/basic_json/dump_canonical.md | 2 +- include/nlohmann/detail/output/serializer.hpp | 238 ++++++++---------- single_include/nlohmann/json.hpp | 238 ++++++++---------- 3 files changed, 211 insertions(+), 267 deletions(-) diff --git a/docs/mkdocs/docs/api/basic_json/dump_canonical.md b/docs/mkdocs/docs/api/basic_json/dump_canonical.md index 1db1c60c05..af585a7f89 100644 --- a/docs/mkdocs/docs/api/basic_json/dump_canonical.md +++ b/docs/mkdocs/docs/api/basic_json/dump_canonical.md @@ -100,4 +100,4 @@ The canonical serialization strictly adheres to [RFC 8785](https://datatracker.i ## Version history -- Added in version 3.12.0. +- Added in version 3.13.0. diff --git a/include/nlohmann/detail/output/serializer.hpp b/include/nlohmann/detail/output/serializer.hpp index 2dfe450dce..12766e7469 100644 --- a/include/nlohmann/detail/output/serializer.hpp +++ b/include/nlohmann/detail/output/serializer.hpp @@ -140,16 +140,16 @@ struct utf16_code_unit_less } }; -inline char* append_exponent_ecmascript(char* buf, int e) noexcept +inline std::size_t append_exponent_ecmascript(std::array& buf, std::size_t pos, int e) noexcept { if (e < 0) { - *buf++ = '-'; + buf[pos++] = '-'; e = -e; } else { - *buf++ = '+'; + buf[pos++] = '+'; } std::array temp{{}}; @@ -157,8 +157,8 @@ inline char* append_exponent_ecmascript(char* buf, int e) noexcept auto val = static_cast(e); if (val == 0) { - *buf++ = '0'; - return buf; + buf[pos++] = '0'; + return pos; } while (val > 0) { @@ -167,56 +167,57 @@ inline char* append_exponent_ecmascript(char* buf, int e) noexcept } while (idx > 0) { - *buf++ = temp[--idx]; + buf[pos++] = temp[--idx]; } - return buf; + return pos; } -inline char* format_buffer_ecmascript(char* buf, int len, int decimal_exponent) noexcept +inline std::size_t format_buffer_ecmascript(std::array& buf, std::size_t len, int decimal_exponent) noexcept { - const int k = len; - const int n = len + decimal_exponent; + const auto k = static_cast(len); + const int n = k + decimal_exponent; if (k <= n && n <= 21) { - std::memset(buf + k, '0', static_cast(n - k)); - return buf + n; + std::memset(buf.data() + k, '0', static_cast(n - k)); + return static_cast(n); } if (0 < n && n <= 21) { - std::memmove(buf + (n + 1), buf + n, static_cast(k - n)); - buf[n] = '.'; - return buf + (k + 1); + 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 + (2 + zeros), buf, static_cast(k)); + std::memmove(buf.data() + (2 + zeros), buf.data(), static_cast(k)); buf[0] = '0'; buf[1] = '.'; - std::memset(buf + 2, '0', zeros); - return buf + (2 + zeros + static_cast(k)); + std::memset(buf.data() + 2, '0', zeros); + return 2 + zeros + static_cast(k); } + std::size_t pos = 0; if (k == 1) { - buf += 1; + pos = 1; } else { - std::memmove(buf + 2, buf + 1, static_cast(k - 1)); + std::memmove(buf.data() + 2, buf.data() + 1, static_cast(k - 1)); buf[1] = '.'; - buf += 1 + static_cast(k); + pos = 1 + static_cast(k); } - *buf++ = 'e'; - return append_exponent_ecmascript(buf, n - 1); + buf[pos++] = 'e'; + return append_exponent_ecmascript(buf, pos, n - 1); } template -inline void get_shortest_digits(FloatType x, char* buf, int& len, int& decimal_exponent, std::true_type /*is_binary64*/) +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)); @@ -251,9 +252,11 @@ inline void get_shortest_digits(FloatType x, char* buf, int& len, int& decimal_e } template -inline void get_shortest_digits(FloatType x, char* buf, int& len, int& decimal_exponent, std::false_type /*is_binary64*/) +inline void get_shortest_digits(FloatType x, std::array& buf, std::size_t& len, int& decimal_exponent, std::false_type /*is_binary64*/) { - ::nlohmann::detail::dtoa_impl::grisu2(buf, len, decimal_exponent, x); + int l = 0; + ::nlohmann::detail::dtoa_impl::grisu2(buf.data(), l, decimal_exponent, x); + len = static_cast(l); } /////////////////// @@ -352,11 +355,27 @@ class serializer } 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 { - using value_type = typename BasicJsonType::object_t::value_type; - const BasicJsonType* container; std::vector sorted_elements{}; std::size_t current_idx = 0; @@ -366,17 +385,7 @@ class serializer { if (c->is_object()) { - const auto* obj = c->m_data.m_value.object; - 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); - }); + sorted_elements = sort_canonical_object_elements(*c->m_data.m_value.object); } } }; @@ -435,6 +444,11 @@ class serializer 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: @@ -476,56 +490,57 @@ class serializer std::vector stack; stack.emplace_back(&val); - while (!stack.empty()) + auto push_or_dump_child = [this, &stack](const BasicJsonType& child) { - canonical_dump_frame& frame = stack.back(); + 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); + } + }; - if (frame.container->is_object()) + while (!stack.empty()) + { + if (stack.back().container->is_object()) { - if (frame.current_idx < frame.sorted_elements.size()) + if (stack.back().current_idx < stack.back().sorted_elements.size()) { - if (frame.current_idx > 0) + if (stack.back().current_idx > 0) { put_char(','); } - const auto* elem = frame.sorted_elements[frame.current_idx]; - ++frame.current_idx; + const auto* elem = stack.back().sorted_elements[stack.back().current_idx]; + ++stack.back().current_idx; put_char('"'); dump_escaped(elem->first); - put_char('"'); - put_char(':'); + put_literal("\":"); - const BasicJsonType& child = elem->second; - 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); - } + push_or_dump_child(elem->second); } else { @@ -535,45 +550,18 @@ class serializer } else // is_array { - const auto* arr = frame.container->m_data.m_value.array; - if (frame.current_idx < arr->size()) + const auto* arr = stack.back().container->m_data.m_value.array; + if (stack.back().current_idx < arr->size()) { - if (frame.current_idx > 0) + if (stack.back().current_idx > 0) { put_char(','); } - const BasicJsonType& child = (*arr)[frame.current_idx]; - ++frame.current_idx; + const BasicJsonType& child = (*arr)[stack.back().current_idx]; + ++stack.back().current_idx; - 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); - } + push_or_dump_child(child); } else { @@ -608,20 +596,7 @@ class serializer put_char('{'); - using value_type = typename BasicJsonType::object_t::value_type; - 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); - }); - + const auto sorted_elements = sort_canonical_object_elements(*obj); for (std::size_t i = 0; i < sorted_elements.size(); ++i) { if (i > 0) @@ -630,8 +605,7 @@ class serializer } put_char('"'); dump_escaped(sorted_elements[i]->first); - put_char('"'); - put_char(':'); + put_literal("\":"); dump_canonical_internal(sorted_elements[i]->second, depth + 1); } @@ -693,12 +667,12 @@ class serializer JSON_THROW(out_of_range::create(exception_id::number_overflow, "cannot serialize non-finite numbers in canonical mode", context)); } -#ifdef __GNUC__ +#if defined(__GNUC__) || defined(__clang__) JSON_HEDLEY_DIAGNOSTIC_PUSH JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") #endif const bool is_zero = (x == 0); -#ifdef __GNUC__ +#if defined(__GNUC__) || defined(__clang__) JSON_HEDLEY_DIAGNOSTIC_POP #endif @@ -715,13 +689,11 @@ class serializer } std::array buf{{}}; - int len = 0; + std::size_t len = 0; int decimal_exponent = 0; - get_shortest_digits(x, buf.data(), len, decimal_exponent, typename dtoa_impl::is_binary64::type{}); - - const char* const end = format_buffer_ecmascript(buf.data(), len, decimal_exponent); - const auto str_len = static_cast(end - buf.data()); + get_shortest_digits(x, buf, len, decimal_exponent, typename dtoa_impl::is_binary64::type{}); + const std::size_t str_len = format_buffer_ecmascript(buf, len, decimal_exponent); put_buffer(buf, str_len); } diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 715ecbf5ce..5e5fc93acc 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -32401,16 +32401,16 @@ struct utf16_code_unit_less } }; -inline char* append_exponent_ecmascript(char* buf, int e) noexcept +inline std::size_t append_exponent_ecmascript(std::array& buf, std::size_t pos, int e) noexcept { if (e < 0) { - *buf++ = '-'; + buf[pos++] = '-'; e = -e; } else { - *buf++ = '+'; + buf[pos++] = '+'; } std::array temp{{}}; @@ -32418,8 +32418,8 @@ inline char* append_exponent_ecmascript(char* buf, int e) noexcept auto val = static_cast(e); if (val == 0) { - *buf++ = '0'; - return buf; + buf[pos++] = '0'; + return pos; } while (val > 0) { @@ -32428,56 +32428,57 @@ inline char* append_exponent_ecmascript(char* buf, int e) noexcept } while (idx > 0) { - *buf++ = temp[--idx]; + buf[pos++] = temp[--idx]; } - return buf; + return pos; } -inline char* format_buffer_ecmascript(char* buf, int len, int decimal_exponent) noexcept +inline std::size_t format_buffer_ecmascript(std::array& buf, std::size_t len, int decimal_exponent) noexcept { - const int k = len; - const int n = len + decimal_exponent; + const auto k = static_cast(len); + const int n = k + decimal_exponent; if (k <= n && n <= 21) { - std::memset(buf + k, '0', static_cast(n - k)); - return buf + n; + std::memset(buf.data() + k, '0', static_cast(n - k)); + return static_cast(n); } if (0 < n && n <= 21) { - std::memmove(buf + (n + 1), buf + n, static_cast(k - n)); - buf[n] = '.'; - return buf + (k + 1); + 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 + (2 + zeros), buf, static_cast(k)); + std::memmove(buf.data() + (2 + zeros), buf.data(), static_cast(k)); buf[0] = '0'; buf[1] = '.'; - std::memset(buf + 2, '0', zeros); - return buf + (2 + zeros + static_cast(k)); + std::memset(buf.data() + 2, '0', zeros); + return 2 + zeros + static_cast(k); } + std::size_t pos = 0; if (k == 1) { - buf += 1; + pos = 1; } else { - std::memmove(buf + 2, buf + 1, static_cast(k - 1)); + std::memmove(buf.data() + 2, buf.data() + 1, static_cast(k - 1)); buf[1] = '.'; - buf += 1 + static_cast(k); + pos = 1 + static_cast(k); } - *buf++ = 'e'; - return append_exponent_ecmascript(buf, n - 1); + buf[pos++] = 'e'; + return append_exponent_ecmascript(buf, pos, n - 1); } template -inline void get_shortest_digits(FloatType x, char* buf, int& len, int& decimal_exponent, std::true_type /*is_binary64*/) +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)); @@ -32512,9 +32513,11 @@ inline void get_shortest_digits(FloatType x, char* buf, int& len, int& decimal_e } template -inline void get_shortest_digits(FloatType x, char* buf, int& len, int& decimal_exponent, std::false_type /*is_binary64*/) +inline void get_shortest_digits(FloatType x, std::array& buf, std::size_t& len, int& decimal_exponent, std::false_type /*is_binary64*/) { - ::nlohmann::detail::dtoa_impl::grisu2(buf, len, decimal_exponent, x); + int l = 0; + ::nlohmann::detail::dtoa_impl::grisu2(buf.data(), l, decimal_exponent, x); + len = static_cast(l); } /////////////////// @@ -32613,11 +32616,27 @@ class serializer } 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 { - using value_type = typename BasicJsonType::object_t::value_type; - const BasicJsonType* container; std::vector sorted_elements{}; std::size_t current_idx = 0; @@ -32627,17 +32646,7 @@ class serializer { if (c->is_object()) { - const auto* obj = c->m_data.m_value.object; - 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); - }); + sorted_elements = sort_canonical_object_elements(*c->m_data.m_value.object); } } }; @@ -32696,6 +32705,11 @@ class serializer 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: @@ -32737,56 +32751,57 @@ class serializer std::vector stack; stack.emplace_back(&val); - while (!stack.empty()) + auto push_or_dump_child = [this, &stack](const BasicJsonType& child) { - canonical_dump_frame& frame = stack.back(); + 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); + } + }; - if (frame.container->is_object()) + while (!stack.empty()) + { + if (stack.back().container->is_object()) { - if (frame.current_idx < frame.sorted_elements.size()) + if (stack.back().current_idx < stack.back().sorted_elements.size()) { - if (frame.current_idx > 0) + if (stack.back().current_idx > 0) { put_char(','); } - const auto* elem = frame.sorted_elements[frame.current_idx]; - ++frame.current_idx; + const auto* elem = stack.back().sorted_elements[stack.back().current_idx]; + ++stack.back().current_idx; put_char('"'); dump_escaped(elem->first); - put_char('"'); - put_char(':'); + put_literal("\":"); - const BasicJsonType& child = elem->second; - 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); - } + push_or_dump_child(elem->second); } else { @@ -32796,45 +32811,18 @@ class serializer } else // is_array { - const auto* arr = frame.container->m_data.m_value.array; - if (frame.current_idx < arr->size()) + const auto* arr = stack.back().container->m_data.m_value.array; + if (stack.back().current_idx < arr->size()) { - if (frame.current_idx > 0) + if (stack.back().current_idx > 0) { put_char(','); } - const BasicJsonType& child = (*arr)[frame.current_idx]; - ++frame.current_idx; + const BasicJsonType& child = (*arr)[stack.back().current_idx]; + ++stack.back().current_idx; - 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); - } + push_or_dump_child(child); } else { @@ -32869,20 +32857,7 @@ class serializer put_char('{'); - using value_type = typename BasicJsonType::object_t::value_type; - 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); - }); - + const auto sorted_elements = sort_canonical_object_elements(*obj); for (std::size_t i = 0; i < sorted_elements.size(); ++i) { if (i > 0) @@ -32891,8 +32866,7 @@ class serializer } put_char('"'); dump_escaped(sorted_elements[i]->first); - put_char('"'); - put_char(':'); + put_literal("\":"); dump_canonical_internal(sorted_elements[i]->second, depth + 1); } @@ -32954,12 +32928,12 @@ class serializer JSON_THROW(out_of_range::create(exception_id::number_overflow, "cannot serialize non-finite numbers in canonical mode", context)); } -#ifdef __GNUC__ +#if defined(__GNUC__) || defined(__clang__) JSON_HEDLEY_DIAGNOSTIC_PUSH JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") #endif const bool is_zero = (x == 0); -#ifdef __GNUC__ +#if defined(__GNUC__) || defined(__clang__) JSON_HEDLEY_DIAGNOSTIC_POP #endif @@ -32976,13 +32950,11 @@ class serializer } std::array buf{{}}; - int len = 0; + std::size_t len = 0; int decimal_exponent = 0; - get_shortest_digits(x, buf.data(), len, decimal_exponent, typename dtoa_impl::is_binary64::type{}); - - const char* const end = format_buffer_ecmascript(buf.data(), len, decimal_exponent); - const auto str_len = static_cast(end - buf.data()); + get_shortest_digits(x, buf, len, decimal_exponent, typename dtoa_impl::is_binary64::type{}); + const std::size_t str_len = format_buffer_ecmascript(buf, len, decimal_exponent); put_buffer(buf, str_len); } From d4d43de6b1e7112567a0f804917a47b96edc570d Mon Sep 17 00:00:00 2001 From: Saurabh Tiwari Date: Fri, 23 Oct 2026 00:09:14 +0530 Subject: [PATCH 6/6] Format canonical numbers as IEEE 754 double and test lone surrogates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - serializer.hpp & single_include: Cast number_integer, number_unsigned, and number_float to double in dump_canonical_scalar to adhere to RFC 8785 §3.2.2.3 IEEE 754 binary64 rules for numbers beyond ±2^53. - serializer.hpp & single_include: Update dump_float_canonical to take double, resolving long double precision static_assert and float representation per JCS. - serializer.hpp & single_include: Add explanatory comments in next_utf16_code_unit and append_exponent_ecmascript. - unit-canonical_json.cpp: Add test cases for integer values beyond ±2^53, float to double formatting, and lone surrogate rejection (RFC 8785 §3.2.2.2). Signed-off-by: Saurabh Tiwari --- include/nlohmann/detail/output/serializer.hpp | 18 +++++++++++------- single_include/nlohmann/json.hpp | 18 +++++++++++------- tests/src/unit-canonical_json.cpp | 19 +++++++++++++++++++ 3 files changed, 41 insertions(+), 14 deletions(-) diff --git a/include/nlohmann/detail/output/serializer.hpp b/include/nlohmann/detail/output/serializer.hpp index 12766e7469..04000c4052 100644 --- a/include/nlohmann/detail/output/serializer.hpp +++ b/include/nlohmann/detail/output/serializer.hpp @@ -42,6 +42,8 @@ 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) @@ -140,6 +142,8 @@ struct utf16_code_unit_less } }; +// 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) @@ -420,19 +424,19 @@ class serializer case value_t::number_integer: { - dump_integer(val.m_data.m_value.number_integer); + dump_float_canonical(static_cast(val.m_data.m_value.number_integer), &val); return; } case value_t::number_unsigned: { - dump_integer(val.m_data.m_value.number_unsigned); + dump_float_canonical(static_cast(val.m_data.m_value.number_unsigned), &val); return; } case value_t::number_float: { - dump_float_canonical(val.m_data.m_value.number_float, &val); + dump_float_canonical(static_cast(val.m_data.m_value.number_float), &val); return; } @@ -658,9 +662,9 @@ class serializer } /*! - @brief dump a floating-point number according to RFC 8785 (ECMAScript Number::toString) + @brief dump a number according to RFC 8785 (ECMAScript Number::toString modeled as IEEE 754 binary64 double) */ - void dump_float_canonical(number_float_t x, const BasicJsonType* context) + void dump_float_canonical(double x, const BasicJsonType* context) { if (!std::isfinite(x)) { @@ -671,7 +675,7 @@ class serializer JSON_HEDLEY_DIAGNOSTIC_PUSH JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") #endif - const bool is_zero = (x == 0); + const bool is_zero = (x == 0.0); #if defined(__GNUC__) || defined(__clang__) JSON_HEDLEY_DIAGNOSTIC_POP #endif @@ -691,7 +695,7 @@ class serializer std::array buf{{}}; std::size_t len = 0; int decimal_exponent = 0; - get_shortest_digits(x, buf, len, decimal_exponent, typename dtoa_impl::is_binary64::type{}); + 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); diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 5e5fc93acc..391dd028ce 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -32303,6 +32303,8 @@ 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) @@ -32401,6 +32403,8 @@ struct utf16_code_unit_less } }; +// 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) @@ -32681,19 +32685,19 @@ class serializer case value_t::number_integer: { - dump_integer(val.m_data.m_value.number_integer); + dump_float_canonical(static_cast(val.m_data.m_value.number_integer), &val); return; } case value_t::number_unsigned: { - dump_integer(val.m_data.m_value.number_unsigned); + dump_float_canonical(static_cast(val.m_data.m_value.number_unsigned), &val); return; } case value_t::number_float: { - dump_float_canonical(val.m_data.m_value.number_float, &val); + dump_float_canonical(static_cast(val.m_data.m_value.number_float), &val); return; } @@ -32919,9 +32923,9 @@ class serializer } /*! - @brief dump a floating-point number according to RFC 8785 (ECMAScript Number::toString) + @brief dump a number according to RFC 8785 (ECMAScript Number::toString modeled as IEEE 754 binary64 double) */ - void dump_float_canonical(number_float_t x, const BasicJsonType* context) + void dump_float_canonical(double x, const BasicJsonType* context) { if (!std::isfinite(x)) { @@ -32932,7 +32936,7 @@ class serializer JSON_HEDLEY_DIAGNOSTIC_PUSH JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") #endif - const bool is_zero = (x == 0); + const bool is_zero = (x == 0.0); #if defined(__GNUC__) || defined(__clang__) JSON_HEDLEY_DIAGNOSTIC_POP #endif @@ -32952,7 +32956,7 @@ class serializer std::array buf{{}}; std::size_t len = 0; int decimal_exponent = 0; - get_shortest_digits(x, buf, len, decimal_exponent, typename dtoa_impl::is_binary64::type{}); + 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); diff --git a/tests/src/unit-canonical_json.cpp b/tests/src/unit-canonical_json.cpp index 63f743971d..d0b4de052c 100644 --- a/tests/src/unit-canonical_json.cpp +++ b/tests/src/unit-canonical_json.cpp @@ -106,6 +106,15 @@ TEST_CASE("canonical JSON serialization (RFC 8785 / JCS)") 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"); @@ -220,6 +229,16 @@ TEST_CASE("canonical JSON serialization (RFC 8785 / JCS)") 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")