| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| /****************************************************************************\ | |
| * Note on documentation: The source files contain links to the online * | |
| * documentation of the public API at https://json.nlohmann.me. This URL * | |
| * contains the most recent documentation and should also be applicable to * | |
| * previous versions; documentation for deprecated functions is not * | |
| * removed, but marked deprecated. See "Generate documentation" section in * | |
| * file docs/README.md. * | |
| \****************************************************************************/ | |
| #ifndef INCLUDE_NLOHMANN_JSON_HPP_ | |
| #define INCLUDE_NLOHMANN_JSON_HPP_ | |
| #include <algorithm> // all_of, find, for_each, none_of | |
| #include <array> // array | |
| #include <cmath> // isnan | |
| #include <cstddef> // nullptr_t, ptrdiff_t, size_t | |
| #include <cstdint> // uint8_t | |
| #include <functional> // hash, less | |
| #include <initializer_list> // initializer_list | |
| #ifndef JSON_NO_IO | |
| #include <iosfwd> // istream, ostream | |
| #endif // JSON_NO_IO | |
| #include <iterator> // make_move_iterator, random_access_iterator_tag | |
| #include <limits> // numeric_limits | |
| #include <map> // map | |
| #include <memory> // unique_ptr | |
| #include <set> // swap, operator!= | |
| #include <stdexcept> // length_error | |
| #include <string> // string, stoi, to_string | |
| #include <type_traits> // enable_if_t, is_same, is_scalar, ... | |
| #include <unordered_map> // swap (for the from_json(..., std::unordered_map&) overload) | |
| #include <utility> // declval, forward, move, pair, swap | |
| #include <vector> // vector | |
| // keep: json.hpp's own basic_json<> default template arguments need the complete definition of | |
| // each of these, not only the forward declarations from json_fwd.hpp, so IWYU's suggestion to | |
| // drop them (nothing in this file otherwise names the type) would break every downstream | |
| // translation unit that relies on basic_json<>'s defaults actually being usable. | |
| // export: client code names what these headers declare (nlohmann::json and ordered_json from | |
| // json_fwd.hpp, adl_serializer for specializations, json_ref behind brace initialization, the | |
| // NLOHMANN_DEFINE_* and NLOHMANN_JSON_NAMESPACE_* macros, and the literals at the end of this file), and include analyzers must | |
| // attribute it to this header, not tell clients to include the internal ones (issue #5812). | |
| // tests/iwyu_consumer checks this. | |
| // #include <nlohmann/adl_serializer.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <utility> | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| // This file contains all macro definitions affecting or depending on the ABI | |
| #ifndef JSON_SKIP_LIBRARY_VERSION_CHECK | |
| #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) | |
| #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 12 || NLOHMANN_JSON_VERSION_PATCH != 0 | |
| #warning "Already included a different version of the library!" | |
| #endif | |
| #endif | |
| #endif | |
| #define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) | |
| #define NLOHMANN_JSON_VERSION_MINOR 12 // NOLINT(modernize-macro-to-enum) | |
| #define NLOHMANN_JSON_VERSION_PATCH 0 // NOLINT(modernize-macro-to-enum) | |
| #ifndef JSON_DIAGNOSTICS | |
| #define JSON_DIAGNOSTICS 0 | |
| #endif | |
| #ifndef JSON_DIAGNOSTIC_POSITIONS | |
| #define JSON_DIAGNOSTIC_POSITIONS 0 | |
| #endif | |
| #ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON | |
| #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 | |
| #endif | |
| #ifndef JSON_BRACE_INIT_COPY_SEMANTICS | |
| #define JSON_BRACE_INIT_COPY_SEMANTICS 0 | |
| #endif | |
| #ifndef JSON_PRECISE_STREAM_POSITION | |
| #define JSON_PRECISE_STREAM_POSITION 0 | |
| #endif | |
| #ifndef JSON_STRICT_NUL_HANDLING | |
| #define JSON_STRICT_NUL_HANDLING 0 | |
| #endif | |
| #ifndef JSON_STRICT_BINARY_UTF8 | |
| #define JSON_STRICT_BINARY_UTF8 0 | |
| #endif | |
| #ifndef JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS | |
| #define JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS 0 | |
| #endif | |
| #ifndef JSON_DISABLE_STREAM_BULK_SCAN | |
| #define JSON_DISABLE_STREAM_BULK_SCAN 0 | |
| #endif | |
| #ifndef JSON_DISABLE_UNLOCKED_FILE_IO | |
| #define JSON_DISABLE_UNLOCKED_FILE_IO 0 | |
| #endif | |
| #if JSON_DIAGNOSTICS | |
| #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS | |
| #endif | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS _dp | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS | |
| #endif | |
| #if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON | |
| #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON | |
| #endif | |
| #if JSON_BRACE_INIT_COPY_SEMANTICS | |
| #define NLOHMANN_JSON_ABI_TAG_BRACE_INIT_COPY_SEMANTICS _bics | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_BRACE_INIT_COPY_SEMANTICS | |
| #endif | |
| #if JSON_PRECISE_STREAM_POSITION | |
| #define NLOHMANN_JSON_ABI_TAG_PRECISE_STREAM_POSITION _psp | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_PRECISE_STREAM_POSITION | |
| #endif | |
| #if JSON_STRICT_NUL_HANDLING | |
| #define NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING _snul | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING | |
| #endif | |
| #if JSON_STRICT_BINARY_UTF8 | |
| #define NLOHMANN_JSON_ABI_TAG_STRICT_BINARY_UTF8 _sbu8 | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_STRICT_BINARY_UTF8 | |
| #endif | |
| #if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS | |
| #define NLOHMANN_JSON_ABI_TAG_OBJECTS_FOR_ENUM_KEYED_MAPS _ekmo | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_OBJECTS_FOR_ENUM_KEYED_MAPS | |
| #endif | |
| #if JSON_DISABLE_STREAM_BULK_SCAN | |
| #define NLOHMANN_JSON_ABI_TAG_DISABLE_STREAM_BULK_SCAN _dsbs | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_DISABLE_STREAM_BULK_SCAN | |
| #endif | |
| #if JSON_DISABLE_UNLOCKED_FILE_IO | |
| #define NLOHMANN_JSON_ABI_TAG_DISABLE_UNLOCKED_FILE_IO _dufio | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_DISABLE_UNLOCKED_FILE_IO | |
| #endif | |
| #ifdef JSON_NO_SIMD | |
| #define NLOHMANN_JSON_ABI_TAG_NO_SIMD _ns | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_NO_SIMD | |
| #endif | |
| #ifdef JSON_VIEW_NO_SIMD | |
| #define NLOHMANN_JSON_ABI_TAG_VIEW_NO_SIMD _vns | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_VIEW_NO_SIMD | |
| #endif | |
| #ifdef JSON_VIEW_USE_SSSE3 | |
| #define NLOHMANN_JSON_ABI_TAG_VIEW_USE_SSSE3 _vssse3 | |
| #else | |
| #define NLOHMANN_JSON_ABI_TAG_VIEW_USE_SSSE3 | |
| #endif | |
| #ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION | |
| #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 | |
| #endif | |
| // Construct the namespace ABI tags component | |
| #define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f, g, h, i, j, k, l, m) json_abi ## a ## b ## c ## d ## e ## f ## g ## h ## i ## j ## k ## l ## m | |
| #define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c, d, e, f, g, h, i, j, k, l, m) \ | |
| NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f, g, h, i, j, k, l, m) | |
| #define NLOHMANN_JSON_ABI_TAGS \ | |
| NLOHMANN_JSON_ABI_TAGS_CONCAT( \ | |
| NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ | |
| NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON, \ | |
| NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS, \ | |
| NLOHMANN_JSON_ABI_TAG_BRACE_INIT_COPY_SEMANTICS, \ | |
| NLOHMANN_JSON_ABI_TAG_PRECISE_STREAM_POSITION, \ | |
| NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING, \ | |
| NLOHMANN_JSON_ABI_TAG_STRICT_BINARY_UTF8, \ | |
| NLOHMANN_JSON_ABI_TAG_OBJECTS_FOR_ENUM_KEYED_MAPS, \ | |
| NLOHMANN_JSON_ABI_TAG_DISABLE_STREAM_BULK_SCAN, \ | |
| NLOHMANN_JSON_ABI_TAG_DISABLE_UNLOCKED_FILE_IO, \ | |
| NLOHMANN_JSON_ABI_TAG_NO_SIMD, \ | |
| NLOHMANN_JSON_ABI_TAG_VIEW_NO_SIMD, \ | |
| NLOHMANN_JSON_ABI_TAG_VIEW_USE_SSSE3) | |
| // Construct the namespace version component | |
| #define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ | |
| _v ## major ## _ ## minor ## _ ## patch | |
| #define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ | |
| NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) | |
| #if NLOHMANN_JSON_NAMESPACE_NO_VERSION | |
| #define NLOHMANN_JSON_NAMESPACE_VERSION | |
| #else | |
| #define NLOHMANN_JSON_NAMESPACE_VERSION \ | |
| NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ | |
| NLOHMANN_JSON_VERSION_MINOR, \ | |
| NLOHMANN_JSON_VERSION_PATCH) | |
| #endif | |
| // Combine namespace components | |
| #define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b | |
| #define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ | |
| NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) | |
| #ifndef NLOHMANN_JSON_NAMESPACE | |
| #define NLOHMANN_JSON_NAMESPACE \ | |
| nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ | |
| NLOHMANN_JSON_ABI_TAGS, \ | |
| NLOHMANN_JSON_NAMESPACE_VERSION) | |
| #endif | |
| #ifndef NLOHMANN_JSON_NAMESPACE_BEGIN | |
| #define NLOHMANN_JSON_NAMESPACE_BEGIN \ | |
| namespace nlohmann \ | |
| { \ | |
| inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ | |
| NLOHMANN_JSON_ABI_TAGS, \ | |
| NLOHMANN_JSON_NAMESPACE_VERSION) \ | |
| { | |
| #endif | |
| #ifndef NLOHMANN_JSON_NAMESPACE_END | |
| #define NLOHMANN_JSON_NAMESPACE_END \ | |
| } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ | |
| } // namespace nlohmann | |
| #endif | |
| // #include <nlohmann/detail/conversions/from_json.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <algorithm> // min, transform | |
| #include <array> // array | |
| #include <forward_list> // forward_list | |
| #include <iterator> // inserter, front_inserter, end | |
| #include <map> // map | |
| #include <string> // string | |
| #include <tuple> // tuple, make_tuple | |
| #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible | |
| #include <unordered_map> // unordered_map | |
| #include <utility> // pair, declval | |
| #include <valarray> // valarray | |
| #include <vector> // vector | |
| // #include <nlohmann/detail/exceptions.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cstddef> // nullptr_t | |
| #include <exception> // exception | |
| #if JSON_DIAGNOSTICS | |
| #include <numeric> // accumulate | |
| #endif | |
| #include <stdexcept> // runtime_error | |
| #include <string> // to_string | |
| #include <vector> // vector | |
| // #include <nlohmann/detail/value_t.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <array> // array | |
| #include <cmath> // isnan, ldexp, trunc | |
| #include <cstddef> // size_t | |
| #include <cstdint> // uint8_t | |
| #include <limits> // numeric_limits | |
| #include <string> // string | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <utility> // declval, pair | |
| // #include <nlohmann/thirdparty/hedley/hedley.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-FileCopyrightText: 2016-2021 Evan Nemerson <evan@nemerson.com> | |
| // SPDX-License-Identifier: MIT | |
| /* Hedley - https://nemequ.github.io/hedley | |
| * Created by Evan Nemerson <evan@nemerson.com> | |
| * SPDX-License-Identifier: CC0-1.0 | |
| */ | |
| #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) | |
| #if defined(JSON_HEDLEY_VERSION) | |
| #undef JSON_HEDLEY_VERSION | |
| #endif | |
| #define JSON_HEDLEY_VERSION 15 | |
| #if defined(JSON_HEDLEY_STRINGIFY_EX) | |
| #undef JSON_HEDLEY_STRINGIFY_EX | |
| #endif | |
| #define JSON_HEDLEY_STRINGIFY_EX(x) #x | |
| #if defined(JSON_HEDLEY_STRINGIFY) | |
| #undef JSON_HEDLEY_STRINGIFY | |
| #endif | |
| #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) | |
| #if defined(JSON_HEDLEY_CONCAT_EX) | |
| #undef JSON_HEDLEY_CONCAT_EX | |
| #endif | |
| #define JSON_HEDLEY_CONCAT_EX(a,b) a##b | |
| #if defined(JSON_HEDLEY_CONCAT) | |
| #undef JSON_HEDLEY_CONCAT | |
| #endif | |
| #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) | |
| #if defined(JSON_HEDLEY_CONCAT3_EX) | |
| #undef JSON_HEDLEY_CONCAT3_EX | |
| #endif | |
| #define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c | |
| #if defined(JSON_HEDLEY_CONCAT3) | |
| #undef JSON_HEDLEY_CONCAT3 | |
| #endif | |
| #define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) | |
| #if defined(JSON_HEDLEY_VERSION_ENCODE) | |
| #undef JSON_HEDLEY_VERSION_ENCODE | |
| #endif | |
| #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) | |
| #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) | |
| #undef JSON_HEDLEY_VERSION_DECODE_MAJOR | |
| #endif | |
| #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) | |
| #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) | |
| #undef JSON_HEDLEY_VERSION_DECODE_MINOR | |
| #endif | |
| #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) | |
| #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) | |
| #undef JSON_HEDLEY_VERSION_DECODE_REVISION | |
| #endif | |
| #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) | |
| #if defined(JSON_HEDLEY_GNUC_VERSION) | |
| #undef JSON_HEDLEY_GNUC_VERSION | |
| #endif | |
| #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) | |
| #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) | |
| #elif defined(__GNUC__) | |
| #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) | |
| #endif | |
| #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) | |
| #undef JSON_HEDLEY_GNUC_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_GNUC_VERSION) | |
| #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_MSVC_VERSION) | |
| #undef JSON_HEDLEY_MSVC_VERSION | |
| #endif | |
| #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) | |
| #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) | |
| #elif defined(_MSC_FULL_VER) && !defined(__ICL) | |
| #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) | |
| #elif defined(_MSC_VER) && !defined(__ICL) | |
| #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) | |
| #endif | |
| #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) | |
| #undef JSON_HEDLEY_MSVC_VERSION_CHECK | |
| #endif | |
| #if !defined(JSON_HEDLEY_MSVC_VERSION) | |
| #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) | |
| #elif defined(_MSC_VER) && (_MSC_VER >= 1400) | |
| #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) | |
| #elif defined(_MSC_VER) && (_MSC_VER >= 1200) | |
| #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) | |
| #else | |
| #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) | |
| #endif | |
| #if defined(JSON_HEDLEY_INTEL_VERSION) | |
| #undef JSON_HEDLEY_INTEL_VERSION | |
| #endif | |
| #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) | |
| #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) | |
| #elif defined(__INTEL_COMPILER) && !defined(__ICL) | |
| #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) | |
| #endif | |
| #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) | |
| #undef JSON_HEDLEY_INTEL_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_INTEL_VERSION) | |
| #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_INTEL_CL_VERSION) | |
| #undef JSON_HEDLEY_INTEL_CL_VERSION | |
| #endif | |
| #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) | |
| #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) | |
| #endif | |
| #if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) | |
| #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_INTEL_CL_VERSION) | |
| #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_PGI_VERSION) | |
| #undef JSON_HEDLEY_PGI_VERSION | |
| #endif | |
| #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) | |
| #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) | |
| #endif | |
| #if defined(JSON_HEDLEY_PGI_VERSION_CHECK) | |
| #undef JSON_HEDLEY_PGI_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_PGI_VERSION) | |
| #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_SUNPRO_VERSION) | |
| #undef JSON_HEDLEY_SUNPRO_VERSION | |
| #endif | |
| #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) | |
| #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) | |
| #elif defined(__SUNPRO_C) | |
| #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) | |
| #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) | |
| #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) | |
| #elif defined(__SUNPRO_CC) | |
| #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) | |
| #endif | |
| #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) | |
| #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_SUNPRO_VERSION) | |
| #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) | |
| #undef JSON_HEDLEY_EMSCRIPTEN_VERSION | |
| #endif | |
| #if defined(__EMSCRIPTEN__) | |
| #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) | |
| #endif | |
| #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) | |
| #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) | |
| #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_ARM_VERSION) | |
| #undef JSON_HEDLEY_ARM_VERSION | |
| #endif | |
| #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) | |
| #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) | |
| #elif defined(__CC_ARM) && defined(__ARMCC_VERSION) | |
| #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) | |
| #endif | |
| #if defined(JSON_HEDLEY_ARM_VERSION_CHECK) | |
| #undef JSON_HEDLEY_ARM_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_ARM_VERSION) | |
| #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_IBM_VERSION) | |
| #undef JSON_HEDLEY_IBM_VERSION | |
| #endif | |
| #if defined(__ibmxl__) | |
| #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) | |
| #elif defined(__xlC__) && defined(__xlC_ver__) | |
| #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) | |
| #elif defined(__xlC__) | |
| #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) | |
| #endif | |
| #if defined(JSON_HEDLEY_IBM_VERSION_CHECK) | |
| #undef JSON_HEDLEY_IBM_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_IBM_VERSION) | |
| #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_VERSION) | |
| #undef JSON_HEDLEY_TI_VERSION | |
| #endif | |
| #if \ | |
| defined(__TI_COMPILER_VERSION__) && \ | |
| ( \ | |
| defined(__TMS470__) || defined(__TI_ARM__) || \ | |
| defined(__MSP430__) || \ | |
| defined(__TMS320C2000__) \ | |
| ) | |
| #if (__TI_COMPILER_VERSION__ >= 16000000) | |
| #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) | |
| #endif | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_VERSION_CHECK) | |
| #undef JSON_HEDLEY_TI_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_VERSION) | |
| #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CL2000_VERSION) | |
| #undef JSON_HEDLEY_TI_CL2000_VERSION | |
| #endif | |
| #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) | |
| #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) | |
| #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CL2000_VERSION) | |
| #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CL430_VERSION) | |
| #undef JSON_HEDLEY_TI_CL430_VERSION | |
| #endif | |
| #if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) | |
| #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) | |
| #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CL430_VERSION) | |
| #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_ARMCL_VERSION) | |
| #undef JSON_HEDLEY_TI_ARMCL_VERSION | |
| #endif | |
| #if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) | |
| #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) | |
| #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_ARMCL_VERSION) | |
| #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CL6X_VERSION) | |
| #undef JSON_HEDLEY_TI_CL6X_VERSION | |
| #endif | |
| #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) | |
| #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) | |
| #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CL6X_VERSION) | |
| #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CL7X_VERSION) | |
| #undef JSON_HEDLEY_TI_CL7X_VERSION | |
| #endif | |
| #if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) | |
| #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) | |
| #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CL7X_VERSION) | |
| #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CLPRU_VERSION) | |
| #undef JSON_HEDLEY_TI_CLPRU_VERSION | |
| #endif | |
| #if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) | |
| #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) | |
| #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_TI_CLPRU_VERSION) | |
| #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_CRAY_VERSION) | |
| #undef JSON_HEDLEY_CRAY_VERSION | |
| #endif | |
| #if defined(_CRAYC) | |
| #if defined(_RELEASE_PATCHLEVEL) | |
| #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) | |
| #else | |
| #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) | |
| #endif | |
| #endif | |
| #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) | |
| #undef JSON_HEDLEY_CRAY_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_CRAY_VERSION) | |
| #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_IAR_VERSION) | |
| #undef JSON_HEDLEY_IAR_VERSION | |
| #endif | |
| #if defined(__IAR_SYSTEMS_ICC__) | |
| #if __VER__ > 1000 | |
| #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) | |
| #else | |
| #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) | |
| #endif | |
| #endif | |
| #if defined(JSON_HEDLEY_IAR_VERSION_CHECK) | |
| #undef JSON_HEDLEY_IAR_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_IAR_VERSION) | |
| #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_TINYC_VERSION) | |
| #undef JSON_HEDLEY_TINYC_VERSION | |
| #endif | |
| #if defined(__TINYC__) | |
| #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) | |
| #endif | |
| #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) | |
| #undef JSON_HEDLEY_TINYC_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_TINYC_VERSION) | |
| #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_DMC_VERSION) | |
| #undef JSON_HEDLEY_DMC_VERSION | |
| #endif | |
| #if defined(__DMC__) | |
| #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) | |
| #endif | |
| #if defined(JSON_HEDLEY_DMC_VERSION_CHECK) | |
| #undef JSON_HEDLEY_DMC_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_DMC_VERSION) | |
| #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_COMPCERT_VERSION) | |
| #undef JSON_HEDLEY_COMPCERT_VERSION | |
| #endif | |
| #if defined(__COMPCERT_VERSION__) | |
| #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) | |
| #endif | |
| #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) | |
| #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_COMPCERT_VERSION) | |
| #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_PELLES_VERSION) | |
| #undef JSON_HEDLEY_PELLES_VERSION | |
| #endif | |
| #if defined(__POCC__) | |
| #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) | |
| #endif | |
| #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) | |
| #undef JSON_HEDLEY_PELLES_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_PELLES_VERSION) | |
| #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_MCST_LCC_VERSION) | |
| #undef JSON_HEDLEY_MCST_LCC_VERSION | |
| #endif | |
| #if defined(__LCC__) && defined(__LCC_MINOR__) | |
| #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) | |
| #endif | |
| #if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) | |
| #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_MCST_LCC_VERSION) | |
| #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_GCC_VERSION) | |
| #undef JSON_HEDLEY_GCC_VERSION | |
| #endif | |
| #if \ | |
| defined(JSON_HEDLEY_GNUC_VERSION) && \ | |
| !defined(__clang__) && \ | |
| !defined(JSON_HEDLEY_INTEL_VERSION) && \ | |
| !defined(JSON_HEDLEY_PGI_VERSION) && \ | |
| !defined(JSON_HEDLEY_ARM_VERSION) && \ | |
| !defined(JSON_HEDLEY_CRAY_VERSION) && \ | |
| !defined(JSON_HEDLEY_TI_VERSION) && \ | |
| !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ | |
| !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ | |
| !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ | |
| !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ | |
| !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ | |
| !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ | |
| !defined(__COMPCERT__) && \ | |
| !defined(JSON_HEDLEY_MCST_LCC_VERSION) | |
| #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION | |
| #endif | |
| #if defined(JSON_HEDLEY_GCC_VERSION_CHECK) | |
| #undef JSON_HEDLEY_GCC_VERSION_CHECK | |
| #endif | |
| #if defined(JSON_HEDLEY_GCC_VERSION) | |
| #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) | |
| #else | |
| #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_HAS_ATTRIBUTE) | |
| #undef JSON_HEDLEY_HAS_ATTRIBUTE | |
| #endif | |
| #if \ | |
| defined(__has_attribute) && \ | |
| ( \ | |
| (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ | |
| ) | |
| # define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) | |
| #else | |
| # define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) | |
| #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE | |
| #endif | |
| #if defined(__has_attribute) | |
| #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) | |
| #else | |
| #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) | |
| #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE | |
| #endif | |
| #if defined(__has_attribute) | |
| #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) | |
| #else | |
| #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) | |
| #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE | |
| #endif | |
| #if \ | |
| defined(__has_cpp_attribute) && \ | |
| defined(__cplusplus) && \ | |
| (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) | |
| #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) | |
| #else | |
| #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) | |
| #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS | |
| #endif | |
| #if !defined(__cplusplus) || !defined(__has_cpp_attribute) | |
| #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) | |
| #elif \ | |
| !defined(JSON_HEDLEY_PGI_VERSION) && \ | |
| !defined(JSON_HEDLEY_IAR_VERSION) && \ | |
| (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ | |
| (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) | |
| #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) | |
| #else | |
| #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) | |
| #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE | |
| #endif | |
| #if defined(__has_cpp_attribute) && defined(__cplusplus) | |
| #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) | |
| #else | |
| #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) | |
| #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE | |
| #endif | |
| #if defined(__has_cpp_attribute) && defined(__cplusplus) | |
| #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) | |
| #else | |
| #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_HAS_BUILTIN) | |
| #undef JSON_HEDLEY_HAS_BUILTIN | |
| #endif | |
| #if defined(__has_builtin) | |
| #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) | |
| #else | |
| #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) | |
| #undef JSON_HEDLEY_GNUC_HAS_BUILTIN | |
| #endif | |
| #if defined(__has_builtin) | |
| #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) | |
| #else | |
| #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) | |
| #undef JSON_HEDLEY_GCC_HAS_BUILTIN | |
| #endif | |
| #if defined(__has_builtin) | |
| #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) | |
| #else | |
| #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_HAS_FEATURE) | |
| #undef JSON_HEDLEY_HAS_FEATURE | |
| #endif | |
| #if defined(__has_feature) | |
| #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) | |
| #else | |
| #define JSON_HEDLEY_HAS_FEATURE(feature) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) | |
| #undef JSON_HEDLEY_GNUC_HAS_FEATURE | |
| #endif | |
| #if defined(__has_feature) | |
| #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) | |
| #else | |
| #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_GCC_HAS_FEATURE) | |
| #undef JSON_HEDLEY_GCC_HAS_FEATURE | |
| #endif | |
| #if defined(__has_feature) | |
| #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) | |
| #else | |
| #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_HAS_EXTENSION) | |
| #undef JSON_HEDLEY_HAS_EXTENSION | |
| #endif | |
| #if defined(__has_extension) | |
| #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) | |
| #else | |
| #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) | |
| #undef JSON_HEDLEY_GNUC_HAS_EXTENSION | |
| #endif | |
| #if defined(__has_extension) | |
| #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) | |
| #else | |
| #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) | |
| #undef JSON_HEDLEY_GCC_HAS_EXTENSION | |
| #endif | |
| #if defined(__has_extension) | |
| #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) | |
| #else | |
| #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) | |
| #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE | |
| #endif | |
| #if defined(__has_declspec_attribute) | |
| #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) | |
| #else | |
| #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) | |
| #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE | |
| #endif | |
| #if defined(__has_declspec_attribute) | |
| #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) | |
| #else | |
| #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) | |
| #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE | |
| #endif | |
| #if defined(__has_declspec_attribute) | |
| #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) | |
| #else | |
| #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_HAS_WARNING) | |
| #undef JSON_HEDLEY_HAS_WARNING | |
| #endif | |
| #if defined(__has_warning) | |
| #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) | |
| #else | |
| #define JSON_HEDLEY_HAS_WARNING(warning) (0) | |
| #endif | |
| #if defined(JSON_HEDLEY_GNUC_HAS_WARNING) | |
| #undef JSON_HEDLEY_GNUC_HAS_WARNING | |
| #endif | |
| #if defined(__has_warning) | |
| #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) | |
| #else | |
| #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_GCC_HAS_WARNING) | |
| #undef JSON_HEDLEY_GCC_HAS_WARNING | |
| #endif | |
| #if defined(__has_warning) | |
| #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) | |
| #else | |
| #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if \ | |
| (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ | |
| defined(__clang__) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ | |
| JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ | |
| JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ | |
| JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ | |
| JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ | |
| (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) | |
| #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) | |
| #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) | |
| #define JSON_HEDLEY_PRAGMA(value) __pragma(value) | |
| #else | |
| #define JSON_HEDLEY_PRAGMA(value) | |
| #endif | |
| #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) | |
| #undef JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| #endif | |
| #if defined(JSON_HEDLEY_DIAGNOSTIC_POP) | |
| #undef JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| #if defined(__clang__) | |
| #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") | |
| #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") | |
| #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") | |
| #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") | |
| #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") | |
| #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") | |
| #elif \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) | |
| #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) | |
| #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") | |
| #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") | |
| #elif \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") | |
| #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") | |
| #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") | |
| #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") | |
| #else | |
| #define JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| #define JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for | |
| HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ | |
| #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) | |
| #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ | |
| #endif | |
| #if defined(__cplusplus) | |
| # if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") | |
| # if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") | |
| # if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") | |
| # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH \ | |
| _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ | |
| _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ | |
| _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ | |
| xpr \ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| # else | |
| # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH \ | |
| _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ | |
| _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ | |
| xpr \ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| # endif | |
| # else | |
| # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH \ | |
| _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ | |
| xpr \ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| # endif | |
| # endif | |
| #endif | |
| #if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x | |
| #endif | |
| #if defined(JSON_HEDLEY_CONST_CAST) | |
| #undef JSON_HEDLEY_CONST_CAST | |
| #endif | |
| #if defined(__cplusplus) | |
| # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr)) | |
| #elif \ | |
| JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) | |
| # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH \ | |
| JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ | |
| ((T) (expr)); \ | |
| JSON_HEDLEY_DIAGNOSTIC_POP \ | |
| })) | |
| #else | |
| # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) | |
| #endif | |
| #if defined(JSON_HEDLEY_REINTERPRET_CAST) | |
| #undef JSON_HEDLEY_REINTERPRET_CAST | |
| #endif | |
| #if defined(__cplusplus) | |
| #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr)) | |
| #else | |
| #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) | |
| #endif | |
| #if defined(JSON_HEDLEY_STATIC_CAST) | |
| #undef JSON_HEDLEY_STATIC_CAST | |
| #endif | |
| #if defined(__cplusplus) | |
| #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr)) | |
| #else | |
| #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) | |
| #endif | |
| #if defined(JSON_HEDLEY_CPP_CAST) | |
| #undef JSON_HEDLEY_CPP_CAST | |
| #endif | |
| #if defined(__cplusplus) | |
| # if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") | |
| # define JSON_HEDLEY_CPP_CAST(T, expr) \ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH \ | |
| _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ | |
| ((T) (expr)) \ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| # elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) | |
| # define JSON_HEDLEY_CPP_CAST(T, expr) \ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH \ | |
| _Pragma("diag_suppress=Pe137") \ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| # else | |
| # define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) | |
| # endif | |
| #else | |
| # define JSON_HEDLEY_CPP_CAST(T, expr) (expr) | |
| #endif | |
| #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) | |
| #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED | |
| #endif | |
| #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") | |
| #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") | |
| #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) | |
| #elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") | |
| #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") | |
| #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") | |
| #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) | |
| #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") | |
| #elif \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ | |
| (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ | |
| (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ | |
| (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") | |
| #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") | |
| #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") | |
| #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") | |
| #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") | |
| #else | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED | |
| #endif | |
| #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) | |
| #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS | |
| #endif | |
| #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") | |
| #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") | |
| #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) | |
| #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") | |
| #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") | |
| #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) | |
| #elif \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") | |
| #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") | |
| #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") | |
| #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") | |
| #else | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS | |
| #endif | |
| #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) | |
| #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES | |
| #endif | |
| #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") | |
| #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") | |
| #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") | |
| #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) | |
| #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) | |
| #elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") | |
| #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") | |
| #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") | |
| #elif \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") | |
| #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") | |
| #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") | |
| #else | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES | |
| #endif | |
| #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) | |
| #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL | |
| #endif | |
| #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") | |
| #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") | |
| #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") | |
| #else | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL | |
| #endif | |
| #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) | |
| #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION | |
| #endif | |
| #if JSON_HEDLEY_HAS_WARNING("-Wunused-function") | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") | |
| #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") | |
| #elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) | |
| #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") | |
| #else | |
| #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION | |
| #endif | |
| #if defined(JSON_HEDLEY_DEPRECATED) | |
| #undef JSON_HEDLEY_DEPRECATED | |
| #endif | |
| #if defined(JSON_HEDLEY_DEPRECATED_FOR) | |
| #undef JSON_HEDLEY_DEPRECATED_FOR | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) | |
| #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) | |
| #elif \ | |
| (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ | |
| JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ | |
| JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) | |
| #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) | |
| #elif defined(__cplusplus) && (__cplusplus >= 201402L) | |
| #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) | |
| #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) | |
| #elif \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ | |
| (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ | |
| (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ | |
| (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ | |
| JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) | |
| #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) | |
| #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) | |
| #elif \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ | |
| JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) | |
| #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) | |
| #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) | |
| #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") | |
| #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") | |
| #else | |
| #define JSON_HEDLEY_DEPRECATED(since) | |
| #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) | |
| #endif | |
| #if defined(JSON_HEDLEY_UNAVAILABLE) | |
| #undef JSON_HEDLEY_UNAVAILABLE | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) | |
| #else | |
| #define JSON_HEDLEY_UNAVAILABLE(available_since) | |
| #endif | |
| #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) | |
| #undef JSON_HEDLEY_WARN_UNUSED_RESULT | |
| #endif | |
| #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) | |
| #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ | |
| (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ | |
| (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ | |
| (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ | |
| (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ | |
| JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) | |
| #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) | |
| #elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) | |
| #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) | |
| #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) | |
| #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) | |
| #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) | |
| #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) | |
| #elif defined(_Check_return_) /* SAL */ | |
| #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ | |
| #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ | |
| #else | |
| #define JSON_HEDLEY_WARN_UNUSED_RESULT | |
| #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) | |
| #endif | |
| #if defined(JSON_HEDLEY_SENTINEL) | |
| #undef JSON_HEDLEY_SENTINEL | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) | |
| #else | |
| #define JSON_HEDLEY_SENTINEL(position) | |
| #endif | |
| #if defined(JSON_HEDLEY_NO_RETURN) | |
| #undef JSON_HEDLEY_NO_RETURN | |
| #endif | |
| #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) | |
| #define JSON_HEDLEY_NO_RETURN __noreturn | |
| #elif \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) | |
| #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L | |
| #define JSON_HEDLEY_NO_RETURN _Noreturn | |
| #elif defined(__cplusplus) && (__cplusplus >= 201103L) | |
| #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) | |
| #elif \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ | |
| JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ | |
| (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ | |
| (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ | |
| (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ | |
| JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) | |
| #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) | |
| #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) | |
| #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") | |
| #elif \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) | |
| #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) | |
| #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") | |
| #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) | |
| #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) | |
| #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) | |
| #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) | |
| #else | |
| #define JSON_HEDLEY_NO_RETURN | |
| #endif | |
| #if defined(JSON_HEDLEY_NO_ESCAPE) | |
| #undef JSON_HEDLEY_NO_ESCAPE | |
| #endif | |
| #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) | |
| #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) | |
| #else | |
| #define JSON_HEDLEY_NO_ESCAPE | |
| #endif | |
| #if defined(JSON_HEDLEY_UNREACHABLE) | |
| #undef JSON_HEDLEY_UNREACHABLE | |
| #endif | |
| #if defined(JSON_HEDLEY_UNREACHABLE_RETURN) | |
| #undef JSON_HEDLEY_UNREACHABLE_RETURN | |
| #endif | |
| #if defined(JSON_HEDLEY_ASSUME) | |
| #undef JSON_HEDLEY_ASSUME | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| #define JSON_HEDLEY_ASSUME(expr) __assume(expr) | |
| #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) | |
| #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) | |
| #elif \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) | |
| #if defined(__cplusplus) | |
| #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) | |
| #else | |
| #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) | |
| #endif | |
| #endif | |
| #if \ | |
| (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ | |
| JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ | |
| JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() | |
| #elif defined(JSON_HEDLEY_ASSUME) | |
| #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) | |
| #endif | |
| #if !defined(JSON_HEDLEY_ASSUME) | |
| #if defined(JSON_HEDLEY_UNREACHABLE) | |
| #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) | |
| #else | |
| #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) | |
| #endif | |
| #endif | |
| #if defined(JSON_HEDLEY_UNREACHABLE) | |
| #if \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) | |
| #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) | |
| #else | |
| #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() | |
| #endif | |
| #else | |
| #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) | |
| #endif | |
| #if !defined(JSON_HEDLEY_UNREACHABLE) | |
| #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) | |
| #endif | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| #if JSON_HEDLEY_HAS_WARNING("-Wpedantic") | |
| #pragma clang diagnostic ignored "-Wpedantic" | |
| #endif | |
| #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) | |
| #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" | |
| #endif | |
| #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) | |
| #if defined(__clang__) | |
| #pragma clang diagnostic ignored "-Wvariadic-macros" | |
| #elif defined(JSON_HEDLEY_GCC_VERSION) | |
| #pragma GCC diagnostic ignored "-Wvariadic-macros" | |
| #endif | |
| #endif | |
| #if defined(JSON_HEDLEY_NON_NULL) | |
| #undef JSON_HEDLEY_NON_NULL | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) | |
| #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) | |
| #else | |
| #define JSON_HEDLEY_NON_NULL(...) | |
| #endif | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #if defined(JSON_HEDLEY_PRINTF_FORMAT) | |
| #undef JSON_HEDLEY_PRINTF_FORMAT | |
| #endif | |
| #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) | |
| #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) | |
| #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) | |
| #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) | |
| #elif \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ | |
| (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ | |
| (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ | |
| (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) | |
| #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) | |
| #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) | |
| #else | |
| #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) | |
| #endif | |
| #if defined(JSON_HEDLEY_CONSTEXPR) | |
| #undef JSON_HEDLEY_CONSTEXPR | |
| #endif | |
| #if defined(__cplusplus) | |
| #if __cplusplus >= 201103L | |
| #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) | |
| #endif | |
| #endif | |
| #if !defined(JSON_HEDLEY_CONSTEXPR) | |
| #define JSON_HEDLEY_CONSTEXPR | |
| #endif | |
| #if defined(JSON_HEDLEY_PREDICT) | |
| #undef JSON_HEDLEY_PREDICT | |
| #endif | |
| #if defined(JSON_HEDLEY_LIKELY) | |
| #undef JSON_HEDLEY_LIKELY | |
| #endif | |
| #if defined(JSON_HEDLEY_UNLIKELY) | |
| #undef JSON_HEDLEY_UNLIKELY | |
| #endif | |
| #if defined(JSON_HEDLEY_UNPREDICTABLE) | |
| #undef JSON_HEDLEY_UNPREDICTABLE | |
| #endif | |
| #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) | |
| #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) | |
| #endif | |
| #if \ | |
| (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) | |
| # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) | |
| # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) | |
| # define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) | |
| # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) | |
| #elif \ | |
| (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ | |
| JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ | |
| JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| # define JSON_HEDLEY_PREDICT(expr, expected, probability) \ | |
| (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) | |
| # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ | |
| (__extension__ ({ \ | |
| double hedley_probability_ = (probability); \ | |
| ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ | |
| })) | |
| # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ | |
| (__extension__ ({ \ | |
| double hedley_probability_ = (probability); \ | |
| ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ | |
| })) | |
| # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) | |
| # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) | |
| #else | |
| # define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) | |
| # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) | |
| # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) | |
| # define JSON_HEDLEY_LIKELY(expr) (!!(expr)) | |
| # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) | |
| #endif | |
| #if !defined(JSON_HEDLEY_UNPREDICTABLE) | |
| #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) | |
| #endif | |
| #if defined(JSON_HEDLEY_MALLOC) | |
| #undef JSON_HEDLEY_MALLOC | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ | |
| (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ | |
| (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ | |
| (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) | |
| #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) | |
| #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") | |
| #elif \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| #define JSON_HEDLEY_MALLOC __declspec(restrict) | |
| #else | |
| #define JSON_HEDLEY_MALLOC | |
| #endif | |
| #if defined(JSON_HEDLEY_PURE) | |
| #undef JSON_HEDLEY_PURE | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ | |
| (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ | |
| (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ | |
| (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ | |
| JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| # define JSON_HEDLEY_PURE __attribute__((__pure__)) | |
| #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) | |
| # define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") | |
| #elif defined(__cplusplus) && \ | |
| ( \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ | |
| ) | |
| # define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") | |
| #else | |
| # define JSON_HEDLEY_PURE | |
| #endif | |
| #if defined(JSON_HEDLEY_CONST) | |
| #undef JSON_HEDLEY_CONST | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ | |
| (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ | |
| (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ | |
| (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ | |
| JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_CONST __attribute__((__const__)) | |
| #elif \ | |
| JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) | |
| #define JSON_HEDLEY_CONST _Pragma("no_side_effect") | |
| #else | |
| #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE | |
| #endif | |
| #if defined(JSON_HEDLEY_RESTRICT) | |
| #undef JSON_HEDLEY_RESTRICT | |
| #endif | |
| #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) | |
| #define JSON_HEDLEY_RESTRICT restrict | |
| #elif \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ | |
| JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ | |
| JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ | |
| defined(__clang__) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_RESTRICT __restrict | |
| #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) | |
| #define JSON_HEDLEY_RESTRICT _Restrict | |
| #else | |
| #define JSON_HEDLEY_RESTRICT | |
| #endif | |
| #if defined(JSON_HEDLEY_INLINE) | |
| #undef JSON_HEDLEY_INLINE | |
| #endif | |
| #if \ | |
| (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ | |
| (defined(__cplusplus) && (__cplusplus >= 199711L)) | |
| #define JSON_HEDLEY_INLINE inline | |
| #elif \ | |
| defined(JSON_HEDLEY_GCC_VERSION) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) | |
| #define JSON_HEDLEY_INLINE __inline__ | |
| #elif \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_INLINE __inline | |
| #else | |
| #define JSON_HEDLEY_INLINE | |
| #endif | |
| #if defined(JSON_HEDLEY_ALWAYS_INLINE) | |
| #undef JSON_HEDLEY_ALWAYS_INLINE | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ | |
| (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ | |
| (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ | |
| (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ | |
| JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) | |
| # define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE | |
| #elif \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| # define JSON_HEDLEY_ALWAYS_INLINE __forceinline | |
| #elif defined(__cplusplus) && \ | |
| ( \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ | |
| ) | |
| # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") | |
| #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) | |
| # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") | |
| #else | |
| # define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE | |
| #endif | |
| #if defined(JSON_HEDLEY_NEVER_INLINE) | |
| #undef JSON_HEDLEY_NEVER_INLINE | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ | |
| JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ | |
| (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ | |
| (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ | |
| (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ | |
| (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ | |
| JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ | |
| JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ | |
| JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) | |
| #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) | |
| #elif \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) | |
| #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) | |
| #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") | |
| #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) | |
| #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") | |
| #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) | |
| #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") | |
| #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) | |
| #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) | |
| #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) | |
| #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) | |
| #else | |
| #define JSON_HEDLEY_NEVER_INLINE | |
| #endif | |
| #if defined(JSON_HEDLEY_PRIVATE) | |
| #undef JSON_HEDLEY_PRIVATE | |
| #endif | |
| #if defined(JSON_HEDLEY_PUBLIC) | |
| #undef JSON_HEDLEY_PUBLIC | |
| #endif | |
| #if defined(JSON_HEDLEY_IMPORT) | |
| #undef JSON_HEDLEY_IMPORT | |
| #endif | |
| #if defined(_WIN32) || defined(__CYGWIN__) | |
| # define JSON_HEDLEY_PRIVATE | |
| # define JSON_HEDLEY_PUBLIC __declspec(dllexport) | |
| # define JSON_HEDLEY_IMPORT __declspec(dllimport) | |
| #else | |
| # if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ | |
| JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ | |
| ( \ | |
| defined(__TI_EABI__) && \ | |
| ( \ | |
| (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ | |
| ) \ | |
| ) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| # define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) | |
| # define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) | |
| # else | |
| # define JSON_HEDLEY_PRIVATE | |
| # define JSON_HEDLEY_PUBLIC | |
| # endif | |
| # define JSON_HEDLEY_IMPORT extern | |
| #endif | |
| #if defined(JSON_HEDLEY_NO_THROW) | |
| #undef JSON_HEDLEY_NO_THROW | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) | |
| #elif \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) | |
| #define JSON_HEDLEY_NO_THROW __declspec(nothrow) | |
| #else | |
| #define JSON_HEDLEY_NO_THROW | |
| #endif | |
| #if defined(JSON_HEDLEY_FALL_THROUGH) | |
| #undef JSON_HEDLEY_FALL_THROUGH | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) | |
| #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) | |
| #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) | |
| #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) | |
| #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) | |
| #elif defined(__fallthrough) /* SAL */ | |
| #define JSON_HEDLEY_FALL_THROUGH __fallthrough | |
| #else | |
| #define JSON_HEDLEY_FALL_THROUGH | |
| #endif | |
| #if defined(JSON_HEDLEY_RETURNS_NON_NULL) | |
| #undef JSON_HEDLEY_RETURNS_NON_NULL | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) | |
| #elif defined(_Ret_notnull_) /* SAL */ | |
| #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ | |
| #else | |
| #define JSON_HEDLEY_RETURNS_NON_NULL | |
| #endif | |
| #if defined(JSON_HEDLEY_ARRAY_PARAM) | |
| #undef JSON_HEDLEY_ARRAY_PARAM | |
| #endif | |
| #if \ | |
| defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ | |
| !defined(__STDC_NO_VLA__) && \ | |
| !defined(__cplusplus) && \ | |
| !defined(JSON_HEDLEY_PGI_VERSION) && \ | |
| !defined(JSON_HEDLEY_TINYC_VERSION) | |
| #define JSON_HEDLEY_ARRAY_PARAM(name) (name) | |
| #else | |
| #define JSON_HEDLEY_ARRAY_PARAM(name) | |
| #endif | |
| #if defined(JSON_HEDLEY_IS_CONSTANT) | |
| #undef JSON_HEDLEY_IS_CONSTANT | |
| #endif | |
| #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) | |
| #undef JSON_HEDLEY_REQUIRE_CONSTEXPR | |
| #endif | |
| /* JSON_HEDLEY_IS_CONSTEXPR_ is for | |
| HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ | |
| #if defined(JSON_HEDLEY_IS_CONSTEXPR_) | |
| #undef JSON_HEDLEY_IS_CONSTEXPR_ | |
| #endif | |
| #if \ | |
| JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ | |
| JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ | |
| (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ | |
| JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ | |
| JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) | |
| #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) | |
| #endif | |
| #if !defined(__cplusplus) | |
| # if \ | |
| JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ | |
| JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ | |
| JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) | |
| #if defined(__INTPTR_TYPE__) | |
| #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) | |
| #else | |
| #include <stdint.h> | |
| #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) | |
| #endif | |
| # elif \ | |
| ( \ | |
| defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ | |
| !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ | |
| !defined(JSON_HEDLEY_PGI_VERSION) && \ | |
| !defined(JSON_HEDLEY_IAR_VERSION)) || \ | |
| (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ | |
| JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ | |
| JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) | |
| #if defined(__INTPTR_TYPE__) | |
| #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) | |
| #else | |
| #include <stdint.h> | |
| #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) | |
| #endif | |
| # elif \ | |
| defined(JSON_HEDLEY_GCC_VERSION) || \ | |
| defined(JSON_HEDLEY_INTEL_VERSION) || \ | |
| defined(JSON_HEDLEY_TINYC_VERSION) || \ | |
| defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ | |
| JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ | |
| defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ | |
| defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ | |
| defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ | |
| defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ | |
| defined(__clang__) | |
| # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ | |
| sizeof(void) != \ | |
| sizeof(*( \ | |
| 1 ? \ | |
| ((void*) ((expr) * 0L) ) : \ | |
| ((struct { char v[sizeof(void) * 2]; } *) 1) \ | |
| ) \ | |
| ) \ | |
| ) | |
| # endif | |
| #endif | |
| #if defined(JSON_HEDLEY_IS_CONSTEXPR_) | |
| #if !defined(JSON_HEDLEY_IS_CONSTANT) | |
| #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) | |
| #endif | |
| #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) | |
| #else | |
| #if !defined(JSON_HEDLEY_IS_CONSTANT) | |
| #define JSON_HEDLEY_IS_CONSTANT(expr) (0) | |
| #endif | |
| #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) | |
| #endif | |
| #if defined(JSON_HEDLEY_BEGIN_C_DECLS) | |
| #undef JSON_HEDLEY_BEGIN_C_DECLS | |
| #endif | |
| #if defined(JSON_HEDLEY_END_C_DECLS) | |
| #undef JSON_HEDLEY_END_C_DECLS | |
| #endif | |
| #if defined(JSON_HEDLEY_C_DECL) | |
| #undef JSON_HEDLEY_C_DECL | |
| #endif | |
| #if defined(__cplusplus) | |
| #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { | |
| #define JSON_HEDLEY_END_C_DECLS } | |
| #define JSON_HEDLEY_C_DECL extern "C" | |
| #else | |
| #define JSON_HEDLEY_BEGIN_C_DECLS | |
| #define JSON_HEDLEY_END_C_DECLS | |
| #define JSON_HEDLEY_C_DECL | |
| #endif | |
| #if defined(JSON_HEDLEY_STATIC_ASSERT) | |
| #undef JSON_HEDLEY_STATIC_ASSERT | |
| #endif | |
| #if \ | |
| !defined(__cplusplus) && ( \ | |
| (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ | |
| (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ | |
| defined(_Static_assert) \ | |
| ) | |
| # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) | |
| #elif \ | |
| (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) | |
| #else | |
| # define JSON_HEDLEY_STATIC_ASSERT(expr, message) | |
| #endif | |
| #if defined(JSON_HEDLEY_NULL) | |
| #undef JSON_HEDLEY_NULL | |
| #endif | |
| #if defined(__cplusplus) | |
| #if __cplusplus >= 201103L | |
| #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) | |
| #elif defined(NULL) | |
| #define JSON_HEDLEY_NULL NULL | |
| #else | |
| #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) | |
| #endif | |
| #elif defined(NULL) | |
| #define JSON_HEDLEY_NULL NULL | |
| #else | |
| #define JSON_HEDLEY_NULL ((void*) 0) | |
| #endif | |
| #if defined(JSON_HEDLEY_MESSAGE) | |
| #undef JSON_HEDLEY_MESSAGE | |
| #endif | |
| #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") | |
| # define JSON_HEDLEY_MESSAGE(msg) \ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH \ | |
| JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ | |
| JSON_HEDLEY_PRAGMA(message msg) \ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #elif \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) | |
| # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) | |
| #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) | |
| # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) | |
| #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) | |
| # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) | |
| #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) | |
| # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) | |
| #else | |
| # define JSON_HEDLEY_MESSAGE(msg) | |
| #endif | |
| #if defined(JSON_HEDLEY_WARNING) | |
| #undef JSON_HEDLEY_WARNING | |
| #endif | |
| #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") | |
| # define JSON_HEDLEY_WARNING(msg) \ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH \ | |
| JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ | |
| JSON_HEDLEY_PRAGMA(clang warning msg) \ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #elif \ | |
| JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ | |
| JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ | |
| JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) | |
| # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) | |
| #elif \ | |
| JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) | |
| #else | |
| # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) | |
| #endif | |
| #if defined(JSON_HEDLEY_REQUIRE) | |
| #undef JSON_HEDLEY_REQUIRE | |
| #endif | |
| #if defined(JSON_HEDLEY_REQUIRE_MSG) | |
| #undef JSON_HEDLEY_REQUIRE_MSG | |
| #endif | |
| #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) | |
| # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") | |
| # define JSON_HEDLEY_REQUIRE(expr) \ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH \ | |
| _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ | |
| __attribute__((diagnose_if(!(expr), #expr, "error"))) \ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH \ | |
| _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ | |
| __attribute__((diagnose_if(!(expr), msg, "error"))) \ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| # else | |
| # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) | |
| # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) | |
| # endif | |
| #else | |
| # define JSON_HEDLEY_REQUIRE(expr) | |
| # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) | |
| #endif | |
| #if defined(JSON_HEDLEY_FLAGS) | |
| #undef JSON_HEDLEY_FLAGS | |
| #endif | |
| #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) | |
| #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) | |
| #else | |
| #define JSON_HEDLEY_FLAGS | |
| #endif | |
| #if defined(JSON_HEDLEY_FLAGS_CAST) | |
| #undef JSON_HEDLEY_FLAGS_CAST | |
| #endif | |
| #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) | |
| # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH \ | |
| _Pragma("warning(disable:188)") \ | |
| ((T) (expr)); \ | |
| JSON_HEDLEY_DIAGNOSTIC_POP \ | |
| })) | |
| #else | |
| # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) | |
| #endif | |
| #if defined(JSON_HEDLEY_EMPTY_BASES) | |
| #undef JSON_HEDLEY_EMPTY_BASES | |
| #endif | |
| #if \ | |
| (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ | |
| JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) | |
| #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) | |
| #else | |
| #define JSON_HEDLEY_EMPTY_BASES | |
| #endif | |
| /* Remaining macros are deprecated. */ | |
| #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) | |
| #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK | |
| #endif | |
| #if defined(__clang__) | |
| #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) | |
| #else | |
| #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) | |
| #endif | |
| #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) | |
| #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE | |
| #endif | |
| #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) | |
| #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) | |
| #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE | |
| #endif | |
| #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) | |
| #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) | |
| #undef JSON_HEDLEY_CLANG_HAS_BUILTIN | |
| #endif | |
| #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) | |
| #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) | |
| #undef JSON_HEDLEY_CLANG_HAS_FEATURE | |
| #endif | |
| #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) | |
| #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) | |
| #undef JSON_HEDLEY_CLANG_HAS_EXTENSION | |
| #endif | |
| #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) | |
| #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) | |
| #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE | |
| #endif | |
| #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) | |
| #if defined(JSON_HEDLEY_CLANG_HAS_WARNING) | |
| #undef JSON_HEDLEY_CLANG_HAS_WARNING | |
| #endif | |
| #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) | |
| #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ | |
| // This file contains all internal macro definitions (except those affecting ABI) | |
| // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| // exclude unsupported compilers | |
| #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) | |
| #if defined(__clang__) | |
| #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 | |
| #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" | |
| #endif | |
| #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) | |
| #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 | |
| #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" | |
| #endif | |
| #endif | |
| #endif | |
| // C++ language standard detection | |
| // if the user manually specified the used C++ version, this is skipped | |
| #if !defined(JSON_HAS_CPP_26) && !defined(JSON_HAS_CPP_23) && !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) | |
| #if (defined(__cplusplus) && __cplusplus > 202302L) || (defined(_MSVC_LANG) && _MSVC_LANG > 202302L) | |
| #define JSON_HAS_CPP_26 | |
| #define JSON_HAS_CPP_23 | |
| #define JSON_HAS_CPP_20 | |
| #define JSON_HAS_CPP_17 | |
| #define JSON_HAS_CPP_14 | |
| #elif (defined(__cplusplus) && __cplusplus > 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG > 202002L) | |
| #define JSON_HAS_CPP_23 | |
| #define JSON_HAS_CPP_20 | |
| #define JSON_HAS_CPP_17 | |
| #define JSON_HAS_CPP_14 | |
| #elif (defined(__cplusplus) && __cplusplus > 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG > 201703L) | |
| #define JSON_HAS_CPP_20 | |
| #define JSON_HAS_CPP_17 | |
| #define JSON_HAS_CPP_14 | |
| #elif (defined(__cplusplus) && __cplusplus > 201402L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 | |
| #define JSON_HAS_CPP_17 | |
| #define JSON_HAS_CPP_14 | |
| #elif (defined(__cplusplus) && __cplusplus > 201103L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) | |
| #define JSON_HAS_CPP_14 | |
| #endif | |
| // the cpp 11 flag is always specified because it is the minimal required version | |
| #define JSON_HAS_CPP_11 | |
| #endif | |
| #ifdef __has_include | |
| #if __has_include(<version>) | |
| #include <version> | |
| #endif | |
| #endif | |
| #if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) | |
| #ifdef JSON_HAS_CPP_17 | |
| #if defined(__cpp_lib_filesystem) | |
| #define JSON_HAS_FILESYSTEM 1 | |
| #elif defined(__cpp_lib_experimental_filesystem) | |
| #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 | |
| #elif !defined(__has_include) | |
| #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 | |
| #elif __has_include(<filesystem>) | |
| #define JSON_HAS_FILESYSTEM 1 | |
| #elif __has_include(<experimental/filesystem>) | |
| #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 | |
| #endif | |
| // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ | |
| #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 | |
| #undef JSON_HAS_FILESYSTEM | |
| #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| #endif | |
| // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support | |
| #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 | |
| #undef JSON_HAS_FILESYSTEM | |
| #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| #endif | |
| // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support | |
| #if defined(__clang_major__) && __clang_major__ < 7 | |
| #undef JSON_HAS_FILESYSTEM | |
| #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| #endif | |
| // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support | |
| #if defined(_MSC_VER) && _MSC_VER < 1914 | |
| #undef JSON_HAS_FILESYSTEM | |
| #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| #endif | |
| // no filesystem support before iOS 13 | |
| #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 | |
| #undef JSON_HAS_FILESYSTEM | |
| #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| #endif | |
| // no filesystem support before macOS Catalina | |
| #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 | |
| #undef JSON_HAS_FILESYSTEM | |
| #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| #endif | |
| #endif | |
| #endif | |
| #ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 | |
| #endif | |
| #ifndef JSON_HAS_FILESYSTEM | |
| #define JSON_HAS_FILESYSTEM 0 | |
| #endif | |
| #ifndef JSON_HAS_THREE_WAY_COMPARISON | |
| #if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L \ | |
| && defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L | |
| #define JSON_HAS_THREE_WAY_COMPARISON 1 | |
| #else | |
| #define JSON_HAS_THREE_WAY_COMPARISON 0 | |
| #endif | |
| #endif | |
| #ifndef JSON_HAS_RANGES | |
| // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has a syntax error | |
| #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 | |
| #define JSON_HAS_RANGES 0 | |
| // libstdc++ < 11 has incomplete C++20 ranges (issue #4440) | |
| #elif defined(_GLIBCXX_RELEASE) && _GLIBCXX_RELEASE < 11 | |
| #define JSON_HAS_RANGES 0 | |
| // clang < 16 with libstdc++ does not implement the ranges customization | |
| // points libstdc++ declares, so its C++20 ranges support is incomplete (issue #5161) | |
| #elif defined(__clang__) && !defined(__apple_build_version__) \ | |
| && __clang_major__ < 16 && defined(__GLIBCXX__) | |
| #define JSON_HAS_RANGES 0 | |
| // libc++ < 16 has incomplete C++20 ranges (issue #4440) | |
| #elif defined(_LIBCPP_VERSION) && _LIBCPP_VERSION < 160000 | |
| #define JSON_HAS_RANGES 0 | |
| // nvcc CUDA 12.0/12.1 chokes on the enable_borrowed_range variable-template | |
| // syntax when compiling as CUDA source; fixed in CUDA 12.2 (issue #3907) | |
| #elif defined(__CUDACC__) && defined(__CUDACC_VER_MAJOR__) && __CUDACC_VER_MAJOR__ == 12 \ | |
| && defined(__CUDACC_VER_MINOR__) && (__CUDACC_VER_MINOR__ == 0 || __CUDACC_VER_MINOR__ == 1) | |
| #define JSON_HAS_RANGES 0 | |
| #elif defined(__cpp_lib_ranges) | |
| #define JSON_HAS_RANGES 1 | |
| #else | |
| #define JSON_HAS_RANGES 0 | |
| #endif | |
| #endif | |
| // std::ranges view conversion (to_json/is_compatible_array_type_impl) additionally | |
| // needs to be disabled on MinGW, whose std::ranges support is incomplete | |
| // (issue #4916); this macro combines both conditions so the check and its | |
| // reason are not duplicated at every use site. | |
| #ifndef JSON_HAS_RANGE_VIEW_CONVERSION | |
| #if JSON_HAS_RANGES && !defined(__MINGW32__) | |
| #define JSON_HAS_RANGE_VIEW_CONVERSION 1 | |
| #else | |
| #define JSON_HAS_RANGE_VIEW_CONVERSION 0 | |
| #endif | |
| #endif | |
| #ifndef JSON_HAS_STD_FORMAT | |
| #if defined(JSON_HAS_CPP_20) && defined(__cpp_lib_format) | |
| #define JSON_HAS_STD_FORMAT 1 | |
| #else | |
| #define JSON_HAS_STD_FORMAT 0 | |
| #endif | |
| #endif | |
| #ifndef JSON_HAS_STATIC_RTTI | |
| #if !defined(_HAS_STATIC_RTTI) || _HAS_STATIC_RTTI != 0 | |
| #define JSON_HAS_STATIC_RTTI 1 | |
| #else | |
| #define JSON_HAS_STATIC_RTTI 0 | |
| #endif | |
| #endif | |
| // the byte order of the target where the compiler tells it (std::endian is | |
| // C++20 and cannot select code in #if): JSON_LITTLE_ENDIAN_TARGET or | |
| // JSON_BIG_ENDIAN_TARGET is 1, or both are 0 where it is unknown (code then | |
| // handles the bytes one at a time); MSVC and x86 targets are little-endian | |
| #if defined(_MSC_VER) || defined(__x86_64__) || defined(__i386__) \ | |
| || (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) | |
| #define JSON_LITTLE_ENDIAN_TARGET 1 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) | |
| #define JSON_BIG_ENDIAN_TARGET 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) | |
| #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ | |
| #define JSON_LITTLE_ENDIAN_TARGET 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) | |
| #define JSON_BIG_ENDIAN_TARGET 1 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) | |
| #else | |
| #define JSON_LITTLE_ENDIAN_TARGET 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) | |
| #define JSON_BIG_ENDIAN_TARGET 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) | |
| #endif | |
| #ifdef JSON_HAS_CPP_17 | |
| #define JSON_INLINE_VARIABLE inline | |
| #else | |
| #define JSON_INLINE_VARIABLE | |
| #endif | |
| #if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address) | |
| #define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]] | |
| #else | |
| #define JSON_NO_UNIQUE_ADDRESS | |
| #endif | |
| // Clang targeting MinGW does not survive the thread_local storage the copy | |
| // constructor uses to bound its descent: every test that copies a value | |
| // segfaults with clang 11.0.1 and clang 18.1.8, while the same tests pass with | |
| // GCC targeting MinGW and with every other toolchain the library is tested on. | |
| // Copying works the same way without the counter, only more slowly. | |
| #if !defined(JSON_NO_THREAD_LOCAL) && defined(__clang__) && defined(__MINGW32__) | |
| #define JSON_NO_THREAD_LOCAL 1 | |
| #endif | |
| // allow disabling exceptions | |
| #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) | |
| #define JSON_THROW(exception) throw exception | |
| #define JSON_TRY try | |
| #define JSON_CATCH(exception) catch(exception) | |
| #define JSON_INTERNAL_CATCH(exception) catch(exception) | |
| #else | |
| #include <cstdlib> | |
| #define JSON_THROW(exception) std::abort() | |
| #define JSON_TRY if(true) | |
| #define JSON_CATCH(exception) if(false) | |
| #define JSON_INTERNAL_CATCH(exception) if(false) | |
| #endif | |
| // override exception macros | |
| #if defined(JSON_THROW_USER) | |
| #undef JSON_THROW | |
| #define JSON_THROW JSON_THROW_USER | |
| #endif | |
| #if defined(JSON_TRY_USER) | |
| #undef JSON_TRY | |
| #define JSON_TRY JSON_TRY_USER | |
| #endif | |
| #if defined(JSON_CATCH_USER) | |
| #undef JSON_CATCH | |
| #define JSON_CATCH JSON_CATCH_USER | |
| #undef JSON_INTERNAL_CATCH | |
| #define JSON_INTERNAL_CATCH JSON_CATCH_USER | |
| #endif | |
| #if defined(JSON_INTERNAL_CATCH_USER) | |
| #undef JSON_INTERNAL_CATCH | |
| #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER | |
| #endif | |
| // allow overriding assert | |
| #if !defined(JSON_ASSERT) | |
| #include <cassert> // assert | |
| #define JSON_ASSERT(x) assert(x) | |
| #endif | |
| // allow accessing some private functions (needed by the test suite) | |
| #if defined(JSON_TESTS_PRIVATE) | |
| #define JSON_PRIVATE_UNLESS_TESTED public | |
| #else | |
| #define JSON_PRIVATE_UNLESS_TESTED private | |
| #endif | |
| /*! | |
| @brief macro to briefly define a mapping between an enum and JSON | |
| @def NLOHMANN_JSON_SERIALIZE_ENUM | |
| @since version 3.4.0 | |
| */ | |
| #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ | |
| template<typename BasicJsonType> \ | |
| inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ | |
| { \ | |
| /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ | |
| static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \ | |
| /* NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) we don't want to depend on <array> */ \ | |
| static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \ | |
| auto it = std::find_if(std::begin(m), std::end(m), \ | |
| [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \ | |
| { \ | |
| return ej_pair.first == e; \ | |
| }); \ | |
| j = ((it != std::end(m)) ? it : std::begin(m))->second; \ | |
| } \ | |
| template<typename BasicJsonType> \ | |
| inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ | |
| { \ | |
| /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ | |
| static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \ | |
| /* NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) we don't want to depend on <array> */ \ | |
| static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \ | |
| auto it = std::find_if(std::begin(m), std::end(m), \ | |
| [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \ | |
| { \ | |
| return ej_pair.second == j; \ | |
| }); \ | |
| e = ((it != std::end(m)) ? it : std::begin(m))->first; \ | |
| } | |
| /*! | |
| @brief macro to briefly define a mapping between an enum and JSON with exception | |
| on invalid input | |
| @def NLOHMANN_JSON_SERIALIZE_ENUM_STRICT | |
| @since version 3.13.0 | |
| */ | |
| #define NLOHMANN_JSON_SERIALIZE_ENUM_STRICT(ENUM_TYPE, ...) \ | |
| template<typename BasicJsonType> \ | |
| inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ | |
| { \ | |
| /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ | |
| static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \ | |
| /* NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) we don't want to depend on <array> */ \ | |
| static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \ | |
| auto it = std::find_if(std::begin(m), std::end(m), \ | |
| [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \ | |
| { \ | |
| return ej_pair.first == e; \ | |
| }); \ | |
| if (it != std::end(m)) j = it->second; \ | |
| else ::nlohmann::detail::templated_json_throw<nlohmann::detail::out_of_range>(nlohmann::detail::out_of_range::create(nlohmann::detail::exception_id::value_out_of_range,"enum value out of range for " #ENUM_TYPE, nullptr)); \ | |
| } \ | |
| template<typename BasicJsonType> \ | |
| inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ | |
| { \ | |
| /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ | |
| static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \ | |
| /* NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) we don't want to depend on <array> */ \ | |
| static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \ | |
| auto it = std::find_if(std::begin(m), std::end(m), \ | |
| [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \ | |
| { \ | |
| return ej_pair.second == j; \ | |
| }); \ | |
| if (it != std::end(m)) e = it->first; \ | |
| else ::nlohmann::detail::templated_json_throw<nlohmann::detail::out_of_range>(nlohmann::detail::out_of_range::create(nlohmann::detail::exception_id::value_out_of_range, nlohmann::detail::concat("enum value out of range for " #ENUM_TYPE ": ", j.dump(-1, ' ', false, nlohmann::detail::error_handler_t::replace)), &j)); \ | |
| } | |
| // Ugly macros to avoid uglier copy-paste when specializing basic_json. They | |
| // may be removed in the future once the class is split. | |
| #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ | |
| template<template<typename, typename, typename...> class ObjectType, \ | |
| template<typename, typename...> class ArrayType, \ | |
| class StringType, class BooleanType, class NumberIntegerType, \ | |
| class NumberUnsignedType, class NumberFloatType, \ | |
| template<typename> class AllocatorType, \ | |
| template<typename, typename = void> class JSONSerializer, \ | |
| class BinaryType, \ | |
| class CustomBaseClass> | |
| #define NLOHMANN_BASIC_JSON_TPL \ | |
| basic_json<ObjectType, ArrayType, StringType, BooleanType, \ | |
| NumberIntegerType, NumberUnsignedType, NumberFloatType, \ | |
| AllocatorType, JSONSerializer, BinaryType, CustomBaseClass> | |
| // Macros to simplify conversion from/to types | |
| // NLOHMANN_JSON_EXPAND to NLOHMANN_JSON_DOUBLE_PASTE63 are generated by tools/macro_builder (see its README.md) | |
| #define NLOHMANN_JSON_EXPAND( x ) x | |
| #define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME | |
| #define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ | |
| NLOHMANN_JSON_PASTE64, \ | |
| NLOHMANN_JSON_PASTE63, \ | |
| NLOHMANN_JSON_PASTE62, \ | |
| NLOHMANN_JSON_PASTE61, \ | |
| NLOHMANN_JSON_PASTE60, \ | |
| NLOHMANN_JSON_PASTE59, \ | |
| NLOHMANN_JSON_PASTE58, \ | |
| NLOHMANN_JSON_PASTE57, \ | |
| NLOHMANN_JSON_PASTE56, \ | |
| NLOHMANN_JSON_PASTE55, \ | |
| NLOHMANN_JSON_PASTE54, \ | |
| NLOHMANN_JSON_PASTE53, \ | |
| NLOHMANN_JSON_PASTE52, \ | |
| NLOHMANN_JSON_PASTE51, \ | |
| NLOHMANN_JSON_PASTE50, \ | |
| NLOHMANN_JSON_PASTE49, \ | |
| NLOHMANN_JSON_PASTE48, \ | |
| NLOHMANN_JSON_PASTE47, \ | |
| NLOHMANN_JSON_PASTE46, \ | |
| NLOHMANN_JSON_PASTE45, \ | |
| NLOHMANN_JSON_PASTE44, \ | |
| NLOHMANN_JSON_PASTE43, \ | |
| NLOHMANN_JSON_PASTE42, \ | |
| NLOHMANN_JSON_PASTE41, \ | |
| NLOHMANN_JSON_PASTE40, \ | |
| NLOHMANN_JSON_PASTE39, \ | |
| NLOHMANN_JSON_PASTE38, \ | |
| NLOHMANN_JSON_PASTE37, \ | |
| NLOHMANN_JSON_PASTE36, \ | |
| NLOHMANN_JSON_PASTE35, \ | |
| NLOHMANN_JSON_PASTE34, \ | |
| NLOHMANN_JSON_PASTE33, \ | |
| NLOHMANN_JSON_PASTE32, \ | |
| NLOHMANN_JSON_PASTE31, \ | |
| NLOHMANN_JSON_PASTE30, \ | |
| NLOHMANN_JSON_PASTE29, \ | |
| NLOHMANN_JSON_PASTE28, \ | |
| NLOHMANN_JSON_PASTE27, \ | |
| NLOHMANN_JSON_PASTE26, \ | |
| NLOHMANN_JSON_PASTE25, \ | |
| NLOHMANN_JSON_PASTE24, \ | |
| NLOHMANN_JSON_PASTE23, \ | |
| NLOHMANN_JSON_PASTE22, \ | |
| NLOHMANN_JSON_PASTE21, \ | |
| NLOHMANN_JSON_PASTE20, \ | |
| NLOHMANN_JSON_PASTE19, \ | |
| NLOHMANN_JSON_PASTE18, \ | |
| NLOHMANN_JSON_PASTE17, \ | |
| NLOHMANN_JSON_PASTE16, \ | |
| NLOHMANN_JSON_PASTE15, \ | |
| NLOHMANN_JSON_PASTE14, \ | |
| NLOHMANN_JSON_PASTE13, \ | |
| NLOHMANN_JSON_PASTE12, \ | |
| NLOHMANN_JSON_PASTE11, \ | |
| NLOHMANN_JSON_PASTE10, \ | |
| NLOHMANN_JSON_PASTE9, \ | |
| NLOHMANN_JSON_PASTE8, \ | |
| NLOHMANN_JSON_PASTE7, \ | |
| NLOHMANN_JSON_PASTE6, \ | |
| NLOHMANN_JSON_PASTE5, \ | |
| NLOHMANN_JSON_PASTE4, \ | |
| NLOHMANN_JSON_PASTE3, \ | |
| NLOHMANN_JSON_PASTE2, \ | |
| NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) | |
| #define NLOHMANN_JSON_PASTE2(func, v1) func(v1) | |
| #define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) | |
| #define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) | |
| #define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) | |
| #define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) | |
| #define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) | |
| #define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) | |
| #define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) | |
| #define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) | |
| #define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) | |
| #define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) | |
| #define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) | |
| #define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) | |
| #define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) | |
| #define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) | |
| #define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) | |
| #define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) | |
| #define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) | |
| #define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) | |
| #define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) | |
| #define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) | |
| #define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) | |
| #define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) | |
| #define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) | |
| #define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) | |
| #define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) | |
| #define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) | |
| #define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) | |
| #define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) | |
| #define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) | |
| #define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) | |
| #define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) | |
| #define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) | |
| #define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) | |
| #define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) | |
| #define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) | |
| #define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) | |
| #define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) | |
| #define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) | |
| #define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) | |
| #define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) | |
| #define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) | |
| #define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) | |
| #define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) | |
| #define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) | |
| #define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) | |
| #define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) | |
| #define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) | |
| #define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) | |
| #define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) | |
| #define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) | |
| #define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) | |
| #define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) | |
| #define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) | |
| #define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) | |
| #define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) | |
| #define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) | |
| #define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) | |
| #define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) | |
| #define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) | |
| #define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) | |
| #define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) | |
| #define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE63, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE63, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE61, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE61, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE59, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE59, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE57, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE57, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE55, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE55, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE53, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE53, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE51, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE51, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE49, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE49, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE47, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE47, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE45, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE45, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE43, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE43, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE41, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE41, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE39, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE39, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE37, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE37, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE35, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE35, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE33, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE33, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE31, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE31, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE29, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE29, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE27, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE27, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE25, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE25, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE23, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE23, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE21, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE21, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE19, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE19, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE17, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE17, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE15, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE15, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE13, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE13, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE11, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE11, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE9, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE9, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE7, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE7, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE5, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE5, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE3, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE3, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE1, \ | |
| NLOHMANN_JSON_DOUBLE_PASTE1)(__VA_ARGS__)) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) func(v1, v2) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE3(func, v3, v4) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE5(func, v3, v4, v5, v6) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE7(func, v3, v4, v5, v6, v7, v8) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE9(func, v3, v4, v5, v6, v7, v8, v9, v10) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE11(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE13(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE15(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE17(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE19(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE21(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE23(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE25(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE27(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE29(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE31(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE33(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE35(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE37(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE39(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE41(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE43(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE45(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE47(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE49(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE51(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE53(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE55(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE57(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE59(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) | |
| #define NLOHMANN_JSON_DOUBLE_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_DOUBLE_PASTE3(func, v1, v2) NLOHMANN_JSON_DOUBLE_PASTE61(func, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) | |
| #define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; | |
| #define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); | |
| #define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) nlohmann_json_t.v1 = !nlohmann_json_j.is_null() ? nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1) : nlohmann_json_default_obj.v1; | |
| #define NLOHMANN_JSON_TO_WITH_NAME(v1, v2) nlohmann_json_j[v1] = nlohmann_json_t.v2; | |
| #define NLOHMANN_JSON_FROM_WITH_NAME(v1, v2) nlohmann_json_j.at(v1).get_to(nlohmann_json_t.v2); | |
| #define NLOHMANN_JSON_FROM_WITH_DEFAULT_WITH_NAME(v1, v2) nlohmann_json_t.v2 = !nlohmann_json_j.is_null() ? nlohmann_json_j.value(v1, nlohmann_json_default_obj.v2) : nlohmann_json_default_obj.v2; | |
| #define NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(...) template<typename BasicJsonType, nlohmann::detail::enable_if_t<nlohmann::detail::is_basic_json<BasicJsonType>::value, int> = 0> __VA_ARGS__ | |
| // Helpers used to dispatch the NLOHMANN_DEFINE_TYPE_*/NLOHMANN_DEFINE_DERIVED_TYPE_* | |
| // macros below between a zero-member and a one-or-more-member implementation | |
| // (issue #4041, e.g. NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type) with no further | |
| // arguments). NLOHMANN_JSON_TYPE_BODY(Prefix, ...) expands to the macro name | |
| // Prefix##EMPTY when __VA_ARGS__ is a single argument (Type alone) and to | |
| // Prefix##MEMBERS for two or more (Type, member...). It reuses the existing | |
| // 64-slot NLOHMANN_JSON_GET_MACRO dispatch with one extra trailing sentinel | |
| // token appended so its own trailing "..." is never left completely empty at | |
| // the lowest supported argument count -- invoking a variadic macro so that | |
| // "..." matches nothing is only granted unconditionally by the standard since | |
| // C++20, and pre-C++20 compilers may reject it under -pedantic regardless of | |
| // what the macro body does. | |
| // | |
| // The EMPTY/MEMBERS suffixes are pasted onto Prefix right in the slot table: | |
| // operands of ## are not macro-expanded, so the dispatch keeps working even if | |
| // user code defines macros named EMPTY or MEMBERS. Producing the bare suffix | |
| // first and pasting it later would let such a macro replace it. | |
| // | |
| // NLOHMANN_JSON_DERIVED_TYPE_BODY(Prefix, ...) answers the same question for | |
| // the derived-type macros, whose fixed prefix is Type,BaseType. It drops the | |
| // leading Type and defers to NLOHMANN_JSON_TYPE_BODY rather than shifting the | |
| // slot table by one: NLOHMANN_JSON_GET_MACRO only resolves 64 positional | |
| // arguments, so dispatching on Type,BaseType,member... directly would run out | |
| // one slot early and cap the derived-type macros at 62 members instead of the | |
| // 63 that NLOHMANN_JSON_PASTE supports. | |
| // | |
| // The slot table below (down to the closing NLOHMANN_JSON_TYPE_BODY_SENTINEL)) | |
| // is generated by tools/macro_builder (see its README.md; run with the | |
| // "type_body" argument). | |
| #define NLOHMANN_JSON_TYPE_BODY(Prefix, ...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ | |
| Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, \ | |
| Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, \ | |
| Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, \ | |
| Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, \ | |
| Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, \ | |
| Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, \ | |
| Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, \ | |
| Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## MEMBERS, Prefix ## EMPTY, \ | |
| NLOHMANN_JSON_TYPE_BODY_SENTINEL)) | |
| #define NLOHMANN_JSON_DERIVED_TYPE_BODY_(Prefix, Type, ...) NLOHMANN_JSON_TYPE_BODY(Prefix, __VA_ARGS__) | |
| #define NLOHMANN_JSON_DERIVED_TYPE_BODY(Prefix, ...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DERIVED_TYPE_BODY_(Prefix, __VA_ARGS__)) | |
| /*! | |
| @brief macro | |
| @def NLOHMANN_DEFINE_TYPE_INTRUSIVE | |
| @since version 3.9.0 | |
| @sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ | |
| */ | |
| #define NLOHMANN_JSON_DEFINE_TYPE_INTRUSIVE_MEMBERS(Type, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }) | |
| #define NLOHMANN_JSON_DEFINE_TYPE_INTRUSIVE_EMPTY(Type) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type&) { nlohmann_json_j = BasicJsonType::object(); }) \ | |
| /* NOLINTNEXTLINE(bugprone-macro-parentheses) Type is used as a declarator type, not in an expression */ \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void from_json(const BasicJsonType&, Type&) noexcept { }) | |
| #define NLOHMANN_DEFINE_TYPE_INTRUSIVE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_TYPE_BODY(NLOHMANN_JSON_DEFINE_TYPE_INTRUSIVE_, __VA_ARGS__)(__VA_ARGS__)) | |
| #define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_NAMES(Type, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_TO_WITH_NAME, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_FROM_WITH_NAME, __VA_ARGS__)) }) | |
| /*! | |
| @brief macro | |
| @def NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT | |
| @since version 3.11.0 | |
| @sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ | |
| */ | |
| #define NLOHMANN_JSON_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT_MEMBERS(Type, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) }) | |
| // identical to NLOHMANN_JSON_DEFINE_TYPE_INTRUSIVE_EMPTY: with no members there is nothing to default | |
| #define NLOHMANN_JSON_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT_EMPTY(Type) NLOHMANN_JSON_DEFINE_TYPE_INTRUSIVE_EMPTY(Type) | |
| #define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_TYPE_BODY(NLOHMANN_JSON_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT_, __VA_ARGS__)(__VA_ARGS__)) | |
| #define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT_WITH_NAMES(Type, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_TO_WITH_NAME, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT_WITH_NAME, __VA_ARGS__)) }) | |
| /*! | |
| @brief macro | |
| @def NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE | |
| @since version 3.11.3 | |
| @sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ | |
| */ | |
| #define NLOHMANN_JSON_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE_MEMBERS(Type, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) }) | |
| #define NLOHMANN_JSON_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE_EMPTY(Type) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type&) { nlohmann_json_j = BasicJsonType::object(); }) | |
| #define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_TYPE_BODY(NLOHMANN_JSON_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE_, __VA_ARGS__)(__VA_ARGS__)) | |
| #define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE_WITH_NAMES(Type, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_TO_WITH_NAME, __VA_ARGS__)) }) | |
| /*! | |
| @brief macro | |
| @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE | |
| @since version 3.9.0 | |
| @sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ | |
| */ | |
| #define NLOHMANN_JSON_DEFINE_TYPE_NON_INTRUSIVE_MEMBERS(Type, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }) | |
| #define NLOHMANN_JSON_DEFINE_TYPE_NON_INTRUSIVE_EMPTY(Type) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type&) { nlohmann_json_j = BasicJsonType::object(); }) \ | |
| /* NOLINTNEXTLINE(bugprone-macro-parentheses) Type is used as a declarator type, not in an expression */ \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void from_json(const BasicJsonType&, Type&) noexcept { }) | |
| #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_TYPE_BODY(NLOHMANN_JSON_DEFINE_TYPE_NON_INTRUSIVE_, __VA_ARGS__)(__VA_ARGS__)) | |
| #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_NAMES(Type, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_TO_WITH_NAME, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_FROM_WITH_NAME, __VA_ARGS__)) }) | |
| /*! | |
| @brief macro | |
| @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT | |
| @since version 3.11.0 | |
| @sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ | |
| */ | |
| #define NLOHMANN_JSON_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT_MEMBERS(Type, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) }) | |
| // identical to NLOHMANN_JSON_DEFINE_TYPE_NON_INTRUSIVE_EMPTY: with no members there is nothing to default | |
| #define NLOHMANN_JSON_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT_EMPTY(Type) NLOHMANN_JSON_DEFINE_TYPE_NON_INTRUSIVE_EMPTY(Type) | |
| #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_TYPE_BODY(NLOHMANN_JSON_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT_, __VA_ARGS__)(__VA_ARGS__)) | |
| #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT_WITH_NAMES(Type, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_TO_WITH_NAME, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT_WITH_NAME, __VA_ARGS__)) }) | |
| /*! | |
| @brief macro | |
| @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE | |
| @since version 3.11.3 | |
| @sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ | |
| */ | |
| #define NLOHMANN_JSON_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE_MEMBERS(Type, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) }) | |
| #define NLOHMANN_JSON_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE_EMPTY(Type) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type&) { nlohmann_json_j = BasicJsonType::object(); }) | |
| #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_TYPE_BODY(NLOHMANN_JSON_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE_, __VA_ARGS__)(__VA_ARGS__)) | |
| #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE_WITH_NAMES(Type, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_TO_WITH_NAME, __VA_ARGS__)) }) | |
| /*! | |
| @brief macro | |
| @def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE | |
| @since version 3.12.0 | |
| @sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ | |
| */ | |
| #define NLOHMANN_JSON_DEFINE_DERIVED_TYPE_INTRUSIVE_MEMBERS(Type, BaseType, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast<BaseType&>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }) | |
| #define NLOHMANN_JSON_DEFINE_DERIVED_TYPE_INTRUSIVE_EMPTY(Type, BaseType) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); }) \ | |
| /* NOLINTNEXTLINE(bugprone-macro-parentheses) Type/BaseType are used as declarator types, not in expressions */ \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast<BaseType&>(nlohmann_json_t)); }) | |
| #define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DERIVED_TYPE_BODY(NLOHMANN_JSON_DEFINE_DERIVED_TYPE_INTRUSIVE_, __VA_ARGS__)(__VA_ARGS__)) | |
| #define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_NAMES(Type, BaseType, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_TO_WITH_NAME, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast<BaseType&>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_FROM_WITH_NAME, __VA_ARGS__)) }) | |
| /*! | |
| @brief macro | |
| @def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT | |
| @since version 3.12.0 | |
| @sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ | |
| */ | |
| #define NLOHMANN_JSON_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT_MEMBERS(Type, BaseType, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType&>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast<BaseType&>(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) }) | |
| // identical to NLOHMANN_JSON_DEFINE_DERIVED_TYPE_INTRUSIVE_EMPTY: with no members there is nothing to default | |
| #define NLOHMANN_JSON_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT_EMPTY(Type, BaseType) NLOHMANN_JSON_DEFINE_DERIVED_TYPE_INTRUSIVE_EMPTY(Type, BaseType) | |
| #define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DERIVED_TYPE_BODY(NLOHMANN_JSON_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT_, __VA_ARGS__)(__VA_ARGS__)) | |
| #define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT_WITH_NAMES(Type, BaseType, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType&>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_TO_WITH_NAME, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast<BaseType&>(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT_WITH_NAME, __VA_ARGS__)) }) | |
| /*! | |
| @brief macro | |
| @def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE | |
| @since version 3.12.0 | |
| @sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ | |
| */ | |
| #define NLOHMANN_JSON_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE_MEMBERS(Type, BaseType, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) }) | |
| #define NLOHMANN_JSON_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE_EMPTY(Type, BaseType) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); }) | |
| #define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DERIVED_TYPE_BODY(NLOHMANN_JSON_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE_, __VA_ARGS__)(__VA_ARGS__)) | |
| #define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE_WITH_NAMES(Type, BaseType, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_TO_WITH_NAME, __VA_ARGS__)) }) | |
| /*! | |
| @brief macro | |
| @def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE | |
| @since version 3.12.0 | |
| @sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ | |
| */ | |
| #define NLOHMANN_JSON_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_MEMBERS(Type, BaseType, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast<BaseType&>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }) | |
| #define NLOHMANN_JSON_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_EMPTY(Type, BaseType) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); }) \ | |
| /* NOLINTNEXTLINE(bugprone-macro-parentheses) Type/BaseType are used as declarator types, not in expressions */ \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast<BaseType&>(nlohmann_json_t)); }) | |
| #define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DERIVED_TYPE_BODY(NLOHMANN_JSON_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_, __VA_ARGS__)(__VA_ARGS__)) | |
| #define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_NAMES(Type, BaseType, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_TO_WITH_NAME, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast<BaseType&>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_FROM_WITH_NAME, __VA_ARGS__)) }) | |
| /*! | |
| @brief macro | |
| @def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT | |
| @since version 3.12.0 | |
| @sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ | |
| */ | |
| #define NLOHMANN_JSON_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT_MEMBERS(Type, BaseType, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast<BaseType&>(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) }) | |
| // identical to NLOHMANN_JSON_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_EMPTY: with no members there is nothing to default | |
| #define NLOHMANN_JSON_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT_EMPTY(Type, BaseType) NLOHMANN_JSON_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_EMPTY(Type, BaseType) | |
| #define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DERIVED_TYPE_BODY(NLOHMANN_JSON_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT_, __VA_ARGS__)(__VA_ARGS__)) | |
| #define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT_WITH_NAMES(Type, BaseType, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_TO_WITH_NAME, __VA_ARGS__)) }) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast<BaseType&>(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT_WITH_NAME, __VA_ARGS__)) }) | |
| /*! | |
| @brief macro | |
| @def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE | |
| @since version 3.12.0 | |
| @sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ | |
| */ | |
| #define NLOHMANN_JSON_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE_MEMBERS(Type, BaseType, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) }) | |
| #define NLOHMANN_JSON_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE_EMPTY(Type, BaseType) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); }) | |
| #define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DERIVED_TYPE_BODY(NLOHMANN_JSON_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE_, __VA_ARGS__)(__VA_ARGS__)) | |
| #define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE_WITH_NAMES(Type, BaseType, ...) \ | |
| NLOHMANN_JSON_BASIC_TYPE_TEMPLATE(void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast<const BaseType &>(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_DOUBLE_PASTE(NLOHMANN_JSON_TO_WITH_NAME, __VA_ARGS__)) }) | |
| // inspired from https://stackoverflow.com/a/26745591 | |
| // allows calling any std function as if (e.g., with begin): | |
| // using std::begin; begin(x); | |
| // | |
| // it allows using the detected idiom to retrieve the return type | |
| // of such an expression | |
| #define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ | |
| namespace detail { \ | |
| using std::std_name; \ | |
| \ | |
| template<typename... T> \ | |
| using result_of_##std_name = decltype(std_name(std::declval<T>()...)); \ | |
| } | |
| #ifndef JSON_USE_IMPLICIT_CONVERSIONS | |
| #define JSON_USE_IMPLICIT_CONVERSIONS 1 | |
| #endif | |
| #if JSON_USE_IMPLICIT_CONVERSIONS | |
| #define JSON_EXPLICIT | |
| #else | |
| #define JSON_EXPLICIT explicit | |
| #endif | |
| #ifndef JSON_DISABLE_ENUM_SERIALIZATION | |
| #define JSON_DISABLE_ENUM_SERIALIZATION 0 | |
| #endif | |
| #ifndef JSON_DELETE_DEPRECATED_FUNCTIONS | |
| #define JSON_DELETE_DEPRECATED_FUNCTIONS 0 | |
| #endif | |
| #ifndef JSON_DISABLE_TUPLE_REFERENCE_CONVERSION | |
| #define JSON_DISABLE_TUPLE_REFERENCE_CONVERSION 0 | |
| #endif | |
| #if JSON_HAS_THREE_WAY_COMPARISON | |
| #include <compare> // partial_ordering | |
| #endif | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /////////////////////////// | |
| // JSON type enumeration // | |
| /////////////////////////// | |
| /*! | |
| @brief the JSON type enumeration | |
| This enumeration collects the different JSON types. It is internally used to | |
| distinguish the stored values, and the functions @ref basic_json::is_null(), | |
| @ref basic_json::is_object(), @ref basic_json::is_array(), | |
| @ref basic_json::is_string(), @ref basic_json::is_boolean(), | |
| @ref basic_json::is_number() (with @ref basic_json::is_number_integer(), | |
| @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), | |
| @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and | |
| @ref basic_json::is_structured() rely on it. | |
| @note There are three enumeration entries (number_integer, number_unsigned, and | |
| number_float), because the library distinguishes these three types for numbers: | |
| @ref basic_json::number_unsigned_t is used for unsigned integers, | |
| @ref basic_json::number_integer_t is used for signed integers, and | |
| @ref basic_json::number_float_t is used for floating-point numbers or to | |
| approximate integers which do not fit in the limits of their respective type. | |
| @sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON | |
| value with the default value for a given type | |
| @since version 1.0.0 | |
| */ | |
| enum class value_t : std::uint8_t | |
| { | |
| null, ///< null value | |
| object, ///< object (unordered set of name/value pairs) | |
| array, ///< array (ordered collection of values) | |
| string, ///< string value | |
| boolean, ///< boolean value | |
| number_integer, ///< number value (signed integer) | |
| number_unsigned, ///< number value (unsigned integer) | |
| number_float, ///< number value (floating-point) | |
| binary, ///< binary array (ordered collection of bytes) | |
| discarded ///< discarded by the parser callback function | |
| }; | |
| /*! | |
| @brief the name of a JSON type, as returned by basic_json::type_name() | |
| Used in exception messages; also by code that reports types without a | |
| basic_json value at hand (such as the zero-copy view). | |
| */ | |
| inline const char* value_type_name(const value_t t) noexcept | |
| { | |
| switch (t) | |
| { | |
| case value_t::null: | |
| return "null"; | |
| case value_t::object: | |
| return "object"; | |
| case value_t::array: | |
| return "array"; | |
| case value_t::string: | |
| return "string"; | |
| case value_t::boolean: | |
| return "boolean"; | |
| case value_t::binary: | |
| return "binary"; | |
| case value_t::discarded: | |
| return "discarded"; | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| return "number"; | |
| default: | |
| return "invalid"; | |
| } | |
| } | |
| /*! | |
| @brief comparison operator for JSON types | |
| Returns an ordering that is similar to Python: | |
| - order: null < boolean < number < object < array < string < binary | |
| - furthermore, each type is not smaller than itself | |
| - discarded values are not comparable | |
| - binary is represented as a b"" string in python and directly comparable to a | |
| string; however, making a binary array directly comparable with a string would | |
| be surprising behavior in a JSON file. | |
| @since version 1.0.0 | |
| */ | |
| #if JSON_HAS_THREE_WAY_COMPARISON | |
| inline std::partial_ordering operator<=>(const value_t lhs, const value_t rhs) noexcept // *NOPAD* | |
| #else | |
| inline bool operator<(const value_t lhs, const value_t rhs) noexcept | |
| #endif | |
| { | |
| static constexpr std::array<std::uint8_t, 9> order = {{ | |
| 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, | |
| 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, | |
| 6 /* binary */ | |
| } | |
| }; | |
| const auto l_index = static_cast<std::size_t>(lhs); | |
| const auto r_index = static_cast<std::size_t>(rhs); | |
| #if JSON_HAS_THREE_WAY_COMPARISON | |
| if (l_index < order.size() && r_index < order.size()) | |
| { | |
| return order[l_index] <=> order[r_index]; // *NOPAD* | |
| } | |
| return std::partial_ordering::unordered; | |
| #else | |
| return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; | |
| #endif | |
| } | |
| // GCC selects the built-in operator< over an operator rewritten from | |
| // a user-defined spaceship operator | |
| // Clang, MSVC, and ICC select the rewritten candidate | |
| // (see GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105200) | |
| #if JSON_HAS_THREE_WAY_COMPARISON && defined(__GNUC__) | |
| inline bool operator<(const value_t lhs, const value_t rhs) noexcept | |
| { | |
| return std::is_lt(lhs <=> rhs); // *NOPAD* | |
| } | |
| #endif | |
| /*! | |
| @brief whether a value of the given type owns heap memory | |
| Strings, binaries, objects, and arrays are stored as pointers to allocated | |
| values; all other types are stored directly in the union. Every enumerator is | |
| listed so that -Wswitch-enum flags this function when a new type is added. | |
| */ | |
| inline bool owns_memory(const value_t t) noexcept | |
| { | |
| switch (t) | |
| { | |
| case value_t::object: | |
| case value_t::array: | |
| case value_t::string: | |
| case value_t::binary: | |
| return true; | |
| case value_t::null: | |
| case value_t::boolean: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| case value_t::discarded: | |
| default: | |
| return false; | |
| } | |
| } | |
| /*! | |
| @brief whether a value of the given type is neither an object nor an array | |
| Unlike basic_json::is_primitive(), this includes value_t::discarded: it names | |
| the types that iterators walk with a primitive_iterator_t (a single value, or no | |
| value for null and discarded) and that JSON Pointer resolution and the | |
| serializer treat as leaves. Every enumerator is listed so that -Wswitch-enum | |
| flags this function when a new type is added. | |
| */ | |
| inline bool is_primitive(const value_t t) noexcept | |
| { | |
| switch (t) | |
| { | |
| case value_t::object: | |
| case value_t::array: | |
| return false; | |
| case value_t::null: | |
| case value_t::string: | |
| case value_t::boolean: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| case value_t::binary: | |
| case value_t::discarded: | |
| default: | |
| return true; | |
| } | |
| } | |
| /*! | |
| @brief compare an integer with a floating point number without precision loss | |
| Widening the integer to the floating point type loses precision beyond the | |
| float's mantissa, which makes equality intransitive: both 2^63-2 and 2^63-1 | |
| round to 2^63, so each compares equal to that float while differing from each | |
| other. Ordering built on that is not a strict weak ordering, so sorting such | |
| values, or using them as keys in an ordered container, is undefined behavior. | |
| Returns a value to be compared against zero with the original operator, which | |
| reproduces the exact ordering. A NaN operand is returned as is, so comparing it | |
| against zero keeps NaN's semantics: false for the relational operators and | |
| unordered for `<=>`. | |
| */ | |
| template<typename IntegerType, typename FloatType> | |
| FloatType compare_integer_with_float(const IntegerType i, const FloatType f) noexcept | |
| { | |
| const auto ordered = [](int c) noexcept | |
| { | |
| return static_cast<FloatType>(c); | |
| }; | |
| if (std::isnan(f)) | |
| { | |
| return f; | |
| } | |
| // values of IntegerType lie in [-bound, bound) when signed and in | |
| // [0, bound) when unsigned; digits excludes the sign bit, so bound is a | |
| // power of two that the float represents exactly; the signedness comes | |
| // from numeric_limits as well, because std::is_signed is false for class | |
| // types such as 128-bit or multiprecision integers | |
| using limits = std::numeric_limits<IntegerType>; | |
| const FloatType bound = std::ldexp(static_cast<FloatType>(1), limits::digits); | |
| if (f >= bound) | |
| { | |
| return ordered(-1); | |
| } | |
| if (limits::is_signed ? (f < -bound) : (f < static_cast<FloatType>(0))) | |
| { | |
| return ordered(1); | |
| } | |
| // f is now within the integer's range, so truncating it is exact | |
| const FloatType truncated = std::trunc(f); | |
| const auto as_integer = static_cast<IntegerType>(truncated); | |
| if (i != as_integer) | |
| { | |
| return ordered(i < as_integer ? -1 : 1); | |
| } | |
| // the integer parts agree, so any fractional part decides | |
| const FloatType fraction = f - truncated; | |
| if (fraction > static_cast<FloatType>(0)) | |
| { | |
| return ordered(-1); | |
| } | |
| if (fraction < static_cast<FloatType>(0)) | |
| { | |
| return ordered(1); | |
| } | |
| return ordered(0); | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/string_escape.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cstddef> // size_t | |
| #include <utility> // move | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /// append @a s to @a out, escaped like @ref escape does | |
| template<typename StringType> | |
| inline void escape_into(StringType& out, const StringType& s) | |
| { | |
| const std::size_t size = s.size(); | |
| std::size_t run = 0; | |
| for (std::size_t i = 0; i < size; ++i) | |
| { | |
| const char c = s[i]; | |
| if (c == '~' || c == '/') | |
| { | |
| out.append(s.data() + run, i - run); | |
| out.append(c == '~' ? "~0" : "~1", 2); | |
| run = i + 1; | |
| } | |
| } | |
| out.append(s.data() + run, size - run); | |
| } | |
| /*! | |
| * @brief string escaping as described in RFC 6901 (Sect. 4) | |
| * @param[in] s string to escape | |
| * @return escaped string | |
| * | |
| * Note the order of escaping "~" to "~0" and "/" to "~1" is important. | |
| * | |
| * The string is rebuilt in a single pass, appending whole runs between the | |
| * characters that need escaping, while repeated replace() calls would move | |
| * the tail of the string once per escaped character. @ref escape_into appends | |
| * the escaped string to an existing one. | |
| */ | |
| template<typename StringType> | |
| inline StringType escape(const StringType& s) | |
| { | |
| // a single scan for both special characters; nothing to escape is the common case | |
| const std::size_t size = s.size(); | |
| std::size_t i = 0; | |
| while (i < size && s[i] != '~' && s[i] != '/') | |
| { | |
| ++i; | |
| } | |
| if (i == size) | |
| { | |
| return s; | |
| } | |
| StringType result; | |
| result.reserve(size + 2); | |
| escape_into(result, s); | |
| return result; | |
| } | |
| /*! | |
| * @brief string unescaping as described in RFC 6901 (Sect. 4) | |
| * @param[in,out] s string to unescape in place | |
| * | |
| * Note the order of escaping "~1" to "/" and "~0" to "~" is important. | |
| * | |
| * Rebuilt in a single pass, see @ref escape. A "~" that is followed by | |
| * neither "0" nor "1" is passed through unchanged; @ref json_pointer rejects | |
| * such input before it gets here. | |
| */ | |
| template<typename StringType> | |
| inline void unescape(StringType& s) | |
| { | |
| auto pos = s.find_first_of('~', 0); | |
| if (pos == StringType::npos) | |
| { | |
| return; | |
| } | |
| StringType result; | |
| result.reserve(s.size()); | |
| std::size_t run = 0; | |
| while (pos != StringType::npos) | |
| { | |
| result.append(s.data() + run, pos - run); | |
| const auto next = pos + 1; | |
| if (next < s.size() && (s[next] == '0' || s[next] == '1')) | |
| { | |
| result.append(s[next] == '0' ? "~" : "/", 1); | |
| run = pos + 2; | |
| } | |
| else | |
| { | |
| result.append("~", 1); | |
| run = pos + 1; | |
| } | |
| pos = s.find_first_of('~', run); | |
| } | |
| result.append(s.data() + run, s.size() - run); | |
| s = std::move(result); | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/input/position_t.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cstddef> // size_t | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /// struct to capture the start position of the current token | |
| struct position_t | |
| { | |
| /// the total number of characters read | |
| std::size_t chars_read_total = 0; | |
| /// the number of characters read in the current line | |
| std::size_t chars_read_current_line = 0; | |
| /// the number of lines read | |
| std::size_t lines_read = 0; | |
| /// conversion to size_t to preserve SAX interface | |
| constexpr operator size_t() const | |
| { | |
| return chars_read_total; | |
| } | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/meta/cpp_future.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-FileCopyrightText: 2018 The Abseil Authors | |
| // SPDX-License-Identifier: MIT AND Apache-2.0 | |
| #include <cstddef> // size_t | |
| #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_arithmetic, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type | |
| #include <utility> // index_sequence, make_index_sequence, index_sequence_for | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| #ifdef JSON_HAS_CPP_17 | |
| #include <algorithm> // clamp | |
| #endif | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| #ifdef __cpp_lib_remove_cvref | |
| template<typename T> | |
| using uncvref_t = std::remove_cvref_t<T>; | |
| #else | |
| template<typename T> | |
| using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type; | |
| #endif | |
| #ifdef JSON_HAS_CPP_14 | |
| // the following utilities are natively available in C++14 | |
| using std::enable_if_t; | |
| using std::index_sequence; | |
| using std::make_index_sequence; | |
| using std::index_sequence_for; | |
| #else | |
| // alias templates to reduce boilerplate | |
| template<bool B, typename T = void> | |
| using enable_if_t = typename std::enable_if<B, T>::type; | |
| // The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h | |
| // which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. | |
| //// START OF CODE FROM GOOGLE ABSEIL | |
| // integer_sequence | |
| // | |
| // Class template representing a compile-time integer sequence. An instantiation | |
| // of `integer_sequence<T, Ints...>` has a sequence of integers encoded in its | |
| // type through its template arguments (which is a common need when | |
| // working with C++11 variadic templates). `absl::integer_sequence` is designed | |
| // to be a drop-in replacement for C++14's `std::integer_sequence`. | |
| // | |
| // Example: | |
| // | |
| // template< class T, T... Ints > | |
| // void user_function(integer_sequence<T, Ints...>); | |
| // | |
| // int main() | |
| // { | |
| // // user_function's `T` will be deduced to `int` and `Ints...` | |
| // // will be deduced to `0, 1, 2, 3, 4`. | |
| // user_function(make_integer_sequence<int, 5>()); | |
| // } | |
| template <typename T, T... Ints> | |
| struct integer_sequence | |
| { | |
| using value_type = T; | |
| static constexpr std::size_t size() noexcept | |
| { | |
| return sizeof...(Ints); | |
| } | |
| }; | |
| // index_sequence | |
| // | |
| // A helper template for an `integer_sequence` of `size_t`, | |
| // `absl::index_sequence` is designed to be a drop-in replacement for C++14's | |
| // `std::index_sequence`. | |
| template <size_t... Ints> | |
| using index_sequence = integer_sequence<size_t, Ints...>; | |
| namespace utility_internal | |
| { | |
| template <typename Seq, size_t SeqSize, size_t Rem> | |
| struct Extend; | |
| // Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. | |
| template <typename T, T... Ints, size_t SeqSize> | |
| struct Extend<integer_sequence<T, Ints...>, SeqSize, 0> | |
| { | |
| using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; | |
| }; | |
| template <typename T, T... Ints, size_t SeqSize> | |
| struct Extend<integer_sequence<T, Ints...>, SeqSize, 1> | |
| { | |
| using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; | |
| }; | |
| // Recursion helper for 'make_integer_sequence<T, N>'. | |
| // 'Gen<T, N>::type' is an alias for 'integer_sequence<T, 0, 1, ... N-1>'. | |
| template <typename T, size_t N> | |
| struct Gen | |
| { | |
| using type = | |
| typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; | |
| }; | |
| template <typename T> | |
| struct Gen<T, 0> | |
| { | |
| using type = integer_sequence<T>; | |
| }; | |
| } // namespace utility_internal | |
| // Compile-time sequences of integers | |
| // make_integer_sequence | |
| // | |
| // This template alias is equivalent to | |
| // `integer_sequence<int, 0, 1, ..., N-1>`, and is designed to be a drop-in | |
| // replacement for C++14's `std::make_integer_sequence`. | |
| template <typename T, T N> | |
| using make_integer_sequence = typename utility_internal::Gen<T, N>::type; | |
| // make_index_sequence | |
| // | |
| // This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, | |
| // and is designed to be a drop-in replacement for C++14's | |
| // `std::make_index_sequence`. | |
| template <size_t N> | |
| using make_index_sequence = make_integer_sequence<size_t, N>; | |
| // index_sequence_for | |
| // | |
| // Converts a typename pack into an index sequence of the same length, and | |
| // is designed to be a drop-in replacement for C++14's | |
| // `std::index_sequence_for()` | |
| template <typename... Ts> | |
| using index_sequence_for = make_index_sequence<sizeof...(Ts)>; | |
| //// END OF CODE FROM GOOGLE ABSEIL | |
| #endif | |
| // dispatch utility (taken from ranges-v3) | |
| template<unsigned N> struct priority_tag : priority_tag < N - 1 > {}; | |
| template<> struct priority_tag<0> {}; | |
| // taken from ranges-v3 | |
| template<typename T> | |
| struct static_const | |
| { | |
| static JSON_INLINE_VARIABLE constexpr T value{}; | |
| }; | |
| #ifndef JSON_HAS_CPP_17 | |
| template<typename T> | |
| constexpr T static_const<T>::value; | |
| #endif | |
| /// @a v bounded to [@a lo, @a hi] (requires !(hi < lo)); like std::clamp, | |
| /// but by value, so that static constexpr members can be passed without an | |
| /// out-of-line definition before C++17 | |
| template<typename T, enable_if_t<std::is_arithmetic<T>::value, int> = 0> | |
| constexpr T clamp(T v, T lo, T hi) noexcept | |
| { | |
| #ifdef __cpp_lib_clamp | |
| return std::clamp(v, lo, hi); | |
| #else | |
| // NOLINTNEXTLINE(readability-avoid-nested-conditional-operator): a constant expression of C++11 | |
| return v < lo ? lo : (hi < v ? hi : v); | |
| #endif | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <limits> // numeric_limits | |
| #include <map> // map, multimap | |
| #include <string> // char_traits | |
| #include <tuple> // tuple | |
| #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type | |
| #include <unordered_map> // unordered_map, unordered_multimap | |
| #include <utility> // declval | |
| #include <vector> // vector | |
| #if defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L | |
| #include <cstddef> // byte | |
| #endif | |
| // #include <nlohmann/detail/iterators/iterator_traits.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <iterator> // random_access_iterator_tag | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| // #include <nlohmann/detail/meta/void_t.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| template<typename ...Ts> struct make_void | |
| { | |
| using type = void; | |
| }; | |
| template<typename ...Ts> using void_t = typename make_void<Ts...>::type; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/meta/cpp_future.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| template<typename It, typename = void> | |
| struct iterator_types {}; | |
| template<typename It> | |
| struct iterator_types < | |
| It, | |
| void_t<typename It::difference_type, typename It::value_type, typename It::pointer, | |
| typename It::reference, typename It::iterator_category >> | |
| { | |
| using difference_type = typename It::difference_type; | |
| using value_type = typename It::value_type; | |
| using pointer = typename It::pointer; | |
| using reference = typename It::reference; | |
| using iterator_category = typename It::iterator_category; | |
| }; | |
| // This is required as some compilers implement std::iterator_traits in a way that | |
| // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. | |
| template<typename T, typename = void> | |
| struct iterator_traits | |
| { | |
| }; | |
| template<typename T> | |
| struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >> | |
| : iterator_types<T> | |
| { | |
| }; | |
| template<typename T> | |
| struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>> | |
| { | |
| using iterator_category = std::random_access_iterator_tag; | |
| using value_type = T; | |
| using difference_type = ptrdiff_t; | |
| using pointer = T*; | |
| using reference = T&; | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| #ifdef JSON_HAS_CPP_17 | |
| #include <optional> // optional | |
| #endif | |
| // #include <nlohmann/detail/meta/call_std/begin.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin) | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/meta/call_std/end.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end) | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/meta/cpp_future.hpp> | |
| // #include <nlohmann/detail/meta/detected.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <type_traits> | |
| // #include <nlohmann/detail/meta/void_t.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| // https://en.cppreference.com/w/cpp/experimental/is_detected | |
| struct nonesuch | |
| { | |
| nonesuch() = delete; | |
| ~nonesuch() = delete; | |
| nonesuch(nonesuch const&) = delete; | |
| nonesuch(nonesuch const&&) = delete; | |
| void operator=(nonesuch const&) = delete; | |
| void operator=(nonesuch&&) = delete; | |
| }; | |
| template<class Default, | |
| class AlwaysVoid, | |
| template<class...> class Op, | |
| class... Args> | |
| struct detector | |
| { | |
| using value_t = std::false_type; | |
| using type = Default; | |
| }; | |
| template<class Default, template<class...> class Op, class... Args> | |
| struct detector<Default, void_t<Op<Args...>>, Op, Args...> | |
| { | |
| using value_t = std::true_type; | |
| using type = Op<Args...>; | |
| }; | |
| template<template<class...> class Op, class... Args> | |
| using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t; | |
| template<template<class...> class Op, class... Args> | |
| struct is_detected_lazy : is_detected<Op, Args...> { }; | |
| template<template<class...> class Op, class... Args> | |
| using detected_t = typename detector<nonesuch, void, Op, Args...>::type; | |
| template<class Default, template<class...> class Op, class... Args> | |
| using detected_or = detector<Default, void, Op, Args...>; | |
| template<class Default, template<class...> class Op, class... Args> | |
| using detected_or_t = typename detected_or<Default, Op, Args...>::type; | |
| template<class Expected, template<class...> class Op, class... Args> | |
| using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>; | |
| template<class To, template<class...> class Op, class... Args> | |
| using is_detected_convertible = | |
| std::is_convertible<detected_t<Op, Args...>, To>; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/json_fwd.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ | |
| #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ | |
| #include <cstdint> // int64_t, uint64_t | |
| #include <map> // map | |
| #include <string> // allocator, string | |
| #include <vector> // vector | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| /*! | |
| @brief namespace for Niels Lohmann | |
| @see https://github.com/nlohmann | |
| @since version 1.0.0 | |
| */ | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| /*! | |
| @brief default JSONSerializer template argument | |
| This serializer ignores the template arguments and uses ADL | |
| ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) | |
| for serialization. | |
| */ | |
| template<typename T = void, typename SFINAE = void> | |
| struct adl_serializer; // IWYU pragma: keep | |
| /// a class to store JSON values | |
| /// @sa https://json.nlohmann.me/api/basic_json/ | |
| template<template<typename U, typename V, typename... Args> class ObjectType = | |
| std::map, | |
| template<typename U, typename... Args> class ArrayType = std::vector, | |
| class StringType = std::string, class BooleanType = bool, | |
| class NumberIntegerType = std::int64_t, | |
| class NumberUnsignedType = std::uint64_t, | |
| class NumberFloatType = double, | |
| template<typename U> class AllocatorType = std::allocator, | |
| template<typename T, typename SFINAE = void> class JSONSerializer = | |
| adl_serializer, | |
| class BinaryType = std::vector<std::uint8_t>, // cppcheck-suppress syntaxError | |
| class CustomBaseClass = void> | |
| class basic_json; // IWYU pragma: keep | |
| /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document | |
| /// @sa https://json.nlohmann.me/api/json_pointer/ | |
| template<typename RefStringType> | |
| class json_pointer; // IWYU pragma: keep | |
| /*! | |
| @brief default specialization | |
| @sa https://json.nlohmann.me/api/json/ | |
| */ | |
| using json = basic_json<>; | |
| /// @brief a minimal map-like container that preserves insertion order | |
| /// @sa https://json.nlohmann.me/api/ordered_map/ | |
| template<class Key, class T, class IgnoredLess, class Allocator> | |
| struct ordered_map; // IWYU pragma: keep | |
| /// @brief specialization that maintains the insertion order of object keys | |
| /// @sa https://json.nlohmann.me/api/ordered_json/ | |
| using ordered_json = basic_json<nlohmann::ordered_map>; | |
| NLOHMANN_JSON_NAMESPACE_END | |
| #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| /*! | |
| @brief detail namespace with internal helper functions | |
| This namespace collects functions that should not be exposed, | |
| implementations of some @ref basic_json methods, and meta-programming helpers. | |
| @since version 2.1.0 | |
| */ | |
| namespace detail | |
| { | |
| ///////////// | |
| // helpers // | |
| ///////////// | |
| // Note to maintainers: | |
| // | |
| // Every trait in this file expects a non-CV-qualified type. | |
| // The only exceptions are in the 'aliases for detected' section | |
| // (i.e., those of the form: decltype(T::member_function(std::declval<T>()))) | |
| // | |
| // In this case, T has to be properly CV-qualified to constraint the function arguments | |
| // (e.g., to_json(BasicJsonType&, const T&)) | |
| template<typename> struct is_basic_json : std::false_type {}; | |
| NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
| struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {}; | |
| // used by exceptions create() member functions | |
| // true_type for the pointer to possibly cv-qualified basic_json or std::nullptr_t | |
| // false_type otherwise | |
| template<typename BasicJsonContext> | |
| struct is_basic_json_context : | |
| std::integral_constant < bool, | |
| is_basic_json<typename std::remove_cv<typename std::remove_pointer<BasicJsonContext>::type>::type>::value | |
| || std::is_same<BasicJsonContext, std::nullptr_t>::value > | |
| {}; | |
| ////////////////////// | |
| // json_ref helpers // | |
| ////////////////////// | |
| template<typename> | |
| class json_ref; | |
| template<typename> | |
| struct is_json_ref : std::false_type {}; | |
| template<typename T> | |
| struct is_json_ref<json_ref<T>> : std::true_type {}; | |
| ////////////////////////// | |
| // aliases for detected // | |
| ////////////////////////// | |
| template<typename T> | |
| using mapped_type_t = typename T::mapped_type; | |
| template<typename T> | |
| using key_type_t = typename T::key_type; | |
| template<typename T> | |
| using value_type_t = typename T::value_type; | |
| template<typename T> | |
| using difference_type_t = typename T::difference_type; | |
| template<typename T> | |
| using pointer_t = typename T::pointer; | |
| template<typename T> | |
| using reference_t = typename T::reference; | |
| template<typename T> | |
| using iterator_category_t = typename T::iterator_category; | |
| template<typename T, typename... Args> | |
| using to_json_function = decltype(T::to_json(std::declval<Args>()...)); | |
| template<typename T, typename... Args> | |
| using from_json_function = decltype(T::from_json(std::declval<Args>()...)); | |
| template<typename T, typename U> | |
| using get_template_function = decltype(std::declval<T>().template get<U>()); | |
| // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists | |
| template<typename BasicJsonType, typename T, typename = void> | |
| struct has_from_json : std::false_type {}; | |
| // trait checking if j.get<T> is valid | |
| // use this trait instead of std::is_constructible or std::is_convertible, | |
| // both rely on, or make use of implicit conversions, and thus fail when T | |
| // has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) | |
| template <typename BasicJsonType, typename T> | |
| struct is_getable | |
| { | |
| static constexpr bool value = is_detected<get_template_function, const BasicJsonType&, T>::value; | |
| }; | |
| template<typename BasicJsonType, typename T> | |
| struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >> | |
| { | |
| using serializer = typename BasicJsonType::template json_serializer<T, void>; | |
| static constexpr bool value = | |
| is_detected_exact<void, from_json_function, serializer, | |
| const BasicJsonType&, T&>::value; | |
| }; | |
| // This trait checks if JSONSerializer<T>::from_json(json const&) exists | |
| // this overload is used for non-default-constructible user-defined-types | |
| template<typename BasicJsonType, typename T, typename = void> | |
| struct has_non_default_from_json : std::false_type {}; | |
| template<typename BasicJsonType, typename T> | |
| struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >> | |
| { | |
| using serializer = typename BasicJsonType::template json_serializer<T, void>; | |
| static constexpr bool value = | |
| is_detected_exact<T, from_json_function, serializer, | |
| const BasicJsonType&>::value; | |
| }; | |
| // This trait checks if BasicJsonType::json_serializer<T>::to_json exists | |
| // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. | |
| template<typename BasicJsonType, typename T, typename = void> | |
| struct has_to_json : std::false_type {}; | |
| template<typename BasicJsonType, typename T> | |
| struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >> | |
| { | |
| using serializer = typename BasicJsonType::template json_serializer<T, void>; | |
| static constexpr bool value = | |
| is_detected_exact<void, to_json_function, serializer, BasicJsonType&, | |
| T>::value; | |
| }; | |
| template<typename T> | |
| using detect_key_compare = typename T::key_compare; | |
| // detects whether two values of type T can be compared with operator== | |
| template<typename T> | |
| using detect_equal_comparable = decltype(static_cast<bool>(std::declval<const T&>() == std::declval<const T&>())); | |
| // obtains the actual object key comparator: object_t::key_compare if the | |
| // object type defines it, and default_object_comparator_t otherwise | |
| // | |
| // note detected_or_t is used rather than std::conditional, because the latter | |
| // names both of its type arguments eagerly; object_t::key_compare would then | |
| // be a hard error for an object type that does not define it | |
| template<typename BasicJsonType> | |
| struct actual_object_comparator | |
| { | |
| using object_t = typename BasicJsonType::object_t; | |
| using object_comparator_t = typename BasicJsonType::default_object_comparator_t; | |
| using type = detected_or_t<object_comparator_t, detect_key_compare, object_t>; | |
| }; | |
| template<typename BasicJsonType> | |
| using actual_object_comparator_t = typename actual_object_comparator<BasicJsonType>::type; | |
| template<typename T> | |
| using detect_key_comp = decltype(std::declval<const T&>().key_comp()); | |
| // whether ObjectType can be constructed from a pair of Iterator together with | |
| // a copy of its own comparator, the way std::map can: it needs a nested | |
| // key_compare, a const key_comp() convertible to it, and a matching | |
| // (Iterator, Iterator, const key_compare&) constructor. | |
| // | |
| // used to preserve a stateful comparator when a copy is built from a range | |
| // past the iterative deep copy's nesting bound (see copy_object_level); an | |
| // object type that does not satisfy this, such as nlohmann::ordered_map | |
| // (which has key_compare for its std::map-like interface, but no key_comp()), | |
| // keeps default-constructing its comparator, just as it always has | |
| template<typename ObjectType, typename Iterator, typename = void> | |
| struct is_comparator_constructible_object_type_impl : std::false_type {}; | |
| template<typename ObjectType, typename Iterator> | |
| struct is_comparator_constructible_object_type_impl < | |
| ObjectType, Iterator, enable_if_t<is_detected<detect_key_compare, ObjectType>::value >> | |
| { | |
| using key_compare = typename ObjectType::key_compare; | |
| static constexpr bool value = | |
| is_detected_convertible<key_compare, detect_key_comp, ObjectType>::value && | |
| std::is_constructible<ObjectType, Iterator, Iterator, const key_compare&>::value; | |
| }; | |
| template<typename ObjectType, typename Iterator> | |
| struct is_comparator_constructible_object_type | |
| : is_comparator_constructible_object_type_impl<ObjectType, Iterator> {}; | |
| ///////////////// | |
| // char_traits // | |
| ///////////////// | |
| // Primary template of char_traits calls std char_traits | |
| template<typename T> | |
| struct char_traits : std::char_traits<T> | |
| {}; | |
| // Explicitly define char traits for unsigned char since it is not standard | |
| template<> | |
| struct char_traits<unsigned char> : std::char_traits<char> | |
| { | |
| using char_type = unsigned char; | |
| using int_type = uint64_t; | |
| // Redefine to_int_type function | |
| static int_type to_int_type(char_type c) noexcept | |
| { | |
| return static_cast<int_type>(c); | |
| } | |
| static char_type to_char_type(int_type i) noexcept | |
| { | |
| return static_cast<char_type>(i); | |
| } | |
| static constexpr int_type eof() noexcept | |
| { | |
| return static_cast<int_type>(std::char_traits<char>::eof()); | |
| } | |
| }; | |
| // Explicitly define char traits for signed char since it is not standard | |
| template<> | |
| struct char_traits<signed char> : std::char_traits<char> | |
| { | |
| using char_type = signed char; | |
| using int_type = uint64_t; | |
| // Redefine to_int_type function | |
| static int_type to_int_type(char_type c) noexcept | |
| { | |
| // cast via unsigned char: sign-extending a negative char_type would make | |
| // byte 0xFF indistinguishable from eof() | |
| return static_cast<int_type>(static_cast<unsigned char>(c)); | |
| } | |
| static char_type to_char_type(int_type i) noexcept | |
| { | |
| return static_cast<char_type>(i); | |
| } | |
| static constexpr int_type eof() noexcept | |
| { | |
| return static_cast<int_type>(std::char_traits<char>::eof()); | |
| } | |
| }; | |
| #if defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L | |
| template<> | |
| struct char_traits<std::byte> : std::char_traits<char> | |
| { | |
| using char_type = std::byte; | |
| using int_type = uint64_t; | |
| static int_type to_int_type(char_type c) noexcept | |
| { | |
| return static_cast<int_type>(std::to_integer<unsigned char>(c)); | |
| } | |
| static char_type to_char_type(int_type i) noexcept | |
| { | |
| return std::byte(static_cast<unsigned char>(i)); | |
| } | |
| static constexpr int_type eof() noexcept | |
| { | |
| return static_cast<int_type>(std::char_traits<char>::eof()); | |
| } | |
| }; | |
| #endif | |
| /////////////////// | |
| // is_ functions // | |
| /////////////////// | |
| #ifdef __cpp_lib_logical_traits | |
| using std::conjunction; | |
| using std::disjunction; | |
| using std::negation; | |
| #else | |
| // https://en.cppreference.com/w/cpp/types/conjunction | |
| template<class...> struct conjunction : std::true_type { }; | |
| template<class B> struct conjunction<B> : B { }; | |
| template<class B, class... Bn> | |
| struct conjunction<B, Bn...> | |
| : std::conditional<static_cast<bool>(B::value), conjunction<Bn...>, B>::type {}; | |
| // https://en.cppreference.com/w/cpp/types/disjunction | |
| template<class...> struct disjunction : std::false_type { }; | |
| template<class B> struct disjunction<B> : B { }; | |
| template<class B, class... Bn> | |
| struct disjunction<B, Bn...> | |
| : std::conditional<static_cast<bool>(B::value), B, disjunction<Bn...>>::type {}; | |
| // https://en.cppreference.com/w/cpp/types/negation | |
| template<class B> struct negation : std::integral_constant < bool, !B::value > { }; | |
| #endif | |
| // Reimplementation of is_constructible and is_default_constructible, due to them being broken for | |
| // std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). | |
| // This causes compile errors in e.g., Clang 3.5 or GCC 4.9. | |
| template <typename T> | |
| struct is_default_constructible : std::is_default_constructible<T> {}; | |
| template <typename T1, typename T2> | |
| struct is_default_constructible<std::pair<T1, T2>> | |
| : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {}; | |
| template <typename T1, typename T2> | |
| struct is_default_constructible<const std::pair<T1, T2>> | |
| : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {}; | |
| template <typename... Ts> | |
| struct is_default_constructible<std::tuple<Ts...>> | |
| : conjunction<is_default_constructible<Ts>...> {}; | |
| template <typename... Ts> | |
| struct is_default_constructible<const std::tuple<Ts...>> | |
| : conjunction<is_default_constructible<Ts>...> {}; | |
| template <typename T, typename... Args> | |
| struct is_constructible : std::is_constructible<T, Args...> {}; | |
| template <typename T1, typename T2> | |
| struct is_constructible<std::pair<T1, T2>> : is_default_constructible<std::pair<T1, T2>> {}; | |
| template <typename T1, typename T2> | |
| struct is_constructible<const std::pair<T1, T2>> : is_default_constructible<const std::pair<T1, T2>> {}; | |
| template <typename... Ts> | |
| struct is_constructible<std::tuple<Ts...>> : is_default_constructible<std::tuple<Ts...>> {}; | |
| template <typename... Ts> | |
| struct is_constructible<const std::tuple<Ts...>> : is_default_constructible<const std::tuple<Ts...>> {}; | |
| template<typename T, typename = void> | |
| struct is_iterator_traits : std::false_type {}; | |
| template<typename T> | |
| struct is_iterator_traits<iterator_traits<T>> | |
| { | |
| private: | |
| using traits = iterator_traits<T>; | |
| public: | |
| static constexpr auto value = | |
| is_detected<value_type_t, traits>::value && | |
| is_detected<difference_type_t, traits>::value && | |
| is_detected<pointer_t, traits>::value && | |
| is_detected<iterator_category_t, traits>::value && | |
| is_detected<reference_t, traits>::value; | |
| }; | |
| template<typename T> | |
| struct is_range | |
| { | |
| private: | |
| using t_ref = typename std::add_lvalue_reference<T>::type; | |
| using iterator = detected_t<result_of_begin, t_ref>; | |
| using sentinel = detected_t<result_of_end, t_ref>; | |
| // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator | |
| // and https://en.cppreference.com/w/cpp/iterator/sentinel_for | |
| // but reimplementing these would be too much work, as a lot of other concepts are used underneath | |
| static constexpr auto is_iterator_begin = | |
| is_iterator_traits<iterator_traits<iterator>>::value; | |
| public: | |
| static constexpr bool value = !std::is_same<iterator, nonesuch>::value && !std::is_same<sentinel, nonesuch>::value && is_iterator_begin; | |
| }; | |
| template<typename R> | |
| using iterator_t = enable_if_t<is_range<R>::value, result_of_begin<decltype(std::declval<R&>())>>; | |
| template<typename T> | |
| using range_value_t = value_type_t<iterator_traits<iterator_t<T>>>; | |
| // The following implementation of is_complete_type is taken from | |
| // https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ | |
| // and is written by Xiang Fan who agreed to use it in this library. | |
| template<typename T, typename = void> | |
| struct is_complete_type : std::false_type {}; | |
| template<typename T> | |
| struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {}; | |
| template<typename BasicJsonType, typename CompatibleObjectType, | |
| typename = void> | |
| struct is_compatible_object_type_impl : std::false_type {}; | |
| template<typename BasicJsonType, typename CompatibleObjectType> | |
| struct is_compatible_object_type_impl < | |
| BasicJsonType, CompatibleObjectType, | |
| enable_if_t < is_detected<mapped_type_t, CompatibleObjectType>::value&& | |
| is_detected<key_type_t, CompatibleObjectType>::value >> | |
| { | |
| using object_t = typename BasicJsonType::object_t; | |
| // macOS's is_constructible does not play well with nonesuch... | |
| static constexpr bool value = | |
| is_constructible<typename object_t::key_type, | |
| typename CompatibleObjectType::key_type>::value && | |
| is_constructible<typename object_t::mapped_type, | |
| typename CompatibleObjectType::mapped_type>::value; | |
| }; | |
| template<typename BasicJsonType, typename CompatibleObjectType> | |
| struct is_compatible_object_type | |
| : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {}; | |
| template<typename T> | |
| using insert_result_t = decltype(std::declval<T&>().insert(std::declval<const value_type_t<T>&>())); | |
| template<typename T> | |
| using insert_result_second_t = decltype(std::declval<T&>().insert(std::declval<const value_type_t<T>&>()).second); | |
| // a map-like type (std::map, std::unordered_map, ...) whose keys are enums; see | |
| // JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS | |
| template<typename T, typename = void> | |
| struct is_enum_keyed_map : std::false_type {}; | |
| template<typename T> | |
| struct is_enum_keyed_map < | |
| T, enable_if_t < is_detected<mapped_type_t, T>::value&& | |
| is_detected<key_type_t, T>::value >> | |
| { | |
| // maps with non-unique keys (std::multimap, std::unordered_multimap, ...) | |
| // are excluded, because an object cannot hold duplicate keys; they are | |
| // detected by insert() returning an iterator instead of a pair<iterator, bool> | |
| // NOLINTNEXTLINE(modernize-type-traits) we use C++11 | |
| static constexpr bool value = std::is_enum<typename T::key_type>::value && | |
| !(is_detected<insert_result_t, T>::value && !is_detected<insert_result_second_t, T>::value); | |
| }; | |
| template<typename BasicJsonType, typename ConstructibleObjectType, | |
| typename = void> | |
| struct is_constructible_object_type_impl : std::false_type {}; | |
| template<typename BasicJsonType, typename ConstructibleObjectType> | |
| struct is_constructible_object_type_impl < | |
| BasicJsonType, ConstructibleObjectType, | |
| enable_if_t < is_detected<mapped_type_t, ConstructibleObjectType>::value&& | |
| is_detected<key_type_t, ConstructibleObjectType>::value >> | |
| { | |
| using object_t = typename BasicJsonType::object_t; | |
| static constexpr bool value = | |
| (is_default_constructible<ConstructibleObjectType>::value && | |
| (std::is_move_assignable<ConstructibleObjectType>::value || | |
| std::is_copy_assignable<ConstructibleObjectType>::value) && | |
| (is_constructible<typename ConstructibleObjectType::key_type, | |
| typename object_t::key_type>::value && | |
| std::is_same < | |
| typename object_t::mapped_type, | |
| typename ConstructibleObjectType::mapped_type >::value)) || | |
| (has_from_json<BasicJsonType, | |
| typename ConstructibleObjectType::mapped_type>::value || | |
| has_non_default_from_json < | |
| BasicJsonType, | |
| typename ConstructibleObjectType::mapped_type >::value); | |
| }; | |
| template<typename BasicJsonType, typename ConstructibleObjectType> | |
| struct is_constructible_object_type | |
| : is_constructible_object_type_impl<BasicJsonType, | |
| ConstructibleObjectType> {}; | |
| template<typename BasicJsonType, typename CompatibleStringType> | |
| struct is_compatible_string_type | |
| { | |
| static constexpr auto value = | |
| is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value; | |
| }; | |
| template<typename BasicJsonType, typename ConstructibleStringType> | |
| struct is_constructible_string_type | |
| { | |
| // launder type through decltype() to fix compilation failure on ICPC | |
| #ifdef __INTEL_COMPILER | |
| using laundered_type = decltype(std::declval<ConstructibleStringType>()); | |
| #else | |
| using laundered_type = ConstructibleStringType; | |
| #endif | |
| static constexpr auto value = | |
| conjunction < | |
| is_constructible<laundered_type, typename BasicJsonType::string_t>, | |
| is_detected_exact<typename BasicJsonType::string_t::value_type, | |
| value_type_t, laundered_type >>::value; | |
| }; | |
| // Forward declarations: iteration_proxy.hpp includes this file, so we cannot | |
| // include it here. | |
| template<typename IteratorType> class iteration_proxy; | |
| template<typename IteratorType> class iteration_proxy_value; | |
| // Identifies nlohmann's internal iteration-proxy types. These must be excluded | |
| // before evaluating any std::ranges concept to avoid circular constraints. | |
| template<typename T> struct is_iteration_proxy_type : std::false_type {}; | |
| template<typename T> struct is_iteration_proxy_type<iteration_proxy<T>> : std::true_type {}; | |
| template<typename T> struct is_iteration_proxy_type<iteration_proxy_value<T>> : std::true_type {}; | |
| // In C++26, std::optional satisfies std::ranges::view; exclude it so the | |
| // range-view overload does not hijack the optional serializer. | |
| #ifdef JSON_HAS_CPP_17 | |
| template<typename T> struct is_range_view_optional_type : std::false_type {}; | |
| template<typename T> struct is_range_view_optional_type<std::optional<T>> : std::true_type {}; | |
| #else | |
| template<typename T> struct is_range_view_optional_type : std::false_type {}; | |
| #endif | |
| #if JSON_HAS_RANGE_VIEW_CONVERSION | |
| // SafeToCheck guards against types that trigger circular constraints when | |
| // std::ranges::view<T> is evaluated on GCC 12 / libstdc++ 12: | |
| // - iteration_proxy / iteration_proxy_value directly | |
| // - views wrapping the above (e.g. owning_view<iteration_proxy<...>>) | |
| // - views wrapping basic_json (e.g. ref_view<json>) — same circularity | |
| // via json's constructors → is_compatible_array_type → here | |
| // nlohmann's plain range_value_t (iterator_traits-based) is safe to call | |
| // before any std::ranges concept is touched, so we use it for the checks. | |
| template < typename T, bool SafeToCheck = | |
| !is_iteration_proxy_type<T>::value && | |
| !is_iteration_proxy_type<detected_t<range_value_t, T>>::value && | |
| !is_basic_json<detected_t<range_value_t, T>>::value && | |
| !is_range_view_optional_type<T>::value > | |
| struct is_compatible_range_view : std::false_type {}; | |
| template<typename T> | |
| struct is_compatible_range_view<T, true> | |
| : std::bool_constant<std::ranges::view<T>> {}; | |
| #endif | |
| template<typename BasicJsonType, typename CompatibleArrayType, typename = void> | |
| struct is_compatible_array_type_impl : std::false_type {}; | |
| template<typename BasicJsonType, typename CompatibleArrayType> | |
| struct is_compatible_array_type_impl < | |
| BasicJsonType, CompatibleArrayType, | |
| enable_if_t < | |
| is_detected<iterator_t, CompatibleArrayType>::value&& | |
| is_iterator_traits<iterator_traits<detected_t<iterator_t, CompatibleArrayType>>>::value&& | |
| // special case for types like std::filesystem::path whose iterator's value_type are themselves | |
| // c.f. https://github.com/nlohmann/json/pull/3073 | |
| !std::is_same<CompatibleArrayType, detected_t<range_value_t, CompatibleArrayType>>::value | |
| // When range-view support is enabled, std::ranges::view types (e.g. std::string_view, | |
| // filter_view) can match BOTH this iterator-based specialization AND the view-based one | |
| // below, causing ambiguity. Exclude views here so the two specializations are mutually | |
| // exclusive: this one handles plain iterable containers, the other handles views. | |
| #if JSON_HAS_RANGE_VIEW_CONVERSION | |
| && !is_compatible_range_view<CompatibleArrayType>::value | |
| #endif | |
| >> | |
| { | |
| static constexpr bool value = | |
| is_constructible<BasicJsonType, | |
| range_value_t<CompatibleArrayType>>::value; | |
| }; | |
| #if JSON_HAS_RANGE_VIEW_CONVERSION | |
| template<typename BasicJsonType, typename CompatibleArrayType> | |
| struct is_compatible_array_type_impl < | |
| BasicJsonType, CompatibleArrayType, | |
| enable_if_t < is_compatible_range_view<CompatibleArrayType>::value | |
| && !std::is_same<detected_t<range_value_t, CompatibleArrayType>, char>::value | |
| && !std::is_same<detected_t<range_value_t, CompatibleArrayType>, wchar_t>::value >> | |
| { | |
| // CompatibleArrayType is a std::ranges::view here, so std::ranges::range_value_t | |
| // is safe and correctly handles C++20 iterators that may lack classic iterator_traits. | |
| static constexpr bool value = | |
| is_constructible<BasicJsonType, | |
| std::ranges::range_value_t<CompatibleArrayType>>::value; | |
| }; | |
| #endif | |
| template<typename BasicJsonType, typename CompatibleArrayType> | |
| struct is_compatible_array_type | |
| : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {}; | |
| template<typename BasicJsonType, typename ConstructibleArrayType, typename = void> | |
| struct is_constructible_array_type_impl : std::false_type {}; | |
| template<typename BasicJsonType, typename ConstructibleArrayType> | |
| struct is_constructible_array_type_impl < | |
| BasicJsonType, ConstructibleArrayType, | |
| enable_if_t<std::is_same<ConstructibleArrayType, | |
| typename BasicJsonType::value_type>::value >> | |
| : std::true_type {}; | |
| template<typename BasicJsonType, typename ConstructibleArrayType> | |
| struct is_constructible_array_type_impl < | |
| BasicJsonType, ConstructibleArrayType, | |
| enable_if_t < !std::is_same<ConstructibleArrayType, | |
| typename BasicJsonType::value_type>::value&& | |
| !is_compatible_string_type<BasicJsonType, ConstructibleArrayType>::value&& | |
| is_default_constructible<ConstructibleArrayType>::value&& | |
| (std::is_move_assignable<ConstructibleArrayType>::value || | |
| std::is_copy_assignable<ConstructibleArrayType>::value)&& | |
| is_detected<iterator_t, ConstructibleArrayType>::value&& | |
| is_iterator_traits<iterator_traits<detected_t<iterator_t, ConstructibleArrayType>>>::value&& | |
| is_detected<range_value_t, ConstructibleArrayType>::value&& | |
| // special case for types like std::filesystem::path whose iterator's value_type are themselves | |
| // c.f. https://github.com/nlohmann/json/pull/3073 | |
| !std::is_same<ConstructibleArrayType, detected_t<range_value_t, ConstructibleArrayType>>::value&& | |
| is_complete_type < | |
| detected_t<range_value_t, ConstructibleArrayType >>::value >> | |
| { | |
| using value_type = range_value_t<ConstructibleArrayType>; | |
| static constexpr bool value = | |
| std::is_same<value_type, | |
| typename BasicJsonType::array_t::value_type>::value || | |
| has_from_json<BasicJsonType, | |
| value_type>::value || | |
| has_non_default_from_json < | |
| BasicJsonType, | |
| value_type >::value; | |
| }; | |
| template<typename BasicJsonType, typename ConstructibleArrayType> | |
| struct is_constructible_array_type | |
| : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {}; | |
| template<typename RealIntegerType, typename CompatibleNumberIntegerType, | |
| typename = void> | |
| struct is_compatible_integer_type_impl : std::false_type {}; | |
| template<typename RealIntegerType, typename CompatibleNumberIntegerType> | |
| struct is_compatible_integer_type_impl < | |
| RealIntegerType, CompatibleNumberIntegerType, | |
| enable_if_t < std::is_integral<RealIntegerType>::value&& | |
| std::is_integral<CompatibleNumberIntegerType>::value&& | |
| !std::is_same<bool, CompatibleNumberIntegerType>::value >> | |
| { | |
| using RealLimits = std::numeric_limits<RealIntegerType>; | |
| using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>; | |
| static constexpr auto value = | |
| is_constructible<RealIntegerType, | |
| CompatibleNumberIntegerType>::value && | |
| CompatibleLimits::is_integer && | |
| RealLimits::is_signed == CompatibleLimits::is_signed; | |
| }; | |
| template<typename RealIntegerType, typename CompatibleNumberIntegerType> | |
| struct is_compatible_integer_type | |
| : is_compatible_integer_type_impl<RealIntegerType, | |
| CompatibleNumberIntegerType> {}; | |
| // whether to_json() stores an integer of type CompatibleNumberIntegerType as | |
| // number_integer | |
| template<typename BasicJsonType, typename CompatibleNumberIntegerType, typename = void> | |
| struct is_compatible_number_integer_type | |
| : is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType> {}; | |
| // if number_unsigned_t is the same type as number_integer_t, unsigned integers | |
| // are stored as number_integer as well (#2573) | |
| template<typename BasicJsonType, typename CompatibleNumberIntegerType> | |
| struct is_compatible_number_integer_type<BasicJsonType, CompatibleNumberIntegerType, | |
| enable_if_t<conjunction<std::is_same<typename BasicJsonType::number_integer_t, typename BasicJsonType::number_unsigned_t>, | |
| std::is_integral<CompatibleNumberIntegerType>, | |
| std::is_unsigned<CompatibleNumberIntegerType>, | |
| negation<std::is_same<bool, CompatibleNumberIntegerType>>>::value>> | |
| : std::is_constructible<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType> {}; | |
| template<typename BasicJsonType, typename CompatibleType, typename = void> | |
| struct is_compatible_type_impl: std::false_type {}; | |
| template<typename BasicJsonType, typename CompatibleType> | |
| struct is_compatible_type_impl < | |
| BasicJsonType, CompatibleType, | |
| enable_if_t<is_complete_type<CompatibleType>::value >> | |
| { | |
| static constexpr bool value = | |
| has_to_json<BasicJsonType, CompatibleType>::value; | |
| }; | |
| template<typename BasicJsonType, typename CompatibleType> | |
| struct is_compatible_type | |
| : is_compatible_type_impl<BasicJsonType, CompatibleType> {}; | |
| // a one-element std::tuple holding a reference to BasicJsonType, as created by | |
| // std::forward_as_tuple(j); see JSON_DISABLE_TUPLE_REFERENCE_CONVERSION | |
| template<typename BasicJsonType, typename T> | |
| struct is_basic_json_reference_tuple : std::false_type {}; | |
| template<typename BasicJsonType, typename T> | |
| struct is_basic_json_reference_tuple<BasicJsonType, std::tuple<T>> | |
| { | |
| static constexpr bool value = | |
| std::is_reference<T>::value && std::is_same<uncvref_t<T>, BasicJsonType>::value; | |
| }; | |
| template<typename BasicJsonType, typename CompatibleArrayType> | |
| struct is_compatible_binary_type | |
| { | |
| static constexpr bool value = | |
| std::is_same<typename BasicJsonType::binary_t::container_type, CompatibleArrayType>::value && | |
| !std::is_same<typename BasicJsonType::binary_t::container_type, std::vector<std::uint8_t>>::value; | |
| }; | |
| template<typename BasicJsonType, typename CompatibleReferenceType> | |
| struct is_compatible_reference_type_impl | |
| { | |
| using JsonType = uncvref_t<BasicJsonType>; | |
| using CVType = typename std::remove_reference<CompatibleReferenceType>::type; | |
| using Type = typename std::remove_cv<CVType>::type; | |
| constexpr static bool value = std::is_reference<CompatibleReferenceType>::value && | |
| (!std::is_const<typename std::remove_reference<BasicJsonType>::type>::value || std::is_const<CVType>::value) && | |
| (std::is_same<typename JsonType::boolean_t, Type>::value || | |
| std::is_same<typename JsonType::number_float_t, Type>::value || | |
| std::is_same<typename JsonType::number_integer_t, Type>::value || | |
| std::is_same<typename JsonType::number_unsigned_t, Type>::value || | |
| std::is_same<typename JsonType::string_t, Type>::value || | |
| std::is_same<typename JsonType::binary_t, Type>::value || | |
| std::is_same<typename JsonType::object_t, Type>::value || | |
| std::is_same<typename JsonType::array_t, Type>::value); | |
| }; | |
| template<typename BasicJsonType, typename CompatibleReferenceType> | |
| struct is_compatible_reference_type | |
| : is_compatible_reference_type_impl<BasicJsonType, CompatibleReferenceType> {}; | |
| template<typename T1, typename T2> | |
| struct is_constructible_tuple : std::false_type {}; | |
| template<typename T1, typename... Args> | |
| struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<is_constructible<T1, Args>...> {}; | |
| template<typename BasicJsonType, typename T> | |
| struct is_json_iterator_of : std::false_type {}; | |
| template<typename BasicJsonType> | |
| struct is_json_iterator_of<BasicJsonType, typename BasicJsonType::iterator> : std::true_type {}; | |
| template<typename BasicJsonType> | |
| struct is_json_iterator_of<BasicJsonType, typename BasicJsonType::const_iterator> : std::true_type | |
| {}; | |
| // checks if a given type T is a template specialization of Primary | |
| template<template <typename...> class Primary, typename T> | |
| struct is_specialization_of : std::false_type {}; | |
| template<template <typename...> class Primary, typename... Args> | |
| struct is_specialization_of<Primary, Primary<Args...>> : std::true_type {}; | |
| template<typename T> | |
| using is_json_pointer = is_specialization_of<::nlohmann::json_pointer, uncvref_t<T>>; | |
| // checks if B is a json_pointer<A> | |
| template <typename A, typename B> | |
| struct is_json_pointer_of : std::false_type {}; | |
| template <typename A> | |
| struct is_json_pointer_of<A, ::nlohmann::json_pointer<A>> : std::true_type {}; | |
| template <typename A> | |
| struct is_json_pointer_of<A, ::nlohmann::json_pointer<A>&> : std::true_type {}; | |
| // checks if A and B are comparable using Compare functor, assuming that | |
| // neither A nor B is a json_pointer type (that case is handled by | |
| // is_comparable below, which never instantiates this helper otherwise) | |
| template<typename Compare, typename A, typename B, typename = void> | |
| struct is_comparable_no_json_pointer : std::false_type {}; | |
| template<typename Compare, typename A, typename B> | |
| struct is_comparable_no_json_pointer < Compare, A, B, enable_if_t < | |
| std::is_constructible <decltype(std::declval<Compare>()(std::declval<A>(), std::declval<B>()))>::value | |
| && std::is_constructible <decltype(std::declval<Compare>()(std::declval<B>(), std::declval<A>()))>::value | |
| >> : std::true_type {}; | |
| // checks if A and B are comparable using Compare functor | |
| // We dispatch on is_json_pointer_of as a plain bool (rather than folding it | |
| // into a single enable_if_t condition together with the checks below) so | |
| // that the Compare(A, B) checks are only ever written - and thus only ever | |
| // instantiated - when A/B are not a json_pointer/string pair. Those checks | |
| // use json_pointer::operator string_t() (GCC, see #4621) resp. the | |
| // deprecated json_pointer/string operator== (Clang, see #5288), and merely | |
| // naming them as later operands of a plain && chain is not sufficient to | |
| // avoid their instantiation on all compilers, even when the first operand | |
| // is false. The dispatch on is_json_pointer_of can be removed once the | |
| // deprecated json_pointer comparison operators have been removed. | |
| template<typename Compare, typename A, typename B, bool = is_json_pointer_of<uncvref_t<A>, uncvref_t<B>>::value> | |
| struct is_comparable : std::false_type {}; | |
| template<typename Compare, typename A, typename B> | |
| struct is_comparable<Compare, A, B, false> : is_comparable_no_json_pointer<Compare, A, B> {}; | |
| template<typename T> | |
| using detect_is_transparent = typename T::is_transparent; | |
| // type trait to check if KeyType can be used as an object key (without a BasicJsonType) | |
| // see is_usable_as_basic_json_key_type below | |
| template<typename Comparator, typename ObjectKeyType, typename KeyTypeCVRef, bool RequireTransparentComparator = true, | |
| bool ExcludeObjectKeyType = RequireTransparentComparator, typename KeyType = uncvref_t<KeyTypeCVRef>> | |
| using is_usable_as_key_type = typename std::conditional < | |
| is_comparable<Comparator, ObjectKeyType, KeyTypeCVRef>::value | |
| && !(ExcludeObjectKeyType && std::is_same<KeyType, | |
| ObjectKeyType>::value) | |
| && (!RequireTransparentComparator | |
| || is_detected <detect_is_transparent, Comparator>::value) | |
| && !is_json_pointer<KeyType>::value, | |
| std::true_type, | |
| std::false_type >::type; | |
| #ifdef JSON_HAS_CPP_17 | |
| // type trait to check if KeyType can only be used as an object key after | |
| // converting it to std::string_view: it is convertible to std::string_view, the | |
| // object's comparator cannot compare it with object_t::key_type directly, but | |
| // can compare a std::string_view. JSON pointers and JSON iterators are ruled out | |
| // first, so that the conversion checks are never instantiated for them (a JSON | |
| // pointer's deprecated conversion to string_t would be named otherwise). | |
| template < typename BasicJsonType, typename KeyTypeCVRef, typename KeyType = uncvref_t<KeyTypeCVRef>, | |
| bool = is_json_pointer<KeyType>::value || is_json_iterator_of<BasicJsonType, KeyType>::value > | |
| struct is_string_view_convertible_key_type : std::false_type {}; | |
| template<typename BasicJsonType, typename KeyTypeCVRef, typename KeyType> | |
| struct is_string_view_convertible_key_type<BasicJsonType, KeyTypeCVRef, KeyType, false> | |
| : std::integral_constant < bool, | |
| std::is_convertible<KeyTypeCVRef, std::string_view>::value | |
| && !is_usable_as_key_type<typename BasicJsonType::object_comparator_t, | |
| typename BasicJsonType::object_t::key_type, KeyTypeCVRef, true, false>::value | |
| && is_usable_as_key_type<typename BasicJsonType::object_comparator_t, | |
| typename BasicJsonType::object_t::key_type, std::string_view, true, false>::value > {}; | |
| #else | |
| template<typename BasicJsonType, typename KeyTypeCVRef> | |
| struct is_string_view_convertible_key_type : std::false_type {}; | |
| #endif | |
| // type trait to check if KeyType can be used as an object key | |
| // true if: | |
| // - KeyType is comparable with BasicJsonType::object_t::key_type | |
| // - if ExcludeObjectKeyType is true, KeyType is not BasicJsonType::object_t::key_type | |
| // - the comparator is transparent or RequireTransparentComparator is false | |
| // - KeyType is not a JSON iterator or json_pointer | |
| template<typename BasicJsonType, typename KeyTypeCVRef, bool RequireTransparentComparator = true, | |
| bool ExcludeObjectKeyType = RequireTransparentComparator, typename KeyType = uncvref_t<KeyTypeCVRef>> | |
| using is_usable_as_basic_json_key_type = typename std::conditional < | |
| (is_usable_as_key_type<typename BasicJsonType::object_comparator_t, | |
| typename BasicJsonType::object_t::key_type, KeyTypeCVRef, | |
| RequireTransparentComparator, ExcludeObjectKeyType>::value | |
| && !is_json_iterator_of<BasicJsonType, KeyType>::value) | |
| || is_string_view_convertible_key_type<BasicJsonType, KeyTypeCVRef>::value | |
| , std::true_type, | |
| std::false_type >::type; | |
| template<typename ObjectType, typename KeyType> | |
| using detect_erase_with_key_type = decltype(std::declval<ObjectType&>().erase(std::declval<KeyType>())); | |
| // type trait to check if object_t has an erase() member functions accepting KeyType | |
| template<typename BasicJsonType, typename KeyType> | |
| using has_erase_with_key_type = typename std::conditional < | |
| is_detected < | |
| detect_erase_with_key_type, | |
| typename BasicJsonType::object_t, KeyType >::value, | |
| std::true_type, | |
| std::false_type >::type; | |
| template<typename ObjectType, typename IteratorType> | |
| using detect_erase_with_iterator = decltype(std::declval<ObjectType&>().erase(std::declval<IteratorType>())); | |
| // type trait to check if erase(iterator) returns void instead of the following | |
| // iterator, as the object types that do not compute a successor the caller may | |
| // not need do | |
| template<typename ObjectType, typename IteratorType> | |
| using erase_returns_void = is_detected_exact<void, detect_erase_with_iterator, ObjectType, IteratorType>; | |
| template<typename T> | |
| using detect_capacity = decltype(std::declval<const T&>().capacity()); | |
| // type trait to check if a type has a capacity() member function | |
| template<typename T> | |
| struct has_capacity : std::integral_constant<bool, is_detected<detect_capacity, T>::value> {}; | |
| // a naive helper to check if a type is an ordered_map (exploits the fact that | |
| // ordered_map inherits capacity() from std::vector) | |
| template <typename T> | |
| struct is_ordered_map : has_capacity<T> {}; | |
| // whether T is a specialization of nlohmann::ordered_map, which only ever | |
| // appends members, so they can only move when its capacity changes | |
| template<typename T> | |
| struct is_nlohmann_ordered_map : std::false_type {}; | |
| template<class Key, class T, class IgnoredLess, class Allocator> | |
| struct is_nlohmann_ordered_map<ordered_map<Key, T, IgnoredLess, Allocator>> : std::true_type {}; | |
| // whether adding or erasing elements never moves the other elements of the | |
| // container T; only node-based standard containers are known to guarantee this | |
| template<typename T> | |
| struct has_stable_elements : std::false_type {}; | |
| template<class Key, class T, class Compare, class Allocator> | |
| struct has_stable_elements<std::map<Key, T, Compare, Allocator>> : std::true_type {}; | |
| template<class Key, class T, class Compare, class Allocator> | |
| struct has_stable_elements<std::multimap<Key, T, Compare, Allocator>> : std::true_type {}; | |
| template<class Key, class T, class Hash, class KeyEqual, class Allocator> | |
| struct has_stable_elements<std::unordered_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {}; | |
| template<class Key, class T, class Hash, class KeyEqual, class Allocator> | |
| struct has_stable_elements<std::unordered_multimap<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {}; | |
| // to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324) | |
| template < typename T, typename U, enable_if_t < !std::is_same<T, U>::value, int > = 0 > | |
| T conditional_static_cast(U value) | |
| { | |
| return static_cast<T>(value); | |
| } | |
| template<typename T, typename U, enable_if_t<std::is_same<T, U>::value, int> = 0> | |
| T conditional_static_cast(U value) | |
| { | |
| return value; | |
| } | |
| // like conditional_static_cast, but converts to bool by comparing with zero, | |
| // because MSVC 2015 warns about any conversion to bool (C4800), even with an | |
| // explicit cast; used for enums whose underlying type is bool | |
| template < typename T, typename U, enable_if_t < !std::is_same<T, bool>::value, int > = 0 > | |
| T bool_aware_static_cast(U value) | |
| { | |
| return conditional_static_cast<T>(value); | |
| } | |
| template<typename T, typename U, enable_if_t<std::is_same<T, bool>::value, int> = 0> | |
| bool bool_aware_static_cast(U value) | |
| { | |
| return value != U(); | |
| } | |
| template<typename... Types> | |
| using all_integral = conjunction<std::is_integral<Types>...>; | |
| template<typename... Types> | |
| using all_signed = conjunction<std::is_signed<Types>...>; | |
| template<typename... Types> | |
| using all_unsigned = conjunction<std::is_unsigned<Types>...>; | |
| template<typename... Types> | |
| using same_sign = disjunction<all_signed<Types...>, all_unsigned<Types...>>; | |
| template<typename OfType, typename T> | |
| using never_out_of_range = std::integral_constant < bool, | |
| (std::is_signed<OfType>::value && (sizeof(T) < sizeof(OfType))) | |
| || (same_sign<OfType, T>::value && sizeof(OfType) == sizeof(T)) >; | |
| template<typename OfType, typename T, | |
| bool OfTypeSigned = std::is_signed<OfType>::value, | |
| bool TSigned = std::is_signed<T>::value> | |
| struct value_in_range_of_impl2; | |
| template<typename OfType, typename T> | |
| struct value_in_range_of_impl2<OfType, T, false, false> | |
| { | |
| static constexpr bool test(T val) | |
| { | |
| using CommonType = typename std::common_type<OfType, T>::type; | |
| return static_cast<CommonType>(val) <= static_cast<CommonType>((std::numeric_limits<OfType>::max)()); | |
| } | |
| }; | |
| template<typename OfType, typename T> | |
| struct value_in_range_of_impl2<OfType, T, true, false> | |
| { | |
| static constexpr bool test(T val) | |
| { | |
| using CommonType = typename std::common_type<OfType, T>::type; | |
| return static_cast<CommonType>(val) <= static_cast<CommonType>((std::numeric_limits<OfType>::max)()); | |
| } | |
| }; | |
| template<typename OfType, typename T> | |
| struct value_in_range_of_impl2<OfType, T, false, true> | |
| { | |
| static constexpr bool test(T val) | |
| { | |
| using CommonType = typename std::common_type<OfType, T>::type; | |
| return val >= 0 && static_cast<CommonType>(val) <= static_cast<CommonType>((std::numeric_limits<OfType>::max)()); | |
| } | |
| }; | |
| template<typename OfType, typename T> | |
| struct value_in_range_of_impl2<OfType, T, true, true> | |
| { | |
| static constexpr bool test(T val) | |
| { | |
| using CommonType = typename std::common_type<OfType, T>::type; | |
| return static_cast<CommonType>(val) >= static_cast<CommonType>((std::numeric_limits<OfType>::min)()) | |
| && static_cast<CommonType>(val) <= static_cast<CommonType>((std::numeric_limits<OfType>::max)()); | |
| } | |
| }; | |
| template<typename OfType, typename T, | |
| bool NeverOutOfRange = never_out_of_range<OfType, T>::value, | |
| typename = detail::enable_if_t<all_integral<OfType, T>::value>> | |
| struct value_in_range_of_impl1; | |
| template<typename OfType, typename T> | |
| struct value_in_range_of_impl1<OfType, T, false> | |
| { | |
| static constexpr bool test(T val) | |
| { | |
| return value_in_range_of_impl2<OfType, T>::test(val); | |
| } | |
| }; | |
| template<typename OfType, typename T> | |
| struct value_in_range_of_impl1<OfType, T, true> | |
| { | |
| static constexpr bool test(T /*val*/) | |
| { | |
| return true; | |
| } | |
| }; | |
| template<typename OfType, typename T> | |
| constexpr bool value_in_range_of(T val) | |
| { | |
| return value_in_range_of_impl1<OfType, T>::test(val); | |
| } | |
| #ifdef __cpp_lib_bool_constant | |
| using std::bool_constant; | |
| #else | |
| template<bool Value> | |
| using bool_constant = std::integral_constant<bool, Value>; | |
| #endif | |
| // Stands in for number_unsigned_t in overload sets if it is the same type as | |
| // number_integer_t, so that the unsigned overloads do not collide with the | |
| // integer ones. Never constructed. Such a basic_json stores every integer as | |
| // number_integer (#2573). | |
| struct same_as_number_integer_type {}; | |
| // NumberUnsignedType, or same_as_number_integer_type if it is the same type as | |
| // NumberIntegerType; basic_json uses this one, as it cannot name its own member | |
| // types through an incomplete basic_json (MSVC reports a recursive alias, and | |
| // old GCC versions crash) | |
| template<typename NumberIntegerType, typename NumberUnsignedType> | |
| using number_unsigned_overload_type = typename std::conditional<std::is_same<NumberIntegerType, NumberUnsignedType>::value, | |
| same_as_number_integer_type, NumberUnsignedType>::type; | |
| // number_unsigned_t of BasicJsonType, or same_as_number_integer_type if it is | |
| // the same type as number_integer_t | |
| template<typename BasicJsonType> | |
| using number_unsigned_overload_t = number_unsigned_overload_type<typename BasicJsonType::number_integer_t, typename BasicJsonType::number_unsigned_t>; | |
| /////////////////////////////////////////////////////////////////////////////// | |
| // is_c_string | |
| /////////////////////////////////////////////////////////////////////////////// | |
| namespace impl | |
| { | |
| template<typename T> | |
| constexpr bool is_c_string() | |
| { | |
| using TUnExt = typename std::remove_extent<T>::type; | |
| using TUnCVExt = typename std::remove_cv<TUnExt>::type; | |
| using TUnPtr = typename std::remove_pointer<T>::type; | |
| using TUnCVPtr = typename std::remove_cv<TUnPtr>::type; | |
| return | |
| (std::is_array<T>::value && std::is_same<TUnCVExt, char>::value) | |
| || (std::is_pointer<T>::value && std::is_same<TUnCVPtr, char>::value); | |
| } | |
| } // namespace impl | |
| // checks whether T is a [cv] char */[cv] char[] C string | |
| template<typename T> | |
| struct is_c_string : bool_constant<impl::is_c_string<T>()> {}; | |
| template<typename T> | |
| using is_c_string_uncvref = is_c_string<uncvref_t<T>>; | |
| /////////////////////////////////////////////////////////////////////////////// | |
| // is_transparent | |
| /////////////////////////////////////////////////////////////////////////////// | |
| namespace impl | |
| { | |
| template<typename T> | |
| constexpr bool is_transparent() | |
| { | |
| return is_detected<detect_is_transparent, T>::value; | |
| } | |
| } // namespace impl | |
| // checks whether T has a member named is_transparent | |
| template<typename T> | |
| struct is_transparent : bool_constant<impl::is_transparent<T>()> {}; | |
| /////////////////////////////////////////////////////////////////////////////// | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/string_concat.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cstring> // strlen | |
| #include <string> // string | |
| #include <utility> // forward | |
| // #include <nlohmann/detail/meta/cpp_future.hpp> | |
| // #include <nlohmann/detail/meta/detected.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| inline std::size_t concat_length() | |
| { | |
| return 0; | |
| } | |
| template<typename... Args> | |
| inline std::size_t concat_length(const char* cstr, const Args& ... rest); | |
| template<typename StringType, typename... Args> | |
| inline std::size_t concat_length(const StringType& str, const Args& ... rest); | |
| template<typename... Args> | |
| inline std::size_t concat_length(const char /*c*/, const Args& ... rest) | |
| { | |
| return 1 + concat_length(rest...); | |
| } | |
| template<typename... Args> | |
| inline std::size_t concat_length(const char* cstr, const Args& ... rest) | |
| { | |
| return ::strlen(cstr) + concat_length(rest...); | |
| } | |
| template<typename StringType, typename... Args> | |
| inline std::size_t concat_length(const StringType& str, const Args& ... rest) | |
| { | |
| return str.size() + concat_length(rest...); | |
| } | |
| template<typename OutStringType> | |
| inline void concat_into(OutStringType& /*out*/) | |
| {} | |
| template<typename StringType, typename Arg> | |
| using string_can_append = decltype(std::declval<StringType&>().append(std::declval < Arg && > ())); | |
| template<typename StringType, typename Arg> | |
| using detect_string_can_append = is_detected<string_can_append, StringType, Arg>; | |
| template<typename StringType, typename Arg> | |
| using string_can_append_op = decltype(std::declval<StringType&>() += std::declval < Arg && > ()); | |
| template<typename StringType, typename Arg> | |
| using detect_string_can_append_op = is_detected<string_can_append_op, StringType, Arg>; | |
| template<typename StringType, typename Arg> | |
| using string_can_append_iter = decltype(std::declval<StringType&>().append(std::declval<const Arg&>().begin(), std::declval<const Arg&>().end())); | |
| template<typename StringType, typename Arg> | |
| using detect_string_can_append_iter = is_detected<string_can_append_iter, StringType, Arg>; | |
| template<typename StringType, typename Arg> | |
| using string_can_append_data = decltype(std::declval<StringType&>().append(std::declval<const Arg&>().data(), std::declval<const Arg&>().size())); | |
| template<typename StringType, typename Arg> | |
| using detect_string_can_append_data = is_detected<string_can_append_data, StringType, Arg>; | |
| template < typename OutStringType, typename Arg, typename... Args, | |
| enable_if_t < !detect_string_can_append<OutStringType, Arg>::value | |
| && detect_string_can_append_op<OutStringType, Arg>::value, int > = 0 > | |
| inline void concat_into(OutStringType& out, Arg && arg, Args && ... rest); | |
| template < typename OutStringType, typename Arg, typename... Args, | |
| enable_if_t < !detect_string_can_append<OutStringType, Arg>::value | |
| && !detect_string_can_append_op<OutStringType, Arg>::value | |
| && detect_string_can_append_iter<OutStringType, Arg>::value, int > = 0 > | |
| inline void concat_into(OutStringType& out, const Arg& arg, Args && ... rest); | |
| template < typename OutStringType, typename Arg, typename... Args, | |
| enable_if_t < !detect_string_can_append<OutStringType, Arg>::value | |
| && !detect_string_can_append_op<OutStringType, Arg>::value | |
| && !detect_string_can_append_iter<OutStringType, Arg>::value | |
| && detect_string_can_append_data<OutStringType, Arg>::value, int > = 0 > | |
| inline void concat_into(OutStringType& out, const Arg& arg, Args && ... rest); | |
| template<typename OutStringType, typename Arg, typename... Args, | |
| enable_if_t<detect_string_can_append<OutStringType, Arg>::value, int> = 0> | |
| inline void concat_into(OutStringType& out, Arg && arg, Args && ... rest) | |
| { | |
| out.append(std::forward<Arg>(arg)); | |
| concat_into(out, std::forward<Args>(rest)...); | |
| } | |
| template < typename OutStringType, typename Arg, typename... Args, | |
| enable_if_t < !detect_string_can_append<OutStringType, Arg>::value | |
| && detect_string_can_append_op<OutStringType, Arg>::value, int > > | |
| inline void concat_into(OutStringType& out, Arg&& arg, Args&& ... rest) | |
| { | |
| out += std::forward<Arg>(arg); | |
| concat_into(out, std::forward<Args>(rest)...); | |
| } | |
| template < typename OutStringType, typename Arg, typename... Args, | |
| enable_if_t < !detect_string_can_append<OutStringType, Arg>::value | |
| && !detect_string_can_append_op<OutStringType, Arg>::value | |
| && detect_string_can_append_iter<OutStringType, Arg>::value, int > > | |
| inline void concat_into(OutStringType& out, const Arg& arg, Args&& ... rest) | |
| { | |
| out.append(arg.begin(), arg.end()); | |
| concat_into(out, std::forward<Args>(rest)...); | |
| } | |
| template < typename OutStringType, typename Arg, typename... Args, | |
| enable_if_t < !detect_string_can_append<OutStringType, Arg>::value | |
| && !detect_string_can_append_op<OutStringType, Arg>::value | |
| && !detect_string_can_append_iter<OutStringType, Arg>::value | |
| && detect_string_can_append_data<OutStringType, Arg>::value, int > > | |
| inline void concat_into(OutStringType& out, const Arg& arg, Args&& ... rest) | |
| { | |
| out.append(arg.data(), arg.size()); | |
| concat_into(out, std::forward<Args>(rest)...); | |
| } | |
| template<typename OutStringType = std::string, typename... Args> | |
| inline OutStringType concat(Args && ... args) | |
| { | |
| OutStringType str; | |
| str.reserve(concat_length(args...)); | |
| concat_into(str, std::forward<Args>(args)...); | |
| return str; | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // With -Wweak-vtables, Clang will complain about the exception classes as they | |
| // have no out-of-line virtual method definitions and their vtable will be | |
| // emitted in every translation unit. This issue cannot be fixed with a | |
| // header-only library as there is no implementation file to move these | |
| // functions to. As a result, we suppress this warning here to avoid client | |
| // code stumbling over this. See https://github.com/nlohmann/json/issues/4087 | |
| // for a discussion. | |
| #if defined(__clang__) | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| JSON_HEDLEY_PRAGMA(clang diagnostic ignored "-Wweak-vtables") | |
| #endif | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| //////////////// | |
| // exceptions // | |
| //////////////// | |
| /*! | |
| @brief the ids of the exceptions thrown by the library | |
| @note The values are part of the public API: they are the `id` member of the | |
| exceptions and appear in their `what()` messages. | |
| @sa https://json.nlohmann.me/home/exceptions/ | |
| */ | |
| enum class exception_id : int | |
| { | |
| // parse_error | |
| syntax_error = 101, ///< unexpected token or invalid literal while parsing JSON | |
| patch_not_an_array = 104, ///< a JSON Patch document is not an array of objects | |
| patch_invalid_operation = 105, ///< a JSON Patch operation is malformed | |
| pointer_index_leading_zero = 106, ///< a JSON Pointer array index has a leading zero | |
| pointer_missing_slash = 107, ///< a JSON Pointer does not start with '/' | |
| pointer_invalid_escape = 108, ///< a JSON Pointer contains an escape other than ~0 and ~1 | |
| pointer_index_not_a_number = 109, ///< a JSON Pointer array index is not a number | |
| unexpected_end_of_input = 110, ///< a binary input ends early, or has bytes left at its end | |
| unexpected_byte = 112, ///< a binary input contains an unexpected byte or invalid length | |
| invalid_string_or_size = 113, ///< a binary input contains an invalid string or size specification | |
| bson_unsupported_type = 114, ///< a BSON record type is not supported | |
| invalid_high_precision_number = 115, ///< a UBJSON/BJData high-precision number cannot be parsed | |
| invalid_document_image = 116, ///< json_document::load() rejects an image | |
| // invalid_iterator | |
| iterators_incompatible = 201, ///< the iterators of a range belong to different values | |
| iterator_from_other_value = 202, ///< an iterator does not belong to the value it is used with | |
| iterator_range_from_other_value = 203, ///< an iterator range does not belong to the value it is used with | |
| iterator_range_out_of_range = 204, ///< an iterator range of a primitive value is not [begin, end) | |
| iterator_out_of_range = 205, ///< an iterator of a primitive value is not begin() | |
| iterator_range_of_null = 206, ///< an iterator range belongs to a null value | |
| iterator_key_not_object = 207, ///< key() is called on an iterator of a non-object | |
| iterator_subscript_on_object = 208, ///< operator[] is called on an iterator of an object | |
| iterator_arithmetic_on_object = 209, ///< an offset operator is used on an iterator of an object | |
| insert_range_incompatible = 210, ///< the iterators of an inserted range belong to different values | |
| insert_range_into_itself = 211, ///< an inserted range belongs to the value it is inserted into | |
| iterators_compare_different_values = 212, ///< iterators of different values are compared | |
| iterator_order_on_object = 213, ///< iterators of an object are compared by order | |
| iterator_value_unavailable = 214, ///< an iterator does not refer to a value | |
| // type_error | |
| object_from_non_pairs = 301, ///< an object is created from an initializer list that is not a list of pairs | |
| type_mismatch = 302, ///< a value has the wrong type for a conversion | |
| incompatible_reference_type = 303, ///< get_ref() is called with a reference type that does not match the value | |
| at_wrong_type = 304, ///< at() is called on a value of the wrong type | |
| subscript_wrong_type = 305, ///< operator[] is called on a value of the wrong type | |
| value_wrong_type = 306, ///< value() is called on a value of the wrong type | |
| erase_wrong_type = 307, ///< erase() is called on a value of the wrong type | |
| push_back_wrong_type = 308, ///< push_back() or operator+= is called on a value of the wrong type | |
| insert_wrong_type = 309, ///< insert() is called on a value of the wrong type | |
| swap_wrong_type = 310, ///< swap() is called on a value of the wrong type | |
| emplace_wrong_type = 311, ///< emplace() or emplace_back() is called on a value of the wrong type | |
| update_wrong_type = 312, ///< update() is called on a value of the wrong type | |
| unflatten_invalid_value = 313, ///< unflatten() finds conflicting paths | |
| unflatten_not_object = 314, ///< unflatten() is called on a non-object | |
| unflatten_value_not_primitive = 315, ///< unflatten() is called on an object with non-primitive values | |
| invalid_utf8 = 316, ///< dump() finds a string that is not valid UTF-8 | |
| type_not_serializable = 317, ///< a value cannot be serialized to the requested binary format | |
| enum_key_duplicate = 318, ///< an enum-keyed map has two keys that serialize to the same string | |
| document_binary_value = 319, ///< a binary value is stored in a json_document | |
| document_image_unsupported = 320, ///< a json_document image cannot be saved or loaded (discarded document, big-endian target) | |
| discarded_value_used = 321, ///< a discarded value is used | |
| // out_of_range | |
| array_index_out_of_range = 401, ///< an array index is out of range | |
| pointer_past_the_end_index = 402, ///< a JSON Pointer uses the array index '-' | |
| key_not_found = 403, ///< an object key is not found | |
| pointer_unresolved = 404, ///< a JSON Pointer reference token cannot be resolved | |
| patch_on_root = 405, ///< the root of a value has no parent, e.g. for a JSON Patch 'remove' or 'add' at the root | |
| number_overflow = 406, ///< a number cannot be stored without overflowing to NaN or INF | |
| integer_too_large = 407, ///< an integer cannot be represented in the binary format | |
| container_too_large = 408, ///< the size of a container in a binary input exceeds the maximal capacity | |
| bson_key_with_null = 409, ///< a BSON key contains U+0000 | |
| value_out_of_range = 410, ///< an enum value is undefined, or a JSON Pointer array index exceeds size_type | |
| patch_add_parent_not_container = 411, ///< the parent of a JSON Patch 'add' target is not a container | |
| length_too_large = 412, ///< a length does not fit into the length field of a binary format | |
| patch_remove_parent_not_container = 413, ///< the parent of a JSON Patch 'remove' target is not a container | |
| patch_move_into_child = 414, ///< a JSON Patch 'move' moves a value into one of its children | |
| subtype_out_of_range = 415, ///< a binary subtype does not fit into one byte | |
| document_too_large = 416, ///< a json_document input, its edit storage, or an image reaches the 32-bit (4 GiB) limit | |
| // other_error | |
| internal_error = 500, ///< unreachable code was reached | |
| patch_test_failed = 501, ///< a JSON Patch 'test' operation failed | |
| size_marker_required = 502 ///< UBJSON/BJData output with type markers requires size markers | |
| }; | |
| /// @brief general exception of the @ref basic_json class | |
| /// @sa https://json.nlohmann.me/api/basic_json/exception/ | |
| class exception : public std::exception | |
| { | |
| public: | |
| /// returns the explanatory string | |
| const char* what() const noexcept override | |
| { | |
| return m.what(); | |
| } | |
| /// the id of the exception | |
| const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) | |
| protected: | |
| JSON_HEDLEY_NON_NULL(3) | |
| exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} // NOLINT(bugprone-throw-keyword-missing) | |
| static std::string name(const std::string& ename, int id_) | |
| { | |
| return concat("[json.exception.", ename, '.', std::to_string(id_), "] "); | |
| } | |
| /// build the message "[json.exception.<ename>.<id>] <diagnostics><what_arg>" | |
| template<typename BasicJsonContext> | |
| static std::string what_impl(const std::string& ename, int id_, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| return concat(name(ename, id_), diagnostics(context), what_arg); | |
| } | |
| static std::string diagnostics(std::nullptr_t /*leaf_element*/) | |
| { | |
| return ""; | |
| } | |
| template<typename BasicJsonType> | |
| static std::string diagnostics(const BasicJsonType* leaf_element) | |
| { | |
| #if JSON_DIAGNOSTICS | |
| std::vector<std::string> tokens; | |
| for (const auto* current = leaf_element; current != nullptr && current->m_parent != nullptr; current = current->m_parent) | |
| { | |
| const auto* parent = current->m_parent; | |
| if (parent->is_array()) | |
| { | |
| for (std::size_t i = 0; i < parent->m_data.m_value.array->size(); ++i) | |
| { | |
| if (&parent->m_data.m_value.array->operator[](i) == current) | |
| { | |
| tokens.emplace_back(std::to_string(i)); | |
| break; | |
| } | |
| } | |
| } | |
| else if (parent->is_object()) | |
| { | |
| for (const auto& element : *parent->m_data.m_value.object) | |
| { | |
| if (&element.second == current) | |
| { | |
| // data() is null-terminated, so a key containing | |
| // a null byte is cut short here rather than | |
| // truncating the whole message at what() | |
| tokens.emplace_back(element.first.data()); | |
| break; | |
| } | |
| } | |
| } | |
| // all other parent types (primitives) contribute no token | |
| } | |
| if (tokens.empty()) | |
| { | |
| return ""; | |
| } | |
| auto str = std::accumulate(tokens.rbegin(), tokens.rend(), std::string{}, | |
| [](const std::string & a, const std::string & b) | |
| { | |
| return concat(a, '/', detail::escape(b)); | |
| }); | |
| return concat('(', str, ") ", get_byte_positions(leaf_element)); | |
| #else | |
| return get_byte_positions(leaf_element); | |
| #endif | |
| } | |
| private: | |
| /// an exception object as storage for error messages | |
| std::runtime_error m; | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| template<typename BasicJsonType> | |
| static std::string get_byte_positions(const BasicJsonType* leaf_element) | |
| { | |
| if ((leaf_element->start_pos() != std::string::npos) && (leaf_element->end_pos() != std::string::npos)) | |
| { | |
| return concat("(bytes ", std::to_string(leaf_element->start_pos()), "-", std::to_string(leaf_element->end_pos()), ") "); | |
| } | |
| return ""; | |
| } | |
| #else | |
| template<typename BasicJsonType> | |
| static std::string get_byte_positions(const BasicJsonType* leaf_element) | |
| { | |
| static_cast<void>(leaf_element); | |
| return ""; | |
| } | |
| #endif | |
| }; | |
| /// @brief exception indicating a parse error | |
| /// @sa https://json.nlohmann.me/api/basic_json/parse_error/ | |
| class parse_error : public exception | |
| { | |
| public: | |
| /*! | |
| @brief create a parse error exception | |
| @param[in] id_ the id of the exception | |
| @param[in] pos the position where the error occurred (or with | |
| chars_read_total=0 if the position cannot be | |
| determined) | |
| @param[in] what_arg the explanatory string | |
| @return parse_error object | |
| */ | |
| template<typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0> | |
| static parse_error create(int id_, const position_t& pos, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| const std::string w = concat(exception::name("parse_error", id_), "parse error", | |
| position_string(pos), ": ", exception::diagnostics(context), what_arg); | |
| return {id_, pos.chars_read_total, w.c_str()}; | |
| } | |
| template<typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0> | |
| static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| const std::string w = concat(exception::name("parse_error", id_), "parse error", | |
| (byte_ != 0 ? (concat(" at byte ", std::to_string(byte_))) : ""), | |
| ": ", exception::diagnostics(context), what_arg); | |
| return {id_, byte_, w.c_str()}; | |
| } | |
| template<typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0> | |
| static parse_error create(exception_id id_, const position_t& pos, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| return create(static_cast<int>(id_), pos, what_arg, context); | |
| } | |
| template<typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0> | |
| static parse_error create(exception_id id_, std::size_t byte_, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| return create(static_cast<int>(id_), byte_, what_arg, context); | |
| } | |
| /*! | |
| @brief byte index of the parse error | |
| The byte index of the last read character in the input file. | |
| @note For an input with n bytes, 1 is the index of the first character and | |
| n+1 is the index of the terminating null byte or the end of file. | |
| This also holds true when reading a byte vector (CBOR or MessagePack). | |
| */ | |
| const std::size_t byte; | |
| private: | |
| parse_error(int id_, std::size_t byte_, const char* what_arg) | |
| : exception(id_, what_arg), byte(byte_) {} | |
| static std::string position_string(const position_t& pos) | |
| { | |
| return concat(" at line ", std::to_string(pos.lines_read + 1), | |
| ", column ", std::to_string(pos.chars_read_current_line)); | |
| } | |
| }; | |
| /// @brief exception indicating errors with iterators | |
| /// @sa https://json.nlohmann.me/api/basic_json/invalid_iterator/ | |
| class invalid_iterator : public exception | |
| { | |
| public: | |
| template<typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0> | |
| static invalid_iterator create(int id_, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| const std::string w = exception::what_impl("invalid_iterator", id_, what_arg, context); | |
| return {id_, w.c_str()}; | |
| } | |
| template<typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0> | |
| static invalid_iterator create(exception_id id_, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| return create(static_cast<int>(id_), what_arg, context); | |
| } | |
| private: | |
| JSON_HEDLEY_NON_NULL(3) | |
| invalid_iterator(int id_, const char* what_arg) | |
| : exception(id_, what_arg) {} | |
| }; | |
| /// @brief exception indicating executing a member function with a wrong type | |
| /// @sa https://json.nlohmann.me/api/basic_json/type_error/ | |
| class type_error : public exception | |
| { | |
| public: | |
| template<typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0> | |
| static type_error create(int id_, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| const std::string w = exception::what_impl("type_error", id_, what_arg, context); | |
| return {id_, w.c_str()}; | |
| } | |
| template<typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0> | |
| static type_error create(exception_id id_, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| return create(static_cast<int>(id_), what_arg, context); | |
| } | |
| private: | |
| JSON_HEDLEY_NON_NULL(3) | |
| type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} | |
| }; | |
| /// @brief exception indicating access out of the defined range | |
| /// @sa https://json.nlohmann.me/api/basic_json/out_of_range/ | |
| class out_of_range : public exception | |
| { | |
| public: | |
| template<typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0> | |
| static out_of_range create(int id_, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| const std::string w = exception::what_impl("out_of_range", id_, what_arg, context); | |
| return {id_, w.c_str()}; | |
| } | |
| template<typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0> | |
| static out_of_range create(exception_id id_, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| return create(static_cast<int>(id_), what_arg, context); | |
| } | |
| private: | |
| JSON_HEDLEY_NON_NULL(3) | |
| out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} | |
| }; | |
| /// @brief exception indicating other library errors | |
| /// @sa https://json.nlohmann.me/api/basic_json/other_error/ | |
| class other_error : public exception | |
| { | |
| public: | |
| template<typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0> | |
| static other_error create(int id_, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| const std::string w = exception::what_impl("other_error", id_, what_arg, context); | |
| return {id_, w.c_str()}; | |
| } | |
| template<typename BasicJsonContext, enable_if_t<is_basic_json_context<BasicJsonContext>::value, int> = 0> | |
| static other_error create(exception_id id_, const std::string& what_arg, BasicJsonContext context) | |
| { | |
| return create(static_cast<int>(id_), what_arg, context); | |
| } | |
| private: | |
| JSON_HEDLEY_NON_NULL(3) | |
| other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} | |
| }; | |
| /*! | |
| @brief helper function to call JSON_THROW from a template | |
| @note JSON_THROW is a macro that, depending on the JSON_THROW_USER / | |
| JSON_TRY_USER / JSON_NOEXCEPTION configuration, may expand to code | |
| that does not reference its argument (e.g. `std::abort()`), which | |
| would trigger a compilation error if the argument's type depends on | |
| a template parameter that is otherwise unused. Wrapping the call in | |
| a templated function avoids this and gives the compiler a single | |
| place to see the (possibly unused) parameter. | |
| */ | |
| template<typename ExceptionType> | |
| void templated_json_throw(ExceptionType exception) | |
| { | |
| JSON_THROW(exception); | |
| // JSON_THROW may expand to code that discards its argument (e.g. when | |
| // exceptions are disabled) - the cast below avoids an unused-parameter | |
| // warning with -Werror in that case | |
| (void)exception; | |
| } | |
| /*! | |
| @brief throws because @a j does not have the type a conversion expects | |
| @param[in] expected the expected type(s), e.g. "array" or "binary or array" | |
| @param[in] j the value with the wrong type | |
| @throw type_error.302 always | |
| */ | |
| template<typename BasicJsonType> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE void throw_type_must_be(const char* expected, const BasicJsonType& j) | |
| { | |
| static_cast<void>(expected); // unused when JSON_NOEXCEPTION is defined | |
| static_cast<void>(j); | |
| JSON_THROW(type_error::create(exception_id::type_mismatch, concat("type must be ", expected, ", but is ", j.type_name()), &j)); | |
| } | |
| /*! | |
| @brief throws because an operation is not supported for the type of @a j | |
| @param[in] id_ the id of the type_error exception (at_wrong_type..update_wrong_type) | |
| @param[in] operation the operation, e.g. "erase()" | |
| @param[in] j the value the operation was called on | |
| @throw type_error always | |
| */ | |
| template<typename BasicJsonType> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE void throw_cannot_use_with(const exception_id id_, const char* operation, const BasicJsonType& j) | |
| { | |
| static_cast<void>(id_); // unused when JSON_NOEXCEPTION is defined | |
| static_cast<void>(operation); | |
| static_cast<void>(j); | |
| JSON_THROW(type_error::create(id_, concat("cannot use ", operation, " with ", j.type_name()), &j)); | |
| } | |
| /*! | |
| @brief throws ExceptionType with a fixed message; kept out of line so that callers do not carry the exception construction | |
| */ | |
| template<typename ExceptionType, typename BasicJsonContext> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE void throw_literal(const exception_id id_, const char* what_arg, BasicJsonContext context) | |
| { | |
| static_cast<void>(id_); // unused when JSON_NOEXCEPTION is defined | |
| static_cast<void>(what_arg); | |
| static_cast<void>(context); | |
| JSON_THROW(ExceptionType::create(id_, what_arg, context)); | |
| } | |
| // JSON Patch errors; constructed out of line so that patch_inplace() does not carry them | |
| template<typename BasicJsonType> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE void throw_patch_add_parent(const BasicJsonType& parent) | |
| { | |
| static_cast<void>(parent); | |
| JSON_THROW(out_of_range::create(exception_id::patch_add_parent_not_container, concat("cannot add value: the JSON Patch 'add' target's parent is of type ", parent.type_name(), ", but must be an object or array"), &parent)); | |
| } | |
| template<typename BasicJsonType> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE void throw_patch_remove_parent(const BasicJsonType& parent) | |
| { | |
| static_cast<void>(parent); | |
| JSON_THROW(out_of_range::create(exception_id::patch_remove_parent_not_container, concat("cannot remove value: the JSON Patch 'remove' target's parent is of type ", parent.type_name(), ", but must be an object or array"), &parent)); | |
| } | |
| template<typename BasicJsonType> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE void throw_patch_not_an_array(const BasicJsonType& j) | |
| { | |
| static_cast<void>(j); | |
| JSON_THROW(parse_error::create(exception_id::patch_not_an_array, 0, "JSON patch must be an array of objects", &j)); | |
| } | |
| template<typename StringType, typename BasicJsonType> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE void throw_patch_missing_member(const StringType& op, const StringType& member, const bool string_type, const BasicJsonType& val) | |
| { | |
| static_cast<void>(op); | |
| static_cast<void>(member); | |
| static_cast<void>(string_type); | |
| static_cast<void>(val); | |
| // context-sensitive error message | |
| JSON_THROW(parse_error::create(exception_id::patch_invalid_operation, 0, concat((op == "op") ? std::string("operation") : concat("operation '", op, '\''), string_type ? " must have string member '" : " must have member '", member, "'"), &val)); | |
| } | |
| template<typename StringType, typename BasicJsonType> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE void throw_patch_move_into_child(const StringType& from_path, const StringType& path, const BasicJsonType& result) | |
| { | |
| static_cast<void>(from_path); | |
| static_cast<void>(path); | |
| static_cast<void>(result); | |
| JSON_THROW(out_of_range::create(exception_id::patch_move_into_child, concat("cannot move value: 'from' path '", from_path, "' is a proper prefix of 'path' '", path, "'"), &result)); | |
| } | |
| template<typename BasicJsonType> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE void throw_patch_test_failed(const BasicJsonType& val) | |
| { | |
| static_cast<void>(val); | |
| JSON_THROW(other_error::create(exception_id::patch_test_failed, concat("unsuccessful: ", val.dump()), &val)); | |
| } | |
| template<typename StringType, typename BasicJsonType> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE void throw_patch_invalid_operation(const StringType& op, const BasicJsonType& val) | |
| { | |
| static_cast<void>(op); | |
| static_cast<void>(val); | |
| JSON_THROW(parse_error::create(exception_id::patch_invalid_operation, 0, concat("operation value '", op, "' is invalid"), &val)); | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| #if defined(__clang__) | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/meta/cpp_future.hpp> | |
| // #include <nlohmann/detail/meta/identity_tag.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| // dispatching helper struct | |
| template <class T> struct identity_tag {}; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/meta/std_fs.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| #if JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| #include <experimental/filesystem> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| namespace std_fs = std::experimental::filesystem; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| #elif JSON_HAS_FILESYSTEM | |
| #include <filesystem> // NOLINT(build/c++17) | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| namespace std_fs = std::filesystem; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| #endif | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| // #include <nlohmann/detail/string_concat.hpp> | |
| // #include <nlohmann/detail/value_t.hpp> | |
| // include after macro_scope.hpp | |
| #ifdef JSON_HAS_CPP_17 | |
| #include <optional> // optional | |
| #endif | |
| #if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| #include <string_view> // u8string_view | |
| #endif | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| template<typename BasicJsonType> | |
| inline void from_json(const BasicJsonType& j, typename std::nullptr_t& n) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_null())) | |
| { | |
| throw_type_must_be("null", j); | |
| } | |
| n = nullptr; | |
| } | |
| #ifdef JSON_HAS_CPP_17 | |
| template < typename BasicJsonType, typename T, | |
| typename std::enable_if < !nlohmann::detail::is_basic_json<T>::value, int >::type = 0 > | |
| void from_json(const BasicJsonType& j, std::optional<T>& opt) | |
| { | |
| if (j.is_null()) | |
| { | |
| opt = std::nullopt; | |
| } | |
| else | |
| { | |
| opt.emplace(j.template get<T>()); | |
| } | |
| } | |
| #endif // JSON_HAS_CPP_17 | |
| // read a number value of any of the three number types into val; | |
| // returns false (leaving val untouched) if j is not a number | |
| template<typename BasicJsonType, typename ArithmeticType> | |
| bool get_number_value(const BasicJsonType& j, ArithmeticType& val) | |
| { | |
| switch (static_cast<value_t>(j)) | |
| { | |
| case value_t::number_unsigned: | |
| { | |
| // never null: a basic_json whose number_unsigned_t is number_integer_t | |
| // stores no number_unsigned values (#2573) | |
| const auto* ptr = j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>(); | |
| JSON_ASSERT(ptr != nullptr); | |
| val = static_cast<ArithmeticType>(*ptr); | |
| return true; | |
| } | |
| case value_t::number_integer: | |
| { | |
| val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); | |
| return true; | |
| } | |
| case value_t::number_float: | |
| { | |
| val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>()); | |
| return true; | |
| } | |
| case value_t::null: | |
| case value_t::object: | |
| case value_t::array: | |
| case value_t::string: | |
| case value_t::boolean: | |
| case value_t::binary: | |
| case value_t::discarded: | |
| default: | |
| return false; | |
| } | |
| } | |
| // overloads for basic_json template parameters | |
| template < typename BasicJsonType, typename ArithmeticType, | |
| enable_if_t < std::is_arithmetic<ArithmeticType>::value&& | |
| !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, | |
| int > = 0 > | |
| void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!get_number_value(j, val))) | |
| { | |
| throw_type_must_be("number", j); | |
| } | |
| } | |
| template<typename BasicJsonType> | |
| inline void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) | |
| { | |
| throw_type_must_be("boolean", j); | |
| } | |
| b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>(); | |
| } | |
| template<typename BasicJsonType> | |
| inline void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_string())) | |
| { | |
| throw_type_must_be("string", j); | |
| } | |
| s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); | |
| } | |
| template < | |
| typename BasicJsonType, typename StringType, | |
| enable_if_t < | |
| std::is_assignable<StringType&, const typename BasicJsonType::string_t>::value | |
| && is_detected_exact<typename BasicJsonType::string_t::value_type, value_type_t, StringType>::value | |
| && !std::is_same<typename BasicJsonType::string_t, StringType>::value | |
| && !is_json_ref<StringType>::value, int > = 0 > | |
| inline void from_json(const BasicJsonType& j, StringType& s) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_string())) | |
| { | |
| throw_type_must_be("string", j); | |
| } | |
| s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); | |
| } | |
| template<typename BasicJsonType> | |
| inline void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) | |
| { | |
| get_arithmetic_value(j, val); | |
| } | |
| template<typename BasicJsonType> | |
| inline void from_json(const BasicJsonType& j, number_unsigned_overload_t<BasicJsonType>& val) | |
| { | |
| get_arithmetic_value(j, val); | |
| } | |
| template<typename BasicJsonType> | |
| inline void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) | |
| { | |
| get_arithmetic_value(j, val); | |
| } | |
| #if !JSON_DISABLE_ENUM_SERIALIZATION | |
| template<typename BasicJsonType, typename EnumType, | |
| enable_if_t<std::is_enum<EnumType>::value, int> = 0> | |
| inline void from_json(const BasicJsonType& j, EnumType& e) | |
| { | |
| using underlying_type = typename std::underlying_type<EnumType>::type; | |
| // get_arithmetic_value() does not accept boolean_t; read the number that to_json() wrote instead | |
| using value_type = typename std::conditional<std::is_same<underlying_type, typename BasicJsonType::boolean_t>::value, | |
| typename BasicJsonType::number_unsigned_t, underlying_type>::type; | |
| value_type val; | |
| get_arithmetic_value(j, val); | |
| e = static_cast<EnumType>(bool_aware_static_cast<underlying_type>(val)); | |
| } | |
| #endif // JSON_DISABLE_ENUM_SERIALIZATION | |
| // forward_list doesn't have an insert method | |
| template<typename BasicJsonType, typename T, typename Allocator, | |
| enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0> | |
| inline void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_array())) | |
| { | |
| throw_type_must_be("array", j); | |
| } | |
| l.clear(); | |
| std::transform(j.rbegin(), j.rend(), | |
| std::front_inserter(l), [](const BasicJsonType & i) | |
| { | |
| return i.template get<T>(); | |
| }); | |
| } | |
| // valarray doesn't have an insert method | |
| template<typename BasicJsonType, typename T, | |
| enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0> | |
| inline void from_json(const BasicJsonType& j, std::valarray<T>& l) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_array())) | |
| { | |
| throw_type_must_be("array", j); | |
| } | |
| l.resize(j.size()); | |
| std::transform(j.begin(), j.end(), std::begin(l), | |
| [](const BasicJsonType & elem) | |
| { | |
| return elem.template get<T>(); | |
| }); | |
| } | |
| // element is not itself a C array: read it directly | |
| template<typename BasicJsonType, typename T> | |
| auto from_json_c_array_element(const BasicJsonType& j, T& e) | |
| -> decltype(e = j.template get<T>(), void()) | |
| { | |
| e = j.template get<T>(); | |
| } | |
| // element is itself a C array: recurse one dimension at a time, so any rank is supported | |
| template<typename BasicJsonType, typename T, std::size_t N> | |
| void from_json_c_array_element(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| { | |
| for (std::size_t i = 0; i < N; ++i) | |
| { | |
| from_json_c_array_element(j.at(i), arr[i]); | |
| } | |
| } | |
| template<typename BasicJsonType, typename T, std::size_t N> | |
| auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| -> decltype(j.template get<typename std::remove_all_extents<T>::type>(), void()) | |
| { | |
| from_json_c_array_element(j, arr); | |
| } | |
| template<typename BasicJsonType> | |
| inline void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) | |
| { | |
| arr = *j.template get_ptr<const typename BasicJsonType::array_t*>(); | |
| } | |
| // fill a std::array from the JSON array j: the size is checked once and the | |
| // elements are read in order, so a short array converts the elements it has and | |
| // then throws the out_of_range error at() would throw for the first missing one | |
| template<typename BasicJsonType, typename T, std::size_t N> | |
| void from_json_std_array(const BasicJsonType& j, std::array<T, N>& arr) | |
| { | |
| const auto& inner_array = *j.template get_ptr<const typename BasicJsonType::array_t*>(); | |
| const std::size_t size = (std::min)(N, inner_array.size()); | |
| for (std::size_t i = 0; i < size; ++i) | |
| { | |
| arr[i] = inner_array[i].template get<T>(); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(size < N)) | |
| { | |
| static_cast<void>(j.at(size)); | |
| } | |
| } | |
| template<typename BasicJsonType, typename T, std::size_t N> | |
| auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, | |
| priority_tag<2> /*unused*/) | |
| -> decltype(j.template get<T>(), void()) | |
| { | |
| from_json_std_array(j, arr); | |
| } | |
| // reserve() is called through this pair (used for arrays and objects alike) | |
| // so from_json_array_impl and the object from_json have a single body for both | |
| // containers that support reserve() and those that don't. | |
| template<typename ConstructibleContainerType> | |
| auto reserve_if_possible(ConstructibleContainerType& c, typename ConstructibleContainerType::size_type size, priority_tag<1> /*unused*/) | |
| -> decltype(c.reserve(size), void()) | |
| { | |
| c.reserve(size); | |
| } | |
| template<typename ConstructibleContainerType> | |
| void reserve_if_possible(ConstructibleContainerType& /*c*/, std::size_t /*size*/, priority_tag<0> /*unused*/) | |
| {} | |
| // append through push_back() where available; containers without it (such as | |
| // std::set) fall back to insert(end(), ...), which is what std::inserter did | |
| template<typename ConstructibleArrayType, typename ValueType> | |
| auto from_json_array_append(ConstructibleArrayType& arr, ValueType&& value, priority_tag<1> /*unused*/) | |
| -> decltype(arr.push_back(std::forward<ValueType>(value)), void()) | |
| { | |
| arr.push_back(std::forward<ValueType>(value)); | |
| } | |
| template<typename ConstructibleArrayType, typename ValueType> | |
| void from_json_array_append(ConstructibleArrayType& arr, ValueType&& value, priority_tag<0> /*unused*/) | |
| { | |
| using std::end; | |
| arr.insert(end(arr), std::forward<ValueType>(value)); | |
| } | |
| template<typename BasicJsonType, typename ConstructibleArrayType, | |
| enable_if_t< | |
| std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value, | |
| int> = 0> | |
| auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/) | |
| -> decltype( | |
| j.template get<typename ConstructibleArrayType::value_type>(), | |
| void()) | |
| { | |
| ConstructibleArrayType ret; | |
| const auto* inner_array = j.template get_ptr<const typename BasicJsonType::array_t*>(); | |
| reserve_if_possible(ret, inner_array->size(), priority_tag<1> {}); | |
| for (const auto& elem : *inner_array) | |
| { | |
| // get<BasicJsonType>() returns *this, this won't call a from_json | |
| // method when value_type is BasicJsonType | |
| from_json_array_append(ret, elem.template get<typename ConstructibleArrayType::value_type>(), priority_tag<1> {}); | |
| } | |
| arr = std::move(ret); | |
| } | |
| template < typename BasicJsonType, typename ConstructibleArrayType, | |
| enable_if_t < | |
| is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value&& | |
| !is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value&& | |
| !is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value&& | |
| !std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value&& | |
| !is_compatible_binary_type<BasicJsonType, ConstructibleArrayType>::value&& | |
| !is_basic_json<ConstructibleArrayType>::value, | |
| int > = 0 > | |
| auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr) | |
| -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}), | |
| j.template get<typename ConstructibleArrayType::value_type>(), | |
| void()) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_array())) | |
| { | |
| throw_type_must_be("array", j); | |
| } | |
| from_json_array_impl(j, arr, priority_tag<3> {}); | |
| } | |
| template < typename BasicJsonType, typename T, std::size_t... Idx > | |
| std::array<T, sizeof...(Idx)> from_json_inplace_array_impl(const BasicJsonType& j, | |
| identity_tag<std::array<T, sizeof...(Idx)>> /*unused*/, index_sequence<Idx...> /*unused*/) | |
| { | |
| return { { j.at(Idx).template get<T>()... } }; | |
| } | |
| // std::is_trivial is deprecated in C++26 (see binary_writer::to_char_type); | |
| // a struct rather than an alias, as astyle indents an #ifdef block of aliases | |
| template<typename T> | |
| struct is_trivial_element | |
| #ifdef JSON_HAS_CPP_26 | |
| : conjunction<std::is_trivially_copyable<T>, std::is_trivially_default_constructible<T>> | |
| #else | |
| : std::is_trivial<T> | |
| #endif | |
| {}; | |
| // the element type may not be default constructible: construct every element | |
| // in place (a pack expansion that is unrolled N times) | |
| template<typename BasicJsonType, typename T, std::size_t N> | |
| std::array<T, N> from_json_make_array(const BasicJsonType& j, identity_tag<std::array<T, N>> tag, | |
| std::false_type /*is_trivial_element*/) | |
| { | |
| return from_json_inplace_array_impl(j, tag, make_index_sequence<N> {}); | |
| } | |
| // a trivial element type cannot tell default construction plus assignment from | |
| // construction in place, so use a loop instead of unrolling N conversions | |
| template<typename BasicJsonType, typename T, std::size_t N> | |
| std::array<T, N> from_json_make_array(const BasicJsonType& j, identity_tag<std::array<T, N>> /*unused*/, | |
| std::true_type /*is_trivial_element*/) | |
| { | |
| std::array<T, N> arr; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): every element is assigned or an exception is thrown | |
| from_json_std_array(j, arr); | |
| return arr; | |
| } | |
| template < typename BasicJsonType, typename T, std::size_t N > | |
| auto from_json(const BasicJsonType& j, identity_tag<std::array<T, N>> tag) | |
| -> decltype(from_json_inplace_array_impl(j, tag, make_index_sequence<N> {})) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_array())) | |
| { | |
| throw_type_must_be("array", j); | |
| } | |
| return from_json_make_array(j, tag, is_trivial_element<T> {}); | |
| } | |
| template<typename BasicJsonType> | |
| inline void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_binary())) | |
| { | |
| throw_type_must_be("binary", j); | |
| } | |
| bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>(); | |
| } | |
| template < typename BasicJsonType, typename CompatibleArrayType, | |
| enable_if_t < is_compatible_binary_type<BasicJsonType, CompatibleArrayType>::value, | |
| int > = 0 > | |
| inline void from_json(const BasicJsonType& j, CompatibleArrayType& bin) | |
| { | |
| if (j.is_binary()) | |
| { | |
| bin = static_cast<CompatibleArrayType>(*j.template get_ptr<const typename BasicJsonType::binary_t*>()); | |
| } | |
| else if (j.is_array()) | |
| { | |
| from_json_array_impl(j, bin, priority_tag<3> {}); | |
| } | |
| else | |
| { | |
| throw_type_must_be("binary or array", j); | |
| } | |
| } | |
| // the keys of the source are sorted for the usual object types, so hinting the | |
| // end makes every insertion constant-time (for containers that order their keys | |
| // the same way); containers without emplace_hint() (such as ordered_map) fall | |
| // back to emplace() | |
| template<typename ConstructibleObjectType, typename Key, typename Value> | |
| auto from_json_object_emplace(ConstructibleObjectType& obj, Key&& key, Value&& value, priority_tag<1> /*unused*/) | |
| -> decltype(obj.emplace_hint(obj.end(), std::forward<Key>(key), std::forward<Value>(value)), void()) | |
| { | |
| obj.emplace_hint(obj.end(), std::forward<Key>(key), std::forward<Value>(value)); | |
| } | |
| template<typename ConstructibleObjectType, typename Key, typename Value> | |
| void from_json_object_emplace(ConstructibleObjectType& obj, Key&& key, Value&& value, priority_tag<0> /*unused*/) | |
| { | |
| obj.emplace(std::forward<Key>(key), std::forward<Value>(value)); | |
| } | |
| template<typename BasicJsonType, typename ConstructibleObjectType, | |
| enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0> | |
| inline void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_object())) | |
| { | |
| throw_type_must_be("object", j); | |
| } | |
| ConstructibleObjectType ret; | |
| const auto* inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>(); | |
| reserve_if_possible(ret, inner_object->size(), priority_tag<1> {}); | |
| for (const auto& p : *inner_object) | |
| { | |
| from_json_object_emplace(ret, p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>(), priority_tag<1> {}); | |
| } | |
| obj = std::move(ret); | |
| } | |
| // overload for arithmetic types, not chosen for basic_json template arguments | |
| // (BooleanType, etc.) | |
| template < typename BasicJsonType, typename ArithmeticType, | |
| enable_if_t < | |
| std::is_arithmetic<ArithmeticType>::value&& | |
| !std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value&& | |
| !std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value&& | |
| !std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value&& | |
| !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, | |
| int > = 0 > | |
| inline void from_json(const BasicJsonType& j, ArithmeticType& val) | |
| { | |
| if (get_number_value(j, val)) | |
| { | |
| return; | |
| } | |
| // unlike get_arithmetic_value(), a boolean is accepted here | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) | |
| { | |
| throw_type_must_be("number", j); | |
| } | |
| val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>()); | |
| } | |
| template<typename BasicJsonType, typename Type> | |
| detail::uncvref_t<Type> from_json_tuple_get_impl(BasicJsonType&& j, detail::identity_tag<Type> /*unused*/, detail::priority_tag<0> /*unused*/) | |
| { | |
| return std::forward<BasicJsonType>(j).template get<detail::uncvref_t<Type>>(); | |
| } | |
| template<typename BasicJsonType, typename Type, | |
| detail::enable_if_t<detail::is_compatible_reference_type<BasicJsonType, Type>::value, int> = 0> | |
| Type from_json_tuple_get_impl(BasicJsonType && j, detail::identity_tag<Type> /*unused*/, detail::priority_tag<1> /*unused*/) | |
| { | |
| return std::forward<BasicJsonType>(j).template get_ref<Type>(); | |
| } | |
| template<typename BasicJsonType, typename Type, | |
| detail::enable_if_t<std::is_arithmetic<uncvref_t<Type>>::value, int> = 0> | |
| detail::uncvref_t<Type> from_json_tuple_get_impl(BasicJsonType && j, detail::identity_tag<Type> /*unused*/, detail::priority_tag<2> /*unused*/) | |
| { | |
| return std::forward<BasicJsonType>(j).template get<detail::uncvref_t<Type>>(); | |
| } | |
| template<std::size_t PTagValue, typename BasicJsonType, typename... Types> | |
| using tuple_type = std::tuple < decltype(from_json_tuple_get_impl(std::declval<BasicJsonType>(), detail::identity_tag<Types> {}, detail::priority_tag<PTagValue> {}))... >; | |
| template<std::size_t PTagValue, typename... Args, typename BasicJsonType, std::size_t... Idx> | |
| tuple_type<PTagValue, const BasicJsonType&, Args...> from_json_tuple_impl_base(const BasicJsonType& j, index_sequence<Idx...> /*unused*/) | |
| { | |
| return tuple_type<PTagValue, const BasicJsonType&, Args...>(from_json_tuple_get_impl(j.at(Idx), detail::identity_tag<Args> {}, detail::priority_tag<PTagValue> {})...); | |
| } | |
| template<std::size_t PTagValue, typename BasicJsonType> | |
| std::tuple<> from_json_tuple_impl_base(const BasicJsonType& /*unused*/, index_sequence<> /*unused*/) | |
| { | |
| return {}; | |
| } | |
| template < typename BasicJsonType, class A1, class A2 > | |
| std::pair<A1, A2> from_json_tuple_impl(const BasicJsonType& j, identity_tag<std::pair<A1, A2>> /*unused*/, priority_tag<0> /*unused*/) | |
| { | |
| return {j.at(0).template get<A1>(), | |
| j.at(1).template get<A2>()}; | |
| } | |
| template<typename BasicJsonType, typename A1, typename A2> | |
| inline void from_json_tuple_impl(const BasicJsonType& j, std::pair<A1, A2>& p, priority_tag<1> /*unused*/) | |
| { | |
| p = from_json_tuple_impl(j, identity_tag<std::pair<A1, A2>> {}, priority_tag<0> {}); | |
| } | |
| template<typename BasicJsonType, typename... Args> | |
| std::tuple<Args...> from_json_tuple_impl(const BasicJsonType& j, identity_tag<std::tuple<Args...>> /*unused*/, priority_tag<2> /*unused*/) | |
| { | |
| static_assert(conjunction<disjunction<negation<std::is_reference<Args>>, is_compatible_reference_type<const BasicJsonType&, Args>>...>::value, | |
| "Can not return a tuple containing references to types not contained in a Json, try Json::get_to()"); | |
| return from_json_tuple_impl_base<1, Args...>(j, index_sequence_for<Args...> {}); | |
| } | |
| template<typename BasicJsonType, typename... Args> | |
| inline void from_json_tuple_impl(const BasicJsonType& j, std::tuple<Args...>& t, priority_tag<3> /*unused*/) | |
| { | |
| t = from_json_tuple_impl_base<2, Args...>(j, index_sequence_for<Args...> {}); | |
| } | |
| template<typename BasicJsonType, typename TupleRelated> | |
| auto from_json(const BasicJsonType& j, TupleRelated&& t) | |
| -> decltype(from_json_tuple_impl(j, std::forward<TupleRelated>(t), priority_tag<3> {})) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_array())) | |
| { | |
| throw_type_must_be("array", j); | |
| } | |
| return from_json_tuple_impl(j, std::forward<TupleRelated>(t), priority_tag<3> {}); | |
| } | |
| // shared body for std::map/std::unordered_map with a non-string Key: both | |
| // containers are read from an array of [key, value] pairs the same way | |
| template<typename BasicJsonType, typename MapType> | |
| void from_json_pair_array_to_map(const BasicJsonType& j, MapType& m) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_array())) | |
| { | |
| throw_type_must_be("array", j); | |
| } | |
| m.clear(); | |
| for (const auto& p : j) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!p.is_array())) | |
| { | |
| throw_type_must_be("array", p); | |
| } | |
| m.emplace(p.at(0).template get<typename MapType::key_type>(), p.at(1).template get<typename MapType::mapped_type>()); | |
| } | |
| } | |
| // read a map with enum keys from an object, using the enum's own from_json for | |
| // the keys (e.g., from NLOHMANN_JSON_SERIALIZE_ENUM); this is the form written | |
| // with JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS | |
| template<typename BasicJsonType, typename Map> | |
| inline bool from_json_enum_keyed_object(const BasicJsonType& j, Map& m, std::true_type /*key is enum*/) | |
| { | |
| if (!j.is_object()) | |
| { | |
| return false; | |
| } | |
| m.clear(); | |
| for (const auto& p : *j.template get_ptr<const typename BasicJsonType::object_t*>()) | |
| { | |
| m.emplace(BasicJsonType(p.first).template get<typename Map::key_type>(), p.second.template get<typename Map::mapped_type>()); | |
| } | |
| return true; | |
| } | |
| template<typename BasicJsonType, typename Map> | |
| inline bool from_json_enum_keyed_object(const BasicJsonType& /*j*/, Map& /*m*/, std::false_type /*key is enum*/) | |
| { | |
| return false; | |
| } | |
| template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator, | |
| typename = enable_if_t < !std::is_constructible < | |
| typename BasicJsonType::string_t, Key >::value >> | |
| void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m) | |
| { | |
| // NOLINTNEXTLINE(modernize-type-traits) we use C++11 | |
| if (from_json_enum_keyed_object(j, m, std::is_enum<Key> {})) | |
| { | |
| return; | |
| } | |
| from_json_pair_array_to_map(j, m); | |
| } | |
| template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator, | |
| typename = enable_if_t < !std::is_constructible < | |
| typename BasicJsonType::string_t, Key >::value >> | |
| void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m) | |
| { | |
| // NOLINTNEXTLINE(modernize-type-traits) we use C++11 | |
| if (from_json_enum_keyed_object(j, m, std::is_enum<Key> {})) | |
| { | |
| return; | |
| } | |
| from_json_pair_array_to_map(j, m); | |
| } | |
| #if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| // Workaround for MSVC 19.51 (and possibly later): in large cpp files, the compiler may fail to resolve with generic has_from_json (issue #4996) | |
| template<typename BasicJsonType> | |
| struct has_from_json<BasicJsonType, std_fs::path, void> : std::true_type {}; | |
| template<typename BasicJsonType> | |
| inline void from_json(const BasicJsonType& j, std_fs::path& p) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_string())) | |
| { | |
| throw_type_must_be("string", j); | |
| } | |
| const auto& s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); | |
| // Checking for C++20 standard or later can be insufficient in case the | |
| // library support for char8_t is either incomplete or was disabled | |
| // altogether. Use the __cpp_lib_char8_t feature test instead. | |
| #if defined(__cpp_lib_char8_t) && (__cpp_lib_char8_t >= 201907L) | |
| p = std_fs::path(std::u8string_view(reinterpret_cast<const char8_t*>(s.data()), s.size())); | |
| #else | |
| p = std_fs::u8path(s); // accepts UTF-8 encoded std::string in C++17, deprecated in C++20 | |
| #endif | |
| } | |
| #endif | |
| struct from_json_fn | |
| { | |
| template<typename BasicJsonType, typename T> | |
| auto operator()(const BasicJsonType& j, T&& val) const | |
| noexcept(noexcept(from_json(j, std::forward<T>(val)))) | |
| -> decltype(from_json(j, std::forward<T>(val))) | |
| { | |
| return from_json(j, std::forward<T>(val)); | |
| } | |
| }; | |
| } // namespace detail | |
| #ifndef JSON_HAS_CPP_17 | |
| /// namespace to hold default `from_json` function | |
| /// to see why this is required: | |
| /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html | |
| namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces,misc-anonymous-namespace-in-header) | |
| { | |
| #endif | |
| JSON_INLINE_VARIABLE constexpr const auto& from_json = // NOLINT(misc-definitions-in-headers) | |
| detail::static_const<detail::from_json_fn>::value; | |
| #ifndef JSON_HAS_CPP_17 | |
| } // namespace | |
| #endif | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/conversions/to_json.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // JSON_HAS_CPP_17 | |
| #ifdef JSON_HAS_CPP_17 | |
| #include <optional> // optional | |
| #endif | |
| #include <iterator> // begin, end, make_move_iterator, move_iterator | |
| #include <memory> // allocator_traits | |
| #include <string> // basic_string, char_traits | |
| #include <tuple> // tuple, get | |
| #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type | |
| #include <utility> // move, forward, declval, pair | |
| #include <valarray> // valarray | |
| #include <vector> // vector | |
| // #include <nlohmann/detail/exceptions.hpp> | |
| // #include <nlohmann/detail/iterators/iteration_proxy.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cstddef> // size_t | |
| #include <iterator> // forward_iterator_tag | |
| #include <tuple> // tuple_size, get, tuple_element | |
| #include <utility> // move | |
| #if JSON_HAS_RANGES | |
| #include <ranges> // enable_borrowed_range | |
| #endif | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| // #include <nlohmann/detail/string_utils.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2008, 2009 Björn Hoehrmann <bjoern@hoehrmann.de> | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <array> // array | |
| #include <cstddef> // size_t | |
| #include <cstdint> // uint8_t, uint32_t | |
| #include <string> // string, to_string | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/output/error_handler.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /// how to treat decoding errors | |
| /// | |
| /// @ref basic_json::dump uses this to decide what to do with ill-formed | |
| /// UTF-8 while escaping a string, and the binary writers (@ref | |
| /// basic_json::to_cbor, @ref basic_json::to_ubjson, @ref | |
| /// basic_json::to_bjdata, @ref basic_json::to_bson) use it the same way for | |
| /// string values and object keys. The binary readers (@ref | |
| /// basic_json::from_cbor, @ref basic_json::from_msgpack, @ref | |
| /// basic_json::from_ubjson, @ref basic_json::from_bjdata, @ref | |
| /// basic_json::from_bson) use it to decide whether to check text strings | |
| /// and object keys for well-formed UTF-8 at all, since none of those | |
| /// formats requires a decoder to do so. | |
| enum class error_handler_t | |
| { | |
| strict, ///< throw a type_error/parse_error exception in case of invalid UTF-8 | |
| replace, ///< replace invalid UTF-8 sequences with U+FFFD | |
| ignore, ///< ignore invalid UTF-8 sequences | |
| keep ///< keep invalid UTF-8 sequences unchanged | |
| }; | |
| /// the default error handler of the CBOR, UBJSON, BJData, and BSON writers: | |
| /// error_handler_t::strict if JSON_STRICT_BINARY_UTF8 is enabled, otherwise | |
| /// error_handler_t::keep (the behavior before version 3.13.0) | |
| constexpr error_handler_t binary_writer_default_error_handler() noexcept | |
| { | |
| #if JSON_STRICT_BINARY_UTF8 | |
| return error_handler_t::strict; | |
| #else | |
| return error_handler_t::keep; | |
| #endif | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| template<typename StringType> | |
| void int_to_string(StringType& target, std::size_t value) | |
| { | |
| // For ADL | |
| using std::to_string; | |
| target = to_string(value); | |
| } | |
| template<typename StringType> | |
| StringType to_string(std::size_t value) | |
| { | |
| StringType result; | |
| int_to_string(result, value); | |
| return result; | |
| } | |
| /// @return a byte as two uppercase hexadecimal digits | |
| inline std::string hex_byte(const std::uint8_t byte) | |
| { | |
| std::string result = "00"; | |
| constexpr const char* nibble_to_hex = "0123456789ABCDEF"; | |
| result[0] = nibble_to_hex[byte / 16]; | |
| result[1] = nibble_to_hex[byte % 16]; | |
| return result; | |
| } | |
| /*! | |
| @brief write a UTF-16 code unit as four lowercase hexadecimal digits | |
| The lowercase counterpart of hex_byte(), used for the `\\uXXXX` escapes of the | |
| serializers, whose output is lowercase. Writes exactly four characters to | |
| @a out and returns the pointer past them. | |
| */ | |
| JSON_HEDLEY_ALWAYS_INLINE char* hex4_lower(const std::uint16_t codeunit, char* out) noexcept | |
| { | |
| constexpr const char* nibble_to_hex = "0123456789abcdef"; | |
| const unsigned int unit = codeunit; | |
| out[0] = nibble_to_hex[(unit >> 12u) & 0x0Fu]; | |
| out[1] = nibble_to_hex[(unit >> 8u) & 0x0Fu]; | |
| out[2] = nibble_to_hex[(unit >> 4u) & 0x0Fu]; | |
| out[3] = nibble_to_hex[unit & 0x0Fu]; | |
| return out + 4; | |
| } | |
| /////////////////// | |
| // UTF-8 encoding // | |
| /////////////////// | |
| /*! | |
| @brief encode a Unicode code point as UTF-8 | |
| Used to turn a decoded code point back into bytes: by the wide-string input | |
| adapters in input_adapters.hpp (one code point per UTF-32 unit, per UTF-16 | |
| unit outside the surrogate range, and per valid UTF-16 surrogate pair), and | |
| by the lexer's handling of u-escapes and surrogate pairs in lexer.hpp. Passing a | |
| code point above U+10FFFF, or one in the surrogate range U+D800..U+DFFF, is | |
| undefined behavior; callers are expected to have rejected those already | |
| (the wide-string adapters pass malformed units through unencoded instead of | |
| calling this function, and the lexer rejects unpaired surrogates before | |
| reaching it). | |
| @tparam Out a callable invoked with one byte (as std::uint32_t, 0x00..0xFF) | |
| at a time, most significant byte first | |
| @param[in] cp the code point to encode (at most U+10FFFF) | |
| @param[in] out called once for each byte of the UTF-8 encoding of @a cp | |
| */ | |
| template<typename Out> | |
| void encode_utf8(std::uint32_t cp, const Out& out) | |
| { | |
| JSON_ASSERT(cp <= 0x10FFFF); | |
| if (cp < 0x80) | |
| { | |
| // 1-byte characters: 0xxxxxxx (ASCII) | |
| out(cp); | |
| } | |
| else if (cp <= 0x7FF) | |
| { | |
| // 2-byte characters: 110xxxxx 10xxxxxx | |
| out(0xC0u | (cp >> 6u)); | |
| out(0x80u | (cp & 0x3Fu)); | |
| } | |
| else if (cp <= 0xFFFF) | |
| { | |
| // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx | |
| out(0xE0u | (cp >> 12u)); | |
| out(0x80u | ((cp >> 6u) & 0x3Fu)); | |
| out(0x80u | (cp & 0x3Fu)); | |
| } | |
| else | |
| { | |
| // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx | |
| out(0xF0u | (cp >> 18u)); | |
| out(0x80u | ((cp >> 12u) & 0x3Fu)); | |
| out(0x80u | ((cp >> 6u) & 0x3Fu)); | |
| out(0x80u | (cp & 0x3Fu)); | |
| } | |
| } | |
| /*! | |
| @brief the shape of a well-formed UTF-8 sequence, by its lead byte | |
| @a length is 1 for ASCII, 2 to 4 for a valid lead byte, and 0 for a byte that | |
| cannot start a well-formed sequence (a continuation byte, 0xC0, 0xC1, or 0xF5 | |
| to 0xFF). For a multibyte sequence, the second byte must lie in | |
| [@a second_lo, @a second_hi], and every later byte in [0x80, 0xBF] | |
| (RFC 3629, section 4; Unicode Table 3-7). The narrower second-byte ranges | |
| exclude overlong forms (0xE0, 0xF0), surrogates (0xED), and code points | |
| beyond U+10FFFF (0xF4). | |
| */ | |
| struct utf8_sequence_shape | |
| { | |
| std::uint8_t length; | |
| std::uint8_t second_lo; | |
| std::uint8_t second_hi; | |
| }; | |
| /// @return the shape of a UTF-8 sequence starting with @a lead, see utf8_sequence_shape | |
| inline utf8_sequence_shape utf8_shape(const std::uint8_t lead) noexcept | |
| { | |
| if (lead < 0x80u) | |
| { | |
| return {1, 0, 0}; | |
| } | |
| if (lead < 0xC2u) | |
| { | |
| return {0, 0, 0}; | |
| } | |
| if (lead <= 0xDFu) | |
| { | |
| return {2, 0x80u, 0xBFu}; | |
| } | |
| if (lead == 0xE0u) | |
| { | |
| return {3, 0xA0u, 0xBFu}; | |
| } | |
| if (lead == 0xEDu) | |
| { | |
| return {3, 0x80u, 0x9Fu}; | |
| } | |
| if (lead <= 0xEFu) | |
| { | |
| return {3, 0x80u, 0xBFu}; | |
| } | |
| if (lead == 0xF0u) | |
| { | |
| return {4, 0x90u, 0xBFu}; | |
| } | |
| if (lead <= 0xF3u) | |
| { | |
| return {4, 0x80u, 0xBFu}; | |
| } | |
| if (lead == 0xF4u) | |
| { | |
| return {4, 0x80u, 0x8Fu}; | |
| } | |
| return {0, 0, 0}; | |
| } | |
| /////////////////// | |
| // UTF-8 decoding // | |
| /////////////////// | |
| // UTF-8 decoder states used by decode() below | |
| JSON_INLINE_VARIABLE constexpr std::uint8_t UTF8_ACCEPT = 0; | |
| JSON_INLINE_VARIABLE constexpr std::uint8_t UTF8_REJECT = 1; | |
| /*! | |
| @brief process a byte of a UTF-8 sequence | |
| This is a single-byte step of a "shift-based" UTF-8 decoder originally | |
| written by Björn Hoehrmann. See | |
| http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details. | |
| The library checks UTF-8 well-formedness (RFC 3629, section 4) in five | |
| places, which differ in speed, diagnostics, and how they read the input: | |
| - decode() below: the serializer, to escape and, in strict mode, reject | |
| ill-formed UTF-8 when dumping a string. The CBOR, MessagePack, BSON, | |
| UBJSON and BJData readers do not use it: none of those specs requires a | |
| decoder to reject ill-formed UTF-8 in text strings, so the readers keep | |
| the bytes as is and leave the check to dump() and the binary writers. | |
| - the per-lead-byte switch in lexer::scan_string(): JSON text, with a | |
| diagnostic for each kind of error. | |
| - validate_one_utf8() and valid_utf8_prefix() in string_scan.hpp: the lexer's | |
| bulk string scan, the bulk path of the BON8 reader, and the BON8 writer. | |
| They must accept exactly what the lexer's switch accepts. | |
| - the byte path of binary_reader::get_bon8_string(): BON8 input without bulk | |
| access, and the bytes the bulk path leaves to it. It keeps its own ranges: | |
| taking them from utf8_shape() made BON8 decoding 2-3% slower (#5891). | |
| - check_utf8() in detail/view/edit.hpp: strings stored in an editable | |
| json_document, with the index of the offending byte. It also uses | |
| utf8_shape(). | |
| All five must accept the same set of sequences, which the test "UTF-8 | |
| validators accept the same sequences" in unit-class_lexer.cpp checks | |
| exhaustively against decode() and utf8_shape(). | |
| @param[in,out] state the current decoder state | |
| @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) | |
| @param[in] byte next byte to decode | |
| @return new state | |
| @note Original source: http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ | |
| @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ | |
| */ | |
| inline std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept | |
| { | |
| static const std::array<std::uint8_t, 400> utf8d = | |
| { | |
| { | |
| 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F | |
| 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F | |
| 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F | |
| 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F | |
| 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F | |
| 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF | |
| 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF | |
| 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF | |
| 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF | |
| 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 | |
| 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 | |
| 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 | |
| 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 | |
| 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 | |
| } | |
| }; | |
| JSON_ASSERT(static_cast<std::size_t>(byte) < utf8d.size()); | |
| const std::uint8_t type = utf8d[byte]; | |
| codep = (state != UTF8_ACCEPT) | |
| ? (byte & 0x3fu) | (codep << 6u) | |
| : (0xFFu >> type) & (byte); | |
| const std::size_t index = 256u + (static_cast<std::size_t>(state) * 16u) + static_cast<std::size_t>(type); | |
| JSON_ASSERT(index < utf8d.size()); | |
| state = utf8d[index]; | |
| return state; | |
| } | |
| /*! | |
| @brief check a string for well-formed UTF-8 (RFC 3629, section 4) | |
| Used by the binary readers (CBOR, MessagePack, UBJSON, BJData, BSON) when an | |
| @ref error_handler_t other than `keep` is requested for a text string value | |
| or object key: none of those formats requires a decoder to reject ill-formed | |
| UTF-8 on its own, so the check is opt-in there, unlike the JSON lexer and the | |
| serializer's @ref decode -based escaping, which always run it. | |
| @param[in] s the string to check | |
| @param[in] first the index to start checking at | |
| @return whether `s.substr(first)` is well-formed UTF-8 | |
| @sa @ref decode | |
| */ | |
| template<typename StringType> | |
| inline bool is_valid_utf8(const StringType& s, const std::size_t first = 0) noexcept | |
| { | |
| std::uint8_t state = UTF8_ACCEPT; | |
| std::uint32_t codepoint = 0; | |
| for (std::size_t i = first; i < s.size(); ++i) | |
| { | |
| decode(state, codepoint, static_cast<std::uint8_t>(s[i])); | |
| if (state == UTF8_REJECT) | |
| { | |
| return false; | |
| } | |
| } | |
| return state == UTF8_ACCEPT; | |
| } | |
| /*! | |
| @brief sanitize a string with ill-formed UTF-8 for @ref error_handler_t::replace or @ref error_handler_t::ignore | |
| Replaces every maximal ill-formed subsequence with U+FFFD (`replace`) or | |
| drops it (`ignore`), using exactly the same boundaries @ref | |
| serializer::dump_escaped_impl uses while escaping a string: a byte that does | |
| not extend the sequence started by the previous byte(s) is reread as the | |
| start of a new one, instead of being swallowed along with them. | |
| @pre @a error_handler is @ref error_handler_t::replace or @ref error_handler_t::ignore | |
| @note Well-formed input is copied through unchanged, including bytes (e.g. | |
| control characters or quotes) that @ref serializer::dump_escaped_impl | |
| would itself escape; this function only concerns itself with | |
| well-formedness, not with producing valid JSON text. | |
| @param[in] s the string to sanitize | |
| @param[in] error_handler @ref error_handler_t::replace or @ref error_handler_t::ignore | |
| @return @a s with every ill-formed subsequence replaced or removed | |
| @sa @ref decode | |
| */ | |
| template<typename StringType> | |
| inline StringType sanitize_utf8(const StringType& s, const error_handler_t error_handler) | |
| { | |
| JSON_ASSERT(error_handler == error_handler_t::replace || error_handler == error_handler_t::ignore); | |
| StringType result; | |
| result.reserve(s.size()); | |
| std::uint32_t codepoint = 0; | |
| std::uint8_t state = UTF8_ACCEPT; | |
| // length of result after the last accepted code point | |
| std::size_t result_len_after_last_accept = 0; | |
| // whether bytes of an as yet unresolved sequence were already appended | |
| bool pending = false; | |
| for (std::size_t i = 0; i < s.size(); ++i) | |
| { | |
| switch (decode(state, codepoint, static_cast<std::uint8_t>(s[i]))) | |
| { | |
| case UTF8_ACCEPT: // decode found a well-formed code point | |
| { | |
| result.push_back(s[i]); | |
| result_len_after_last_accept = result.size(); | |
| pending = false; | |
| break; | |
| } | |
| case UTF8_REJECT: // decode found an ill-formed byte | |
| { | |
| // in case we saw this byte for the first time, read it again, | |
| // because it may be fine for itself, just not for the | |
| // sequence that came before it | |
| if (pending) | |
| { | |
| --i; | |
| } | |
| // drop the bytes of the ill-formed sequence buffered below | |
| result.resize(result_len_after_last_accept); | |
| if (error_handler == error_handler_t::replace) | |
| { | |
| result.append("\xEF\xBF\xBD"); | |
| result_len_after_last_accept = result.size(); | |
| } | |
| pending = false; | |
| state = UTF8_ACCEPT; | |
| break; | |
| } | |
| default: // decode found yet incomplete multibyte code point | |
| { | |
| result.push_back(s[i]); | |
| pending = true; | |
| break; | |
| } | |
| } | |
| } | |
| // the string ended with an incomplete sequence | |
| if (state != UTF8_ACCEPT) | |
| { | |
| result.resize(result_len_after_last_accept); | |
| if (error_handler == error_handler_t::replace) | |
| { | |
| result.append("\xEF\xBF\xBD"); | |
| } | |
| } | |
| return result; | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/value_t.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| template<typename IteratorType> class iteration_proxy_value | |
| { | |
| public: | |
| using difference_type = std::ptrdiff_t; | |
| using value_type = iteration_proxy_value; | |
| using pointer = value_type *; | |
| using reference = value_type &; | |
| using iterator_category = std::forward_iterator_tag; | |
| using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type; | |
| private: | |
| /// the iterator | |
| IteratorType anchor{}; | |
| /// an index for arrays (used to create key names) | |
| std::size_t array_index = 0; | |
| /// last stringified array index | |
| mutable std::size_t array_index_last = 0; | |
| /// a string representation of the array index | |
| mutable string_type array_index_str = "0"; | |
| /// an empty string (to return a reference for primitive values) | |
| string_type empty_str{}; | |
| public: | |
| explicit iteration_proxy_value() = default; | |
| explicit iteration_proxy_value(IteratorType it, std::size_t array_index_ = 0) | |
| noexcept(std::is_nothrow_move_constructible<IteratorType>::value | |
| && std::is_nothrow_default_constructible<string_type>::value) | |
| : anchor(std::move(it)) | |
| , array_index(array_index_) | |
| {} | |
| iteration_proxy_value(iteration_proxy_value const&) = default; | |
| iteration_proxy_value& operator=(iteration_proxy_value const&) = default; | |
| // older GCCs are a bit fussy and require explicit noexcept specifiers on defaulted functions | |
| iteration_proxy_value(iteration_proxy_value&&) | |
| noexcept(std::is_nothrow_move_constructible<IteratorType>::value | |
| && std::is_nothrow_move_constructible<string_type>::value) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor,cppcoreguidelines-noexcept-move-operations) | |
| iteration_proxy_value& operator=(iteration_proxy_value&&) | |
| noexcept(std::is_nothrow_move_assignable<IteratorType>::value | |
| && std::is_nothrow_move_assignable<string_type>::value) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor,cppcoreguidelines-noexcept-move-operations) | |
| ~iteration_proxy_value() = default; | |
| /// dereference operator (needed for range-based for) | |
| const iteration_proxy_value& operator*() const | |
| { | |
| return *this; | |
| } | |
| /// increment operator (needed for range-based for) | |
| iteration_proxy_value& operator++() | |
| { | |
| ++anchor; | |
| ++array_index; | |
| return *this; | |
| } | |
| iteration_proxy_value operator++(int)& // NOLINT(cert-dcl21-cpp) | |
| { | |
| auto tmp = iteration_proxy_value(anchor, array_index); | |
| ++anchor; | |
| ++array_index; | |
| return tmp; | |
| } | |
| /// equality operator (needed for InputIterator) | |
| bool operator==(const iteration_proxy_value& o) const | |
| { | |
| return anchor == o.anchor; | |
| } | |
| /// inequality operator (needed for range-based for) | |
| bool operator!=(const iteration_proxy_value& o) const | |
| { | |
| return anchor != o.anchor; | |
| } | |
| /// return key of the iterator | |
| const string_type& key() const | |
| { | |
| JSON_ASSERT(anchor.m_object != nullptr); | |
| if (anchor.m_object->is_array()) | |
| { | |
| // use integer array index as key | |
| if (array_index != array_index_last) | |
| { | |
| int_to_string( array_index_str, array_index ); | |
| array_index_last = array_index; | |
| } | |
| return array_index_str; | |
| } | |
| if (anchor.m_object->is_object()) | |
| { | |
| // use key from the object | |
| return anchor.key(); | |
| } | |
| // use an empty key for all primitive types | |
| return empty_str; | |
| } | |
| /// return value of the iterator | |
| typename IteratorType::reference value() const | |
| { | |
| return anchor.value(); | |
| } | |
| }; | |
| /// proxy class for the items() function | |
| template<typename IteratorType> class iteration_proxy | |
| { | |
| private: | |
| /// the container to iterate | |
| typename IteratorType::pointer container = nullptr; | |
| public: | |
| explicit iteration_proxy() = default; | |
| /// construct iteration proxy from a container | |
| explicit iteration_proxy(typename IteratorType::reference cont) noexcept | |
| : container(&cont) {} | |
| iteration_proxy(iteration_proxy const&) = default; | |
| iteration_proxy& operator=(iteration_proxy const&) = default; | |
| iteration_proxy(iteration_proxy&&) noexcept = default; | |
| iteration_proxy& operator=(iteration_proxy&&) noexcept = default; | |
| ~iteration_proxy() = default; | |
| /// return iterator begin (needed for range-based for) | |
| iteration_proxy_value<IteratorType> begin() const noexcept | |
| { | |
| return iteration_proxy_value<IteratorType>(container->begin()); | |
| } | |
| /// return iterator end (needed for range-based for) | |
| iteration_proxy_value<IteratorType> end() const noexcept | |
| { | |
| return iteration_proxy_value<IteratorType>(container->end()); | |
| } | |
| }; | |
| // Structured Bindings Support | |
| // For further reference see https://blog.tartanllama.xyz/structured-bindings/ | |
| // And see https://github.com/nlohmann/json/pull/1391 | |
| template<std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0> | |
| auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key()) | |
| { | |
| return i.key(); | |
| } | |
| // Structured Bindings Support | |
| // For further reference see https://blog.tartanllama.xyz/structured-bindings/ | |
| // And see https://github.com/nlohmann/json/pull/1391 | |
| template<std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0> | |
| auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value()) | |
| { | |
| return i.value(); | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // The Addition to the STD Namespace is required to add | |
| // Structured Bindings Support to the iteration_proxy_value class | |
| // For further reference see https://blog.tartanllama.xyz/structured-bindings/ | |
| // And see https://github.com/nlohmann/json/pull/1391 | |
| namespace std | |
| { | |
| // Fix: https://github.com/nlohmann/json/issues/1401 | |
| #if defined(__clang__) | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| JSON_HEDLEY_PRAGMA(clang diagnostic ignored "-Wmismatched-tags") | |
| #endif | |
| template<typename IteratorType> | |
| class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>> // NOLINT(cert-dcl58-cpp,bugprone-std-namespace-modification) | |
| : public std::integral_constant<std::size_t, 2> {}; | |
| template<std::size_t N, typename IteratorType> | |
| class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >> // NOLINT(cert-dcl58-cpp,bugprone-std-namespace-modification) | |
| { | |
| public: | |
| using type = decltype( | |
| get<N>(std::declval < | |
| ::nlohmann::detail::iteration_proxy_value<IteratorType >> ())); | |
| }; | |
| #if defined(__clang__) | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| } // namespace std | |
| #if JSON_HAS_RANGES | |
| template <typename IteratorType> | |
| inline constexpr bool ::std::ranges::enable_borrowed_range<::nlohmann::detail::iteration_proxy<IteratorType>> = true; | |
| #endif | |
| // #include <nlohmann/detail/meta/cpp_future.hpp> | |
| // #include <nlohmann/detail/meta/std_fs.hpp> | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| // #include <nlohmann/detail/value_t.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| ////////////////// | |
| // constructors // | |
| ////////////////// | |
| /* | |
| * Note all external_constructor<>::construct functions need to store the new | |
| * value with j.replace_value(), which destroys the old one to avoid a memory | |
| * leak in case j contains an allocated value (e.g., a string). See bug issue | |
| * https://github.com/nlohmann/json/issues/2865 for more information. | |
| * | |
| * A value that has to be allocated is created before the old one is destroyed: | |
| * were it the other way around, an exception while creating the new value would | |
| * leave j with the type of the new value, but the pointer to the destroyed old one. | |
| */ | |
| // a move iterator over the elements of an rvalue container, unless they are | |
| // const (e.g., std::set): libstdc++ before GCC 5 defines the reference of a | |
| // std::move_iterator as value_type&&, which cannot bind to a const element | |
| template<typename Iterator> | |
| std::move_iterator<Iterator> make_move_iterator_if_mutable_impl(const Iterator& it, std::true_type /*mutable*/) | |
| { | |
| return std::make_move_iterator(it); | |
| } | |
| template<typename Iterator> | |
| Iterator make_move_iterator_if_mutable_impl(const Iterator& it, std::false_type /*mutable*/) | |
| { | |
| return it; | |
| } | |
| template<typename Iterator> | |
| using is_mutable_iterator = std::integral_constant < bool, | |
| !std::is_const<typename std::remove_reference<decltype(*std::declval<Iterator&>())>::type>::value >; | |
| template<typename Iterator> | |
| auto make_move_iterator_if_mutable(const Iterator& it) | |
| -> decltype(make_move_iterator_if_mutable_impl(it, is_mutable_iterator<Iterator> {})) | |
| { | |
| return make_move_iterator_if_mutable_impl(it, is_mutable_iterator<Iterator> {}); | |
| } | |
| template<value_t> struct external_constructor; | |
| template<> | |
| struct external_constructor<value_t::boolean> | |
| { | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept | |
| { | |
| j.replace_value(value_t::boolean, b); | |
| } | |
| }; | |
| template<> | |
| struct external_constructor<value_t::string> | |
| { | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) | |
| { | |
| const typename BasicJsonType::json_value value(s); | |
| j.replace_value(value_t::string, value); | |
| } | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) | |
| { | |
| const typename BasicJsonType::json_value value(std::move(s)); | |
| j.replace_value(value_t::string, value); | |
| } | |
| template < typename BasicJsonType, typename CompatibleStringType, | |
| enable_if_t < !std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value, | |
| int > = 0 > | |
| static void construct(BasicJsonType& j, const CompatibleStringType& str) | |
| { | |
| const typename BasicJsonType::json_value value(j.template create<typename BasicJsonType::string_t>(str)); | |
| j.replace_value(value_t::string, value); | |
| } | |
| }; | |
| template<> | |
| struct external_constructor<value_t::binary> | |
| { | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b) | |
| { | |
| const typename BasicJsonType::json_value value(b); | |
| j.replace_value(value_t::binary, value); | |
| } | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b) | |
| { | |
| const typename BasicJsonType::json_value value(std::move(b)); | |
| j.replace_value(value_t::binary, value); | |
| } | |
| }; | |
| template<> | |
| struct external_constructor<value_t::number_float> | |
| { | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept | |
| { | |
| j.replace_value(value_t::number_float, val); | |
| } | |
| }; | |
| template<> | |
| struct external_constructor<value_t::number_unsigned> | |
| { | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept | |
| { | |
| j.replace_value(value_t::number_unsigned, val); | |
| } | |
| }; | |
| template<> | |
| struct external_constructor<value_t::number_integer> | |
| { | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept | |
| { | |
| j.replace_value(value_t::number_integer, val); | |
| } | |
| }; | |
| template<> | |
| struct external_constructor<value_t::array> | |
| { | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) | |
| { | |
| const typename BasicJsonType::json_value value(arr); | |
| j.replace_value(value_t::array, value); | |
| } | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) | |
| { | |
| const typename BasicJsonType::json_value value(std::move(arr)); | |
| j.replace_value(value_t::array, value); | |
| } | |
| template < typename BasicJsonType, typename CompatibleArrayType, | |
| enable_if_t < !std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value | |
| #if JSON_HAS_RANGE_VIEW_CONVERSION | |
| && !is_compatible_range_view<CompatibleArrayType>::value | |
| #endif | |
| , int > = 0 > | |
| static void construct(BasicJsonType& j, const CompatibleArrayType& arr) | |
| { | |
| using std::begin; | |
| using std::end; | |
| const typename BasicJsonType::json_value value(j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr))); | |
| j.replace_value(value_t::array, value); | |
| } | |
| /// an rvalue container: move its elements | |
| template<typename BasicJsonType, typename CompatibleArrayType> | |
| static void construct_moving(BasicJsonType& j, CompatibleArrayType& arr) | |
| { | |
| using std::begin; | |
| using std::end; | |
| const typename BasicJsonType::json_value value(j.template create<typename BasicJsonType::array_t>(make_move_iterator_if_mutable(begin(arr)), make_move_iterator_if_mutable(end(arr)))); | |
| j.replace_value(value_t::array, value); | |
| } | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, const std::vector<bool>& arr) | |
| { | |
| const typename BasicJsonType::json_value value(j.template create<typename BasicJsonType::array_t>(arr.begin(), arr.end())); | |
| j.replace_value(value_t::array, value); | |
| } | |
| template<typename BasicJsonType, typename T, | |
| enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0> | |
| static void construct(BasicJsonType& j, const std::valarray<T>& arr) | |
| { | |
| const typename BasicJsonType::json_value value(j.template create<typename BasicJsonType::array_t>(std::begin(arr), std::end(arr))); | |
| j.replace_value(value_t::array, value); | |
| } | |
| #if JSON_HAS_RANGE_VIEW_CONVERSION | |
| template<typename BasicJsonType, typename CompatibleArrayType, | |
| enable_if_t<is_compatible_range_view<std::remove_cvref_t<CompatibleArrayType>>::value, int> = 0> | |
| static void construct(BasicJsonType& j, CompatibleArrayType && arr) | |
| { | |
| // no range constructor: a view's begin() and end() may have different | |
| // types, and the view may only be iterable once | |
| typename BasicJsonType::array_t elements; | |
| for (auto&& x : std::forward<CompatibleArrayType>(arr)) | |
| { | |
| elements.push_back(x); | |
| } | |
| const typename BasicJsonType::json_value value(std::move(elements)); | |
| j.replace_value(value_t::array, value); | |
| } | |
| #endif | |
| }; | |
| template<> | |
| struct external_constructor<value_t::object> | |
| { | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) | |
| { | |
| const typename BasicJsonType::json_value value(obj); | |
| j.replace_value(value_t::object, value); | |
| } | |
| template<typename BasicJsonType> | |
| static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) | |
| { | |
| const typename BasicJsonType::json_value value(std::move(obj)); | |
| j.replace_value(value_t::object, value); | |
| } | |
| /// an rvalue container: move its values | |
| template<typename BasicJsonType, typename CompatibleObjectType> | |
| static void construct_moving(BasicJsonType& j, CompatibleObjectType& obj) | |
| { | |
| using std::begin; | |
| using std::end; | |
| const typename BasicJsonType::json_value value(j.template create<typename BasicJsonType::object_t>(make_move_iterator_if_mutable(begin(obj)), make_move_iterator_if_mutable(end(obj)))); | |
| j.replace_value(value_t::object, value); | |
| } | |
| template < typename BasicJsonType, typename CompatibleObjectType, | |
| enable_if_t < !std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int > = 0 > | |
| static void construct(BasicJsonType& j, const CompatibleObjectType& obj) | |
| { | |
| using std::begin; | |
| using std::end; | |
| const typename BasicJsonType::json_value value(j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj))); | |
| j.replace_value(value_t::object, value); | |
| } | |
| }; | |
| ///////////// | |
| // to_json // | |
| ///////////// | |
| #ifdef JSON_HAS_CPP_17 | |
| // whether storing the value of a std::optional<T> cannot throw; MSVC 2017 | |
| // evaluates std::is_nothrow_assignable as true even if T's to_json throws, so | |
| // the exception would call std::terminate (#5642) | |
| #if defined(_MSC_VER) && !defined(__clang__) && _MSC_VER < 1920 | |
| template<typename BasicJsonType, typename T> | |
| using is_nothrow_optional_to_json = std::false_type; | |
| #else | |
| template<typename BasicJsonType, typename T> | |
| using is_nothrow_optional_to_json = std::is_nothrow_assignable<BasicJsonType&, const T&>; | |
| #endif | |
| template<typename BasicJsonType, typename T, | |
| enable_if_t<std::is_constructible<BasicJsonType, T>::value, int> = 0> | |
| void to_json(BasicJsonType& j, const std::optional<T>& opt) noexcept(is_nothrow_optional_to_json<BasicJsonType, T>::value) | |
| { | |
| if (opt.has_value()) | |
| { | |
| // explicit construction, as the conversion from a basic_json with a different | |
| // string type is explicit if JSON_USE_IMPLICIT_CONVERSIONS is 0 (#2649) | |
| j = BasicJsonType(*opt); | |
| } | |
| else | |
| { | |
| j = nullptr; | |
| } | |
| } | |
| #endif | |
| template<typename BasicJsonType, typename T, | |
| enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0> | |
| inline void to_json(BasicJsonType& j, T b) noexcept | |
| { | |
| external_constructor<value_t::boolean>::construct(j, b); | |
| } | |
| template < typename BasicJsonType, typename BoolRef, | |
| enable_if_t < | |
| ((std::is_same<std::vector<bool>::reference, BoolRef>::value | |
| && !std::is_same <std::vector<bool>::reference, typename BasicJsonType::boolean_t&>::value) | |
| || (std::is_same<std::vector<bool>::const_reference, BoolRef>::value | |
| && !std::is_same <detail::uncvref_t<std::vector<bool>::const_reference>, | |
| typename BasicJsonType::boolean_t >::value)) | |
| && std::is_convertible<const BoolRef&, typename BasicJsonType::boolean_t>::value, int > = 0 > | |
| inline void to_json(BasicJsonType& j, const BoolRef& b) noexcept | |
| { | |
| external_constructor<value_t::boolean>::construct(j, static_cast<typename BasicJsonType::boolean_t>(b)); | |
| } | |
| template<typename BasicJsonType, typename CompatibleString, | |
| enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0> | |
| inline void to_json(BasicJsonType& j, const CompatibleString& s) | |
| { | |
| external_constructor<value_t::string>::construct(j, s); | |
| } | |
| template<typename BasicJsonType> | |
| inline void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) | |
| { | |
| external_constructor<value_t::string>::construct(j, std::move(s)); | |
| } | |
| template<typename BasicJsonType, typename FloatType, | |
| enable_if_t<std::is_floating_point<FloatType>::value, int> = 0> | |
| inline void to_json(BasicJsonType& j, FloatType val) noexcept | |
| { | |
| external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val)); | |
| } | |
| template<typename BasicJsonType, typename CompatibleNumberUnsignedType, | |
| enable_if_t<is_compatible_integer_type<number_unsigned_overload_t<BasicJsonType>, CompatibleNumberUnsignedType>::value, int> = 0> | |
| inline void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept | |
| { | |
| external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val)); | |
| } | |
| template<typename BasicJsonType, typename CompatibleNumberIntegerType, | |
| enable_if_t<is_compatible_number_integer_type<BasicJsonType, CompatibleNumberIntegerType>::value, int> = 0> | |
| inline void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept | |
| { | |
| external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val)); | |
| } | |
| #if !JSON_DISABLE_ENUM_SERIALIZATION | |
| template<typename BasicJsonType, typename EnumType, | |
| enable_if_t<std::is_enum<EnumType>::value, int> = 0> | |
| inline void to_json(BasicJsonType& j, EnumType e) noexcept | |
| { | |
| using underlying_type = typename std::underlying_type<EnumType>::type; | |
| static constexpr value_t integral_value_t = std::is_unsigned<underlying_type>::value ? value_t::number_unsigned : value_t::number_integer; | |
| external_constructor<integral_value_t>::construct(j, bool_aware_static_cast<underlying_type>(e)); | |
| } | |
| #endif // JSON_DISABLE_ENUM_SERIALIZATION | |
| template<typename BasicJsonType> | |
| inline void to_json(BasicJsonType& j, const std::vector<bool>& e) | |
| { | |
| external_constructor<value_t::array>::construct(j, e); | |
| } | |
| template < typename BasicJsonType, typename CompatibleArrayType, | |
| enable_if_t < is_compatible_array_type<BasicJsonType, | |
| CompatibleArrayType>::value&& | |
| !is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value&& | |
| !is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value&& | |
| !std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value&& | |
| !is_compatible_binary_type<BasicJsonType, CompatibleArrayType>::value&& | |
| !is_basic_json<CompatibleArrayType>::value | |
| #if JSON_HAS_RANGE_VIEW_CONVERSION | |
| && !is_compatible_range_view<CompatibleArrayType>::value | |
| #endif | |
| #if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS | |
| && !is_enum_keyed_map<CompatibleArrayType>::value | |
| #endif | |
| , | |
| int > = 0 > | |
| inline void to_json(BasicJsonType& j, const CompatibleArrayType& arr) | |
| { | |
| external_constructor<value_t::array>::construct(j, arr); | |
| } | |
| // types that have a dedicated to_json overload and must not be treated as generic containers | |
| template<typename T> | |
| struct has_dedicated_to_json : std::false_type {}; | |
| #if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| template<> | |
| struct has_dedicated_to_json<std_fs::path> : std::true_type {}; | |
| #endif | |
| #if defined(__cpp_lib_char8_t) | |
| template<typename Tr, typename Allocator> | |
| struct has_dedicated_to_json<std::basic_string<char8_t, Tr, Allocator>> : std::true_type {}; | |
| #endif | |
| #if JSON_HAS_RANGE_VIEW_CONVERSION | |
| template<typename T> | |
| struct is_range_view_type : is_compatible_range_view<T> {}; | |
| #else | |
| template<typename T> | |
| struct is_range_view_type : std::false_type {}; | |
| #endif | |
| #if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS | |
| template<typename T> | |
| struct is_enum_keyed_map_type : is_enum_keyed_map<T> {}; | |
| #else | |
| template<typename T> | |
| struct is_enum_keyed_map_type : std::false_type {}; | |
| #endif | |
| // rvalue (non-const) container: the generic to_json takes its elements by move | |
| template<typename T> | |
| using is_movable_container_rvalue = negation<disjunction< | |
| std::is_lvalue_reference<T>, | |
| std::is_const<T>, | |
| has_dedicated_to_json<T>, | |
| is_basic_json<T>, | |
| is_enum_keyed_map_type<T>, | |
| std::is_same<T, std::vector<bool>>>>; | |
| // rvalue array-like containers; object types are ruled out before views are | |
| // checked, as std::ranges::view<T> for the object_t of an ordered_json would | |
| // need that ordered_json to be complete (GCC 11, see #3312) | |
| template<typename BasicJsonType, typename T> | |
| using is_rvalue_array_to_json = conjunction<is_movable_container_rvalue<T>, | |
| negation<is_compatible_object_type<BasicJsonType, T>>, | |
| negation<is_range_view_type<T>>, | |
| is_compatible_array_type<BasicJsonType, T>, | |
| negation<disjunction< | |
| std::is_same<T, typename BasicJsonType::array_t>, | |
| std::is_same<T, typename BasicJsonType::binary_t>, | |
| is_compatible_string_type<BasicJsonType, T>, | |
| is_compatible_binary_type<BasicJsonType, T>>>>; | |
| // rvalue containers: their elements are moved instead of copied | |
| template<typename BasicJsonType, typename CompatibleArrayType, | |
| enable_if_t<is_rvalue_array_to_json<BasicJsonType, CompatibleArrayType>::value, int> = 0> | |
| inline void to_json(BasicJsonType& j, CompatibleArrayType && arr) // NOLINT(cppcoreguidelines-missing-std-forward) | |
| { | |
| external_constructor<value_t::array>::construct_moving(j, arr); | |
| } | |
| #if JSON_HAS_RANGE_VIEW_CONVERSION | |
| template < typename BasicJsonType, typename T, | |
| enable_if_t < is_compatible_range_view<std::remove_cvref_t<T>>::value | |
| && !is_compatible_string_type<BasicJsonType, std::remove_cvref_t<T>>::value | |
| && !is_compatible_object_type<BasicJsonType, std::remove_cvref_t<T>>::value | |
| && !is_basic_json<std::remove_cvref_t<T>>::value, int > = 0 > | |
| inline void to_json(BasicJsonType& j, T && arr) | |
| { | |
| external_constructor<value_t::array>::construct(j, std::forward<T>(arr)); | |
| } | |
| #endif | |
| template<typename BasicJsonType> | |
| inline void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin) | |
| { | |
| external_constructor<value_t::binary>::construct(j, bin); | |
| } | |
| template < typename BasicJsonType, typename CompatibleArrayType, | |
| enable_if_t < is_compatible_binary_type<BasicJsonType, CompatibleArrayType>::value, | |
| int > = 0 > | |
| inline void to_json(BasicJsonType& j, const CompatibleArrayType& bin) | |
| { | |
| external_constructor<value_t::binary>::construct(j, typename BasicJsonType::binary_t(bin)); | |
| } | |
| template<typename BasicJsonType, typename T, | |
| enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0> | |
| inline void to_json(BasicJsonType& j, const std::valarray<T>& arr) | |
| { | |
| external_constructor<value_t::array>::construct(j, std::move(arr)); | |
| } | |
| template<typename BasicJsonType> | |
| inline void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) | |
| { | |
| external_constructor<value_t::array>::construct(j, std::move(arr)); | |
| } | |
| template < typename BasicJsonType, typename CompatibleObjectType, | |
| enable_if_t < is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value&& !is_basic_json<CompatibleObjectType>::value, int > = 0 > | |
| inline void to_json(BasicJsonType& j, const CompatibleObjectType& obj) | |
| { | |
| external_constructor<value_t::object>::construct(j, obj); | |
| } | |
| #if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS | |
| // store a map with enum keys as an object, using the enum's own to_json for the | |
| // keys (e.g., from NLOHMANN_JSON_SERIALIZE_ENUM); without the macro, such maps | |
| // are stored as arrays of [key, value] pairs | |
| template < typename BasicJsonType, typename EnumKeyedMap, | |
| enable_if_t < is_enum_keyed_map<EnumKeyedMap>::value&& !is_basic_json<EnumKeyedMap>::value, int > = 0 > | |
| inline void to_json(BasicJsonType& j, const EnumKeyedMap& map) | |
| { | |
| typename BasicJsonType::object_t obj; | |
| for (const auto& p : map) | |
| { | |
| BasicJsonType key = p.first; | |
| if (JSON_HEDLEY_UNLIKELY(!key.is_string())) | |
| { | |
| throw_type_must_be("string", key); | |
| } | |
| auto& key_string = *key.template get_ptr<typename BasicJsonType::string_t*>(); | |
| if (JSON_HEDLEY_UNLIKELY(!obj.emplace(key_string, BasicJsonType(p.second)).second)) | |
| { | |
| JSON_THROW(type_error::create(exception_id::enum_key_duplicate, concat("duplicate object key '", key_string, "'"), &key)); | |
| } | |
| } | |
| external_constructor<value_t::object>::construct(j, std::move(obj)); | |
| } | |
| #endif | |
| // rvalue object-like containers (views have no key_type and mapped_type, so | |
| // they are no compatible object type) | |
| template<typename BasicJsonType, typename T> | |
| using is_rvalue_object_to_json = conjunction<is_movable_container_rvalue<T>, | |
| negation<std::is_same<T, typename BasicJsonType::object_t>>, | |
| is_compatible_object_type<BasicJsonType, T>>; | |
| template<typename BasicJsonType, typename CompatibleObjectType, | |
| enable_if_t<is_rvalue_object_to_json<BasicJsonType, CompatibleObjectType>::value, int> = 0> | |
| inline void to_json(BasicJsonType& j, CompatibleObjectType && obj) // NOLINT(cppcoreguidelines-missing-std-forward) | |
| { | |
| external_constructor<value_t::object>::construct_moving(j, obj); | |
| } | |
| template<typename BasicJsonType> | |
| inline void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) | |
| { | |
| external_constructor<value_t::object>::construct(j, std::move(obj)); | |
| } | |
| template < | |
| typename BasicJsonType, typename T, std::size_t N, | |
| enable_if_t < !std::is_constructible<typename BasicJsonType::string_t, | |
| const T(&)[N]>::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| int > = 0 > | |
| inline void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| { | |
| external_constructor<value_t::array>::construct(j, arr); | |
| } | |
| template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 > | |
| inline void to_json(BasicJsonType& j, const std::pair<T1, T2>& p) | |
| { | |
| j = { p.first, p.second }; | |
| } | |
| // for https://github.com/nlohmann/json/pull/1134 | |
| template<typename BasicJsonType, typename T, | |
| enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0> | |
| inline void to_json(BasicJsonType& j, const T& b) | |
| { | |
| j = { {b.key(), b.value()} }; | |
| } | |
| template<typename BasicJsonType, typename Tuple, std::size_t... Idx> | |
| inline void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/) | |
| { | |
| j = { std::get<Idx>(t)... }; | |
| } | |
| // A one-element braced list does not reliably wrap its element: with | |
| // JSON_BRACE_INIT_COPY_SEMANTICS it copies it, which would serialize | |
| // std::tuple<int>{5} as 5 rather than [5], and some compilers (e.g., Apple clang | |
| // 15 and 16) copy an element that is itself a basic_json even without it, so | |
| // std::tuple<json>{true} became true rather than [true]. Build what the default | |
| // deduction builds instead: an object if the element is a [string, value] pair, | |
| // a one-element array otherwise. | |
| template<typename BasicJsonType, typename Tuple> | |
| inline void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<0> /*unused*/) | |
| { | |
| BasicJsonType element(std::get<0>(t)); | |
| // same test as the initializer-list constructor, including the cast that | |
| // keeps a string type constructible from 0 from selecting operator[](key) | |
| const bool is_member = element.is_array() && element.size() == 2 | |
| && element[static_cast<typename BasicJsonType::size_type>(0)].is_string(); | |
| if (is_member) | |
| { | |
| j = BasicJsonType::object({std::move(element)}); | |
| } | |
| else | |
| { | |
| j = BasicJsonType::array({std::move(element)}); | |
| } | |
| } | |
| template<typename BasicJsonType, typename Tuple> | |
| inline void to_json_tuple_impl(BasicJsonType& j, const Tuple& /*unused*/, index_sequence<> /*unused*/) | |
| { | |
| using array_t = typename BasicJsonType::array_t; | |
| j = array_t(); | |
| } | |
| template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0> | |
| inline void to_json(BasicJsonType& j, const T& t) | |
| { | |
| to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {}); | |
| } | |
| #if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| #if defined(__cpp_lib_char8_t) | |
| template<typename BasicJsonType, typename Tr, typename Allocator> | |
| inline void to_json(BasicJsonType& j, const std::basic_string<char8_t, Tr, Allocator>& s) | |
| { | |
| using OtherAllocator = typename std::allocator_traits<Allocator>::template rebind_alloc<char>; | |
| j = std::basic_string<char, std::char_traits<char>, OtherAllocator>(s.begin(), s.end(), s.get_allocator()); | |
| } | |
| #endif | |
| // Workaround for MSVC 19.51 (and possibly later): in large cpp files, the compiler may fail to resolve with generic has_to_json (issue #4996) | |
| template<typename BasicJsonType> | |
| struct has_to_json<BasicJsonType, std_fs::path, void> : std::true_type {}; | |
| template<typename BasicJsonType> | |
| inline void to_json(BasicJsonType& j, const std_fs::path& p) | |
| { | |
| // Returns either a std::string or a std::u8string depending whether library | |
| // support for char8_t is enabled. | |
| j = p.u8string(); | |
| } | |
| #endif | |
| struct to_json_fn | |
| { | |
| template<typename BasicJsonType, typename T> | |
| auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val)))) | |
| -> decltype(to_json(j, std::forward<T>(val)), void()) | |
| { | |
| return to_json(j, std::forward<T>(val)); | |
| } | |
| }; | |
| } // namespace detail | |
| #ifndef JSON_HAS_CPP_17 | |
| /// namespace to hold default `to_json` function | |
| /// to see why this is required: | |
| /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html | |
| namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces,misc-anonymous-namespace-in-header) | |
| { | |
| #endif | |
| JSON_INLINE_VARIABLE constexpr const auto& to_json = // NOLINT(misc-definitions-in-headers) | |
| detail::static_const<detail::to_json_fn>::value; | |
| #ifndef JSON_HAS_CPP_17 | |
| } // namespace | |
| #endif | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/meta/identity_tag.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| /// @sa https://json.nlohmann.me/api/adl_serializer/ | |
| template<typename ValueType, typename> | |
| struct adl_serializer | |
| { | |
| /// @brief convert a JSON value to any value type | |
| /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ | |
| template<typename BasicJsonType, typename TargetType = ValueType> | |
| static auto from_json(BasicJsonType && j, TargetType& val) noexcept( | |
| noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val))) | |
| -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void()) | |
| { | |
| ::nlohmann::from_json(std::forward<BasicJsonType>(j), val); | |
| } | |
| /// @brief convert a JSON value to any value type | |
| /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ | |
| template<typename BasicJsonType, typename TargetType = ValueType> | |
| static auto from_json(BasicJsonType && j) noexcept( | |
| noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))) | |
| -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})) | |
| { | |
| return ::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}); | |
| } | |
| /// @brief convert any value type to a JSON value | |
| /// @sa https://json.nlohmann.me/api/adl_serializer/to_json/ | |
| template<typename BasicJsonType, typename TargetType = ValueType> | |
| static auto to_json(BasicJsonType& j, TargetType && val) noexcept( | |
| noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val)))) | |
| -> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void()) | |
| { | |
| ::nlohmann::to_json(j, std::forward<TargetType>(val)); | |
| } | |
| }; | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // IWYU pragma: export | |
| // #include <nlohmann/byte_container_with_subtype.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cstdint> // uint8_t, uint64_t | |
| #include <tuple> // tie | |
| #include <utility> // move | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| /// @brief an internal type for a backed binary type | |
| /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/ | |
| template<typename BinaryType> | |
| class byte_container_with_subtype : public BinaryType | |
| { | |
| public: | |
| using container_type = BinaryType; | |
| using subtype_type = std::uint64_t; | |
| /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ | |
| byte_container_with_subtype() noexcept(noexcept(container_type())) | |
| : container_type() | |
| {} | |
| /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ | |
| byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b))) | |
| : container_type(b) | |
| {} | |
| /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ | |
| byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b)))) | |
| : container_type(std::move(b)) | |
| {} | |
| /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ | |
| byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b))) | |
| : container_type(b) | |
| , m_subtype(subtype_) | |
| , m_has_subtype(true) | |
| {} | |
| /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ | |
| byte_container_with_subtype(container_type&& b, subtype_type subtype_) noexcept(noexcept(container_type(std::move(b)))) | |
| : container_type(std::move(b)) | |
| , m_subtype(subtype_) | |
| , m_has_subtype(true) | |
| {} | |
| bool operator==(const byte_container_with_subtype& rhs) const | |
| { | |
| return std::tie(static_cast<const BinaryType&>(*this), m_subtype, m_has_subtype) == | |
| std::tie(static_cast<const BinaryType&>(rhs), rhs.m_subtype, rhs.m_has_subtype); | |
| } | |
| bool operator!=(const byte_container_with_subtype& rhs) const | |
| { | |
| return !(rhs == *this); | |
| } | |
| /// @brief sets the binary subtype | |
| /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/set_subtype/ | |
| void set_subtype(subtype_type subtype_) noexcept | |
| { | |
| m_subtype = subtype_; | |
| m_has_subtype = true; | |
| } | |
| /// @brief return the binary subtype | |
| /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/subtype/ | |
| constexpr subtype_type subtype() const noexcept | |
| { | |
| return m_has_subtype ? m_subtype : static_cast<subtype_type>(-1); | |
| } | |
| /// @brief return whether the value has a subtype | |
| /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/has_subtype/ | |
| constexpr bool has_subtype() const noexcept | |
| { | |
| return m_has_subtype; | |
| } | |
| /// @brief clears the binary subtype | |
| /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/clear_subtype/ | |
| void clear_subtype() noexcept | |
| { | |
| m_subtype = 0; | |
| m_has_subtype = false; | |
| } | |
| private: | |
| subtype_type m_subtype = 0; | |
| bool m_has_subtype = false; | |
| }; | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/abi_config.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /*! | |
| @brief the configuration macros that json_view.hpp reads | |
| json.hpp undefines these macros at its end (see macro_unscope.hpp), so code | |
| that builds on the library after it (json_view.hpp) reads them here. A macro | |
| is added when the view starts to depend on it. Like the | |
| macros, they are part of the ABI namespace, so they always match the | |
| basic_json they are used with. | |
| */ | |
| struct abi_config | |
| { | |
| /// JSON_STRICT_NUL_HANDLING: a null byte is an error, not the end of input | |
| static constexpr bool strict_nul_handling = JSON_STRICT_NUL_HANDLING != 0; | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| // IWYU pragma: export | |
| // #include <nlohmann/detail/conversions/from_json.hpp> | |
| // IWYU pragma: keep | |
| // #include <nlohmann/detail/conversions/to_json.hpp> | |
| // IWYU pragma: keep | |
| // #include <nlohmann/detail/exceptions.hpp> | |
| // IWYU pragma: export | |
| // #include <nlohmann/detail/hash.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cstdint> // uint8_t | |
| #include <cstddef> // size_t | |
| #include <functional> // hash | |
| #include <vector> // vector | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| // #include <nlohmann/detail/recursion_depth_limit.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cstddef> // size_t | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /*! | |
| @brief the number of nesting levels an operation recurses into | |
| Operations that walk a value (copying, comparing, serializing, hashing, merging, | |
| ...) recurse once | |
| per nesting level, which is fastest, but a value nested deeply enough would | |
| exhaust the call stack. So they recurse only this many levels deep and finish | |
| whatever lies below with an explicit stack. All of them share this limit. | |
| Most of them pass the depth down as an argument. The copy constructor and the | |
| comparison operators cannot, as their signatures are fixed, so they count it | |
| in basic_json::nesting_depth() instead, a byte per thread; the limit must | |
| therefore stay below 255. | |
| @sa https://github.com/nlohmann/json/issues/5387 | |
| */ | |
| constexpr std::size_t recursion_depth_limit() noexcept | |
| { | |
| return 128; | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/value_t.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| // boost::hash_combine | |
| inline std::size_t combine(std::size_t seed, std::size_t h) noexcept | |
| { | |
| seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U); | |
| return seed; | |
| } | |
| template<typename BasicJsonType> | |
| std::size_t hash_iteratively(const BasicJsonType& j); | |
| /*! | |
| @brief hash a JSON value | |
| The hash function tries to rely on std::hash where possible. Furthermore, the | |
| type of the JSON value is taken into account, so null, false, and numbers may | |
| hash differently from each other, but any two numbers that compare equal | |
| under operator== hash equally regardless of which of number_integer, | |
| number_unsigned, or number_float actually holds the value. | |
| Hashing an array or an object hashes its elements, which used to call this | |
| function again once per nesting level, so a value nested deeply enough | |
| exhausted the call stack and terminated the process. The descent is bounded | |
| here: once @ref recursion_depth_limit levels have been entered, @ref | |
| hash_iteratively hashes what is left without the call stack. A value nested | |
| less deeply than that - all but a vanishing minority - is hashed exactly as | |
| before, without allocating. | |
| @tparam BasicJsonType basic_json specialization | |
| @param j JSON value to hash | |
| @param depth nesting level of @a j, counted from the value passed by the caller | |
| @return hash value of j | |
| */ | |
| template<typename BasicJsonType> | |
| std::size_t hash(const BasicJsonType& j, const std::size_t depth = 0) | |
| { | |
| using string_t = typename BasicJsonType::string_t; | |
| using number_float_t = typename BasicJsonType::number_float_t; | |
| const auto type = static_cast<std::size_t>(j.type()); | |
| switch (j.type()) | |
| { | |
| case BasicJsonType::value_t::null: | |
| case BasicJsonType::value_t::discarded: | |
| { | |
| return combine(type, 0); | |
| } | |
| case BasicJsonType::value_t::object: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(depth >= recursion_depth_limit())) | |
| { | |
| return hash_iteratively(j); | |
| } | |
| auto seed = combine(type, j.size()); | |
| for (const auto& element : j.items()) | |
| { | |
| const auto h = std::hash<string_t> {}(element.key()); | |
| seed = combine(seed, h); | |
| seed = combine(seed, hash(element.value(), depth + 1)); | |
| } | |
| return seed; | |
| } | |
| case BasicJsonType::value_t::array: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(depth >= recursion_depth_limit())) | |
| { | |
| return hash_iteratively(j); | |
| } | |
| auto seed = combine(type, j.size()); | |
| for (const auto& element : j) | |
| { | |
| seed = combine(seed, hash(element, depth + 1)); | |
| } | |
| return seed; | |
| } | |
| case BasicJsonType::value_t::string: | |
| { | |
| const auto h = std::hash<string_t> {}(j.template get_ref<const string_t&>()); | |
| return combine(type, h); | |
| } | |
| case BasicJsonType::value_t::boolean: | |
| { | |
| const auto h = std::hash<bool> {}(j.template get<bool>()); | |
| return combine(type, h); | |
| } | |
| case BasicJsonType::value_t::number_integer: | |
| case BasicJsonType::value_t::number_unsigned: | |
| case BasicJsonType::value_t::number_float: | |
| { | |
| // operator== compares numbers by their mathematical value across | |
| // number_integer, number_unsigned, and number_float, so equal | |
| // numbers of different internal types (0, 0U, 0.0) must hash the | |
| // same. Two equal numbers have the same value, which converts to | |
| // the same number_float_t, so all numbers share one type tag and | |
| // hash that converted value. Adding zero turns -0.0 (equal to 0) | |
| // into 0.0, as std::hash need not map both to the same hash. | |
| // The converse does not hold: converting a number_float_t value | |
| // to an integer type is lossy, so the result can hash | |
| // differently, and unequal numbers that convert to the same | |
| // number_float_t (e.g., 2^53 and 2^53 + 1) share a hash. | |
| const auto number_type = static_cast<std::size_t>(BasicJsonType::value_t::number_float); | |
| const auto value = j.template get<number_float_t>() + static_cast<number_float_t>(0); | |
| const auto h = std::hash<number_float_t> {}(value); | |
| return combine(number_type, h); | |
| } | |
| case BasicJsonType::value_t::binary: | |
| { | |
| auto seed = combine(type, j.get_binary().size()); | |
| const auto h = std::hash<bool> {}(j.get_binary().has_subtype()); | |
| seed = combine(seed, h); | |
| seed = combine(seed, static_cast<std::size_t>(j.get_binary().subtype())); | |
| for (const auto byte : j.get_binary()) | |
| { | |
| // the cast is needed for binary types whose value type is not | |
| // an integer (e.g., std::byte) | |
| seed = combine(seed, std::hash<std::uint8_t> {}(static_cast<std::uint8_t>(byte))); | |
| } | |
| return seed; | |
| } | |
| default: // LCOV_EXCL_LINE | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE | |
| return 0; // LCOV_EXCL_LINE | |
| } | |
| } | |
| /// an array or object whose elements @ref hash_iteratively is hashing | |
| template<typename BasicJsonType> | |
| struct hash_frame | |
| { | |
| hash_frame(const BasicJsonType* value_, std::size_t seed_) noexcept | |
| : value(value_), position(value_->cbegin()), seed(seed_) | |
| {} | |
| const BasicJsonType* value; | |
| typename BasicJsonType::const_iterator position; | |
| std::size_t seed; | |
| }; | |
| /*! | |
| @brief hash the array or object @a j without the call stack | |
| Computes the same value as @ref hash, keeping the arrays and objects it has | |
| entered on an explicit stack instead of descending into them. Only reached for | |
| values nested deeper than @ref recursion_depth_limit. | |
| @tparam BasicJsonType basic_json specialization | |
| @param j array or object to hash | |
| @return hash value of j | |
| */ | |
| template<typename BasicJsonType> | |
| std::size_t hash_iteratively(const BasicJsonType& j) | |
| { | |
| using string_t = typename BasicJsonType::string_t; | |
| std::vector<hash_frame<BasicJsonType>> stack; | |
| stack.emplace_back(&j, combine(static_cast<std::size_t>(j.type()), j.size())); | |
| while (true) | |
| { | |
| // a copy, as entering an element below can reallocate the stack; the | |
| // frame itself is only changed through stack.back() | |
| const hash_frame<BasicJsonType> frame = stack.back(); | |
| if (frame.position == frame.value->cend()) | |
| { | |
| // all elements are hashed: fold this value's hash into its parent's | |
| // seed, exactly where the recursive version returns it | |
| const std::size_t h = frame.seed; | |
| stack.pop_back(); | |
| if (stack.empty()) | |
| { | |
| return h; | |
| } | |
| stack.back().seed = combine(stack.back().seed, h); | |
| continue; | |
| } | |
| if (frame.value->is_object()) | |
| { | |
| stack.back().seed = combine(stack.back().seed, std::hash<string_t> {}(frame.position.key())); | |
| } | |
| // advance before entering the element, which pushes onto the stack | |
| const BasicJsonType& element = *frame.position; | |
| ++stack.back().position; | |
| if (element.is_structured()) | |
| { | |
| stack.emplace_back(&element, combine(static_cast<std::size_t>(element.type()), element.size())); | |
| } | |
| else | |
| { | |
| stack.back().seed = combine(stack.back().seed, hash(element)); | |
| } | |
| } | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/input/binary_reader.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <array> // array | |
| #include <cmath> // ldexp | |
| #include <cstddef> // size_t | |
| #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t, uintmax_t | |
| #include <cstring> // memcpy | |
| #include <iterator> // back_inserter | |
| #include <limits> // numeric_limits | |
| #include <string> // char_traits, string | |
| #include <utility> // make_pair, move | |
| #include <vector> // vector | |
| #ifdef __cpp_lib_byteswap | |
| #include <bit> //byteswap | |
| #endif | |
| // #include <nlohmann/detail/exceptions.hpp> | |
| // #include <nlohmann/detail/input/input_adapters.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <algorithm> // count, find, max, min | |
| #include <array> // array | |
| #include <cstddef> // size_t | |
| #include <cstdint> // uint32_t | |
| #include <cstring> // strlen | |
| #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next, reverse_iterator | |
| #include <limits> // numeric_limits | |
| #include <memory> // unique_ptr | |
| #include <streambuf> // streambuf | |
| #include <string> // string, char_traits | |
| #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer | |
| #include <utility> // declval, move, pair | |
| #include <vector> // vector | |
| #ifndef JSON_NO_IO | |
| #include <cstdio> // FILE * | |
| #include <istream> // istream | |
| #endif // JSON_NO_IO | |
| // #include <nlohmann/detail/exceptions.hpp> | |
| // #include <nlohmann/detail/iterators/iterator_traits.hpp> | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| // #include <nlohmann/detail/string_utils.hpp> | |
| #ifndef JSON_NO_IO | |
| // Which unlocked stdio functions file_input_adapter uses (see | |
| // JSON_DISABLE_UNLOCKED_FILE_IO): 1 = POSIX flockfile/getc_unlocked, | |
| // 2 = Microsoft CRT _lock_file/_fgetc_nolock, 0 = none (std::fgetc, which | |
| // locks the file for every character). Only C libraries known to declare | |
| // the functions are listed; the macros are tested after <cstdio>, which | |
| // defines __GLIBC__. MemorySanitizer builds always use std::fgetc: glibc's | |
| // inline getc_unlocked reads the stdio buffer directly, which glibc (not | |
| // instrumented) filled, so MemorySanitizer would report a false positive. | |
| #if defined(__has_feature) | |
| #if __has_feature(memory_sanitizer) | |
| #define JSON_UNLOCKED_FILE_IO_MSAN 1 | |
| #endif | |
| #endif | |
| #if JSON_DISABLE_UNLOCKED_FILE_IO || defined(JSON_UNLOCKED_FILE_IO_MSAN) | |
| #define JSON_UNLOCKED_FILE_IO 0 | |
| #elif defined(_MSC_VER) | |
| #define JSON_UNLOCKED_FILE_IO 2 | |
| #elif defined(__GLIBC__) || defined(__APPLE__) || defined(__ANDROID__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) | |
| #define JSON_UNLOCKED_FILE_IO 1 | |
| #else | |
| #define JSON_UNLOCKED_FILE_IO 0 | |
| #endif | |
| #undef JSON_UNLOCKED_FILE_IO_MSAN | |
| #endif // JSON_NO_IO | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /// the supported input formats | |
| enum class input_format_t { json, cbor, msgpack, ubjson, bson, bjdata, bon8 }; | |
| /// @return the name of a binary input format, as used in exception messages | |
| inline const char* input_format_name(const input_format_t format) noexcept | |
| { | |
| switch (format) | |
| { | |
| case input_format_t::cbor: | |
| return "CBOR"; | |
| case input_format_t::msgpack: | |
| return "MessagePack"; | |
| case input_format_t::ubjson: | |
| return "UBJSON"; | |
| case input_format_t::bson: | |
| return "BSON"; | |
| case input_format_t::bjdata: | |
| return "BJData"; | |
| case input_format_t::bon8: | |
| return "BON8"; | |
| case input_format_t::json: // LCOV_EXCL_LINE | |
| default: // LCOV_EXCL_LINE | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE | |
| return ""; // LCOV_EXCL_LINE | |
| } | |
| } | |
| /// @return the message of the parse_error thrown or reported for an empty input | |
| inline const char* empty_input_message() noexcept | |
| { | |
| return "attempting to parse an empty input; check that your input string or stream contains the expected JSON"; | |
| } | |
| //////////////////// | |
| // input adapters // | |
| //////////////////// | |
| #ifndef JSON_NO_IO | |
| /*! | |
| A growable array of characters for the part of a token that an input adapter | |
| copied out of its window: unlike std::vector<char>::push_back(), appending a | |
| character takes no reference to a local, and is a few instructions when there | |
| is room. | |
| */ | |
| class token_carry_buffer | |
| { | |
| public: | |
| token_carry_buffer() = default; | |
| token_carry_buffer(const token_carry_buffer&) = delete; | |
| token_carry_buffer& operator=(const token_carry_buffer&) = delete; | |
| token_carry_buffer(token_carry_buffer&& rhs) noexcept | |
| : m_data(std::move(rhs.m_data)), m_end(rhs.m_end), m_capacity_end(rhs.m_capacity_end) | |
| { | |
| rhs.m_end = rhs.m_capacity_end = nullptr; | |
| } | |
| token_carry_buffer& operator=(token_carry_buffer&&) = delete; | |
| ~token_carry_buffer() = default; | |
| void clear() noexcept | |
| { | |
| m_end = m_data.get(); | |
| } | |
| void push_back(char c) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(m_end == m_capacity_end)) | |
| { | |
| grow(1); | |
| } | |
| *m_end++ = c; | |
| } | |
| void append(const char* first, const char* last) | |
| { | |
| const auto n = static_cast<std::size_t>(last - first); | |
| const auto room = static_cast<std::size_t>(m_capacity_end - m_end); | |
| if (n > room) | |
| { | |
| grow(n); | |
| } | |
| if (n != 0) | |
| { | |
| std::memcpy(m_end, first, n); | |
| } | |
| m_end += n; | |
| } | |
| /// replace the contents of @a out | |
| void copy_to(std::vector<char>& out) const | |
| { | |
| out.assign(m_data.get(), m_end); | |
| } | |
| private: | |
| /// make room for @a extra more characters | |
| JSON_HEDLEY_NEVER_INLINE void grow(std::size_t extra) | |
| { | |
| const auto size = static_cast<std::size_t>(m_end - m_data.get()); | |
| const auto capacity = static_cast<std::size_t>(m_capacity_end - m_data.get()); | |
| const std::size_t new_capacity = (std::max)(capacity < 32 ? static_cast<std::size_t>(32) : 2 * capacity, size + extra); | |
| std::unique_ptr<char[]> data(new char[new_capacity]); // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| if (size != 0) | |
| { | |
| std::memcpy(data.get(), m_data.get(), size); | |
| } | |
| m_data = std::move(data); | |
| m_end = m_data.get() + size; | |
| m_capacity_end = m_data.get() + new_capacity; | |
| } | |
| std::unique_ptr<char[]> m_data{}; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays,readability-redundant-member-init) | |
| char* m_end = nullptr; | |
| char* m_capacity_end = nullptr; | |
| }; | |
| /*! | |
| Input adapter for stdio file access. This adapter read only 1 byte and do not use any | |
| buffer. This adapter is a very low level adapter. | |
| */ | |
| class file_input_adapter | |
| { | |
| public: | |
| using char_type = char; | |
| JSON_HEDLEY_NON_NULL(2) | |
| explicit file_input_adapter(std::FILE* f) noexcept | |
| : m_file(f) | |
| { | |
| JSON_ASSERT(m_file != nullptr); | |
| lock(); | |
| } | |
| // make class move-only | |
| file_input_adapter(const file_input_adapter&) = delete; | |
| file_input_adapter(file_input_adapter&& rhs) noexcept | |
| : m_file(rhs.m_file) | |
| { | |
| // the lock is owned by the thread, not the adapter: hand it over | |
| rhs.m_file = nullptr; | |
| } | |
| file_input_adapter& operator=(const file_input_adapter&) = delete; | |
| file_input_adapter& operator=(file_input_adapter&&) = delete; | |
| ~file_input_adapter() | |
| { | |
| unlock(); | |
| } | |
| std::char_traits<char>::int_type get_character() noexcept | |
| { | |
| // the file is locked for the lifetime of the adapter, so the | |
| // per-character lock of std::fgetc can be skipped | |
| #if JSON_UNLOCKED_FILE_IO == 1 | |
| return getc_unlocked(m_file); | |
| #elif JSON_UNLOCKED_FILE_IO == 2 | |
| return _fgetc_nolock(m_file); | |
| #else | |
| return std::fgetc(m_file); | |
| #endif | |
| } | |
| // returns the number of characters successfully read | |
| template<class T> | |
| std::size_t get_elements(T* dest, std::size_t count = 1) | |
| { | |
| return fread(dest, 1, sizeof(T) * count, m_file); | |
| } | |
| private: | |
| // Lock the file once for the whole parse instead of once per character. | |
| // The lock is recursive, so fread() and the user's own stdio calls on the | |
| // same thread keep working. | |
| void lock() noexcept | |
| { | |
| #if JSON_UNLOCKED_FILE_IO == 1 | |
| flockfile(m_file); | |
| #elif JSON_UNLOCKED_FILE_IO == 2 | |
| _lock_file(m_file); | |
| #endif | |
| } | |
| void unlock() noexcept | |
| { | |
| // a moved-from adapter has no file and holds no lock | |
| if (m_file == nullptr) | |
| { | |
| return; | |
| } | |
| #if JSON_UNLOCKED_FILE_IO == 1 | |
| funlockfile(m_file); | |
| #elif JSON_UNLOCKED_FILE_IO == 2 | |
| _unlock_file(m_file); | |
| #endif | |
| } | |
| /// the file pointer to read from | |
| std::FILE* m_file; | |
| }; | |
| /*! | |
| Input adapter for a (caching) istream. Does not skip a UTF Byte Order Mark | |
| itself; that is done by the lexer's skip_bom(). Does not support changing | |
| the underlying std::streambuf | |
| in mid-input. Maintains underlying std::istream and std::streambuf to support | |
| subsequent use of standard std::istream operations to process any input | |
| characters following those used in parsing the JSON input. Clears the | |
| std::istream flags; any input errors (e.g., EOF) will be detected by the first | |
| subsequent call for input from the std::istream. | |
| */ | |
| class input_stream_adapter | |
| { | |
| public: | |
| using char_type = char; | |
| ~input_stream_adapter() | |
| { | |
| // clear stream flags; we use underlying streambuf I/O, do not | |
| // maintain ifstream flags, except eof | |
| if (is != nullptr) | |
| { | |
| #if JSON_PRECISE_STREAM_POSITION | |
| // consume the character last returned by get_character() unless it | |
| // was given back with release_lookahead() | |
| commit_lookahead(); | |
| #endif | |
| // only call clear() if there is something to clear: it throws | |
| // std::ios_base::failure if the stream has exceptions() enabled | |
| // for a state bit that remains set, and a destructor must not throw | |
| if ((is->rdstate() & ~std::ios::eofbit) != 0) | |
| { | |
| is->clear(is->rdstate() & std::ios::eofbit); | |
| } | |
| } | |
| } | |
| explicit input_stream_adapter(std::istream& i) | |
| : is(&i), sb(i.rdbuf()) | |
| {} | |
| // deleted because of pointer members | |
| input_stream_adapter(const input_stream_adapter&) = delete; | |
| input_stream_adapter& operator=(input_stream_adapter&) = delete; | |
| input_stream_adapter& operator=(input_stream_adapter&&) = delete; | |
| input_stream_adapter(input_stream_adapter&& rhs) noexcept | |
| : is(rhs.is), sb(rhs.sb) | |
| #if JSON_PRECISE_STREAM_POSITION | |
| , lookahead(rhs.lookahead) | |
| #endif | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| , token_carry(std::move(rhs.token_carry)) | |
| , token_segment(rhs.token_segment) | |
| , current_in_get_area(rhs.current_in_get_area) | |
| , tracking_token(rhs.tracking_token) | |
| , no_get_area(rhs.no_get_area) | |
| #endif | |
| { | |
| rhs.is = nullptr; | |
| rhs.sb = nullptr; | |
| #if JSON_PRECISE_STREAM_POSITION | |
| rhs.lookahead = false; | |
| #endif | |
| } | |
| #if JSON_PRECISE_STREAM_POSITION | |
| // Whether the character last returned by get_character() can be given back | |
| // to the input with release_lookahead(). | |
| static constexpr bool supports_lookahead = true; | |
| // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to | |
| // ensure that std::char_traits<char>::eof() and the character 0xFF do not | |
| // end up as the same value, e.g., 0xFFFFFFFF. | |
| // | |
| // The character is peeked rather than consumed: it is only stepped over | |
| // once the next character is requested, or when the adapter is destroyed. | |
| // Until then, release_lookahead() can leave it in the input. | |
| std::char_traits<char>::int_type get_character() | |
| { | |
| if (lookahead) | |
| { | |
| // step over the character returned by the previous call | |
| sb->sbumpc(); | |
| } | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| // sgetc() refills the get area if it is exhausted | |
| const bool refill = streambuf_access::get_ptr(sb) == streambuf_access::get_end(sb); | |
| if (JSON_HEDLEY_UNLIKELY(refill)) | |
| { | |
| save_token_segment(); | |
| } | |
| #endif | |
| auto res = sb->sgetc(); | |
| // set eof manually, as we don't use the istream interface. | |
| if (JSON_HEDLEY_UNLIKELY(res == std::char_traits<char>::eof())) | |
| { | |
| // there is nothing to step over next time | |
| lookahead = false; | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| current_in_get_area = false; | |
| #endif | |
| is->clear(is->rdstate() | std::ios::eofbit); | |
| } | |
| else | |
| { | |
| lookahead = true; | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| if (JSON_HEDLEY_UNLIKELY(refill)) | |
| { | |
| // the peeked character is at gptr(), unless the streambuf has | |
| // no get area | |
| after_refill(res, streambuf_access::get_ptr(sb) != streambuf_access::get_end(sb)); | |
| } | |
| else | |
| { | |
| current_in_get_area = true; | |
| } | |
| #endif | |
| } | |
| return res; | |
| } | |
| // Leave the character last returned by get_character() in the input, so | |
| // that the next read from the stream - by this adapter or by the caller | |
| // once parsing is done - sees it again. Unlike putting a consumed | |
| // character back, this cannot fail. | |
| void release_lookahead() noexcept | |
| { | |
| lookahead = false; | |
| } | |
| #else | |
| // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to | |
| // ensure that std::char_traits<char>::eof() and the character 0xFF do not | |
| // end up as the same value, e.g., 0xFFFFFFFF. | |
| // | |
| // The character is consumed, so the character that terminates a number | |
| // stays consumed after parsing; see JSON_PRECISE_STREAM_POSITION. | |
| std::char_traits<char>::int_type get_character() | |
| { | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| // the character is in the get area: step over it, as sbumpc() does | |
| const char* const next = streambuf_access::get_ptr(sb); | |
| if (JSON_HEDLEY_LIKELY(next != streambuf_access::get_end(sb))) | |
| { | |
| current_in_get_area = true; | |
| streambuf_access::bump(sb, 1); | |
| return std::char_traits<char>::to_int_type(*next); | |
| } | |
| if (no_get_area) | |
| { | |
| return get_character_no_get_area(); | |
| } | |
| #endif | |
| return get_character_slow(); | |
| } | |
| #endif | |
| template<class T> | |
| std::size_t get_elements(T* dest, std::size_t count = 1) | |
| { | |
| #if JSON_PRECISE_STREAM_POSITION | |
| commit_lookahead(); | |
| #endif | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| // the elements are in the get area: copy them, as sgetn() does, but | |
| // without the virtual call | |
| const char* const first = streambuf_access::get_ptr(sb); | |
| const auto available = static_cast<std::size_t>(streambuf_access::get_end(sb) - first); | |
| if (JSON_HEDLEY_LIKELY(count * sizeof(T) <= available && count * sizeof(T) <= static_cast<std::size_t>((std::numeric_limits<int>::max)()))) | |
| { | |
| std::memcpy(dest, first, count * sizeof(T)); | |
| streambuf_access::bump(sb, static_cast<int>(count * sizeof(T))); | |
| return count * sizeof(T); | |
| } | |
| #endif | |
| auto res = static_cast<std::size_t>(sb->sgetn(reinterpret_cast<char*>(dest), static_cast<std::streamsize>(count * sizeof(T)))); | |
| if (JSON_HEDLEY_UNLIKELY(res < count * sizeof(T))) | |
| { | |
| is->clear(is->rdstate() | std::ios::eofbit); | |
| } | |
| return res; | |
| } | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| // The lexer may scan the characters in the get area of the streambuf | |
| // directly (SWAR fast paths). The get area is only a window into the | |
| // input: it ends wherever the streambuf's buffer ends, and is refilled by | |
| // the next get_character(). The lexer therefore keeps counting the | |
| // position itself and treats the end of the window as "unknown", not as | |
| // the end of the input. | |
| static constexpr bool supports_bulk_scan = true; | |
| static constexpr bool bulk_window = true; | |
| // Pointer to the next unread character; only valid when | |
| // bulk_remaining() > 0. The character before it is the one last returned | |
| // by get_character(). | |
| const char* bulk_data() const | |
| { | |
| return current_end(); | |
| } | |
| // Number of unread characters in the get area. | |
| std::size_t bulk_remaining() const | |
| { | |
| if (!current_in_get_area) | |
| { | |
| return 0; | |
| } | |
| return static_cast<std::size_t>(streambuf_access::get_end(sb) - current_end()); | |
| } | |
| // Consume @a n characters previously inspected via bulk_data(); the last | |
| // of them becomes the character last returned by get_character(). | |
| void bulk_skip(std::size_t n) | |
| { | |
| JSON_ASSERT(n <= bulk_remaining()); | |
| // gbump() takes an int, but a get area (e.g., of a std::stringbuf) can | |
| // be larger | |
| constexpr auto max_bump = static_cast<std::size_t>((std::numeric_limits<int>::max)()); | |
| for (; n > max_bump; n -= max_bump) | |
| { | |
| streambuf_access::bump(sb, static_cast<int>(max_bump)); | |
| } | |
| streambuf_access::bump(sb, static_cast<int>(n)); | |
| } | |
| // The adapter keeps the current token for the lexer's error messages: the | |
| // part in the get area is only remembered as a pointer, and copied out | |
| // when the get area is about to be refilled. | |
| static constexpr bool supports_token_tracking = true; | |
| // Start a token with the characters read from now on. Until this is | |
| // called, nothing is tracked (the binary readers never call it). | |
| void begin_token() noexcept | |
| { | |
| tracking_token = true; | |
| token_carry.clear(); | |
| token_segment = current_end(); | |
| } | |
| // Start a new token with the character @a c last returned by | |
| // get_character(). | |
| void mark_token_start(std::char_traits<char>::int_type c) | |
| { | |
| tracking_token = true; | |
| token_carry.clear(); | |
| if (current_in_get_area) | |
| { | |
| token_segment = current_end() - 1; | |
| } | |
| else | |
| { | |
| token_segment = nullptr; | |
| token_carry.push_back(std::char_traits<char>::to_char_type(c)); | |
| } | |
| } | |
| // Copy the characters read since mark_token_start() to @a out, without the | |
| // last one if @a drop_last. | |
| void copy_token(std::vector<char>& out, bool drop_last) const | |
| { | |
| token_carry.copy_to(out); | |
| if (token_segment != nullptr) | |
| { | |
| out.insert(out.end(), token_segment, current_end()); | |
| } | |
| if (drop_last && !out.empty()) | |
| { | |
| out.pop_back(); | |
| } | |
| } | |
| #endif | |
| private: | |
| #if !JSON_PRECISE_STREAM_POSITION | |
| // the get area is exhausted, or there is none | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| JSON_HEDLEY_NEVER_INLINE | |
| #endif | |
| std::char_traits<char>::int_type get_character_slow() | |
| { | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| // sbumpc() refills the get area if it is exhausted | |
| const bool refill = streambuf_access::get_ptr(sb) == streambuf_access::get_end(sb); | |
| if (JSON_HEDLEY_UNLIKELY(refill)) | |
| { | |
| save_token_segment(); | |
| } | |
| #endif | |
| auto res = sb->sbumpc(); | |
| // set eof manually, as we don't use the istream interface. | |
| if (JSON_HEDLEY_UNLIKELY(res == std::char_traits<char>::eof())) | |
| { | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| current_in_get_area = false; | |
| #endif | |
| is->clear(is->rdstate() | std::ios::eofbit); | |
| } | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| else if (JSON_HEDLEY_UNLIKELY(refill)) | |
| { | |
| // the consumed character is at gptr() - 1, unless the streambuf | |
| // has no get area and returned it from uflow() | |
| const char* const next = streambuf_access::get_ptr(sb); | |
| after_refill(res, next != nullptr && next != streambuf_access::get_begin(sb)); | |
| } | |
| else | |
| { | |
| current_in_get_area = true; | |
| } | |
| #endif | |
| return res; | |
| } | |
| #endif | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| // Reads the protected get-area pointers of any std::streambuf. Naming the | |
| // members through a derived class makes forming the member pointers | |
| // accessible; calling them on another streambuf object is then ordinary | |
| // member access through a pointer to member. | |
| struct streambuf_access : std::streambuf | |
| { | |
| static const char* get_ptr(std::streambuf* s) | |
| { | |
| return (s->*(&streambuf_access::gptr))(); | |
| } | |
| static const char* get_end(std::streambuf* s) | |
| { | |
| return (s->*(&streambuf_access::egptr))(); | |
| } | |
| static const char* get_begin(std::streambuf* s) | |
| { | |
| return (s->*(&streambuf_access::eback))(); | |
| } | |
| static void bump(std::streambuf* s, int n) | |
| { | |
| (s->*(&streambuf_access::gbump))(n); | |
| } | |
| // sbumpc() for an exhausted get area | |
| static std::streambuf::int_type next_character(std::streambuf* s) | |
| { | |
| return (s->*(&streambuf_access::uflow))(); | |
| } | |
| }; | |
| // one past the character last returned by get_character(), if that is in | |
| // the get area | |
| const char* current_end() const | |
| { | |
| #if JSON_PRECISE_STREAM_POSITION | |
| // the character is peeked at gptr() and not stepped over yet, unless | |
| // it was given back with release_lookahead() | |
| return streambuf_access::get_ptr(sb) + (lookahead ? 1 : 0); | |
| #else | |
| return streambuf_access::get_ptr(sb); | |
| #endif | |
| } | |
| // the get area is about to be replaced: copy the token's part in it | |
| void save_token_segment() | |
| { | |
| if (token_segment != nullptr) | |
| { | |
| token_carry.append(token_segment, streambuf_access::get_end(sb)); | |
| token_segment = nullptr; | |
| } | |
| } | |
| #if !JSON_PRECISE_STREAM_POSITION | |
| // The streambuf has no get area (e.g., std::cin synchronized with stdio): | |
| // every character comes from uflow(), and the token is kept by value. | |
| JSON_HEDLEY_NEVER_INLINE std::char_traits<char>::int_type get_character_no_get_area() | |
| { | |
| // the get area is exhausted, so this is what sbumpc() does | |
| const auto res = streambuf_access::next_character(sb); | |
| if (JSON_HEDLEY_UNLIKELY(res == std::char_traits<char>::eof() || streambuf_access::get_end(sb) != nullptr)) | |
| { | |
| return get_character_no_get_area_other(res); | |
| } | |
| // current_in_get_area is false: only the first character of a get | |
| // area, or the end of the input, is read here | |
| if (tracking_token) | |
| { | |
| token_carry.push_back(std::char_traits<char>::to_char_type(res)); | |
| } | |
| return res; | |
| } | |
| // @a res came from uflow() of a streambuf without a get area: it is the | |
| // end of the input, or the streambuf has a get area now | |
| JSON_HEDLEY_NEVER_INLINE std::char_traits<char>::int_type get_character_no_get_area_other(std::char_traits<char>::int_type res) | |
| { | |
| if (res == std::char_traits<char>::eof()) | |
| { | |
| current_in_get_area = false; | |
| is->clear(is->rdstate() | std::ios::eofbit); | |
| return res; | |
| } | |
| // the consumed character is at gptr() - 1 | |
| after_refill(res, streambuf_access::get_ptr(sb) != streambuf_access::get_begin(sb)); | |
| return res; | |
| } | |
| #endif | |
| // character @a c was just read into a new get area (@a in_get_area) or | |
| // returned without one | |
| void after_refill(std::char_traits<char>::int_type c, bool in_get_area) | |
| { | |
| current_in_get_area = in_get_area; | |
| no_get_area = !in_get_area; | |
| if (!tracking_token) | |
| { | |
| return; | |
| } | |
| if (in_get_area) | |
| { | |
| token_segment = current_end() - 1; | |
| } | |
| else | |
| { | |
| token_carry.push_back(std::char_traits<char>::to_char_type(c)); | |
| } | |
| } | |
| #endif | |
| #if JSON_PRECISE_STREAM_POSITION | |
| // Step over the character last returned by get_character(). The character | |
| // has already been peeked successfully, so for every streambuf with a get | |
| // area this is a pointer increment that cannot fail. | |
| void commit_lookahead() | |
| { | |
| if (lookahead) | |
| { | |
| lookahead = false; | |
| sb->sbumpc(); | |
| } | |
| } | |
| #endif | |
| /// the associated input stream | |
| std::istream* is = nullptr; | |
| std::streambuf* sb = nullptr; | |
| #if JSON_PRECISE_STREAM_POSITION | |
| /// whether get_character() peeked a character that is not consumed yet | |
| bool lookahead = false; | |
| #endif | |
| #if !JSON_DISABLE_STREAM_BULK_SCAN | |
| /// the part of the current token that was in earlier get areas | |
| token_carry_buffer token_carry{}; // NOLINT(readability-redundant-member-init) | |
| /// start of the current token's part in the get area, or nullptr | |
| const char* token_segment = nullptr; | |
| /// whether the character last returned by get_character() is in the get area | |
| bool current_in_get_area = false; | |
| /// whether a token is tracked at all; the binary readers never start one | |
| bool tracking_token = false; | |
| /// whether the streambuf had no get area when it was last asked for a | |
| /// character | |
| bool no_get_area = false; | |
| #endif | |
| }; | |
| #endif // JSON_NO_IO | |
| // General-purpose iterator-based adapter. It might not be as fast as | |
| // theoretically possible for some containers, but it is extremely versatile. | |
| // SentinelType defaults to IteratorType for backward compatibility, but may be | |
| // a different type, e.g. a C++20 sentinel such as std::default_sentinel_t when | |
| // IteratorType is a std::counted_iterator. | |
| template<typename IteratorType, typename SentinelType = IteratorType> | |
| class iterator_input_adapter | |
| { | |
| // Whether the number of elements between two positions can be computed in | |
| // O(1): either the iterator and the sentinel have the same type (plain | |
| // std::distance) or, in C++20, the sentinel is a sized sentinel for the | |
| // iterator (std::ranges::distance), e.g. std::default_sentinel_t paired | |
| // with std::counted_iterator. | |
| // | |
| // JSON_HAS_RANGES gates the C++20 branch: on standard libraries with an | |
| // incomplete <ranges> (libstdc++ < 11, see #4440) evaluating | |
| // std::contiguous_iterator on a std::counted_iterator is a hard error | |
| // instead of yielding false, and these traits are instantiated for every | |
| // adapter. Such toolchains fall back to the pointer-only test and simply | |
| // use the byte-at-a-time scanner. | |
| static constexpr bool sentinel_is_sized = | |
| #if JSON_HAS_RANGES && defined(__cpp_lib_concepts) && defined(JSON_HAS_CPP_20) | |
| std::is_same<IteratorType, SentinelType>::value || std::sized_sentinel_for<SentinelType, IteratorType>; | |
| #else | |
| std::is_same<IteratorType, SentinelType>::value; | |
| #endif | |
| public: | |
| using char_type = typename std::iterator_traits<IteratorType>::value_type; | |
| // Whether the lexer may reconstruct already-consumed input on demand (for | |
| // diagnostics) instead of copying every scanned character eagerly. This is | |
| // only sound for multi-pass, randomly-addressable byte input: the iterator | |
| // must be random-access (so the consumed prefix can be revisited in O(1)) | |
| // and each element must map 1:1 to an input byte (wide inputs are wrapped | |
| // in wide_string_input_adapter, which does not expose this). | |
| static constexpr bool supports_seek = | |
| std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value | |
| && sentinel_is_sized | |
| && sizeof(char_type) == 1; | |
| iterator_input_adapter(IteratorType first, SentinelType last) | |
| : begin(first), current(std::move(first)), end(std::move(last)) | |
| {} | |
| typename char_traits<char_type>::int_type get_character() | |
| { | |
| if (JSON_HEDLEY_LIKELY(current != end)) | |
| { | |
| auto result = char_traits<char_type>::to_int_type(*current); | |
| std::advance(current, 1); | |
| return result; | |
| } | |
| ++eof_reads; | |
| return char_traits<char_type>::eof(); | |
| } | |
| // number of characters consumed from the input so far | |
| std::size_t get_consumed_count() const | |
| { | |
| return static_cast<std::size_t>(std::distance(begin, current)); | |
| } | |
| // number of get_character() calls so far, including those that returned | |
| // EOF; the lexer derives its position from it (see lexer::lazy_position) | |
| std::size_t get_read_count() const | |
| { | |
| return get_consumed_count() + eof_reads; | |
| } | |
| // number of newlines in the consumed range [0, last_index); @a line_start | |
| // is set to the index after the last of them (0 if there is none); only | |
| // valid when supports_seek | |
| std::size_t count_consumed_lines(std::size_t last_index, std::size_t& line_start) const | |
| { | |
| const auto to = std::next(begin, static_cast<typename std::iterator_traits<IteratorType>::difference_type>(last_index)); | |
| const auto newline = char_traits<char_type>::to_char_type('\n'); | |
| using reverse_it = std::reverse_iterator<IteratorType>; | |
| const auto last_newline = std::find(reverse_it(to), reverse_it(begin), newline); | |
| line_start = static_cast<std::size_t>(std::distance(begin, last_newline.base())); | |
| return static_cast<std::size_t>(std::count(begin, last_newline.base(), newline)); | |
| } | |
| // append the already-consumed characters in the half-open range | |
| // [first_index, last_index) to @a out; only valid when supports_seek | |
| template<typename ContainerType> | |
| void copy_consumed_range(std::size_t first_index, std::size_t last_index, ContainerType& out) const | |
| { | |
| const auto from = std::next(begin, static_cast<typename std::iterator_traits<IteratorType>::difference_type>(first_index)); | |
| const auto to = std::next(begin, static_cast<typename std::iterator_traits<IteratorType>::difference_type>(last_index)); | |
| out.insert(out.end(), from, to); | |
| } | |
| // Copy up to count * sizeof(T) bytes into dest, returning the number of | |
| // bytes actually read. For contiguous iterators (e.g. pointers) this is a | |
| // single std::memcpy; for general iterators we fall back to processing the | |
| // range one-by-one. | |
| template<class T> | |
| std::size_t get_elements(T* dest, std::size_t count = 1) | |
| { | |
| return get_elements_impl(dest, count, std::integral_constant<bool, iterator_is_contiguous> {}); | |
| } | |
| private: | |
| // whether IteratorType refers to a contiguous range and therefore supports | |
| // a std::memcpy fast path (pointers always do; in C++20 we can also detect | |
| // library iterators such as those of std::vector and std::string). The | |
| // available element count must also be computable in O(1), hence | |
| // sentinel_is_sized. | |
| static constexpr bool iterator_is_contiguous = sentinel_is_sized && | |
| #if JSON_HAS_RANGES && defined(__cpp_lib_concepts) && defined(JSON_HAS_CPP_20) | |
| (std::contiguous_iterator<IteratorType> || std::is_pointer<IteratorType>::value); | |
| #else | |
| std::is_pointer<IteratorType>::value; | |
| #endif | |
| // number of unread elements in [current, end) | |
| std::size_t remaining_count() const | |
| { | |
| #if JSON_HAS_RANGES && defined(__cpp_lib_concepts) && defined(JSON_HAS_CPP_20) | |
| // std::ranges::distance also supports sized sentinels of a different | |
| // type (e.g. std::counted_iterator + std::default_sentinel_t) | |
| return static_cast<std::size_t>(std::ranges::distance(current, end)); | |
| #else | |
| return static_cast<std::size_t>(std::distance(current, end)); | |
| #endif | |
| } | |
| public: | |
| // Whether the remaining input is a single contiguous block of 1-byte | |
| // elements that the lexer can inspect directly (used for the SWAR string | |
| // fast path). | |
| static constexpr bool supports_bulk_scan = | |
| iterator_is_contiguous && sizeof(char_type) == 1; | |
| // Pointer to the next unread element; only valid when bulk_remaining() > 0. | |
| const char_type* bulk_data() const | |
| { | |
| return &*current; | |
| } | |
| // Number of unread elements available as one contiguous block. | |
| std::size_t bulk_remaining() const | |
| { | |
| return remaining_count(); | |
| } | |
| // Consume @a n elements previously inspected via bulk_data(). | |
| void bulk_skip(std::size_t n) | |
| { | |
| std::advance(current, static_cast<typename std::iterator_traits<IteratorType>::difference_type>(n)); | |
| } | |
| private: | |
| // contiguous fast path: bulk copy the remaining range with std::memcpy | |
| template<class T> | |
| std::size_t get_elements_impl(T* dest, std::size_t count, std::true_type /*contiguous*/) | |
| { | |
| const std::size_t wanted = count * sizeof(T); | |
| const std::size_t available = remaining_count() * sizeof(char_type); | |
| const std::size_t copied = (std::min)(wanted, available); | |
| if (JSON_HEDLEY_LIKELY(copied != 0)) | |
| { | |
| // the copy must stay within both buffers: the caller-provided | |
| // destination holds `wanted` bytes and the remaining input range | |
| // holds `available` bytes, and `copied` is the minimum of the two | |
| JSON_ASSERT(copied <= wanted); // does not overrun the destination | |
| JSON_ASSERT(copied <= available); // does not read past the input end | |
| // &*current yields the raw address for both raw pointers and | |
| // non-pointer contiguous iterators (e.g. std::vector's iterator) | |
| std::memcpy(dest, &*current, copied); | |
| std::advance(current, static_cast<typename std::iterator_traits<IteratorType>::difference_type>(copied / sizeof(char_type))); | |
| } | |
| return copied; | |
| } | |
| // general fallback: copy the range one element at a time | |
| template<class T> | |
| std::size_t get_elements_impl(T* dest, std::size_t count, std::false_type /*contiguous*/) | |
| { | |
| auto* ptr = reinterpret_cast<char*>(dest); | |
| for (std::size_t read_index = 0; read_index < count * sizeof(T); ++read_index) | |
| { | |
| if (JSON_HEDLEY_LIKELY(current != end)) | |
| { | |
| ptr[read_index] = static_cast<char>(*current); | |
| std::advance(current, 1); | |
| } | |
| else | |
| { | |
| return read_index; | |
| } | |
| } | |
| return count * sizeof(T); | |
| } | |
| IteratorType begin; | |
| IteratorType current; | |
| SentinelType end; | |
| /// number of get_character() calls that returned EOF | |
| std::size_t eof_reads = 0; | |
| template<typename BaseInputAdapter, size_t T> | |
| friend struct wide_string_input_helper; | |
| bool empty() const | |
| { | |
| return current == end; | |
| } | |
| }; | |
| template<typename BaseInputAdapter, size_t T> | |
| struct wide_string_input_helper; | |
| template<typename BaseInputAdapter> | |
| struct wide_string_input_helper<BaseInputAdapter, 4> | |
| { | |
| // UTF-32 | |
| static void fill_buffer(BaseInputAdapter& input, | |
| std::array<std::char_traits<char>::int_type, 4>& utf8_bytes, | |
| size_t& utf8_bytes_index, | |
| size_t& utf8_bytes_filled) | |
| { | |
| utf8_bytes_index = 0; | |
| if (JSON_HEDLEY_UNLIKELY(input.empty())) | |
| { | |
| utf8_bytes[0] = std::char_traits<char>::eof(); | |
| utf8_bytes_filled = 1; | |
| } | |
| else | |
| { | |
| // get the current character; converted to an unsigned type so that | |
| // a negative unit (wint_t is signed on some platforms) is not | |
| // mistaken for an ASCII character or for EOF | |
| const auto wc = static_cast<std::uint32_t>(input.get_character()); | |
| if (wc <= 0x10FFFF) | |
| { | |
| // UTF-32 to UTF-8 encoding | |
| utf8_bytes_filled = 0; | |
| encode_utf8(static_cast<std::uint32_t>(wc), [&utf8_bytes, &utf8_bytes_filled](std::uint32_t byte) | |
| { | |
| utf8_bytes[utf8_bytes_filled++] = static_cast<std::char_traits<char>::int_type>(byte); | |
| }); | |
| } | |
| else | |
| { | |
| // A code point above U+10FFFF has no UTF-8 encoding. Passing the | |
| // unit through would narrow it to int, where 0xFFFFFFFF becomes | |
| // char_traits<char>::eof() and would end the input silently, so | |
| // emit a byte that is never valid UTF-8 and let the decoder | |
| // reject it. | |
| utf8_bytes[0] = 0xFF; | |
| utf8_bytes_filled = 1; | |
| } | |
| } | |
| } | |
| }; | |
| template<typename BaseInputAdapter> | |
| struct wide_string_input_helper<BaseInputAdapter, 2> | |
| { | |
| // UTF-16 | |
| static void fill_buffer(BaseInputAdapter& input, | |
| std::array<std::char_traits<char>::int_type, 4>& utf8_bytes, | |
| size_t& utf8_bytes_index, | |
| size_t& utf8_bytes_filled) | |
| { | |
| utf8_bytes_index = 0; | |
| if (JSON_HEDLEY_UNLIKELY(input.empty())) | |
| { | |
| utf8_bytes[0] = std::char_traits<char>::eof(); | |
| utf8_bytes_filled = 1; | |
| } | |
| else | |
| { | |
| // get the current character | |
| const auto wc = input.get_character(); | |
| if (0xD800 > wc || wc >= 0xE000) | |
| { | |
| // a UTF-16 code unit outside the surrogate range is a valid | |
| // code point (at most U+FFFF) on its own | |
| utf8_bytes_filled = 0; | |
| encode_utf8(static_cast<std::uint32_t>(wc), [&utf8_bytes, &utf8_bytes_filled](std::uint32_t byte) | |
| { | |
| utf8_bytes[utf8_bytes_filled++] = static_cast<std::char_traits<char>::int_type>(byte); | |
| }); | |
| } | |
| else | |
| { | |
| // A supplementary code point is a high surrogate (0xD800..0xDBFF) | |
| // followed by a low surrogate (0xDC00..0xDFFF). A lone low | |
| // surrogate, a high surrogate at the end of the input, or a high | |
| // surrogate followed by any other unit is malformed UTF-16. In | |
| // that case the offending unit is passed through unchanged so the | |
| // UTF-8 decoder rejects it, matching how \uXXXX surrogate escapes | |
| // are handled in the lexer. | |
| bool valid_pair = false; | |
| if (wc <= 0xDBFF && JSON_HEDLEY_UNLIKELY(!input.empty())) | |
| { | |
| // only consume the next unit if it completes the pair | |
| const auto wc2 = static_cast<unsigned int>(*input.current); | |
| if (0xDC00 <= wc2 && wc2 <= 0xDFFF) | |
| { | |
| input.get_character(); | |
| const auto charcode = 0x10000u + (((static_cast<unsigned int>(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu)); | |
| utf8_bytes_filled = 0; | |
| encode_utf8(charcode, [&utf8_bytes, &utf8_bytes_filled](std::uint32_t byte) | |
| { | |
| utf8_bytes[utf8_bytes_filled++] = static_cast<std::char_traits<char>::int_type>(byte); | |
| }); | |
| valid_pair = true; | |
| } | |
| } | |
| if (!valid_pair) | |
| { | |
| // emit a byte that is never valid UTF-8 (see the UTF-32 case) | |
| utf8_bytes[0] = 0xFF; | |
| utf8_bytes_filled = 1; | |
| } | |
| } | |
| } | |
| } | |
| }; | |
| // Wraps another input adapter to convert wide character types into individual bytes. | |
| template<typename BaseInputAdapter, typename WideCharType> | |
| class wide_string_input_adapter | |
| { | |
| public: | |
| using char_type = char; | |
| wide_string_input_adapter(BaseInputAdapter base) | |
| : base_adapter(base) {} | |
| typename std::char_traits<char>::int_type get_character() noexcept | |
| { | |
| // check if the buffer needs to be filled | |
| if (utf8_bytes_index == utf8_bytes_filled) | |
| { | |
| fill_buffer<sizeof(WideCharType)>(); | |
| JSON_ASSERT(utf8_bytes_filled > 0); | |
| JSON_ASSERT(utf8_bytes_index == 0); | |
| } | |
| // use buffer | |
| JSON_ASSERT(utf8_bytes_filled > 0); | |
| JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled); | |
| return utf8_bytes[utf8_bytes_index++]; | |
| } | |
| // parsing binary with wchar doesn't make sense, but since the parsing mode can be runtime, we need something here | |
| template<class T> | |
| JSON_HEDLEY_NO_RETURN std::size_t get_elements(T* /*dest*/, std::size_t /*count*/ = 1) | |
| { | |
| JSON_THROW(parse_error::create(exception_id::unexpected_byte, 1, "wide string type cannot be interpreted as binary data", nullptr)); | |
| } | |
| private: | |
| BaseInputAdapter base_adapter; | |
| template<size_t T> | |
| void fill_buffer() | |
| { | |
| wide_string_input_helper<BaseInputAdapter, T>::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled); | |
| } | |
| /// a buffer for UTF-8 bytes | |
| std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; | |
| /// index to the utf8_codes array for the next valid byte | |
| std::size_t utf8_bytes_index = 0; | |
| /// number of valid bytes in the utf8_codes array | |
| std::size_t utf8_bytes_filled = 0; | |
| }; | |
| template<typename IteratorType, typename SentinelType = IteratorType, typename Enable = void> | |
| struct iterator_input_adapter_factory | |
| { | |
| using iterator_type = IteratorType; | |
| using sentinel_type = SentinelType; | |
| using char_type = typename std::iterator_traits<iterator_type>::value_type; | |
| using adapter_type = iterator_input_adapter<iterator_type, sentinel_type>; | |
| static adapter_type create(IteratorType first, SentinelType last) | |
| { | |
| return adapter_type(std::move(first), std::move(last)); | |
| } | |
| }; | |
| // Detection: whether IteratorType and SentinelType can be compared with != | |
| template<typename IteratorType, typename SentinelType, typename = void> | |
| struct can_compare_ne_impl : std::false_type {}; | |
| template<typename IteratorType, typename SentinelType> | |
| struct can_compare_ne_impl < IteratorType, SentinelType, | |
| void_t < decltype(std::declval<IteratorType>() != std::declval<SentinelType>()) >> | |
| : std::true_type {}; | |
| // Workaround for reversed operator order | |
| template<typename IteratorType, typename SentinelType, typename = void> | |
| struct can_compare_ne_reversed : std::false_type {}; | |
| template<typename IteratorType, typename SentinelType> | |
| struct can_compare_ne_reversed < IteratorType, SentinelType, | |
| void_t < decltype(std::declval<SentinelType>() != std::declval<IteratorType>()) >> | |
| : std::true_type {}; | |
| template<typename IteratorType, typename SentinelType> | |
| struct can_compare_ne_either_order : std::integral_constant < bool, | |
| can_compare_ne_impl<IteratorType, SentinelType>::value || | |
| can_compare_ne_reversed<IteratorType, SentinelType>::value > {}; | |
| // std::nullptr_t is excluded explicitly: a literal `nullptr` passed as a | |
| // trailing default argument (e.g. parse(s, nullptr, ...)) must never be | |
| // mistaken for a sentinel, and some compilers (e.g. GCC 4.8) unreliably | |
| // SFINAE the `operator!=` detection above for std::nullptr_t against | |
| // container/string types, which would otherwise make such calls ambiguous | |
| // with the compatible-input overload. | |
| template<typename IteratorType, typename SentinelType> | |
| struct can_compare_ne : std::integral_constant < bool, | |
| !std::is_same<SentinelType, std::nullptr_t>::value && | |
| can_compare_ne_either_order<IteratorType, SentinelType>::value > {}; | |
| template<typename T> | |
| struct is_iterator_of_multibyte | |
| { | |
| using value_type = typename std::iterator_traits<T>::value_type; | |
| enum // NOLINT(cppcoreguidelines-use-enum-class) | |
| { | |
| value = sizeof(value_type) > 1 | |
| }; | |
| }; | |
| template<typename IteratorType, typename SentinelType> | |
| struct iterator_input_adapter_factory<IteratorType, SentinelType, enable_if_t<is_iterator_of_multibyte<IteratorType>::value>> | |
| { | |
| using iterator_type = IteratorType; | |
| using sentinel_type = SentinelType; | |
| using char_type = typename std::iterator_traits<iterator_type>::value_type; | |
| using base_adapter_type = iterator_input_adapter<iterator_type, sentinel_type>; | |
| using adapter_type = wide_string_input_adapter<base_adapter_type, char_type>; | |
| static adapter_type create(IteratorType first, SentinelType last) | |
| { | |
| return adapter_type(base_adapter_type(std::move(first), std::move(last))); | |
| } | |
| }; | |
| // General purpose iterator-based input (iterator+sentinel pair; SentinelType | |
| // defaults to IteratorType for the common same-type case, but may differ for | |
| // C++20 ranges-style iterator+sentinel pairs). Only enable for types that can | |
| // be compared with !=. | |
| template < typename IteratorType, typename SentinelType = IteratorType, | |
| typename = typename std::enable_if < | |
| can_compare_ne<IteratorType, SentinelType>::value >::type > | |
| typename iterator_input_adapter_factory<IteratorType, SentinelType>::adapter_type input_adapter(IteratorType first, SentinelType last) | |
| { | |
| using factory_type = iterator_input_adapter_factory<IteratorType, SentinelType>; | |
| return factory_type::create(first, last); | |
| } | |
| // The element type a container's data() points at, cv-qualifiers removed. | |
| // Ill-formed - and therefore SFINAE-friendly - for types without data(). | |
| template<typename ContainerType> | |
| using container_data_t = typename std::remove_cv<typename std::remove_pointer < | |
| decltype(std::declval<const ContainerType&>().data()) >::type >::type; | |
| // The container's own element type, cv-qualifiers removed. It is looked up on | |
| // the bare type so it is also found when ContainerType is deduced as a | |
| // reference by the forwarding-reference overload below. | |
| template<typename ContainerType> | |
| using container_value_t = typename std::remove_cv < | |
| typename std::remove_cv<typename std::remove_reference<ContainerType>::type>::type::value_type >::type; | |
| // Detect a container that stores its elements contiguously as single bytes | |
| // (std::string, std::vector<char/unsigned char>, std::array<char, N>, | |
| // std::string_view, ...). Such inputs are wrapped in a pointer-based adapter so | |
| // they benefit from the contiguous fast paths (bulk string scanning, memcpy for | |
| // binary formats) in every C++ standard - not only in C++20, where the standard | |
| // library iterators model std::contiguous_iterator and are detected directly. | |
| // | |
| // data() and size() on their own would be duck typing: they say nothing about | |
| // size() counting the units data() points at, and reading [data(), data() + | |
| // size()) as bytes would be wrong for a type where it does not. Requiring the | |
| // container's own value_type to be that same single-byte element ties the two | |
| // together; every contiguous standard container satisfies it. Anything else | |
| // keeps the iterator-based adapter, which is always correct - only slower. | |
| template<typename ContainerType, typename = void> | |
| struct is_contiguous_byte_container : std::false_type {}; | |
| template<typename ContainerType> | |
| struct is_contiguous_byte_container < ContainerType, void_t < | |
| container_data_t<ContainerType>, | |
| container_value_t<ContainerType>, | |
| decltype(std::declval<const ContainerType&>().size()) >> | |
| : std::integral_constant < bool, | |
| std::is_pointer<decltype(std::declval<const ContainerType&>().data())>::value&& | |
| std::is_integral<container_data_t<ContainerType>>::value&& | |
| sizeof(container_data_t<ContainerType>) == 1 && | |
| std::is_same<container_data_t<ContainerType>, container_value_t<ContainerType>>::value > {}; | |
| // Convenience shorthand from container to iterator | |
| // Enables ADL on begin(container) and end(container) | |
| // Encloses the using declarations in namespace for not to leak them to outside scope | |
| namespace container_input_adapter_factory_impl | |
| { | |
| using std::begin; | |
| using std::end; | |
| template<typename ContainerType, typename Enable = void> | |
| struct container_input_adapter_factory {}; | |
| template<typename ContainerType> | |
| struct container_input_adapter_factory< ContainerType, | |
| void_t<decltype(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>()))>> | |
| { | |
| using adapter_type = decltype(input_adapter(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>()))); | |
| static adapter_type create(ContainerType&& container) | |
| { | |
| // container is forwarded twice on purpose: the resulting begin/end | |
| // iterator types must match adapter_type, computed the same way | |
| // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved) | |
| return input_adapter(begin(std::forward<ContainerType>(container)), end(std::forward<ContainerType>(container))); | |
| } | |
| }; | |
| } // namespace container_input_adapter_factory_impl | |
| // General container path (iterator-based). Contiguous single-byte containers | |
| // are excluded here and routed through the pointer-based overload below. | |
| template < typename ContainerType, | |
| enable_if_t < !is_contiguous_byte_container<ContainerType>::value, int > = 0 > | |
| typename container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::adapter_type input_adapter(ContainerType && container) | |
| { | |
| return container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::create(std::forward<ContainerType>(container)); | |
| } | |
| // Contiguous single-byte containers (std::string, std::vector<char>, ...) are | |
| // wrapped in a pointer-based adapter so the contiguous fast paths apply in every | |
| // standard. The pointer keeps the container's own element type (const char* for | |
| // std::string, const std::uint8_t* for std::vector<std::uint8_t>, ...), so the | |
| // resulting char_type - and therefore the parsing behavior - is byte-for-byte | |
| // identical to the iterator-based path; only the raw pointer additionally | |
| // enables the bulk fast paths. The container outlives the adapter for the whole | |
| // parse (temporaries live until the end of the full expression), exactly as the | |
| // iterators it replaces did. | |
| template < typename ContainerType, | |
| enable_if_t < is_contiguous_byte_container<ContainerType>::value, int > = 0 > | |
| auto input_adapter(const ContainerType& container) | |
| -> decltype(input_adapter(container.data(), container.data() + container.size())) | |
| { | |
| return input_adapter(container.data(), container.data() + container.size()); | |
| } | |
| // specialization for std::string | |
| using string_input_adapter_type = decltype(input_adapter(std::declval<std::string>())); | |
| #ifndef JSON_NO_IO | |
| // Special cases with fast paths | |
| inline file_input_adapter input_adapter(std::FILE* file) | |
| { | |
| if (file == nullptr) | |
| { | |
| JSON_THROW(parse_error::create(exception_id::syntax_error, 0, empty_input_message(), nullptr)); | |
| } | |
| return file_input_adapter(file); | |
| } | |
| inline input_stream_adapter input_adapter(std::istream& stream) | |
| { | |
| if (stream.rdbuf() == nullptr) | |
| { | |
| JSON_THROW(parse_error::create(exception_id::syntax_error, 0, empty_input_message(), nullptr)); | |
| } | |
| return input_stream_adapter(stream); | |
| } | |
| inline input_stream_adapter input_adapter(std::istream&& stream) | |
| { | |
| return input_adapter(stream); | |
| } | |
| #endif // JSON_NO_IO | |
| using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval<const char*>(), std::declval<const char*>())); | |
| // Null-delimited strings, and the like. | |
| template < typename CharT, | |
| typename std::enable_if < | |
| std::is_pointer<CharT>::value&& | |
| !std::is_array<CharT>::value&& | |
| std::is_integral<typename std::remove_pointer<CharT>::type>::value&& | |
| sizeof(typename std::remove_pointer<CharT>::type) == 1, | |
| int >::type = 0 > | |
| contiguous_bytes_input_adapter input_adapter(CharT b) | |
| { | |
| if (b == nullptr) | |
| { | |
| JSON_THROW(parse_error::create(exception_id::syntax_error, 0, empty_input_message(), nullptr)); | |
| } | |
| auto length = std::strlen(reinterpret_cast<const char*>(b)); | |
| const auto* ptr = reinterpret_cast<const char*>(b); | |
| return input_adapter(ptr, ptr + length); // cppcheck-suppress[nullPointerArithmeticRedundantCheck] | |
| } | |
| template<typename T, std::size_t N> | |
| auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| { | |
| #if JSON_STRICT_NUL_HANDLING | |
| // A text-literal array from string-literal initialization (e.g. | |
| // json::parse("123") or json::parse(L"123")) carries a trailing '\0' | |
| // contributed by the compiler, not by the source text; drop exactly that | |
| // one byte so it is not mistaken for real trailing data. This covers all | |
| // character types that string literals can use: char, wchar_t, char16_t, | |
| // char32_t, and (C++20) char8_t. Every other element type (unsigned char, | |
| // std::uint8_t, ...) keeps the full extent unconditionally, since a | |
| // trailing zero byte there is genuine data (e.g. CBOR/MessagePack). This | |
| // intentionally does not strlen()-scan the array (as the pointer overload | |
| // above does for a null-delimited string): for an array that is not | |
| // NUL-terminated within its bounds, that would read past the end of the | |
| // array. | |
| using char_t = typename std::remove_cv<T>::type; | |
| constexpr bool is_text_literal_type = std::is_same<char_t, char>::value | |
| || std::is_same<char_t, wchar_t>::value | |
| || std::is_same<char_t, char16_t>::value | |
| || std::is_same<char_t, char32_t>::value | |
| #if defined(__cpp_char8_t) | |
| || std::is_same<char_t, char8_t>::value | |
| #endif | |
| ; | |
| if (is_text_literal_type && N > 0 && array[N - 1] == 0) | |
| { | |
| return input_adapter(array, array + N - 1); | |
| } | |
| #endif | |
| return input_adapter(array, array + N); | |
| } | |
| // This class only handles inputs that construct a contiguous_bytes_input_adapter | |
| // (e.g. span_input_adapter). It's required so that expressions like {ptr, len} | |
| // can be implicitly cast to the correct adapter. | |
| class span_input_adapter | |
| { | |
| public: | |
| template < typename CharT, | |
| typename std::enable_if < | |
| std::is_pointer<CharT>::value&& | |
| std::is_integral<typename std::remove_pointer<CharT>::type>::value&& | |
| sizeof(typename std::remove_pointer<CharT>::type) == 1, | |
| int >::type = 0 > | |
| span_input_adapter(CharT b, std::size_t l) | |
| : ia(reinterpret_cast<const char*>(b), reinterpret_cast<const char*>(b) + l) {} | |
| template<class IteratorType, | |
| typename std::enable_if< | |
| std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value, | |
| int>::type = 0> | |
| span_input_adapter(IteratorType first, IteratorType last) | |
| : ia(input_adapter(first, last)) {} | |
| contiguous_bytes_input_adapter&& get() | |
| { | |
| return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg) | |
| } | |
| private: | |
| contiguous_bytes_input_adapter ia; | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/input/json_sax.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <algorithm> // copy, find_if, min | |
| #include <array> // array | |
| #include <cstddef> | |
| #include <functional> // hash | |
| #include <limits> // numeric_limits | |
| #include <memory> // unique_ptr | |
| #include <new> // operator new | |
| #include <string> // string | |
| #include <type_traits> // enable_if_t | |
| #include <utility> // move, pair | |
| #include <vector> // vector | |
| // #include <nlohmann/detail/exceptions.hpp> | |
| // #include <nlohmann/detail/input/lexer.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <array> // array | |
| #include <cstddef> // size_t | |
| #include <cstdint> // uint32_t | |
| #include <cstdio> // snprintf | |
| #include <cstring> // memcmp | |
| #include <initializer_list> // initializer_list | |
| #include <limits> // numeric_limits | |
| #include <string> // char_traits, string | |
| #include <utility> // move | |
| #include <vector> // vector | |
| // #include <nlohmann/detail/bit_ops.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cstdint> // uint64_t | |
| #include <cstring> // memcpy | |
| #if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64)) && (!defined(__SIZEOF_INT128__) || (!defined(__GNUC__) && !defined(__clang__))) | |
| #include <intrin0.h> // __umulh, _umul128, _BitScanForward64, _BitScanReverse64 | |
| #endif | |
| #ifdef _MSC_VER | |
| #include <cstdlib> // _byteswap_ushort, _byteswap_ulong, _byteswap_uint64 | |
| #endif | |
| #if defined(_MSC_VER) && !defined(__clang__) && (defined(_M_IX86) || defined(_M_ARM)) | |
| #include <intrin.h> // _BitScanForward, _BitScanReverse | |
| #endif | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // JSON_HEDLEY_ALWAYS_INLINE, NLOHMANN_JSON_NAMESPACE_BEGIN | |
| #if defined(__cpp_lib_bit_cast) || defined(__cpp_lib_bitops) || defined(__cpp_lib_byteswap) | |
| #include <bit> // bit_cast, byteswap, countl_zero, countr_zero | |
| #endif | |
| // Portable bit-level helpers for the number and string scanners. They use | |
| // compiler builtins or platform-specific intrinsics where available, the | |
| // C++20 <bit> functions next, and plain C++ otherwise, so they work regardless | |
| // of byte order. (The builtins and intrinsics come first: MSVC's | |
| // std::countl_zero checks for LZCNT at run time unless AVX2 is enabled.) | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /// number of leading zero bits of x (x != 0) | |
| inline int count_leading_zeros(std::uint64_t x) noexcept | |
| { | |
| #if defined(__GNUC__) || defined(__clang__) | |
| return __builtin_clzll(x); | |
| #elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64)) | |
| unsigned long index = 0; // NOLINT(runtime/int): the type _BitScan*64 takes | |
| _BitScanReverse64(&index, x); | |
| return 63 - static_cast<int>(index); | |
| #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_ARM)) | |
| unsigned long index = 0; // NOLINT(runtime/int): the type _BitScan* takes | |
| if (_BitScanReverse(&index, static_cast<unsigned long>(x >> 32u))) // NOLINT(runtime/int) | |
| { | |
| return 31 - static_cast<int>(index); | |
| } | |
| _BitScanReverse(&index, static_cast<unsigned long>(x)); // NOLINT(runtime/int) | |
| return 63 - static_cast<int>(index); | |
| #elif defined(__cpp_lib_bitops) | |
| return std::countl_zero(x); | |
| #else | |
| int n = 0; | |
| for (int shift = 32; shift != 0; shift >>= 1) | |
| { | |
| if ((x >> (64 - shift)) == 0) | |
| { | |
| n += shift; | |
| x <<= shift; | |
| } | |
| } | |
| return n; | |
| #endif | |
| } | |
| /// number of trailing zero bits of x (x != 0) | |
| inline int count_trailing_zeros(std::uint64_t x) noexcept | |
| { | |
| #if defined(__GNUC__) || defined(__clang__) | |
| return __builtin_ctzll(x); | |
| #elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64)) | |
| unsigned long index = 0; // NOLINT(runtime/int): the type _BitScan*64 takes | |
| _BitScanForward64(&index, x); | |
| return static_cast<int>(index); | |
| #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_ARM)) | |
| unsigned long index = 0; // NOLINT(runtime/int): the type _BitScan* takes | |
| if (_BitScanForward(&index, static_cast<unsigned long>(x))) // NOLINT(runtime/int) | |
| { | |
| return static_cast<int>(index); | |
| } | |
| _BitScanForward(&index, static_cast<unsigned long>(x >> 32u)); // NOLINT(runtime/int) | |
| return 32 + static_cast<int>(index); | |
| #elif defined(__cpp_lib_bitops) | |
| return std::countr_zero(x); | |
| #else | |
| int n = 0; | |
| for (int shift = 32; shift != 0; shift >>= 1) | |
| { | |
| if ((x << (64 - shift)) == 0) | |
| { | |
| n += shift; | |
| x >>= shift; | |
| } | |
| } | |
| return n; | |
| #endif | |
| } | |
| /// the object representation of @a from as a @a To (std::bit_cast in C++20) | |
| template<typename To, typename From> | |
| JSON_HEDLEY_ALWAYS_INLINE To bit_cast(const From& from) noexcept | |
| { | |
| static_assert(sizeof(To) == sizeof(From), "bit_cast needs types of the same size"); | |
| #if defined(__cpp_lib_bit_cast) | |
| return std::bit_cast<To>(from); | |
| #else | |
| To to {}; | |
| std::memcpy(&to, &from, sizeof(To)); | |
| return to; | |
| #endif | |
| } | |
| /// x with its bytes in reverse order (std::byteswap in C++23); compilers lower | |
| /// it to a single bswap/rev/movbe | |
| inline std::uint16_t byteswap(std::uint16_t x) noexcept | |
| { | |
| #if defined(__GNUC__) || defined(__clang__) | |
| return __builtin_bswap16(x); | |
| #elif defined(_MSC_VER) | |
| return _byteswap_ushort(x); | |
| #elif defined(__cpp_lib_byteswap) | |
| return std::byteswap(x); | |
| #else | |
| return static_cast<std::uint16_t>((x >> 8u) | (x << 8u)); | |
| #endif | |
| } | |
| /// x with its bytes in reverse order (std::byteswap in C++23) | |
| inline std::uint32_t byteswap(std::uint32_t x) noexcept | |
| { | |
| #if defined(__GNUC__) || defined(__clang__) | |
| return __builtin_bswap32(x); | |
| #elif defined(_MSC_VER) | |
| return _byteswap_ulong(x); | |
| #elif defined(__cpp_lib_byteswap) | |
| return std::byteswap(x); | |
| #else | |
| return ((x & 0x000000FFu) << 24u) | ((x & 0x0000FF00u) << 8u) | |
| | ((x & 0x00FF0000u) >> 8u) | ((x & 0xFF000000u) >> 24u); | |
| #endif | |
| } | |
| /// x with its bytes in reverse order (std::byteswap in C++23) | |
| inline std::uint64_t byteswap(std::uint64_t x) noexcept | |
| { | |
| #if defined(__GNUC__) || defined(__clang__) | |
| return __builtin_bswap64(x); | |
| #elif defined(_MSC_VER) | |
| return _byteswap_uint64(x); | |
| #elif defined(__cpp_lib_byteswap) | |
| return std::byteswap(x); | |
| #else | |
| x = ((x & 0x00000000FFFFFFFFull) << 32u) | ((x & 0xFFFFFFFF00000000ull) >> 32u); | |
| x = ((x & 0x0000FFFF0000FFFFull) << 16u) | ((x & 0xFFFF0000FFFF0000ull) >> 16u); | |
| x = ((x & 0x00FF00FF00FF00FFull) << 8u) | ((x & 0xFF00FF00FF00FF00ull) >> 8u); | |
| return x; | |
| #endif | |
| } | |
| /// the 128-bit product of two 64-bit numbers | |
| struct uint128_parts | |
| { | |
| std::uint64_t low; | |
| std::uint64_t high; | |
| }; | |
| inline uint128_parts full_multiplication(std::uint64_t a, std::uint64_t b) noexcept | |
| { | |
| #if defined(__SIZEOF_INT128__) | |
| __extension__ using uint128 = unsigned __int128; | |
| const uint128 r = static_cast<uint128>(a) * b; | |
| return {static_cast<std::uint64_t>(r), static_cast<std::uint64_t>(r >> 64u)}; | |
| #elif defined(_MSC_VER) && defined(_M_X64) | |
| std::uint64_t high = 0; | |
| const std::uint64_t low = _umul128(a, b, &high); | |
| return {low, high}; | |
| #elif defined(_MSC_VER) && defined(_M_ARM64) | |
| return {a * b, __umulh(a, b)}; | |
| #else | |
| const std::uint64_t a_lo = a & 0xFFFFFFFFu; | |
| const std::uint64_t a_hi = a >> 32u; | |
| const std::uint64_t b_lo = b & 0xFFFFFFFFu; | |
| const std::uint64_t b_hi = b >> 32u; | |
| const std::uint64_t lo_lo = a_lo * b_lo; | |
| const std::uint64_t hi_lo = a_hi * b_lo; | |
| const std::uint64_t lo_hi = a_lo * b_hi; | |
| const std::uint64_t hi_hi = a_hi * b_hi; | |
| const std::uint64_t cross = (lo_lo >> 32u) + (hi_lo & 0xFFFFFFFFu) + lo_hi; | |
| return {(cross << 32u) | (lo_lo & 0xFFFFFFFFu), (hi_lo >> 32u) + (cross >> 32u) + hi_hi}; | |
| #endif | |
| } | |
| /// eight bytes as a little-endian word (a single load on little-endian | |
| /// targets; always inlined, as GCC otherwise calls it in the number loops) | |
| JSON_HEDLEY_ALWAYS_INLINE std::uint64_t read_eight_bytes(const unsigned char* b) noexcept | |
| { | |
| #if JSON_LITTLE_ENDIAN_TARGET | |
| // the byte order already matches | |
| std::uint64_t result = 0; | |
| std::memcpy(&result, b, sizeof(result)); | |
| return result; | |
| #else | |
| return static_cast<std::uint64_t>(b[0]) | (static_cast<std::uint64_t>(b[1]) << 8u) | |
| | (static_cast<std::uint64_t>(b[2]) << 16u) | (static_cast<std::uint64_t>(b[3]) << 24u) | |
| | (static_cast<std::uint64_t>(b[4]) << 32u) | (static_cast<std::uint64_t>(b[5]) << 40u) | |
| | (static_cast<std::uint64_t>(b[6]) << 48u) | (static_cast<std::uint64_t>(b[7]) << 56u); | |
| #endif | |
| } | |
| /// eight bytes as a little-endian word | |
| JSON_HEDLEY_ALWAYS_INLINE std::uint64_t read_eight_bytes(const char* p) noexcept | |
| { | |
| return read_eight_bytes(reinterpret_cast<const unsigned char*>(p)); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/input/input_adapters.hpp> | |
| // #include <nlohmann/detail/input/number_parse.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2021 The fast_float authors <https://github.com/fastfloat/fast_float> | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <algorithm> // any_of | |
| #include <array> // array | |
| #include <cfloat> // FLT_EVAL_METHOD | |
| #include <clocale> // localeconv | |
| #include <cstddef> // size_t | |
| #include <cstdint> // int64_t, uint64_t | |
| #include <cstdlib> // strtof, strtod, strtold | |
| #include <limits> // numeric_limits | |
| #include <string> // string | |
| #include <type_traits> // conditional, integral_constant, is_signed, true_type, false_type | |
| #include <utility> // move | |
| // #include <nlohmann/detail/bit_ops.hpp> | |
| // #include <nlohmann/detail/input/pow5_table.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2021 The fast_float authors <https://github.com/fastfloat/fast_float> | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <array> // array | |
| #include <cstdint> // int64_t, uint64_t | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /// the range of decimal exponents covered by pow5_128() | |
| constexpr std::int64_t pow5_128_smallest_power = -342; | |
| constexpr std::int64_t pow5_128_largest_power = 308; | |
| // every entry of pow5_128() holds two 64-bit halves of 5^q, one per covered power of 5 | |
| static_assert((pow5_128_largest_power - pow5_128_smallest_power + 1) * 2 == 1302, | |
| "pow5_128_smallest_power/pow5_128_largest_power must match the size of the pow5_128() table"); | |
| /*! | |
| @brief 128-bit approximations of 5^q for q in [-342, 308] | |
| Entry q (at index 2 * (q + 342)) holds the most significant 128 bits of 5^q, | |
| normalized so that the highest bit is set: for q >= 0 the truncated value, for | |
| q < 0 the value rounded up. This is the table of fast_float (Daniel Lemire and | |
| contributors, used under the MIT license), generated like its | |
| script/table_generation.py; unit-class_lexer.cpp recomputes every entry. | |
| */ | |
| inline const std::array<std::uint64_t, 1302>& pow5_128() noexcept | |
| { | |
| static const std::array<std::uint64_t, 1302> table = | |
| { | |
| { | |
| 0xeef453d6923bd65au, 0x113faa2906a13b3fu, 0x9558b4661b6565f8u, 0x4ac7ca59a424c507u, | |
| 0xbaaee17fa23ebf76u, 0x5d79bcf00d2df649u, 0xe95a99df8ace6f53u, 0xf4d82c2c107973dcu, | |
| 0x91d8a02bb6c10594u, 0x79071b9b8a4be869u, 0xb64ec836a47146f9u, 0x9748e2826cdee284u, | |
| 0xe3e27a444d8d98b7u, 0xfd1b1b2308169b25u, 0x8e6d8c6ab0787f72u, 0xfe30f0f5e50e20f7u, | |
| 0xb208ef855c969f4fu, 0xbdbd2d335e51a935u, 0xde8b2b66b3bc4723u, 0xad2c788035e61382u, | |
| 0x8b16fb203055ac76u, 0x4c3bcb5021afcc31u, 0xaddcb9e83c6b1793u, 0xdf4abe242a1bbf3du, | |
| 0xd953e8624b85dd78u, 0xd71d6dad34a2af0du, 0x87d4713d6f33aa6bu, 0x8672648c40e5ad68u, | |
| 0xa9c98d8ccb009506u, 0x680efdaf511f18c2u, 0xd43bf0effdc0ba48u, 0x0212bd1b2566def2u, | |
| 0x84a57695fe98746du, 0x014bb630f7604b57u, 0xa5ced43b7e3e9188u, 0x419ea3bd35385e2du, | |
| 0xcf42894a5dce35eau, 0x52064cac828675b9u, 0x818995ce7aa0e1b2u, 0x7343efebd1940993u, | |
| 0xa1ebfb4219491a1fu, 0x1014ebe6c5f90bf8u, 0xca66fa129f9b60a6u, 0xd41a26e077774ef6u, | |
| 0xfd00b897478238d0u, 0x8920b098955522b4u, 0x9e20735e8cb16382u, 0x55b46e5f5d5535b0u, | |
| 0xc5a890362fddbc62u, 0xeb2189f734aa831du, 0xf712b443bbd52b7bu, 0xa5e9ec7501d523e4u, | |
| 0x9a6bb0aa55653b2du, 0x47b233c92125366eu, 0xc1069cd4eabe89f8u, 0x999ec0bb696e840au, | |
| 0xf148440a256e2c76u, 0xc00670ea43ca250du, 0x96cd2a865764dbcau, 0x380406926a5e5728u, | |
| 0xbc807527ed3e12bcu, 0xc605083704f5ecf2u, 0xeba09271e88d976bu, 0xf7864a44c633682eu, | |
| 0x93445b8731587ea3u, 0x7ab3ee6afbe0211du, 0xb8157268fdae9e4cu, 0x5960ea05bad82964u, | |
| 0xe61acf033d1a45dfu, 0x6fb92487298e33bdu, 0x8fd0c16206306babu, 0xa5d3b6d479f8e056u, | |
| 0xb3c4f1ba87bc8696u, 0x8f48a4899877186cu, 0xe0b62e2929aba83cu, 0x331acdabfe94de87u, | |
| 0x8c71dcd9ba0b4925u, 0x9ff0c08b7f1d0b14u, 0xaf8e5410288e1b6fu, 0x07ecf0ae5ee44dd9u, | |
| 0xdb71e91432b1a24au, 0xc9e82cd9f69d6150u, 0x892731ac9faf056eu, 0xbe311c083a225cd2u, | |
| 0xab70fe17c79ac6cau, 0x6dbd630a48aaf406u, 0xd64d3d9db981787du, 0x092cbbccdad5b108u, | |
| 0x85f0468293f0eb4eu, 0x25bbf56008c58ea5u, 0xa76c582338ed2621u, 0xaf2af2b80af6f24eu, | |
| 0xd1476e2c07286faau, 0x1af5af660db4aee1u, 0x82cca4db847945cau, 0x50d98d9fc890ed4du, | |
| 0xa37fce126597973cu, 0xe50ff107bab528a0u, 0xcc5fc196fefd7d0cu, 0x1e53ed49a96272c8u, | |
| 0xff77b1fcbebcdc4fu, 0x25e8e89c13bb0f7au, 0x9faacf3df73609b1u, 0x77b191618c54e9acu, | |
| 0xc795830d75038c1du, 0xd59df5b9ef6a2417u, 0xf97ae3d0d2446f25u, 0x4b0573286b44ad1du, | |
| 0x9becce62836ac577u, 0x4ee367f9430aec32u, 0xc2e801fb244576d5u, 0x229c41f793cda73fu, | |
| 0xf3a20279ed56d48au, 0x6b43527578c1110fu, 0x9845418c345644d6u, 0x830a13896b78aaa9u, | |
| 0xbe5691ef416bd60cu, 0x23cc986bc656d553u, 0xedec366b11c6cb8fu, 0x2cbfbe86b7ec8aa8u, | |
| 0x94b3a202eb1c3f39u, 0x7bf7d71432f3d6a9u, 0xb9e08a83a5e34f07u, 0xdaf5ccd93fb0cc53u, | |
| 0xe858ad248f5c22c9u, 0xd1b3400f8f9cff68u, 0x91376c36d99995beu, 0x23100809b9c21fa1u, | |
| 0xb58547448ffffb2du, 0xabd40a0c2832a78au, 0xe2e69915b3fff9f9u, 0x16c90c8f323f516cu, | |
| 0x8dd01fad907ffc3bu, 0xae3da7d97f6792e3u, 0xb1442798f49ffb4au, 0x99cd11cfdf41779cu, | |
| 0xdd95317f31c7fa1du, 0x40405643d711d583u, 0x8a7d3eef7f1cfc52u, 0x482835ea666b2572u, | |
| 0xad1c8eab5ee43b66u, 0xda3243650005eecfu, 0xd863b256369d4a40u, 0x90bed43e40076a82u, | |
| 0x873e4f75e2224e68u, 0x5a7744a6e804a291u, 0xa90de3535aaae202u, 0x711515d0a205cb36u, | |
| 0xd3515c2831559a83u, 0x0d5a5b44ca873e03u, 0x8412d9991ed58091u, 0xe858790afe9486c2u, | |
| 0xa5178fff668ae0b6u, 0x626e974dbe39a872u, 0xce5d73ff402d98e3u, 0xfb0a3d212dc8128fu, | |
| 0x80fa687f881c7f8eu, 0x7ce66634bc9d0b99u, 0xa139029f6a239f72u, 0x1c1fffc1ebc44e80u, | |
| 0xc987434744ac874eu, 0xa327ffb266b56220u, 0xfbe9141915d7a922u, 0x4bf1ff9f0062baa8u, | |
| 0x9d71ac8fada6c9b5u, 0x6f773fc3603db4a9u, 0xc4ce17b399107c22u, 0xcb550fb4384d21d3u, | |
| 0xf6019da07f549b2bu, 0x7e2a53a146606a48u, 0x99c102844f94e0fbu, 0x2eda7444cbfc426du, | |
| 0xc0314325637a1939u, 0xfa911155fefb5308u, 0xf03d93eebc589f88u, 0x793555ab7eba27cau, | |
| 0x96267c7535b763b5u, 0x4bc1558b2f3458deu, 0xbbb01b9283253ca2u, 0x9eb1aaedfb016f16u, | |
| 0xea9c227723ee8bcbu, 0x465e15a979c1cadcu, 0x92a1958a7675175fu, 0x0bfacd89ec191ec9u, | |
| 0xb749faed14125d36u, 0xcef980ec671f667bu, 0xe51c79a85916f484u, 0x82b7e12780e7401au, | |
| 0x8f31cc0937ae58d2u, 0xd1b2ecb8b0908810u, 0xb2fe3f0b8599ef07u, 0x861fa7e6dcb4aa15u, | |
| 0xdfbdcece67006ac9u, 0x67a791e093e1d49au, 0x8bd6a141006042bdu, 0xe0c8bb2c5c6d24e0u, | |
| 0xaecc49914078536du, 0x58fae9f773886e18u, 0xda7f5bf590966848u, 0xaf39a475506a899eu, | |
| 0x888f99797a5e012du, 0x6d8406c952429603u, 0xaab37fd7d8f58178u, 0xc8e5087ba6d33b83u, | |
| 0xd5605fcdcf32e1d6u, 0xfb1e4a9a90880a64u, 0x855c3be0a17fcd26u, 0x5cf2eea09a55067fu, | |
| 0xa6b34ad8c9dfc06fu, 0xf42faa48c0ea481eu, 0xd0601d8efc57b08bu, 0xf13b94daf124da26u, | |
| 0x823c12795db6ce57u, 0x76c53d08d6b70858u, 0xa2cb1717b52481edu, 0x54768c4b0c64ca6eu, | |
| 0xcb7ddcdda26da268u, 0xa9942f5dcf7dfd09u, 0xfe5d54150b090b02u, 0xd3f93b35435d7c4cu, | |
| 0x9efa548d26e5a6e1u, 0xc47bc5014a1a6dafu, 0xc6b8e9b0709f109au, 0x359ab6419ca1091bu, | |
| 0xf867241c8cc6d4c0u, 0xc30163d203c94b62u, 0x9b407691d7fc44f8u, 0x79e0de63425dcf1du, | |
| 0xc21094364dfb5636u, 0x985915fc12f542e4u, 0xf294b943e17a2bc4u, 0x3e6f5b7b17b2939du, | |
| 0x979cf3ca6cec5b5au, 0xa705992ceecf9c42u, 0xbd8430bd08277231u, 0x50c6ff782a838353u, | |
| 0xece53cec4a314ebdu, 0xa4f8bf5635246428u, 0x940f4613ae5ed136u, 0x871b7795e136be99u, | |
| 0xb913179899f68584u, 0x28e2557b59846e3fu, 0xe757dd7ec07426e5u, 0x331aeada2fe589cfu, | |
| 0x9096ea6f3848984fu, 0x3ff0d2c85def7621u, 0xb4bca50b065abe63u, 0x0fed077a756b53a9u, | |
| 0xe1ebce4dc7f16dfbu, 0xd3e8495912c62894u, 0x8d3360f09cf6e4bdu, 0x64712dd7abbbd95cu, | |
| 0xb080392cc4349decu, 0xbd8d794d96aacfb3u, 0xdca04777f541c567u, 0xecf0d7a0fc5583a0u, | |
| 0x89e42caaf9491b60u, 0xf41686c49db57244u, 0xac5d37d5b79b6239u, 0x311c2875c522ced5u, | |
| 0xd77485cb25823ac7u, 0x7d633293366b828bu, 0x86a8d39ef77164bcu, 0xae5dff9c02033197u, | |
| 0xa8530886b54dbdebu, 0xd9f57f830283fdfcu, 0xd267caa862a12d66u, 0xd072df63c324fd7bu, | |
| 0x8380dea93da4bc60u, 0x4247cb9e59f71e6du, 0xa46116538d0deb78u, 0x52d9be85f074e608u, | |
| 0xcd795be870516656u, 0x67902e276c921f8bu, 0x806bd9714632dff6u, 0x00ba1cd8a3db53b6u, | |
| 0xa086cfcd97bf97f3u, 0x80e8a40eccd228a4u, 0xc8a883c0fdaf7df0u, 0x6122cd128006b2cdu, | |
| 0xfad2a4b13d1b5d6cu, 0x796b805720085f81u, 0x9cc3a6eec6311a63u, 0xcbe3303674053bb0u, | |
| 0xc3f490aa77bd60fcu, 0xbedbfc4411068a9cu, 0xf4f1b4d515acb93bu, 0xee92fb5515482d44u, | |
| 0x991711052d8bf3c5u, 0x751bdd152d4d1c4au, 0xbf5cd54678eef0b6u, 0xd262d45a78a0635du, | |
| 0xef340a98172aace4u, 0x86fb897116c87c34u, 0x9580869f0e7aac0eu, 0xd45d35e6ae3d4da0u, | |
| 0xbae0a846d2195712u, 0x8974836059cca109u, 0xe998d258869facd7u, 0x2bd1a438703fc94bu, | |
| 0x91ff83775423cc06u, 0x7b6306a34627ddcfu, 0xb67f6455292cbf08u, 0x1a3bc84c17b1d542u, | |
| 0xe41f3d6a7377eecau, 0x20caba5f1d9e4a93u, 0x8e938662882af53eu, 0x547eb47b7282ee9cu, | |
| 0xb23867fb2a35b28du, 0xe99e619a4f23aa43u, 0xdec681f9f4c31f31u, 0x6405fa00e2ec94d4u, | |
| 0x8b3c113c38f9f37eu, 0xde83bc408dd3dd04u, 0xae0b158b4738705eu, 0x9624ab50b148d445u, | |
| 0xd98ddaee19068c76u, 0x3badd624dd9b0957u, 0x87f8a8d4cfa417c9u, 0xe54ca5d70a80e5d6u, | |
| 0xa9f6d30a038d1dbcu, 0x5e9fcf4ccd211f4cu, 0xd47487cc8470652bu, 0x7647c3200069671fu, | |
| 0x84c8d4dfd2c63f3bu, 0x29ecd9f40041e073u, 0xa5fb0a17c777cf09u, 0xf468107100525890u, | |
| 0xcf79cc9db955c2ccu, 0x7182148d4066eeb4u, 0x81ac1fe293d599bfu, 0xc6f14cd848405530u, | |
| 0xa21727db38cb002fu, 0xb8ada00e5a506a7cu, 0xca9cf1d206fdc03bu, 0xa6d90811f0e4851cu, | |
| 0xfd442e4688bd304au, 0x908f4a166d1da663u, 0x9e4a9cec15763e2eu, 0x9a598e4e043287feu, | |
| 0xc5dd44271ad3cdbau, 0x40eff1e1853f29fdu, 0xf7549530e188c128u, 0xd12bee59e68ef47cu, | |
| 0x9a94dd3e8cf578b9u, 0x82bb74f8301958ceu, 0xc13a148e3032d6e7u, 0xe36a52363c1faf01u, | |
| 0xf18899b1bc3f8ca1u, 0xdc44e6c3cb279ac1u, 0x96f5600f15a7b7e5u, 0x29ab103a5ef8c0b9u, | |
| 0xbcb2b812db11a5deu, 0x7415d448f6b6f0e7u, 0xebdf661791d60f56u, 0x111b495b3464ad21u, | |
| 0x936b9fcebb25c995u, 0xcab10dd900beec34u, 0xb84687c269ef3bfbu, 0x3d5d514f40eea742u, | |
| 0xe65829b3046b0afau, 0x0cb4a5a3112a5112u, 0x8ff71a0fe2c2e6dcu, 0x47f0e785eaba72abu, | |
| 0xb3f4e093db73a093u, 0x59ed216765690f56u, 0xe0f218b8d25088b8u, 0x306869c13ec3532cu, | |
| 0x8c974f7383725573u, 0x1e414218c73a13fbu, 0xafbd2350644eeacfu, 0xe5d1929ef90898fau, | |
| 0xdbac6c247d62a583u, 0xdf45f746b74abf39u, 0x894bc396ce5da772u, 0x6b8bba8c328eb783u, | |
| 0xab9eb47c81f5114fu, 0x066ea92f3f326564u, 0xd686619ba27255a2u, 0xc80a537b0efefebdu, | |
| 0x8613fd0145877585u, 0xbd06742ce95f5f36u, 0xa798fc4196e952e7u, 0x2c48113823b73704u, | |
| 0xd17f3b51fca3a7a0u, 0xf75a15862ca504c5u, 0x82ef85133de648c4u, 0x9a984d73dbe722fbu, | |
| 0xa3ab66580d5fdaf5u, 0xc13e60d0d2e0ebbau, 0xcc963fee10b7d1b3u, 0x318df905079926a8u, | |
| 0xffbbcfe994e5c61fu, 0xfdf17746497f7052u, 0x9fd561f1fd0f9bd3u, 0xfeb6ea8bedefa633u, | |
| 0xc7caba6e7c5382c8u, 0xfe64a52ee96b8fc0u, 0xf9bd690a1b68637bu, 0x3dfdce7aa3c673b0u, | |
| 0x9c1661a651213e2du, 0x06bea10ca65c084eu, 0xc31bfa0fe5698db8u, 0x486e494fcff30a62u, | |
| 0xf3e2f893dec3f126u, 0x5a89dba3c3efccfau, 0x986ddb5c6b3a76b7u, 0xf89629465a75e01cu, | |
| 0xbe89523386091465u, 0xf6bbb397f1135823u, 0xee2ba6c0678b597fu, 0x746aa07ded582e2cu, | |
| 0x94db483840b717efu, 0xa8c2a44eb4571cdcu, 0xba121a4650e4ddebu, 0x92f34d62616ce413u, | |
| 0xe896a0d7e51e1566u, 0x77b020baf9c81d17u, 0x915e2486ef32cd60u, 0x0ace1474dc1d122eu, | |
| 0xb5b5ada8aaff80b8u, 0x0d819992132456bau, 0xe3231912d5bf60e6u, 0x10e1fff697ed6c69u, | |
| 0x8df5efabc5979c8fu, 0xca8d3ffa1ef463c1u, 0xb1736b96b6fd83b3u, 0xbd308ff8a6b17cb2u, | |
| 0xddd0467c64bce4a0u, 0xac7cb3f6d05ddbdeu, 0x8aa22c0dbef60ee4u, 0x6bcdf07a423aa96bu, | |
| 0xad4ab7112eb3929du, 0x86c16c98d2c953c6u, 0xd89d64d57a607744u, 0xe871c7bf077ba8b7u, | |
| 0x87625f056c7c4a8bu, 0x11471cd764ad4972u, 0xa93af6c6c79b5d2du, 0xd598e40d3dd89bcfu, | |
| 0xd389b47879823479u, 0x4aff1d108d4ec2c3u, 0x843610cb4bf160cbu, 0xcedf722a585139bau, | |
| 0xa54394fe1eedb8feu, 0xc2974eb4ee658828u, 0xce947a3da6a9273eu, 0x733d226229feea32u, | |
| 0x811ccc668829b887u, 0x0806357d5a3f525fu, 0xa163ff802a3426a8u, 0xca07c2dcb0cf26f7u, | |
| 0xc9bcff6034c13052u, 0xfc89b393dd02f0b5u, 0xfc2c3f3841f17c67u, 0xbbac2078d443ace2u, | |
| 0x9d9ba7832936edc0u, 0xd54b944b84aa4c0du, 0xc5029163f384a931u, 0x0a9e795e65d4df11u, | |
| 0xf64335bcf065d37du, 0x4d4617b5ff4a16d5u, 0x99ea0196163fa42eu, 0x504bced1bf8e4e45u, | |
| 0xc06481fb9bcf8d39u, 0xe45ec2862f71e1d6u, 0xf07da27a82c37088u, 0x5d767327bb4e5a4cu, | |
| 0x964e858c91ba2655u, 0x3a6a07f8d510f86fu, 0xbbe226efb628afeau, 0x890489f70a55368bu, | |
| 0xeadab0aba3b2dbe5u, 0x2b45ac74ccea842eu, 0x92c8ae6b464fc96fu, 0x3b0b8bc90012929du, | |
| 0xb77ada0617e3bbcbu, 0x09ce6ebb40173744u, 0xe55990879ddcaabdu, 0xcc420a6a101d0515u, | |
| 0x8f57fa54c2a9eab6u, 0x9fa946824a12232du, 0xb32df8e9f3546564u, 0x47939822dc96abf9u, | |
| 0xdff9772470297ebdu, 0x59787e2b93bc56f7u, 0x8bfbea76c619ef36u, 0x57eb4edb3c55b65au, | |
| 0xaefae51477a06b03u, 0xede622920b6b23f1u, 0xdab99e59958885c4u, 0xe95fab368e45ecedu, | |
| 0x88b402f7fd75539bu, 0x11dbcb0218ebb414u, 0xaae103b5fcd2a881u, 0xd652bdc29f26a119u, | |
| 0xd59944a37c0752a2u, 0x4be76d3346f0495fu, 0x857fcae62d8493a5u, 0x6f70a4400c562ddbu, | |
| 0xa6dfbd9fb8e5b88eu, 0xcb4ccd500f6bb952u, 0xd097ad07a71f26b2u, 0x7e2000a41346a7a7u, | |
| 0x825ecc24c873782fu, 0x8ed400668c0c28c8u, 0xa2f67f2dfa90563bu, 0x728900802f0f32fau, | |
| 0xcbb41ef979346bcau, 0x4f2b40a03ad2ffb9u, 0xfea126b7d78186bcu, 0xe2f610c84987bfa8u, | |
| 0x9f24b832e6b0f436u, 0x0dd9ca7d2df4d7c9u, 0xc6ede63fa05d3143u, 0x91503d1c79720dbbu, | |
| 0xf8a95fcf88747d94u, 0x75a44c6397ce912au, 0x9b69dbe1b548ce7cu, 0xc986afbe3ee11abau, | |
| 0xc24452da229b021bu, 0xfbe85badce996168u, 0xf2d56790ab41c2a2u, 0xfae27299423fb9c3u, | |
| 0x97c560ba6b0919a5u, 0xdccd879fc967d41au, 0xbdb6b8e905cb600fu, 0x5400e987bbc1c920u, | |
| 0xed246723473e3813u, 0x290123e9aab23b68u, 0x9436c0760c86e30bu, 0xf9a0b6720aaf6521u, | |
| 0xb94470938fa89bceu, 0xf808e40e8d5b3e69u, 0xe7958cb87392c2c2u, 0xb60b1d1230b20e04u, | |
| 0x90bd77f3483bb9b9u, 0xb1c6f22b5e6f48c2u, 0xb4ecd5f01a4aa828u, 0x1e38aeb6360b1af3u, | |
| 0xe2280b6c20dd5232u, 0x25c6da63c38de1b0u, 0x8d590723948a535fu, 0x579c487e5a38ad0eu, | |
| 0xb0af48ec79ace837u, 0x2d835a9df0c6d851u, 0xdcdb1b2798182244u, 0xf8e431456cf88e65u, | |
| 0x8a08f0f8bf0f156bu, 0x1b8e9ecb641b58ffu, 0xac8b2d36eed2dac5u, 0xe272467e3d222f3fu, | |
| 0xd7adf884aa879177u, 0x5b0ed81dcc6abb0fu, 0x86ccbb52ea94baeau, 0x98e947129fc2b4e9u, | |
| 0xa87fea27a539e9a5u, 0x3f2398d747b36224u, 0xd29fe4b18e88640eu, 0x8eec7f0d19a03aadu, | |
| 0x83a3eeeef9153e89u, 0x1953cf68300424acu, 0xa48ceaaab75a8e2bu, 0x5fa8c3423c052dd7u, | |
| 0xcdb02555653131b6u, 0x3792f412cb06794du, 0x808e17555f3ebf11u, 0xe2bbd88bbee40bd0u, | |
| 0xa0b19d2ab70e6ed6u, 0x5b6aceaeae9d0ec4u, 0xc8de047564d20a8bu, 0xf245825a5a445275u, | |
| 0xfb158592be068d2eu, 0xeed6e2f0f0d56712u, 0x9ced737bb6c4183du, 0x55464dd69685606bu, | |
| 0xc428d05aa4751e4cu, 0xaa97e14c3c26b886u, 0xf53304714d9265dfu, 0xd53dd99f4b3066a8u, | |
| 0x993fe2c6d07b7fabu, 0xe546a8038efe4029u, 0xbf8fdb78849a5f96u, 0xde98520472bdd033u, | |
| 0xef73d256a5c0f77cu, 0x963e66858f6d4440u, 0x95a8637627989aadu, 0xdde7001379a44aa8u, | |
| 0xbb127c53b17ec159u, 0x5560c018580d5d52u, 0xe9d71b689dde71afu, 0xaab8f01e6e10b4a6u, | |
| 0x9226712162ab070du, 0xcab3961304ca70e8u, 0xb6b00d69bb55c8d1u, 0x3d607b97c5fd0d22u, | |
| 0xe45c10c42a2b3b05u, 0x8cb89a7db77c506au, 0x8eb98a7a9a5b04e3u, 0x77f3608e92adb242u, | |
| 0xb267ed1940f1c61cu, 0x55f038b237591ed3u, 0xdf01e85f912e37a3u, 0x6b6c46dec52f6688u, | |
| 0x8b61313bbabce2c6u, 0x2323ac4b3b3da015u, 0xae397d8aa96c1b77u, 0xabec975e0a0d081au, | |
| 0xd9c7dced53c72255u, 0x96e7bd358c904a21u, 0x881cea14545c7575u, 0x7e50d64177da2e54u, | |
| 0xaa242499697392d2u, 0xdde50bd1d5d0b9e9u, 0xd4ad2dbfc3d07787u, 0x955e4ec64b44e864u, | |
| 0x84ec3c97da624ab4u, 0xbd5af13bef0b113eu, 0xa6274bbdd0fadd61u, 0xecb1ad8aeacdd58eu, | |
| 0xcfb11ead453994bau, 0x67de18eda5814af2u, 0x81ceb32c4b43fcf4u, 0x80eacf948770ced7u, | |
| 0xa2425ff75e14fc31u, 0xa1258379a94d028du, 0xcad2f7f5359a3b3eu, 0x096ee45813a04330u, | |
| 0xfd87b5f28300ca0du, 0x8bca9d6e188853fcu, 0x9e74d1b791e07e48u, 0x775ea264cf55347eu, | |
| 0xc612062576589ddau, 0x95364afe032a819eu, 0xf79687aed3eec551u, 0x3a83ddbd83f52205u, | |
| 0x9abe14cd44753b52u, 0xc4926a9672793543u, 0xc16d9a0095928a27u, 0x75b7053c0f178294u, | |
| 0xf1c90080baf72cb1u, 0x5324c68b12dd6339u, 0x971da05074da7beeu, 0xd3f6fc16ebca5e04u, | |
| 0xbce5086492111aeau, 0x88f4bb1ca6bcf585u, 0xec1e4a7db69561a5u, 0x2b31e9e3d06c32e6u, | |
| 0x9392ee8e921d5d07u, 0x3aff322e62439fd0u, 0xb877aa3236a4b449u, 0x09befeb9fad487c3u, | |
| 0xe69594bec44de15bu, 0x4c2ebe687989a9b4u, 0x901d7cf73ab0acd9u, 0x0f9d37014bf60a11u, | |
| 0xb424dc35095cd80fu, 0x538484c19ef38c95u, 0xe12e13424bb40e13u, 0x2865a5f206b06fbau, | |
| 0x8cbccc096f5088cbu, 0xf93f87b7442e45d4u, 0xafebff0bcb24aafeu, 0xf78f69a51539d749u, | |
| 0xdbe6fecebdedd5beu, 0xb573440e5a884d1cu, 0x89705f4136b4a597u, 0x31680a88f8953031u, | |
| 0xabcc77118461cefcu, 0xfdc20d2b36ba7c3eu, 0xd6bf94d5e57a42bcu, 0x3d32907604691b4du, | |
| 0x8637bd05af6c69b5u, 0xa63f9a49c2c1b110u, 0xa7c5ac471b478423u, 0x0fcf80dc33721d54u, | |
| 0xd1b71758e219652bu, 0xd3c36113404ea4a9u, 0x83126e978d4fdf3bu, 0x645a1cac083126eau, | |
| 0xa3d70a3d70a3d70au, 0x3d70a3d70a3d70a4u, 0xccccccccccccccccu, 0xcccccccccccccccdu, | |
| 0x8000000000000000u, 0x0000000000000000u, 0xa000000000000000u, 0x0000000000000000u, | |
| 0xc800000000000000u, 0x0000000000000000u, 0xfa00000000000000u, 0x0000000000000000u, | |
| 0x9c40000000000000u, 0x0000000000000000u, 0xc350000000000000u, 0x0000000000000000u, | |
| 0xf424000000000000u, 0x0000000000000000u, 0x9896800000000000u, 0x0000000000000000u, | |
| 0xbebc200000000000u, 0x0000000000000000u, 0xee6b280000000000u, 0x0000000000000000u, | |
| 0x9502f90000000000u, 0x0000000000000000u, 0xba43b74000000000u, 0x0000000000000000u, | |
| 0xe8d4a51000000000u, 0x0000000000000000u, 0x9184e72a00000000u, 0x0000000000000000u, | |
| 0xb5e620f480000000u, 0x0000000000000000u, 0xe35fa931a0000000u, 0x0000000000000000u, | |
| 0x8e1bc9bf04000000u, 0x0000000000000000u, 0xb1a2bc2ec5000000u, 0x0000000000000000u, | |
| 0xde0b6b3a76400000u, 0x0000000000000000u, 0x8ac7230489e80000u, 0x0000000000000000u, | |
| 0xad78ebc5ac620000u, 0x0000000000000000u, 0xd8d726b7177a8000u, 0x0000000000000000u, | |
| 0x878678326eac9000u, 0x0000000000000000u, 0xa968163f0a57b400u, 0x0000000000000000u, | |
| 0xd3c21bcecceda100u, 0x0000000000000000u, 0x84595161401484a0u, 0x0000000000000000u, | |
| 0xa56fa5b99019a5c8u, 0x0000000000000000u, 0xcecb8f27f4200f3au, 0x0000000000000000u, | |
| 0x813f3978f8940984u, 0x4000000000000000u, 0xa18f07d736b90be5u, 0x5000000000000000u, | |
| 0xc9f2c9cd04674edeu, 0xa400000000000000u, 0xfc6f7c4045812296u, 0x4d00000000000000u, | |
| 0x9dc5ada82b70b59du, 0xf020000000000000u, 0xc5371912364ce305u, 0x6c28000000000000u, | |
| 0xf684df56c3e01bc6u, 0xc732000000000000u, 0x9a130b963a6c115cu, 0x3c7f400000000000u, | |
| 0xc097ce7bc90715b3u, 0x4b9f100000000000u, 0xf0bdc21abb48db20u, 0x1e86d40000000000u, | |
| 0x96769950b50d88f4u, 0x1314448000000000u, 0xbc143fa4e250eb31u, 0x17d955a000000000u, | |
| 0xeb194f8e1ae525fdu, 0x5dcfab0800000000u, 0x92efd1b8d0cf37beu, 0x5aa1cae500000000u, | |
| 0xb7abc627050305adu, 0xf14a3d9e40000000u, 0xe596b7b0c643c719u, 0x6d9ccd05d0000000u, | |
| 0x8f7e32ce7bea5c6fu, 0xe4820023a2000000u, 0xb35dbf821ae4f38bu, 0xdda2802c8a800000u, | |
| 0xe0352f62a19e306eu, 0xd50b2037ad200000u, 0x8c213d9da502de45u, 0x4526f422cc340000u, | |
| 0xaf298d050e4395d6u, 0x9670b12b7f410000u, 0xdaf3f04651d47b4cu, 0x3c0cdd765f114000u, | |
| 0x88d8762bf324cd0fu, 0xa5880a69fb6ac800u, 0xab0e93b6efee0053u, 0x8eea0d047a457a00u, | |
| 0xd5d238a4abe98068u, 0x72a4904598d6d880u, 0x85a36366eb71f041u, 0x47a6da2b7f864750u, | |
| 0xa70c3c40a64e6c51u, 0x999090b65f67d924u, 0xd0cf4b50cfe20765u, 0xfff4b4e3f741cf6du, | |
| 0x82818f1281ed449fu, 0xbff8f10e7a8921a4u, 0xa321f2d7226895c7u, 0xaff72d52192b6a0du, | |
| 0xcbea6f8ceb02bb39u, 0x9bf4f8a69f764490u, 0xfee50b7025c36a08u, 0x02f236d04753d5b4u, | |
| 0x9f4f2726179a2245u, 0x01d762422c946590u, 0xc722f0ef9d80aad6u, 0x424d3ad2b7b97ef5u, | |
| 0xf8ebad2b84e0d58bu, 0xd2e0898765a7deb2u, 0x9b934c3b330c8577u, 0x63cc55f49f88eb2fu, | |
| 0xc2781f49ffcfa6d5u, 0x3cbf6b71c76b25fbu, 0xf316271c7fc3908au, 0x8bef464e3945ef7au, | |
| 0x97edd871cfda3a56u, 0x97758bf0e3cbb5acu, 0xbde94e8e43d0c8ecu, 0x3d52eeed1cbea317u, | |
| 0xed63a231d4c4fb27u, 0x4ca7aaa863ee4bddu, 0x945e455f24fb1cf8u, 0x8fe8caa93e74ef6au, | |
| 0xb975d6b6ee39e436u, 0xb3e2fd538e122b44u, 0xe7d34c64a9c85d44u, 0x60dbbca87196b616u, | |
| 0x90e40fbeea1d3a4au, 0xbc8955e946fe31cdu, 0xb51d13aea4a488ddu, 0x6babab6398bdbe41u, | |
| 0xe264589a4dcdab14u, 0xc696963c7eed2dd1u, 0x8d7eb76070a08aecu, 0xfc1e1de5cf543ca2u, | |
| 0xb0de65388cc8ada8u, 0x3b25a55f43294bcbu, 0xdd15fe86affad912u, 0x49ef0eb713f39ebeu, | |
| 0x8a2dbf142dfcc7abu, 0x6e3569326c784337u, 0xacb92ed9397bf996u, 0x49c2c37f07965404u, | |
| 0xd7e77a8f87daf7fbu, 0xdc33745ec97be906u, 0x86f0ac99b4e8dafdu, 0x69a028bb3ded71a3u, | |
| 0xa8acd7c0222311bcu, 0xc40832ea0d68ce0cu, 0xd2d80db02aabd62bu, 0xf50a3fa490c30190u, | |
| 0x83c7088e1aab65dbu, 0x792667c6da79e0fau, 0xa4b8cab1a1563f52u, 0x577001b891185938u, | |
| 0xcde6fd5e09abcf26u, 0xed4c0226b55e6f86u, 0x80b05e5ac60b6178u, 0x544f8158315b05b4u, | |
| 0xa0dc75f1778e39d6u, 0x696361ae3db1c721u, 0xc913936dd571c84cu, 0x03bc3a19cd1e38e9u, | |
| 0xfb5878494ace3a5fu, 0x04ab48a04065c723u, 0x9d174b2dcec0e47bu, 0x62eb0d64283f9c76u, | |
| 0xc45d1df942711d9au, 0x3ba5d0bd324f8394u, 0xf5746577930d6500u, 0xca8f44ec7ee36479u, | |
| 0x9968bf6abbe85f20u, 0x7e998b13cf4e1ecbu, 0xbfc2ef456ae276e8u, 0x9e3fedd8c321a67eu, | |
| 0xefb3ab16c59b14a2u, 0xc5cfe94ef3ea101eu, 0x95d04aee3b80ece5u, 0xbba1f1d158724a12u, | |
| 0xbb445da9ca61281fu, 0x2a8a6e45ae8edc97u, 0xea1575143cf97226u, 0xf52d09d71a3293bdu, | |
| 0x924d692ca61be758u, 0x593c2626705f9c56u, 0xb6e0c377cfa2e12eu, 0x6f8b2fb00c77836cu, | |
| 0xe498f455c38b997au, 0x0b6dfb9c0f956447u, 0x8edf98b59a373fecu, 0x4724bd4189bd5eacu, | |
| 0xb2977ee300c50fe7u, 0x58edec91ec2cb657u, 0xdf3d5e9bc0f653e1u, 0x2f2967b66737e3edu, | |
| 0x8b865b215899f46cu, 0xbd79e0d20082ee74u, 0xae67f1e9aec07187u, 0xecd8590680a3aa11u, | |
| 0xda01ee641a708de9u, 0xe80e6f4820cc9495u, 0x884134fe908658b2u, 0x3109058d147fdcddu, | |
| 0xaa51823e34a7eedeu, 0xbd4b46f0599fd415u, 0xd4e5e2cdc1d1ea96u, 0x6c9e18ac7007c91au, | |
| 0x850fadc09923329eu, 0x03e2cf6bc604ddb0u, 0xa6539930bf6bff45u, 0x84db8346b786151cu, | |
| 0xcfe87f7cef46ff16u, 0xe612641865679a63u, 0x81f14fae158c5f6eu, 0x4fcb7e8f3f60c07eu, | |
| 0xa26da3999aef7749u, 0xe3be5e330f38f09du, 0xcb090c8001ab551cu, 0x5cadf5bfd3072cc5u, | |
| 0xfdcb4fa002162a63u, 0x73d9732fc7c8f7f6u, 0x9e9f11c4014dda7eu, 0x2867e7fddcdd9afau, | |
| 0xc646d63501a1511du, 0xb281e1fd541501b8u, 0xf7d88bc24209a565u, 0x1f225a7ca91a4226u, | |
| 0x9ae757596946075fu, 0x3375788de9b06958u, 0xc1a12d2fc3978937u, 0x0052d6b1641c83aeu, | |
| 0xf209787bb47d6b84u, 0xc0678c5dbd23a49au, 0x9745eb4d50ce6332u, 0xf840b7ba963646e0u, | |
| 0xbd176620a501fbffu, 0xb650e5a93bc3d898u, 0xec5d3fa8ce427affu, 0xa3e51f138ab4cebeu, | |
| 0x93ba47c980e98cdfu, 0xc66f336c36b10137u, 0xb8a8d9bbe123f017u, 0xb80b0047445d4184u, | |
| 0xe6d3102ad96cec1du, 0xa60dc059157491e5u, 0x9043ea1ac7e41392u, 0x87c89837ad68db2fu, | |
| 0xb454e4a179dd1877u, 0x29babe4598c311fbu, 0xe16a1dc9d8545e94u, 0xf4296dd6fef3d67au, | |
| 0x8ce2529e2734bb1du, 0x1899e4a65f58660cu, 0xb01ae745b101e9e4u, 0x5ec05dcff72e7f8fu, | |
| 0xdc21a1171d42645du, 0x76707543f4fa1f73u, 0x899504ae72497ebau, 0x6a06494a791c53a8u, | |
| 0xabfa45da0edbde69u, 0x0487db9d17636892u, 0xd6f8d7509292d603u, 0x45a9d2845d3c42b6u, | |
| 0x865b86925b9bc5c2u, 0x0b8a2392ba45a9b2u, 0xa7f26836f282b732u, 0x8e6cac7768d7141eu, | |
| 0xd1ef0244af2364ffu, 0x3207d795430cd926u, 0x8335616aed761f1fu, 0x7f44e6bd49e807b8u, | |
| 0xa402b9c5a8d3a6e7u, 0x5f16206c9c6209a6u, 0xcd036837130890a1u, 0x36dba887c37a8c0fu, | |
| 0x802221226be55a64u, 0xc2494954da2c9789u, 0xa02aa96b06deb0fdu, 0xf2db9baa10b7bd6cu, | |
| 0xc83553c5c8965d3du, 0x6f92829494e5acc7u, 0xfa42a8b73abbf48cu, 0xcb772339ba1f17f9u, | |
| 0x9c69a97284b578d7u, 0xff2a760414536efbu, 0xc38413cf25e2d70du, 0xfef5138519684abau, | |
| 0xf46518c2ef5b8cd1u, 0x7eb258665fc25d69u, 0x98bf2f79d5993802u, 0xef2f773ffbd97a61u, | |
| 0xbeeefb584aff8603u, 0xaafb550ffacfd8fau, 0xeeaaba2e5dbf6784u, 0x95ba2a53f983cf38u, | |
| 0x952ab45cfa97a0b2u, 0xdd945a747bf26183u, 0xba756174393d88dfu, 0x94f971119aeef9e4u, | |
| 0xe912b9d1478ceb17u, 0x7a37cd5601aab85du, 0x91abb422ccb812eeu, 0xac62e055c10ab33au, | |
| 0xb616a12b7fe617aau, 0x577b986b314d6009u, 0xe39c49765fdf9d94u, 0xed5a7e85fda0b80bu, | |
| 0x8e41ade9fbebc27du, 0x14588f13be847307u, 0xb1d219647ae6b31cu, 0x596eb2d8ae258fc8u, | |
| 0xde469fbd99a05fe3u, 0x6fca5f8ed9aef3bbu, 0x8aec23d680043beeu, 0x25de7bb9480d5854u, | |
| 0xada72ccc20054ae9u, 0xaf561aa79a10ae6au, 0xd910f7ff28069da4u, 0x1b2ba1518094da04u, | |
| 0x87aa9aff79042286u, 0x90fb44d2f05d0842u, 0xa99541bf57452b28u, 0x353a1607ac744a53u, | |
| 0xd3fa922f2d1675f2u, 0x42889b8997915ce8u, 0x847c9b5d7c2e09b7u, 0x69956135febada11u, | |
| 0xa59bc234db398c25u, 0x43fab9837e699095u, 0xcf02b2c21207ef2eu, 0x94f967e45e03f4bbu, | |
| 0x8161afb94b44f57du, 0x1d1be0eebac278f5u, 0xa1ba1ba79e1632dcu, 0x6462d92a69731732u, | |
| 0xca28a291859bbf93u, 0x7d7b8f7503cfdcfeu, 0xfcb2cb35e702af78u, 0x5cda735244c3d43eu, | |
| 0x9defbf01b061adabu, 0x3a0888136afa64a7u, 0xc56baec21c7a1916u, 0x088aaa1845b8fdd0u, | |
| 0xf6c69a72a3989f5bu, 0x8aad549e57273d45u, 0x9a3c2087a63f6399u, 0x36ac54e2f678864bu, | |
| 0xc0cb28a98fcf3c7fu, 0x84576a1bb416a7ddu, 0xf0fdf2d3f3c30b9fu, 0x656d44a2a11c51d5u, | |
| 0x969eb7c47859e743u, 0x9f644ae5a4b1b325u, 0xbc4665b596706114u, 0x873d5d9f0dde1feeu, | |
| 0xeb57ff22fc0c7959u, 0xa90cb506d155a7eau, 0x9316ff75dd87cbd8u, 0x09a7f12442d588f2u, | |
| 0xb7dcbf5354e9beceu, 0x0c11ed6d538aeb2fu, 0xe5d3ef282a242e81u, 0x8f1668c8a86da5fau, | |
| 0x8fa475791a569d10u, 0xf96e017d694487bcu, 0xb38d92d760ec4455u, 0x37c981dcc395a9acu, | |
| 0xe070f78d3927556au, 0x85bbe253f47b1417u, 0x8c469ab843b89562u, 0x93956d7478ccec8eu, | |
| 0xaf58416654a6babbu, 0x387ac8d1970027b2u, 0xdb2e51bfe9d0696au, 0x06997b05fcc0319eu, | |
| 0x88fcf317f22241e2u, 0x441fece3bdf81f03u, 0xab3c2fddeeaad25au, 0xd527e81cad7626c3u, | |
| 0xd60b3bd56a5586f1u, 0x8a71e223d8d3b074u, 0x85c7056562757456u, 0xf6872d5667844e49u, | |
| 0xa738c6bebb12d16cu, 0xb428f8ac016561dbu, 0xd106f86e69d785c7u, 0xe13336d701beba52u, | |
| 0x82a45b450226b39cu, 0xecc0024661173473u, 0xa34d721642b06084u, 0x27f002d7f95d0190u, | |
| 0xcc20ce9bd35c78a5u, 0x31ec038df7b441f4u, 0xff290242c83396ceu, 0x7e67047175a15271u, | |
| 0x9f79a169bd203e41u, 0x0f0062c6e984d386u, 0xc75809c42c684dd1u, 0x52c07b78a3e60868u, | |
| 0xf92e0c3537826145u, 0xa7709a56ccdf8a82u, 0x9bbcc7a142b17ccbu, 0x88a66076400bb691u, | |
| 0xc2abf989935ddbfeu, 0x6acff893d00ea435u, 0xf356f7ebf83552feu, 0x0583f6b8c4124d43u, | |
| 0x98165af37b2153deu, 0xc3727a337a8b704au, 0xbe1bf1b059e9a8d6u, 0x744f18c0592e4c5cu, | |
| 0xeda2ee1c7064130cu, 0x1162def06f79df73u, 0x9485d4d1c63e8be7u, 0x8addcb5645ac2ba8u, | |
| 0xb9a74a0637ce2ee1u, 0x6d953e2bd7173692u, 0xe8111c87c5c1ba99u, 0xc8fa8db6ccdd0437u, | |
| 0x910ab1d4db9914a0u, 0x1d9c9892400a22a2u, 0xb54d5e4a127f59c8u, 0x2503beb6d00cab4bu, | |
| 0xe2a0b5dc971f303au, 0x2e44ae64840fd61du, 0x8da471a9de737e24u, 0x5ceaecfed289e5d2u, | |
| 0xb10d8e1456105dadu, 0x7425a83e872c5f47u, 0xdd50f1996b947518u, 0xd12f124e28f77719u, | |
| 0x8a5296ffe33cc92fu, 0x82bd6b70d99aaa6fu, 0xace73cbfdc0bfb7bu, 0x636cc64d1001550bu, | |
| 0xd8210befd30efa5au, 0x3c47f7e05401aa4eu, 0x8714a775e3e95c78u, 0x65acfaec34810a71u, | |
| 0xa8d9d1535ce3b396u, 0x7f1839a741a14d0du, 0xd31045a8341ca07cu, 0x1ede48111209a050u, | |
| 0x83ea2b892091e44du, 0x934aed0aab460432u, 0xa4e4b66b68b65d60u, 0xf81da84d5617853fu, | |
| 0xce1de40642e3f4b9u, 0x36251260ab9d668eu, 0x80d2ae83e9ce78f3u, 0xc1d72b7c6b426019u, | |
| 0xa1075a24e4421730u, 0xb24cf65b8612f81fu, 0xc94930ae1d529cfcu, 0xdee033f26797b627u, | |
| 0xfb9b7cd9a4a7443cu, 0x169840ef017da3b1u, 0x9d412e0806e88aa5u, 0x8e1f289560ee864eu, | |
| 0xc491798a08a2ad4eu, 0xf1a6f2bab92a27e2u, 0xf5b5d7ec8acb58a2u, 0xae10af696774b1dbu, | |
| 0x9991a6f3d6bf1765u, 0xacca6da1e0a8ef29u, 0xbff610b0cc6edd3fu, 0x17fd090a58d32af3u, | |
| 0xeff394dcff8a948eu, 0xddfc4b4cef07f5b0u, 0x95f83d0a1fb69cd9u, 0x4abdaf101564f98eu, | |
| 0xbb764c4ca7a4440fu, 0x9d6d1ad41abe37f1u, 0xea53df5fd18d5513u, 0x84c86189216dc5edu, | |
| 0x92746b9be2f8552cu, 0x32fd3cf5b4e49bb4u, 0xb7118682dbb66a77u, 0x3fbc8c33221dc2a1u, | |
| 0xe4d5e82392a40515u, 0x0fabaf3feaa5334au, 0x8f05b1163ba6832du, 0x29cb4d87f2a7400eu, | |
| 0xb2c71d5bca9023f8u, 0x743e20e9ef511012u, 0xdf78e4b2bd342cf6u, 0x914da9246b255416u, | |
| 0x8bab8eefb6409c1au, 0x1ad089b6c2f7548eu, 0xae9672aba3d0c320u, 0xa184ac2473b529b1u, | |
| 0xda3c0f568cc4f3e8u, 0xc9e5d72d90a2741eu, 0x8865899617fb1871u, 0x7e2fa67c7a658892u, | |
| 0xaa7eebfb9df9de8du, 0xddbb901b98feeab7u, 0xd51ea6fa85785631u, 0x552a74227f3ea565u, | |
| 0x8533285c936b35deu, 0xd53a88958f87275fu, 0xa67ff273b8460356u, 0x8a892abaf368f137u, | |
| 0xd01fef10a657842cu, 0x2d2b7569b0432d85u, 0x8213f56a67f6b29bu, 0x9c3b29620e29fc73u, | |
| 0xa298f2c501f45f42u, 0x8349f3ba91b47b8fu, 0xcb3f2f7642717713u, 0x241c70a936219a73u, | |
| 0xfe0efb53d30dd4d7u, 0xed238cd383aa0110u, 0x9ec95d1463e8a506u, 0xf4363804324a40aau, | |
| 0xc67bb4597ce2ce48u, 0xb143c6053edcd0d5u, 0xf81aa16fdc1b81dau, 0xdd94b7868e94050au, | |
| 0x9b10a4e5e9913128u, 0xca7cf2b4191c8326u, 0xc1d4ce1f63f57d72u, 0xfd1c2f611f63a3f0u, | |
| 0xf24a01a73cf2dccfu, 0xbc633b39673c8cecu, 0x976e41088617ca01u, 0xd5be0503e085d813u, | |
| 0xbd49d14aa79dbc82u, 0x4b2d8644d8a74e18u, 0xec9c459d51852ba2u, 0xddf8e7d60ed1219eu, | |
| 0x93e1ab8252f33b45u, 0xcabb90e5c942b503u, 0xb8da1662e7b00a17u, 0x3d6a751f3b936243u, | |
| 0xe7109bfba19c0c9du, 0x0cc512670a783ad4u, 0x906a617d450187e2u, 0x27fb2b80668b24c5u, | |
| 0xb484f9dc9641e9dau, 0xb1f9f660802dedf6u, 0xe1a63853bbd26451u, 0x5e7873f8a0396973u, | |
| 0x8d07e33455637eb2u, 0xdb0b487b6423e1e8u, 0xb049dc016abc5e5fu, 0x91ce1a9a3d2cda62u, | |
| 0xdc5c5301c56b75f7u, 0x7641a140cc7810fbu, 0x89b9b3e11b6329bau, 0xa9e904c87fcb0a9du, | |
| 0xac2820d9623bf429u, 0x546345fa9fbdcd44u, 0xd732290fbacaf133u, 0xa97c177947ad4095u, | |
| 0x867f59a9d4bed6c0u, 0x49ed8eabcccc485du, 0xa81f301449ee8c70u, 0x5c68f256bfff5a74u, | |
| 0xd226fc195c6a2f8cu, 0x73832eec6fff3111u, 0x83585d8fd9c25db7u, 0xc831fd53c5ff7eabu, | |
| 0xa42e74f3d032f525u, 0xba3e7ca8b77f5e55u, 0xcd3a1230c43fb26fu, 0x28ce1bd2e55f35ebu, | |
| 0x80444b5e7aa7cf85u, 0x7980d163cf5b81b3u, 0xa0555e361951c366u, 0xd7e105bcc332621fu, | |
| 0xc86ab5c39fa63440u, 0x8dd9472bf3fefaa7u, 0xfa856334878fc150u, 0xb14f98f6f0feb951u, | |
| 0x9c935e00d4b9d8d2u, 0x6ed1bf9a569f33d3u, 0xc3b8358109e84f07u, 0x0a862f80ec4700c8u, | |
| 0xf4a642e14c6262c8u, 0xcd27bb612758c0fau, 0x98e7e9cccfbd7dbdu, 0x8038d51cb897789cu, | |
| 0xbf21e44003acdd2cu, 0xe0470a63e6bd56c3u, 0xeeea5d5004981478u, 0x1858ccfce06cac74u, | |
| 0x95527a5202df0ccbu, 0x0f37801e0c43ebc8u, 0xbaa718e68396cffdu, 0xd30560258f54e6bau, | |
| 0xe950df20247c83fdu, 0x47c6b82ef32a2069u, 0x91d28b7416cdd27eu, 0x4cdc331d57fa5441u, | |
| 0xb6472e511c81471du, 0xe0133fe4adf8e952u, 0xe3d8f9e563a198e5u, 0x58180fddd97723a6u, | |
| 0x8e679c2f5e44ff8fu, 0x570f09eaa7ea7648u, | |
| } | |
| }; | |
| return table; | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // std::from_chars lives in <charconv>, but being in C++17 mode does not | |
| // guarantee the header exists: GCC 7 sets __cplusplus to C++17 yet ships no | |
| // <charconv> (added in GCC 8; floating-point support in GCC 11). Guard the | |
| // include with __has_include so such toolchains fall back to the scalar path. | |
| #if defined(JSON_HAS_CPP_17) && defined(__has_include) | |
| #if __has_include(<charconv>) | |
| #include <charconv> // from_chars (only used when __cpp_lib_to_chars is defined) | |
| #include <system_error> // errc | |
| #endif | |
| #endif | |
| // This file contains the value-conversion helpers used by the lexer to turn an | |
| // already-validated number token into a value. Integers and binary32/binary64 | |
| // floats (float, double, and long double where it is binary64) are converted | |
| // by the library itself, without the locale/errno overhead of | |
| // std::strtoull/std::strtod and correctly rounded; other long double formats | |
| // use std::from_chars or std::strtold. They are free functions so the lexer | |
| // stays focused on scanning (see lexer::convert_number()) and so that other | |
| // parsers of JSON text can convert tokens exactly like it does. | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| // whether an integer of a signed type is negative; the overload for other types | |
| // avoids comparing an unsigned value with zero | |
| template<typename NumberType> | |
| constexpr bool is_negative_integer(NumberType x, std::true_type /*is_signed*/) noexcept | |
| { | |
| return x < 0; | |
| } | |
| template<typename NumberType> | |
| constexpr bool is_negative_integer(NumberType /*unused*/, std::false_type /*is_signed*/) noexcept | |
| { | |
| return false; | |
| } | |
| /*! | |
| @brief fast integer parser for an already-validated unsigned integer | |
| The number scanner has already checked that [first, last) is a valid JSON | |
| integer, so this only needs to accumulate the digits and detect overflow. This | |
| avoids the locale/errno machinery of std::strtoull, which dominates | |
| integer-heavy inputs. | |
| @param[in] first pointer to the first character (a digit) | |
| @param[in] last pointer past the last character | |
| @param[out] value the parsed value on success | |
| @return true if the value fit into @a NumberUnsignedType; false on overflow, in | |
| which case the caller falls back to floating-point parsing (matching the | |
| previous std::strtoull behavior) | |
| */ | |
| template<typename NumberUnsignedType> | |
| bool parse_integer_unsigned(const char* first, const char* last, NumberUnsignedType& value) noexcept | |
| { | |
| // accumulate in the widest unsigned type used by the previous strtoull | |
| // path so the overflow behavior is unchanged for custom number types | |
| std::uint64_t x = 0; | |
| constexpr std::uint64_t cutoff = (std::numeric_limits<std::uint64_t>::max)() / 10u; | |
| constexpr std::uint64_t cutlim = (std::numeric_limits<std::uint64_t>::max)() % 10u; | |
| for (const char* p = first; p != last; ++p) | |
| { | |
| const auto digit = static_cast<std::uint64_t>(static_cast<unsigned char>(*p) - static_cast<unsigned char>('0')); | |
| if (JSON_HEDLEY_UNLIKELY(x > cutoff || (x == cutoff && digit > cutlim))) | |
| { | |
| return false; | |
| } | |
| x = (x * 10u) + digit; | |
| } | |
| value = static_cast<NumberUnsignedType>(x); | |
| // reject values that do not round-trip into a narrower NumberUnsignedType, | |
| // and values that wrap around to negative numbers if it is a signed type | |
| // (number_unsigned_t may be the same type as number_integer_t, #2573) | |
| return static_cast<std::uint64_t>(value) == x && !is_negative_integer(value, std::is_signed<NumberUnsignedType>()); | |
| } | |
| /*! | |
| @brief fast integer parser for an already-validated negative integer | |
| @param[in] first pointer to the leading '-' | |
| @param[in] last pointer past the last character | |
| @param[out] value the parsed (negative) value on success | |
| @return true on success; false on overflow (caller falls back to float) | |
| */ | |
| template<typename NumberIntegerType> | |
| bool parse_integer_signed(const char* first, const char* last, NumberIntegerType& value) noexcept | |
| { | |
| // the state machine only reaches the signed path via a leading '-' | |
| JSON_ASSERT(first != last && *first == '-'); | |
| std::uint64_t magnitude = 0; | |
| // |INT64_MIN| == INT64_MAX + 1; this is the largest admissible magnitude | |
| constexpr std::uint64_t limit = static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()) + 1u; | |
| for (const char* p = first + 1; p != last; ++p) | |
| { | |
| const auto digit = static_cast<std::uint64_t>(static_cast<unsigned char>(*p) - static_cast<unsigned char>('0')); | |
| if (JSON_HEDLEY_UNLIKELY(magnitude > (limit - digit) / 10u)) | |
| { | |
| return false; | |
| } | |
| magnitude = (magnitude * 10u) + digit; | |
| } | |
| const std::int64_t x = (magnitude == limit) | |
| ? (std::numeric_limits<std::int64_t>::min)() | |
| : -static_cast<std::int64_t>(magnitude); | |
| value = static_cast<NumberIntegerType>(x); | |
| // reject values that do not round-trip into a narrower NumberIntegerType | |
| return static_cast<std::int64_t>(value) == x; | |
| } | |
| /*! | |
| @brief parameters of the IEEE-754 binary32 and binary64 formats for the float | |
| conversion (after fast_float's binary_format) | |
| */ | |
| template<int Digits> | |
| struct ieee_binary_format; | |
| template<> | |
| struct ieee_binary_format<24> // binary32 | |
| { | |
| static constexpr int mantissa_bits() noexcept | |
| { | |
| return 23; | |
| } | |
| static constexpr int sign_bit() noexcept | |
| { | |
| return 31; | |
| } | |
| static constexpr int minimum_exponent() noexcept | |
| { | |
| return -127; | |
| } | |
| static constexpr int infinite_power() noexcept | |
| { | |
| return 0xFF; | |
| } | |
| // w * 10^q with w < 2^64 is below half the smallest subnormal number for | |
| // q < smallest_power_of_ten() and at least infinity for q > largest_power_of_ten() | |
| static constexpr int smallest_power_of_ten() noexcept | |
| { | |
| return -64; | |
| } | |
| static constexpr int largest_power_of_ten() noexcept | |
| { | |
| return 38; | |
| } | |
| // w * 10^q can only be exactly between two numbers for q in this range | |
| static constexpr int min_exponent_round_to_even() noexcept | |
| { | |
| return -17; | |
| } | |
| static constexpr int max_exponent_round_to_even() noexcept | |
| { | |
| return 10; | |
| } | |
| // Clinger's fast path: w and 10^|q| are exact | |
| static constexpr int max_exponent_fast_path() noexcept | |
| { | |
| return 10; | |
| } | |
| static constexpr std::uint64_t max_mantissa_fast_path() noexcept | |
| { | |
| return std::uint64_t{2} << 23u; | |
| } | |
| // a midpoint between two numbers has at most this many significant digits | |
| static constexpr std::int64_t max_digits() noexcept | |
| { | |
| return 114; | |
| } | |
| }; | |
| template<> | |
| struct ieee_binary_format<53> // binary64 | |
| { | |
| static constexpr int mantissa_bits() noexcept | |
| { | |
| return 52; | |
| } | |
| static constexpr int sign_bit() noexcept | |
| { | |
| return 63; | |
| } | |
| static constexpr int minimum_exponent() noexcept | |
| { | |
| return -1023; | |
| } | |
| static constexpr int infinite_power() noexcept | |
| { | |
| return 0x7FF; | |
| } | |
| static constexpr int smallest_power_of_ten() noexcept | |
| { | |
| return -342; | |
| } | |
| static constexpr int largest_power_of_ten() noexcept | |
| { | |
| return 308; | |
| } | |
| static constexpr int min_exponent_round_to_even() noexcept | |
| { | |
| return -4; | |
| } | |
| static constexpr int max_exponent_round_to_even() noexcept | |
| { | |
| return 23; | |
| } | |
| static constexpr int max_exponent_fast_path() noexcept | |
| { | |
| return 22; | |
| } | |
| static constexpr std::uint64_t max_mantissa_fast_path() noexcept | |
| { | |
| return std::uint64_t{2} << 52u; | |
| } | |
| static constexpr std::int64_t max_digits() noexcept | |
| { | |
| return 769; | |
| } | |
| }; | |
| /*! | |
| @brief whether @a FloatType is IEEE-754 binary32 or binary64 | |
| These formats (float, double, and long double where it is binary64, e.g. | |
| with MSVC or on Apple arm64) are converted by parse_float_native(). The | |
| predicate is the one the serializer uses to choose Grisu2. | |
| */ | |
| template<typename FloatType> | |
| struct has_native_float_format | |
| { | |
| static constexpr bool value = | |
| (std::numeric_limits<FloatType>::is_iec559 && std::numeric_limits<FloatType>::digits == 24 && std::numeric_limits<FloatType>::max_exponent == 128) || | |
| (std::numeric_limits<FloatType>::is_iec559 && std::numeric_limits<FloatType>::digits == 53 && std::numeric_limits<FloatType>::max_exponent == 1024); | |
| }; | |
| /// the C++ type (float or double) that holds a binary32 or binary64 @a FloatType | |
| template<typename FloatType> | |
| using native_float_t = typename std::conditional<std::numeric_limits<FloatType>::digits == 24, float, double>::type; | |
| /// the value of the eight ASCII digits in @a v (see read_eight_bytes()), three | |
| /// multiplications instead of eight (after simdjson and fast_float); always | |
| /// inlined, as GCC otherwise calls it in the number loops | |
| JSON_HEDLEY_ALWAYS_INLINE std::uint32_t parse_eight_digits(std::uint64_t v) noexcept | |
| { | |
| v = ((v & 0x0F0F0F0F0F0F0F0Fu) * 2561u) >> 8u; | |
| v = ((v & 0x00FF00FF00FF00FFu) * 6553601u) >> 16u; | |
| return static_cast<std::uint32_t>(((v & 0x0000FFFF0000FFFFu) * 42949672960001u) >> 32u); | |
| } | |
| /// whether the eight bytes in @a v (see read_eight_bytes()) are all ASCII | |
| /// digits (after fast_float) | |
| JSON_HEDLEY_ALWAYS_INLINE bool is_eight_digits(std::uint64_t v) noexcept | |
| { | |
| return ((v & 0xF0F0F0F0F0F0F0F0u) | (((v + 0x0606060606060606u) & 0xF0F0F0F0F0F0F0F0u) >> 4u)) == 0x3333333333333333u; | |
| } | |
| /*! | |
| @brief skip the ASCII digits starting at data[i] and accumulate their value | |
| Eight digits are taken at a time while at least eight bytes remain. @a w wraps | |
| around after 19 digits; the caller only uses it for shorter digit runs. | |
| @return the index of the first byte at or after @a i that is not a digit | |
| */ | |
| JSON_HEDLEY_ALWAYS_INLINE std::size_t accumulate_digits(const char* data, std::size_t i, std::size_t avail, std::uint64_t& w) noexcept | |
| { | |
| while (avail - i >= 8) | |
| { | |
| const std::uint64_t v = read_eight_bytes(data + i); | |
| if (!is_eight_digits(v)) | |
| { | |
| break; | |
| } | |
| w = (w * 100000000u) + parse_eight_digits(v); | |
| i += 8; | |
| } | |
| while (i < avail && data[i] >= '0' && data[i] <= '9') | |
| { | |
| w = (w * 10u) + static_cast<std::uint64_t>(data[i] - '0'); | |
| ++i; | |
| } | |
| return i; | |
| } | |
| /// whether [first, last) contains a digit other than '0'; a plain loop, as | |
| /// GCC calls std::any_of out of line even for the usual empty range | |
| JSON_HEDLEY_ALWAYS_INLINE bool has_nonzero_digit(const char* first, const char* last) noexcept | |
| { | |
| for (; first != last; ++first) | |
| { | |
| if (*first != '0') | |
| { | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| /*! | |
| @brief accumulate the validated digits [p, last) into @a w, as long as | |
| @a remaining digits still fit into it | |
| Eight digits are taken at a time while at least eight remain, and @a remaining | |
| is decreased by the number of digits taken. | |
| @return a pointer past the last digit taken | |
| */ | |
| JSON_HEDLEY_ALWAYS_INLINE const char* accumulate_significant_digits(const char* p, const char* last, int& remaining, std::uint64_t& w) noexcept | |
| { | |
| while (remaining >= 8 && last - p >= 8) | |
| { | |
| w = (w * 100000000u) + parse_eight_digits(read_eight_bytes(p)); | |
| p += 8; | |
| remaining -= 8; | |
| } | |
| for (; remaining > 0 && p != last; ++p, --remaining) | |
| { | |
| w = (w * 10u) + static_cast<std::uint64_t>(*p - '0'); | |
| } | |
| return p; | |
| } | |
| /// the value of the validated exponent digits [+-]?[0-9]+ in [first, last), | |
| /// saturated far beyond every range | |
| inline std::int64_t parse_float_exponent(const char* first, const char* last) noexcept | |
| { | |
| const bool negative = *first == '-'; | |
| first += (*first == '-' || *first == '+') ? 1 : 0; | |
| constexpr std::int64_t saturation = 100000000000000000; // 10^17 | |
| std::int64_t value = 0; | |
| for (; first != last; ++first) | |
| { | |
| if (value < saturation) | |
| { | |
| value = (value * 10) + (*first - '0'); | |
| } | |
| } | |
| return negative ? -value : value; | |
| } | |
| /// a float token as w * 10^exponent, see parse_float_significand() | |
| struct float_significand | |
| { | |
| std::uint64_t w = 0; ///< the first (at most 19) significant digits | |
| std::int64_t exponent = 0; ///< the decimal exponent of the last digit in w | |
| bool negative = false; ///< whether the token starts with '-' | |
| bool truncated = false; ///< whether nonzero digits follow the ones in w | |
| }; | |
| /*! | |
| @brief split a validated number token into sign, significand, and exponent | |
| The lexer has validated the token against the JSON grammar and knows where its | |
| parts are, so this needs no character classification: the integer part ends at | |
| @a decimal_point_position (or @a mantissa_end), the fraction at @a mantissa_end, | |
| and an exponent follows. At most 19 significant digits are kept; the value then | |
| lies in [w, w + 1) * 10^exponent, and is exactly w * 10^exponent unless | |
| truncated is set. | |
| @param[in] first pointer to the first character of the token | |
| @param[in] last pointer past the last character | |
| @param[in] decimal_point_position index of the '.' in the token, or | |
| std::string::npos if there is none | |
| @param[in] mantissa_end index of the 'e'/'E', or the token length | |
| */ | |
| JSON_HEDLEY_ALWAYS_INLINE float_significand parse_float_significand(const char* first, const char* last, | |
| std::size_t decimal_point_position, std::size_t mantissa_end) noexcept | |
| { | |
| float_significand s; | |
| const char* p = first; | |
| s.negative = *p == '-'; | |
| p += s.negative ? 1 : 0; | |
| const bool has_dot = decimal_point_position != std::string::npos; | |
| const char* const mantissa_last = first + mantissa_end; | |
| const char* const integer_last = has_dot ? first + decimal_point_position : mantissa_last; | |
| std::uint64_t w = 0; | |
| int remaining = 19; // digits that still fit into w | |
| if (*p != '0') // the integer part is "0" or [1-9][0-9]* | |
| { | |
| p = accumulate_significant_digits(p, integer_last, remaining, w); | |
| s.exponent = integer_last - p; | |
| s.truncated = has_nonzero_digit(p, integer_last); | |
| } | |
| if (has_dot) | |
| { | |
| p = integer_last + 1; | |
| if (w == 0) | |
| { | |
| // zeros after the decimal point of "0." are not significant | |
| const char* const zeros = p; | |
| while (p != mantissa_last && *p == '0') | |
| { | |
| ++p; | |
| } | |
| s.exponent -= p - zeros; | |
| } | |
| const char* const digits = p; | |
| p = accumulate_significant_digits(p, mantissa_last, remaining, w); | |
| s.exponent -= p - digits; | |
| s.truncated = s.truncated || has_nonzero_digit(p, mantissa_last); | |
| } | |
| if (mantissa_last != last) | |
| { | |
| s.exponent += parse_float_exponent(mantissa_last + 1, last); | |
| } | |
| s.w = w; | |
| return s; | |
| } | |
| /*! | |
| @brief the bits of the float nearest to w * 10^q (Eisel-Lemire) | |
| The algorithm of Daniel Lemire, "Number Parsing at a Gigabyte per Second" | |
| (Software: Practice and Experience, 2021), after fast_float's compute_float | |
| (used under the MIT license). With a 128-bit approximation of 5^q, the product | |
| is always sufficient to round correctly for w < 2^64 (Noble Mushtak and Daniel | |
| Lemire, "Fast number parsing without fallback", Software: Practice and | |
| Experience, 2023). Only integer arithmetic is used, so the result does not | |
| depend on the floating-point environment. | |
| It is always inlined, like decimal_to_float(), so that hot loops of callers | |
| keep the whole conversion inline. | |
| @tparam Format ieee_binary_format<24> (binary32) or ieee_binary_format<53> (binary64) | |
| @param[in] q decimal exponent | |
| @param[in] w significand | |
| @return the IEEE-754 bits of the positive result (0 for underflow, infinity | |
| for overflow) | |
| */ | |
| template<typename Format> | |
| JSON_HEDLEY_ALWAYS_INLINE std::uint64_t eisel_lemire(std::int64_t q, std::uint64_t w) noexcept | |
| { | |
| constexpr int mantissa_bits = Format::mantissa_bits(); | |
| constexpr std::uint64_t infinity = static_cast<std::uint64_t>(Format::infinite_power()) << mantissa_bits; | |
| if (w == 0 || q < Format::smallest_power_of_ten()) | |
| { | |
| return 0; | |
| } | |
| if (q > Format::largest_power_of_ten()) | |
| { | |
| return infinity; | |
| } | |
| const int lz = count_leading_zeros(w); | |
| w <<= static_cast<unsigned>(lz); | |
| const auto index = static_cast<std::size_t>(2 * (q - pow5_128_smallest_power)); | |
| uint128_parts product = full_multiplication(w, pow5_128()[index]); | |
| constexpr std::uint64_t precision_mask = 0xFFFFFFFFFFFFFFFFu >> (mantissa_bits + 3); | |
| if ((product.high & precision_mask) == precision_mask) | |
| { | |
| // the lower bits may carry into the result: use the next 64 bits of 5^q | |
| const uint128_parts second = full_multiplication(w, pow5_128()[index + 1]); | |
| product.low += second.high; | |
| if (second.high > product.low) | |
| { | |
| ++product.high; | |
| } | |
| } | |
| const auto upperbit = static_cast<int>(product.high >> 63u); | |
| const int shift = upperbit + 64 - mantissa_bits - 3; | |
| std::uint64_t mantissa = product.high >> static_cast<unsigned>(shift); | |
| // floor(log2(10^q)) + 63 + bias, with log2(10) ~ 217706 / 2^16 | |
| std::int64_t power2 = (((152170 + 65536) * q) >> 16) + 63 + upperbit - lz - Format::minimum_exponent(); | |
| if (power2 <= 0) // subnormal | |
| { | |
| if (-power2 + 1 >= 64) | |
| { | |
| return 0; | |
| } | |
| mantissa >>= static_cast<unsigned>(-power2 + 1); | |
| // no tie is possible here: that needs a small |q| | |
| mantissa += (mantissa & 1u); | |
| mantissa >>= 1u; | |
| // rounding up may produce the smallest normal number | |
| power2 = (mantissa < (std::uint64_t{1} << mantissa_bits)) ? 0 : 1; | |
| return (mantissa & ((std::uint64_t{1} << mantissa_bits) - 1)) | (static_cast<std::uint64_t>(power2) << mantissa_bits); | |
| } | |
| // a value exactly between two floats rounds to even; this can only | |
| // happen for small |q|, where 5^q is exact | |
| if (product.low <= 1 && q >= Format::min_exponent_round_to_even() && q <= Format::max_exponent_round_to_even() | |
| && (mantissa & 3u) == 1 && (mantissa << static_cast<unsigned>(shift)) == product.high) | |
| { | |
| mantissa &= ~std::uint64_t{1}; | |
| } | |
| mantissa += (mantissa & 1u); | |
| mantissa >>= 1u; | |
| if (mantissa >= (std::uint64_t{2} << mantissa_bits)) | |
| { | |
| mantissa = std::uint64_t{1} << mantissa_bits; | |
| ++power2; | |
| } | |
| mantissa &= ~(std::uint64_t{1} << mantissa_bits); | |
| if (power2 >= Format::infinite_power()) | |
| { | |
| return infinity; | |
| } | |
| return mantissa | (static_cast<std::uint64_t>(power2) << mantissa_bits); | |
| } | |
| /// an unsigned integer of up to 4096 bits for digit_comparison() (32-bit limbs, | |
| /// so only 32x32->64-bit multiplications are needed) | |
| class float_bigint | |
| { | |
| public: | |
| explicit float_bigint(std::uint64_t value) noexcept | |
| { | |
| for (; value != 0; value >>= 32u) | |
| { | |
| limbs[count++] = static_cast<std::uint32_t>(value); | |
| } | |
| } | |
| /// *this = *this * factor + summand | |
| void multiply_add(std::uint32_t factor, std::uint32_t summand) noexcept | |
| { | |
| std::uint64_t carry = summand; | |
| for (std::size_t i = 0; i < count; ++i) | |
| { | |
| const std::uint64_t product = (static_cast<std::uint64_t>(limbs[i]) * factor) + carry; | |
| limbs[i] = static_cast<std::uint32_t>(product); | |
| carry = product >> 32u; | |
| } | |
| if (carry != 0) | |
| { | |
| JSON_ASSERT(count < limbs.size()); | |
| limbs[count++] = static_cast<std::uint32_t>(carry); | |
| } | |
| } | |
| /// *this = *this * 5^n | |
| void multiply_power_of_five(std::int64_t n) noexcept | |
| { | |
| static const std::array<std::uint32_t, 14> powers = | |
| { | |
| {1u, 5u, 25u, 125u, 625u, 3125u, 15625u, 78125u, 390625u, 1953125u, 9765625u, 48828125u, 244140625u, 1220703125u} | |
| }; | |
| for (; n >= 13; n -= 13) | |
| { | |
| multiply_add(powers[13], 0); | |
| } | |
| multiply_add(powers[static_cast<std::size_t>(n)], 0); | |
| } | |
| /// *this = *this * 2^n | |
| void shift_left(std::int64_t n) noexcept | |
| { | |
| if (count == 0) | |
| { | |
| return; | |
| } | |
| const auto limb_shift = static_cast<std::size_t>(n / 32); | |
| const auto bit_shift = static_cast<unsigned>(n % 32); | |
| JSON_ASSERT(count + limb_shift + 1 <= limbs.size()); | |
| if (bit_shift != 0) | |
| { | |
| std::uint32_t carry = 0; | |
| for (std::size_t i = 0; i < count; ++i) | |
| { | |
| const std::uint32_t limb = limbs[i]; | |
| limbs[i] = (limb << bit_shift) | carry; | |
| carry = limb >> (32u - bit_shift); | |
| } | |
| if (carry != 0) | |
| { | |
| limbs[count++] = carry; | |
| } | |
| } | |
| if (limb_shift != 0) | |
| { | |
| for (std::size_t i = count; i-- > 0;) | |
| { | |
| limbs[i + limb_shift] = limbs[i]; | |
| } | |
| for (std::size_t i = 0; i < limb_shift; ++i) | |
| { | |
| limbs[i] = 0; | |
| } | |
| count += limb_shift; | |
| } | |
| } | |
| /// -1, 0, or 1 if *this is less than, equal to, or greater than @a other | |
| int compare(const float_bigint& other) const noexcept | |
| { | |
| if (count != other.count) | |
| { | |
| return count < other.count ? -1 : 1; | |
| } | |
| for (std::size_t i = count; i-- > 0;) | |
| { | |
| if (limbs[i] != other.limbs[i]) | |
| { | |
| return limbs[i] < other.limbs[i] ? -1 : 1; | |
| } | |
| } | |
| return 0; | |
| } | |
| private: | |
| std::array<std::uint32_t, 128> limbs{{}}; | |
| std::size_t count = 0; | |
| }; | |
| /*! | |
| @brief round a token exactly when eisel_lemire() cannot decide (slow path) | |
| The value v of the token lies strictly between two adjacent floats, whose | |
| lower one has the bits @a lower, and the result depends on whether v is below, | |
| at, or above the midpoint m between them. Both are compared exactly as big | |
| integers: v = D * 10^s with the significant digits D (at most | |
| Format::max_digits() of them, more than any midpoint has; further nonzero | |
| digits only put v above m) and m = (2 * mantissa + 1) * 2^(e - 1). This is the | |
| digit comparison of fast_float (Daniel Lemire and contributors, used under the | |
| MIT license), simplified by starting from the two candidates. | |
| @param[in] first pointer to the first character of the token | |
| @param[in] last pointer past the last character | |
| @param[in] lower the bits of the float below v | |
| @return the bits of the correctly rounded result | |
| */ | |
| template<typename Format> | |
| std::uint64_t digit_comparison(const char* first, const char* last, std::uint64_t lower) noexcept | |
| { | |
| const char* p = first + ((*first == '-') ? 1 : 0); | |
| // D, in chunks of up to 9 digits, and s | |
| float_bigint digits(0); | |
| std::int64_t count = 0; | |
| std::int64_t point = 0; // the value is 0.D... * 10^point | |
| bool truncated = false; | |
| std::uint32_t chunk = 0; | |
| int chunk_digits = 0; | |
| static const std::array<std::uint32_t, 10> powers_of_ten = {{1u, 10u, 100u, 1000u, 10000u, 100000u, 1000000u, 10000000u, 100000000u, 1000000000u}}; | |
| const auto append = [&](char c) noexcept | |
| { | |
| if (count < Format::max_digits()) | |
| { | |
| chunk = (chunk * 10u) + static_cast<std::uint32_t>(c - '0'); | |
| ++count; | |
| if (++chunk_digits == 9) | |
| { | |
| digits.multiply_add(powers_of_ten[9], chunk); | |
| chunk = 0; | |
| chunk_digits = 0; | |
| } | |
| } | |
| else | |
| { | |
| truncated = truncated || c != '0'; | |
| } | |
| }; | |
| bool significant = false; | |
| for (; p != last && *p >= '0' && *p <= '9'; ++p) | |
| { | |
| significant = significant || *p != '0'; | |
| if (significant) | |
| { | |
| append(*p); | |
| ++point; | |
| } | |
| } | |
| if (p != last && *p == '.') | |
| { | |
| for (++p; p != last && *p >= '0' && *p <= '9'; ++p) | |
| { | |
| significant = significant || *p != '0'; | |
| if (significant) | |
| { | |
| append(*p); | |
| } | |
| else | |
| { | |
| --point; | |
| } | |
| } | |
| } | |
| if (chunk_digits != 0) | |
| { | |
| digits.multiply_add(powers_of_ten[static_cast<std::size_t>(chunk_digits)], chunk); | |
| } | |
| if (p != last) | |
| { | |
| point += parse_float_exponent(p + 1, last); | |
| } | |
| const std::int64_t s = point - count; // v = D * 10^s | |
| // the midpoint above the lower candidate | |
| constexpr int mantissa_bits = Format::mantissa_bits(); | |
| const std::uint64_t exponent_field = lower >> mantissa_bits; | |
| std::uint64_t mantissa = lower & ((std::uint64_t{1} << mantissa_bits) - 1); | |
| std::int64_t e = 1 + Format::minimum_exponent() - mantissa_bits; // of the smallest subnormal number | |
| if (exponent_field != 0) | |
| { | |
| mantissa |= std::uint64_t{1} << mantissa_bits; | |
| e += static_cast<std::int64_t>(exponent_field) - 1; | |
| } | |
| float_bigint midpoint((2 * mantissa) + 1); | |
| const std::int64_t midpoint_exponent = e - 1; // m = midpoint * 2^midpoint_exponent | |
| // compare D * 5^s * 2^s with midpoint * 2^midpoint_exponent | |
| if (s >= 0) | |
| { | |
| digits.multiply_power_of_five(s); | |
| } | |
| else | |
| { | |
| midpoint.multiply_power_of_five(-s); | |
| } | |
| const std::int64_t shift = s - midpoint_exponent; | |
| if (shift >= 0) | |
| { | |
| digits.shift_left(shift); | |
| } | |
| else | |
| { | |
| midpoint.shift_left(-shift); | |
| } | |
| const int order = digits.compare(midpoint); | |
| const bool round_up = order > 0 || (order == 0 && (truncated || (mantissa & 1u) != 0)); | |
| return lower + (round_up ? 1u : 0u); | |
| } | |
| /// the double with the IEEE-754 bits @a bits | |
| inline void float_from_bits(std::uint64_t bits, double& value) noexcept | |
| { | |
| static_assert(sizeof(double) == sizeof(std::uint64_t), "double must have 64 bits"); | |
| value = bit_cast<double>(bits); | |
| } | |
| /// the float with the IEEE-754 bits @a bits (the lower 32) | |
| inline void float_from_bits(std::uint64_t bits, float& value) noexcept | |
| { | |
| static_assert(sizeof(float) == sizeof(std::uint32_t), "float must have 32 bits"); | |
| value = bit_cast<float>(static_cast<std::uint32_t>(bits)); | |
| } | |
| /// the powers of ten that are exact in binary64 (up to 10^22) | |
| inline double exact_power_of_ten(std::int64_t n, double /*tag*/) noexcept | |
| { | |
| static const std::array<double, 23> powers = | |
| { | |
| { | |
| 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, | |
| 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22 | |
| } | |
| }; | |
| return powers[static_cast<std::size_t>(n)]; | |
| } | |
| /// the powers of ten that are exact in binary32 (up to 10^10) | |
| inline float exact_power_of_ten(std::int64_t n, float /*tag*/) noexcept | |
| { | |
| static const std::array<float, 11> powers = | |
| { | |
| {1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f, 1e7f, 1e8f, 1e9f, 1e10f} | |
| }; | |
| return powers[static_cast<std::size_t>(n)]; | |
| } | |
| /*! | |
| @brief the binary32/binary64 value of a significand that was not truncated | |
| The result is (-1)^negative * w * 10^exponent, correctly rounded (ties to | |
| even): with Clinger's fast path where w and 10^|exponent| are exact, so that a | |
| single floating-point operation rounds (only where intermediate results are not | |
| kept in extended precision, see FLT_EVAL_METHOD), and with eisel_lemire() | |
| otherwise. A value too large for the type becomes ±infinity, a value too small | |
| ±0. | |
| This is the core of the conversion that other parsers of JSON text share: they | |
| can split a token themselves and still get the lexer's result. It is always | |
| inlined, so that their hot loops keep the whole conversion inline. | |
| @param[in] s the significand, with s.truncated == false | |
| */ | |
| template<typename FloatType> | |
| JSON_HEDLEY_ALWAYS_INLINE FloatType decimal_to_float(const float_significand& s) noexcept | |
| { | |
| using result_type = native_float_t<FloatType>; | |
| using format = ieee_binary_format<std::numeric_limits<FloatType>::digits>; | |
| JSON_ASSERT(!s.truncated); | |
| #if !defined(FLT_EVAL_METHOD) || FLT_EVAL_METHOD == 0 | |
| if (s.exponent >= -format::max_exponent_fast_path() && s.exponent <= format::max_exponent_fast_path() | |
| && s.w <= format::max_mantissa_fast_path()) | |
| { | |
| auto value = static_cast<result_type>(s.w); | |
| if (s.exponent < 0) | |
| { | |
| value /= exact_power_of_ten(-s.exponent, result_type{}); | |
| } | |
| else | |
| { | |
| value *= exact_power_of_ten(s.exponent, result_type{}); | |
| } | |
| const FloatType result = s.negative ? -value : value; | |
| return result; | |
| } | |
| #endif | |
| result_type value{}; | |
| float_from_bits(eisel_lemire<format>(s.exponent, s.w) | (s.negative ? (std::uint64_t{1} << format::sign_bit()) : 0u), value); | |
| const FloatType result = value; | |
| return result; | |
| } | |
| /*! | |
| @brief convert a validated number token to the nearest binary32/binary64 value | |
| The conversion is correctly rounded (ties to even) and independent of the | |
| locale and of the C and C++ libraries: | |
| 1. parse_float_significand() splits the token into w * 10^q. | |
| 2. If no digits were dropped, decimal_to_float() rounds w * 10^q (Clinger's | |
| fast path or Eisel-Lemire). | |
| 3. Otherwise, the value lies in [w, w + 1) * 10^q: if eisel_lemire() rounds | |
| both ends to the same value, so does the token (in all but rare cases). | |
| 4. Otherwise, digit_comparison() compares the token exactly with the midpoint | |
| between the two candidates. | |
| A value too large for the type becomes ±infinity (the parser reports | |
| out_of_range.406), a value too small ±0. | |
| @param[in] first pointer to the first character of the token | |
| @param[in] last pointer past the last character | |
| @param[in] decimal_point_position index of the '.' in the token, or | |
| std::string::npos if there is none | |
| @param[in] mantissa_end index of the 'e'/'E', or the token length | |
| */ | |
| template<typename FloatType> | |
| FloatType parse_float_native(const char* first, const char* last, | |
| std::size_t decimal_point_position, std::size_t mantissa_end) noexcept | |
| { | |
| using result_type = native_float_t<FloatType>; | |
| using format = ieee_binary_format<std::numeric_limits<FloatType>::digits>; | |
| static_assert(std::numeric_limits<result_type>::digits == std::numeric_limits<FloatType>::digits, "unexpected float format"); | |
| const float_significand s = parse_float_significand(first, last, decimal_point_position, mantissa_end); | |
| if (JSON_HEDLEY_LIKELY(!s.truncated)) | |
| { | |
| return decimal_to_float<FloatType>(s); | |
| } | |
| std::uint64_t bits = eisel_lemire<format>(s.exponent, s.w); | |
| if (JSON_HEDLEY_UNLIKELY(bits != eisel_lemire<format>(s.exponent, s.w + 1))) | |
| { | |
| bits = digit_comparison<format>(first, last, bits); | |
| } | |
| result_type value{}; | |
| float_from_bits(bits | (s.negative ? (std::uint64_t{1} << format::sign_bit()) : 0u), value); | |
| const FloatType result = value; | |
| return result; | |
| } | |
| /*! | |
| @brief parse a float with std::from_chars when available | |
| Only used for the formats parse_float_native() does not convert (long double | |
| formats other than binary64). std::from_chars is locale-independent and | |
| correctly rounded. It is used only when __cpp_lib_to_chars indicates full | |
| floating-point support and only when it consumes the entire token ([first, | |
| last)). An under-/overflow (result_out_of_range) also declines, so the | |
| caller's strtold fallback supplies the well-defined ±inf/0 result the parser | |
| expects (side-stepping the P4168 divergence between implementations). | |
| @return true if the value was parsed exactly and fully; false to fall back | |
| */ | |
| template<typename FloatType> | |
| bool parse_float_from_chars(const char* first, const char* last, FloatType& out) noexcept | |
| { | |
| // JSON_HAS_CPP_17 must gate the use as well as the <charconv> include above: | |
| // some standard libraries (e.g. libstdc++ 15) define __cpp_lib_to_chars even | |
| // in C++14 mode, where <charconv> is not included. | |
| #if defined(JSON_HAS_CPP_17) && defined(__cpp_lib_to_chars) | |
| const auto result = std::from_chars(first, last, out); | |
| return result.ec == std::errc() && result.ptr == last; | |
| #else | |
| static_cast<void>(first); | |
| static_cast<void>(last); | |
| static_cast<void>(out); | |
| return false; | |
| #endif | |
| } | |
| /// binary32 and binary64: the library's own conversion, which always succeeds | |
| template<typename FloatType> | |
| bool convert_float_fast(const char* first, const char* last, std::size_t decimal_point_position, | |
| std::size_t mantissa_end, FloatType& value, std::true_type /*native*/) noexcept | |
| { | |
| value = parse_float_native<FloatType>(first, last, decimal_point_position, mantissa_end); | |
| return true; | |
| } | |
| /// other formats (long double on x87, binary128, double-double): std::from_chars, if available | |
| template<typename FloatType> | |
| bool convert_float_fast(const char* first, const char* last, std::size_t /*decimal_point_position*/, | |
| std::size_t /*mantissa_end*/, FloatType& value, std::false_type /*native*/) noexcept | |
| { | |
| return parse_float_from_chars(first, last, value); | |
| } | |
| /*! | |
| @brief convert a validated float token without the C library, if possible | |
| float, double, and long double where it is binary64 are always converted, by | |
| parse_float_native(). Other long double formats are converted with | |
| std::from_chars where the standard library supports it. | |
| @param[in] first pointer to the first character of the token | |
| @param[in] last pointer past the last character | |
| @param[in] decimal_point_position index of the '.' in the token, or | |
| std::string::npos if there is none | |
| @param[in] mantissa_end offset just past the last mantissa byte (the | |
| index of 'e'/'E', or the token length) | |
| @param[out] value the converted value on success | |
| @return true if the value was converted; false if convert_float_locale_aware() | |
| must convert it | |
| */ | |
| template<typename FloatType> | |
| bool convert_float_fast(const char* first, const char* last, std::size_t decimal_point_position, | |
| std::size_t mantissa_end, FloatType& value) noexcept | |
| { | |
| return convert_float_fast(first, last, decimal_point_position, mantissa_end, value, | |
| std::integral_constant<bool, has_native_float_format<FloatType>::value> {}); | |
| } | |
| /// std::strtof, std::strtod, or std::strtold, chosen by the type of @a f | |
| JSON_HEDLEY_NON_NULL(2) | |
| inline void strtof_by_type(float& f, const char* str, char** endptr) noexcept | |
| { | |
| f = std::strtof(str, endptr); | |
| } | |
| /// std::strtof, std::strtod, or std::strtold, chosen by the type of @a f | |
| JSON_HEDLEY_NON_NULL(2) | |
| inline void strtof_by_type(double& f, const char* str, char** endptr) noexcept | |
| { | |
| f = std::strtod(str, endptr); | |
| } | |
| /// std::strtof, std::strtod, or std::strtold, chosen by the type of @a f | |
| JSON_HEDLEY_NON_NULL(2) | |
| inline void strtof_by_type(long double& f, const char* str, char** endptr) noexcept | |
| { | |
| f = std::strtold(str, endptr); | |
| } | |
| /// return the decimal point of the current locale (it may be longer than one byte) | |
| inline std::string get_decimal_point() | |
| { | |
| const auto* loc = localeconv(); | |
| JSON_ASSERT(loc != nullptr); | |
| return (loc->decimal_point == nullptr || *loc->decimal_point == '\0') ? "." : loc->decimal_point; | |
| } | |
| /*! | |
| @brief convert a validated float token with strtof/strtod/strtold | |
| Only used for what convert_float_fast() does not convert: long double formats | |
| other than binary64 where std::from_chars is unavailable or reports an under- | |
| or overflow, and floating-point types that are not IEEE-754 (see | |
| has_native_float_format). | |
| These functions expect the decimal point of the *current* locale, so it is | |
| looked up right before the conversion instead of once when the lexer is | |
| constructed: a locale change in between (by a parser callback, a SAX | |
| handler, or another thread) must not truncate the value (#5198). A | |
| single-byte decimal point is substituted in place and restored afterwards, | |
| because the token is also handed to the SAX interface. A longer one (e.g., | |
| the two-byte U+066B of ar_EG.UTF-8 or fa_IR.UTF-8) is put into a copy of the | |
| token instead (#5660). | |
| The token has been validated before, so if the conversion stops early and | |
| the decimal point changed in the meantime, the locale changed between the | |
| lookup and the call, and the conversion is repeated with the new decimal | |
| point. If it did not change, the value strtod parsed up to that point is | |
| kept. | |
| Note that changing the locale in another thread *while* strtod runs is | |
| undefined behavior of the C library, which this function cannot prevent. | |
| @param[in,out] token the token with '.' as decimal point; a | |
| single-byte decimal point is put in | |
| place during the conversion and | |
| restored afterwards (data() must be | |
| NUL-terminated) | |
| @param[in] decimal_point_position index of the '.' in @a token, or | |
| std::string::npos if there is none | |
| @param[out] value the converted value | |
| */ | |
| template<typename StringType, typename FloatType> | |
| void convert_float_locale_aware(StringType& token, std::size_t decimal_point_position, FloatType& value) | |
| { | |
| const bool has_dot = decimal_point_position != std::string::npos; | |
| std::string decimal_point = get_decimal_point(); | |
| for (;;) | |
| { | |
| char* endptr = nullptr; // NOLINT(misc-const-correctness,cppcoreguidelines-pro-type-vararg,hicpp-vararg) | |
| bool complete = false; | |
| if (!has_dot || decimal_point.size() == 1) | |
| { | |
| const bool substitute = has_dot && decimal_point[0] != '.'; | |
| if (substitute) | |
| { | |
| token[decimal_point_position] = static_cast<typename StringType::value_type>(decimal_point[0]); | |
| } | |
| strtof_by_type(value, token.data(), &endptr); | |
| if (substitute) | |
| { | |
| // the caller hands the token on (e.g. to the SAX interface) with '.' | |
| token[decimal_point_position] = '.'; | |
| } | |
| complete = endptr == token.data() + token.size(); | |
| } | |
| else | |
| { | |
| std::string buffer(token.data(), token.size()); | |
| buffer.replace(decimal_point_position, 1, decimal_point); | |
| strtof_by_type(value, buffer.data(), &endptr); | |
| complete = endptr == buffer.data() + buffer.size(); | |
| } | |
| if (JSON_HEDLEY_LIKELY(complete)) | |
| { | |
| return; | |
| } | |
| // retry only if the locale changed; otherwise, this would loop forever | |
| std::string current_decimal_point = get_decimal_point(); | |
| if (current_decimal_point == decimal_point) | |
| { | |
| return; | |
| } | |
| decimal_point = std::move(current_decimal_point); | |
| } | |
| } | |
| /*! | |
| @brief convert a validated float token like the lexer does | |
| For parsers of JSON text other than the lexer, which converts its own token | |
| buffer in place. float, double, and long double where it is binary64 are | |
| converted without allocation and independent of the locale; only other long | |
| double formats that std::from_chars does not support need a copy of the token | |
| for convert_float_locale_aware(). | |
| @param[in] first pointer to the first character of the token | |
| @param[in] last pointer past the last character | |
| @param[in] decimal_point_position index of the '.' in the token, or | |
| std::string::npos if there is none | |
| @param[in] mantissa_end index of the 'e'/'E', or the token length | |
| @return the value, ±infinity if it overflows | |
| */ | |
| template<typename FloatType> | |
| FloatType convert_float(const char* first, const char* last, std::size_t decimal_point_position, std::size_t mantissa_end) | |
| { | |
| FloatType value{}; | |
| if (!convert_float_fast(first, last, decimal_point_position, mantissa_end, value)) | |
| { | |
| std::string token(first, last); | |
| convert_float_locale_aware(token, decimal_point_position, value); | |
| } | |
| return value; | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/input/position_t.hpp> | |
| // #include <nlohmann/detail/input/string_scan.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <array> // array | |
| #include <cstddef> // size_t | |
| #include <cstdint> // uint64_t, uint8_t | |
| #include <cstring> // memcpy | |
| // #include <nlohmann/detail/bit_ops.hpp> | |
| // #include <nlohmann/detail/input/simd_scan.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-FileCopyrightText: 2018-2025 The simdjson authors <https://github.com/simdjson/simdjson> | |
| // SPDX-License-Identifier: MIT | |
| #include <array> // array | |
| #include <atomic> // atomic | |
| #include <cstddef> // size_t | |
| #include <cstdint> // uint8_t, uint64_t | |
| // #include <nlohmann/detail/bit_ops.hpp> | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // Vector code for runs of string bytes, used by the lexer for contiguous input | |
| // (see string_bulk_run()). NEON (AArch64) and SSE2 (x86-64) belong to the | |
| // baseline instruction sets and are used by default. The vector UTF-8 check | |
| // needs NEON or SSSE3. SSSE3 is not part of x86-64, and the code must not | |
| // depend on the flags of a translation unit (two translation units with | |
| // different flags would have different definitions of the same inline | |
| // functions): the check is compiled for SSSE3 with a function attribute and | |
| // used where the CPU has SSSE3 (all x86-64 CPUs since about 2011), else the | |
| // portable check. Code compiled for SSSE3 anyway (-mssse3 or more) skips the | |
| // CPU check. JSON_NO_SIMD selects the portable code everywhere. | |
| // NLOHMANN_JSON_NO_TARGET_ATTRIBUTE (for compilers that ignore the target | |
| // attribute and then reject the SSSE3 intrinsics) keeps the check portable | |
| // without disabling the SSE2 code. | |
| #if !defined(JSON_NO_SIMD) && defined(__aarch64__) && (defined(__GNUC__) || defined(__clang__)) && defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ | |
| #include <arm_neon.h> | |
| #define JSON_SCAN_NEON 1 | |
| #else | |
| #define JSON_SCAN_NEON 0 | |
| #endif | |
| // (x86 only: other targets can define __SSE2__ as well, e.g., WebAssembly with -msse2, but have no <cpuid.h>) | |
| #if !defined(JSON_NO_SIMD) && !JSON_SCAN_NEON && (defined(__x86_64__) || defined(__i386__) || defined(_M_X64) || defined(_M_IX86)) && !defined(_M_ARM64EC) && (defined(__SSE2__) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2)) | |
| #include <emmintrin.h> | |
| #define JSON_SCAN_SSE2 1 | |
| #else | |
| #define JSON_SCAN_SSE2 0 | |
| #endif | |
| #if JSON_SCAN_SSE2 && defined(__SSSE3__) | |
| #include <tmmintrin.h> | |
| #define JSON_SCAN_SSSE3 1 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) | |
| #else | |
| #define JSON_SCAN_SSSE3 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) | |
| #endif | |
| #if JSON_SCAN_SSE2 && !JSON_SCAN_SSSE3 && !defined(NLOHMANN_JSON_NO_TARGET_ATTRIBUTE) && ((defined(__clang__) && __clang_major__ >= 4) || (defined(__GNUC__) && !defined(__clang__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)) && !defined(__cpp_modules))) | |
| // (GCC before 4.9 has no SSSE3 intrinsics without -mssse3; GCC with C++20 | |
| // modules drops the target attribute from functions it reads from a module | |
| // interface and then rejects the intrinsics: "needs isa option -mssse3") | |
| // <cpuid.h> of GCC before 11 has no include guard, and json.hpp and | |
| // json_view.hpp both include it | |
| #ifndef NLOHMANN_JSON_CPUID_INCLUDED | |
| #define NLOHMANN_JSON_CPUID_INCLUDED | |
| #include <cpuid.h> | |
| #endif | |
| #include <tmmintrin.h> | |
| #define JSON_SCAN_SSSE3_DISPATCH 1 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) | |
| #define JSON_SCAN_SSSE3_TARGET __attribute__((target("ssse3"))) | |
| #elif JSON_SCAN_SSE2 && !JSON_SCAN_SSSE3 && defined(_MSC_VER) | |
| // (MSVC compiles intrinsics of any instruction set) | |
| #include <intrin.h> | |
| #include <tmmintrin.h> | |
| #define JSON_SCAN_SSSE3_DISPATCH 1 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) | |
| #define JSON_SCAN_SSSE3_TARGET | |
| #else | |
| #define JSON_SCAN_SSSE3_DISPATCH 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) | |
| #define JSON_SCAN_SSSE3_TARGET | |
| #endif | |
| #define JSON_SCAN_VECTOR (JSON_SCAN_NEON || JSON_SCAN_SSE2) | |
| #define JSON_SCAN_VECTOR_UTF8 (JSON_SCAN_NEON || JSON_SCAN_SSSE3 || JSON_SCAN_SSSE3_DISPATCH) | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| #if JSON_SCAN_VECTOR | |
| /*! | |
| @brief the first byte of a string run that is a quote, a backslash, a control | |
| character, or not ASCII, 16 bytes per step | |
| Stops at such a byte, or where fewer than 16 bytes are left (the caller tells | |
| the two apart). A signed compare with 0x20 finds control characters and | |
| non-ASCII bytes at once. | |
| */ | |
| JSON_HEDLEY_ALWAYS_INLINE const unsigned char* vector_plain_run(const unsigned char* p, const unsigned char* e) noexcept | |
| { | |
| while (e - p >= 16) | |
| { | |
| #if JSON_SCAN_NEON | |
| const uint8x16_t in = vld1q_u8(p); | |
| const uint8x16_t special = vorrq_u8(vorrq_u8(vceqq_u8(in, vdupq_n_u8('"')), vceqq_u8(in, vdupq_n_u8('\\'))), | |
| vcltq_s8(vreinterpretq_s8_u8(in), vdupq_n_s8(0x20))); | |
| // one nibble per byte (the usual NEON replacement of x86's movemask, see | |
| // D. Kutenin, "Porting x86 vector bitmask optimizations to Arm NEON", 2022) | |
| const std::uint64_t bits = vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(vreinterpretq_u16_u8(special), 4)), 0); | |
| if (bits != 0) | |
| { | |
| return p + (count_trailing_zeros(bits) >> 2u); | |
| } | |
| #else | |
| const __m128i in = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(p))); // NOLINT(bugprone-casting-through-void) | |
| const __m128i special = _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(in, _mm_set1_epi8('"')), _mm_cmpeq_epi8(in, _mm_set1_epi8('\\'))), | |
| _mm_cmplt_epi8(in, _mm_set1_epi8(0x20))); | |
| const auto bits = static_cast<std::uint64_t>(static_cast<unsigned>(_mm_movemask_epi8(special))); | |
| if (bits != 0) | |
| { | |
| return p + count_trailing_zeros(bits); | |
| } | |
| #endif | |
| p += 16; | |
| } | |
| return p; | |
| } | |
| #endif | |
| #if JSON_SCAN_VECTOR | |
| /// vector_plain_run() for runs that are already longer than a few words: | |
| /// inline with SSE2, out of line with NEON, where a larger string loop slows | |
| /// down the rest of the lexer | |
| #if JSON_SCAN_NEON | |
| JSON_HEDLEY_NEVER_INLINE inline | |
| #else | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| #endif | |
| const unsigned char* vector_plain_run_long(const unsigned char* p, const unsigned char* e) noexcept | |
| { | |
| return vector_plain_run(p, e); | |
| } | |
| #endif | |
| #if JSON_SCAN_SSSE3_DISPATCH | |
| /// whether the CPU has SSSE3 (CPUID leaf 1, ECX bit 9) | |
| inline bool cpu_ssse3() noexcept | |
| { | |
| #if defined(_MSC_VER) && !defined(__clang__) | |
| std::array<int, 4> regs {{}}; | |
| __cpuid(regs.data(), 1); | |
| return (static_cast<unsigned>(regs[2]) & (1u << 9u)) != 0; | |
| #else | |
| unsigned eax = 0; | |
| unsigned ebx = 0; | |
| unsigned ecx = 0; | |
| unsigned edx = 0; | |
| return __get_cpuid(1, &eax, &ebx, &ecx, &edx) != 0 && (ecx & (1u << 9u)) != 0; | |
| #endif | |
| } | |
| /// whether the CPU has SSSE3, asked once: the answer is kept in an atomic | |
| /// that is initialized at compile time, so that neither a guard of a local | |
| /// static nor a global constructor is needed (threads that ask at the same | |
| /// time all store the same answer) | |
| JSON_HEDLEY_ALWAYS_INLINE bool cpu_has_ssse3() noexcept | |
| { | |
| static std::atomic<int> known{0}; // 0: not asked yet, 1: no, 2: yes | |
| int state = known.load(std::memory_order_relaxed); | |
| if (JSON_HEDLEY_UNLIKELY(state == 0)) | |
| { | |
| state = cpu_ssse3() ? 2 : 1; | |
| known.store(state, std::memory_order_relaxed); | |
| } | |
| return state == 2; | |
| } | |
| #endif | |
| #if JSON_SCAN_VECTOR_UTF8 | |
| /// Tables of the UTF-8 check of J. Keiser and D. Lemire, "Validating UTF-8 In | |
| /// Less Than One Instruction Per Byte" (2021), as in simdjson ("lookup4"): each | |
| /// maps a nibble (high and low nibble of the previous byte, high nibble of the | |
| /// current byte) to the errors it allows; a byte pair is ill-formed if all | |
| /// three have an error bit in common. | |
| template<typename Dummy = void> | |
| struct utf8_lookup4 | |
| { | |
| static constexpr std::uint8_t too_short = 1u << 0u, too_long = 1u << 1u, overlong_3 = 1u << 2u, too_large = 1u << 3u; | |
| static constexpr std::uint8_t surrogate = 1u << 4u, overlong_2 = 1u << 5u, too_large_1000 = 1u << 6u, overlong_4 = 1u << 6u; | |
| static constexpr std::uint8_t two_conts = 1u << 7u, carry = too_short | too_long | two_conts; | |
| static const std::array<std::uint8_t, 16> byte_1_high; | |
| static const std::array<std::uint8_t, 16> byte_1_low; | |
| static const std::array<std::uint8_t, 16> byte_2_high; | |
| }; | |
| template<typename Dummy> | |
| const std::array<std::uint8_t, 16> utf8_lookup4<Dummy>::byte_1_high = | |
| { | |
| { | |
| too_long, too_long, too_long, too_long, too_long, too_long, too_long, too_long, | |
| two_conts, two_conts, two_conts, two_conts, | |
| too_short | overlong_2, too_short, too_short | overlong_3 | surrogate, too_short | too_large | too_large_1000 | overlong_4 | |
| } | |
| }; | |
| template<typename Dummy> | |
| const std::array<std::uint8_t, 16> utf8_lookup4<Dummy>::byte_1_low = | |
| { | |
| { | |
| carry | overlong_3 | overlong_2 | overlong_4, carry | overlong_2, carry, carry, | |
| carry | too_large, carry | too_large | too_large_1000, carry | too_large | too_large_1000, carry | too_large | too_large_1000, | |
| carry | too_large | too_large_1000, carry | too_large | too_large_1000, carry | too_large | too_large_1000, carry | too_large | too_large_1000, | |
| carry | too_large | too_large_1000, carry | too_large | too_large_1000 | surrogate, carry | too_large | too_large_1000, carry | too_large | too_large_1000 | |
| } | |
| }; | |
| template<typename Dummy> | |
| const std::array<std::uint8_t, 16> utf8_lookup4<Dummy>::byte_2_high = | |
| { | |
| { | |
| too_short, too_short, too_short, too_short, too_short, too_short, too_short, too_short, | |
| static_cast<std::uint8_t>(too_long | overlong_2 | two_conts | overlong_3 | too_large_1000 | overlong_4), | |
| static_cast<std::uint8_t>(too_long | overlong_2 | two_conts | overlong_3 | too_large), | |
| static_cast<std::uint8_t>(too_long | overlong_2 | two_conts | surrogate | too_large), | |
| static_cast<std::uint8_t>(too_long | overlong_2 | two_conts | surrogate | too_large), | |
| too_short, too_short, too_short, too_short | |
| } | |
| }; | |
| /*! | |
| @brief the run of plain string bytes and well-formed UTF-8 at p (a character | |
| boundary), 16 bytes per step | |
| The first quote, backslash, or control character is found with vector | |
| compares, and the UTF-8 check of J. Keiser and D. Lemire covers the bytes up | |
| to it. Returns true with @a block at that byte; returns false with @a block at | |
| the start of the 16 bytes where the check found ill-formed UTF-8 or where | |
| fewer than 16 bytes are left, for the caller to finish one sequence at a time. | |
| Out of line, so that no constants of the check occupy registers in the | |
| caller's loop. On x86-64, it is compiled for SSSE3 (see cpu_has_ssse3()). | |
| */ | |
| JSON_SCAN_SSSE3_TARGET JSON_HEDLEY_NEVER_INLINE inline bool vector_utf8_run(const unsigned char* p, const unsigned char* e, const unsigned char*& block_out) noexcept | |
| { | |
| using lookup = utf8_lookup4<>; | |
| const unsigned char* block = p; | |
| #if JSON_SCAN_NEON | |
| const uint8x16_t t1h = vld1q_u8(lookup::byte_1_high.data()); | |
| const uint8x16_t t1l = vld1q_u8(lookup::byte_1_low.data()); | |
| const uint8x16_t t2h = vld1q_u8(lookup::byte_2_high.data()); | |
| uint8x16_t prev = vdupq_n_u8(0); | |
| while (e - block >= 16) | |
| { | |
| const uint8x16_t in = vld1q_u8(block); | |
| const uint8x16_t special = vorrq_u8(vorrq_u8(vceqq_u8(in, vdupq_n_u8('"')), vceqq_u8(in, vdupq_n_u8('\\'))), vcltq_u8(in, vdupq_n_u8(0x20))); | |
| const uint8x16_t prev1 = vextq_u8(prev, in, 15); | |
| const uint8x16_t sc = vandq_u8(vandq_u8(vqtbl1q_u8(t1h, vshrq_n_u8(prev1, 4)), vqtbl1q_u8(t1l, vandq_u8(prev1, vdupq_n_u8(0x0F)))), vqtbl1q_u8(t2h, vshrq_n_u8(in, 4))); | |
| const uint8x16_t must23 = vorrq_u8(vqsubq_u8(vextq_u8(prev, in, 14), vdupq_n_u8(0xE0 - 0x80)), vqsubq_u8(vextq_u8(prev, in, 13), vdupq_n_u8(0xF0 - 0x80))); | |
| const uint8x16_t err = veorq_u8(vandq_u8(must23, vdupq_n_u8(0x80)), sc); | |
| const std::uint64_t special_bits = vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(vreinterpretq_u16_u8(special), 4)), 0); | |
| const std::uint64_t err_bits = vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(vreinterpretq_u16_u8(vtstq_u8(err, err)), 4)), 0); | |
| if (special_bits != 0) | |
| { | |
| // errors up to the special byte count (an incomplete sequence | |
| // before a quote shows at the quote); the bytes after it do not | |
| const unsigned k = static_cast<unsigned>(count_trailing_zeros(special_bits)) >> 2u; | |
| const std::uint64_t upto = k == 15 ? ~std::uint64_t{0} : | |
| (std::uint64_t{1} << (4u * (k + 1u))) - 1u; | |
| if ((err_bits & upto) == 0) | |
| { | |
| block_out = block + k; | |
| return true; | |
| } | |
| break; | |
| } | |
| if (err_bits != 0) | |
| { | |
| break; | |
| } | |
| prev = in; | |
| block += 16; | |
| } | |
| #else | |
| // the same with SSSE3 (pshufb for the table lookups; nibbles from 16-bit | |
| // shifts, as there are no byte shifts) | |
| const __m128i t1h = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(lookup::byte_1_high.data()))); // NOLINT(bugprone-casting-through-void) | |
| const __m128i t1l = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(lookup::byte_1_low.data()))); // NOLINT(bugprone-casting-through-void) | |
| const __m128i t2h = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(lookup::byte_2_high.data()))); // NOLINT(bugprone-casting-through-void) | |
| const __m128i nibble = _mm_set1_epi8(0x0F); | |
| const __m128i zero = _mm_setzero_si128(); | |
| __m128i prev = zero; | |
| while (e - block >= 16) | |
| { | |
| const __m128i in = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(block))); // NOLINT(bugprone-casting-through-void) | |
| const __m128i special = _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(in, _mm_set1_epi8('"')), _mm_cmpeq_epi8(in, _mm_set1_epi8('\\'))), | |
| _mm_cmpeq_epi8(_mm_subs_epu8(in, _mm_set1_epi8(0x1F)), zero)); // in < 0x20 | |
| const __m128i prev1 = _mm_alignr_epi8(in, prev, 15); | |
| const __m128i sc = _mm_and_si128(_mm_and_si128(_mm_shuffle_epi8(t1h, _mm_and_si128(_mm_srli_epi16(prev1, 4), nibble)), | |
| _mm_shuffle_epi8(t1l, _mm_and_si128(prev1, nibble))), | |
| _mm_shuffle_epi8(t2h, _mm_and_si128(_mm_srli_epi16(in, 4), nibble))); | |
| const __m128i must23 = _mm_or_si128(_mm_subs_epu8(_mm_alignr_epi8(in, prev, 14), _mm_set1_epi8(0xE0 - 0x80)), | |
| _mm_subs_epu8(_mm_alignr_epi8(in, prev, 13), _mm_set1_epi8(0xF0 - 0x80))); | |
| const __m128i err = _mm_xor_si128(_mm_and_si128(must23, _mm_set1_epi8(static_cast<char>(-128))), sc); | |
| const auto special_bits = static_cast<unsigned>(_mm_movemask_epi8(special)); | |
| const auto err_bits = ~static_cast<unsigned>(_mm_movemask_epi8(_mm_cmpeq_epi8(err, zero))) & 0xFFFFu; | |
| if (special_bits != 0) | |
| { | |
| const auto k = static_cast<unsigned>(count_trailing_zeros(static_cast<std::uint64_t>(special_bits))); | |
| if ((err_bits & ((2u << k) - 1u)) == 0) | |
| { | |
| block_out = block + k; | |
| return true; | |
| } | |
| break; | |
| } | |
| if (err_bits != 0) | |
| { | |
| break; | |
| } | |
| prev = in; | |
| block += 16; | |
| } | |
| #endif | |
| block_out = block; | |
| return false; | |
| } | |
| #endif | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // Optional SIMD backend for bulk UTF-8 validation. This is an opt-in external | |
| // dependency: nlohmann/json itself stays header-only and the C++11 scalar | |
| // validator below is always available; defining JSON_USE_SIMDUTF additionally | |
| // requires the simdutf headers on the include path and linking the simdutf | |
| // library. See string_bulk_run(). | |
| // | |
| // simdutf.h itself requires C++17 - it rejects older standards with an #error - | |
| // so the backend is only compiled in from C++17 on. Below that the macro has no | |
| // effect and the scalar validator is used; it accepts and rejects exactly the | |
| // same input, so only throughput differs. macro_scope.hpp is included above to | |
| // have JSON_HAS_CPP_17 available for this test. | |
| #if defined(JSON_USE_SIMDUTF) && defined(JSON_HAS_CPP_17) | |
| #include <simdutf.h> | |
| #endif | |
| // This file contains the byte-level string-scanning helpers used by the lexer's | |
| // contiguous fast path. They operate purely on raw bytes (no dependency on the | |
| // lexer's template parameters) so they are free functions, keeping the lexer | |
| // itself focused on the state machine; see lexer::get_after_string_run(). | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| // classify a single byte as needing individual string handling: the closing | |
| // quote, an escape, a control character, or a non-ASCII (UTF-8) | |
| // lead/continuation byte. Ordinary bytes (0x20..0x7F except '"' and '\\') are | |
| // copied verbatim, which the bulk scanner does 8 bytes at a time. | |
| inline bool is_string_special(unsigned char c) noexcept | |
| { | |
| return c == '\"' || c == '\\' || c < 0x20u || c >= 0x80u; | |
| } | |
| // SWAR helper: return a word whose high bit is set in every byte of @a v that | |
| // is_string_special(); zero if the 8 bytes are all ordinary. | |
| inline std::uint64_t swar_string_special(std::uint64_t v) noexcept | |
| { | |
| constexpr std::uint64_t ones = 0x0101010101010101ull; | |
| constexpr std::uint64_t high = 0x8080808080808080ull; | |
| const std::uint64_t q = v ^ 0x2222222222222222ull; // '"' (0x22) | |
| const std::uint64_t b = v ^ 0x5C5C5C5C5C5C5C5Cull; // '\\' (0x5C) | |
| const std::uint64_t has_quote = (q - ones) & ~q & high; | |
| const std::uint64_t has_backslash = (b - ones) & ~b & high; | |
| const std::uint64_t has_control = (v - 0x2020202020202020ull) & ~v & high; // < 0x20 | |
| const std::uint64_t has_non_ascii = v & high; // >= 0x80 | |
| return has_quote | has_backslash | has_control | has_non_ascii; | |
| } | |
| // return the index of the first is_string_special() byte in [data, data+n), or | |
| // n if every byte is ordinary; scans 8 bytes at a time | |
| JSON_HEDLEY_ALWAYS_INLINE std::size_t find_string_special(const unsigned char* data, std::size_t n) noexcept | |
| { | |
| std::size_t i = 0; | |
| for (; i + 8 <= n; i += 8) | |
| { | |
| const std::uint64_t special = swar_string_special(read_eight_bytes(data + i)); | |
| if (special != 0) | |
| { | |
| // the lowest flagged byte is the first special one: the borrows of | |
| // the subtractions can only flag bytes above a true hit | |
| return i + (static_cast<std::size_t>(count_trailing_zeros(special)) / 8); | |
| } | |
| } | |
| for (; i < n; ++i) | |
| { | |
| if (is_string_special(data[i])) | |
| { | |
| return i; | |
| } | |
| } | |
| return n; | |
| } | |
| // classify a byte as one the serializer must NOT copy verbatim when | |
| // ensure_ascii is requested: the closing quote, an escape, a control character | |
| // (< 0x20), DEL (0x7F), or any non-ASCII byte (>= 0x80). Everything else - | |
| // printable ASCII except '"' and '\\' - is emitted unchanged. Note this differs | |
| // from is_string_special() only in that 0x7F is also a stop (it is escaped as | |
| // \u007f under ensure_ascii). | |
| constexpr bool is_ascii_copyable(unsigned char c) noexcept | |
| { | |
| return c >= 0x20u && c < 0x7Fu && c != '"' && c != '\\'; | |
| } | |
| // return the index of the first byte in [data, data+n) that is NOT | |
| // is_ascii_copyable(), or n if every byte can be copied verbatim; scans 8 bytes | |
| // at a time. Used by the serializer's ensure_ascii fast path. | |
| inline std::size_t find_ascii_copyable_run(const unsigned char* data, std::size_t n) noexcept | |
| { | |
| constexpr std::uint64_t ones = 0x0101010101010101ull; | |
| constexpr std::uint64_t high = 0x8080808080808080ull; | |
| std::size_t i = 0; | |
| for (; i + 8 <= n; i += 8) | |
| { | |
| const std::uint64_t v = read_eight_bytes(data + i); | |
| const std::uint64_t q = v ^ 0x2222222222222222ull; // '"' (0x22) | |
| const std::uint64_t b = v ^ 0x5C5C5C5C5C5C5C5Cull; // '\\' (0x5C) | |
| const std::uint64_t d = v ^ 0x7F7F7F7F7F7F7F7Full; // DEL (0x7F) | |
| const std::uint64_t stop = ((q - ones) & ~q & high) // == '"' | |
| | ((b - ones) & ~b & high) // == '\\' | |
| | ((d - ones) & ~d & high) // == 0x7F | |
| | ((v - 0x2020202020202020ull) & ~v & high) // < 0x20 | |
| | (v & high); // >= 0x80 | |
| if (stop != 0) | |
| { | |
| // the lowest flagged byte is the first one to stop at (see | |
| // find_string_special()) | |
| return i + (static_cast<std::size_t>(count_trailing_zeros(stop)) / 8); | |
| } | |
| } | |
| for (; i < n; ++i) | |
| { | |
| if (!is_ascii_copyable(data[i])) | |
| { | |
| return i; | |
| } | |
| } | |
| return n; | |
| } | |
| // Validate one UTF-8 sequence at the front of [data, data+avail). Returns its | |
| // length (2..4) only when the bytes form a *well-formed* sequence using exactly | |
| // the same ranges as scan_string()'s per-byte switch, so the bulk path accepts | |
| // precisely what the byte path accepts. Returns 0 for anything that is invalid, | |
| // incomplete, or that the byte path must diagnose (the caller then defers to | |
| // that path, keeping error messages unchanged). Lead bytes < 0x80 are handled | |
| // by the caller and never passed here. | |
| inline std::size_t validate_one_utf8(const unsigned char* data, std::size_t avail) noexcept | |
| { | |
| const unsigned char c0 = data[0]; | |
| if (c0 >= 0xC2 && c0 <= 0xDF) // U+0080..U+07FF | |
| { | |
| if (avail >= 2 && data[1] >= 0x80 && data[1] <= 0xBF) | |
| { | |
| return 2; | |
| } | |
| } | |
| else if (c0 == 0xE0) // U+0800..U+0FFF | |
| { | |
| if (avail >= 3 && data[1] >= 0xA0 && data[1] <= 0xBF && data[2] >= 0x80 && data[2] <= 0xBF) | |
| { | |
| return 3; | |
| } | |
| } | |
| else if ((c0 >= 0xE1 && c0 <= 0xEC) || c0 == 0xEE || c0 == 0xEF) // U+1000..U+CFFF, U+E000..U+FFFF | |
| { | |
| if (avail >= 3 && data[1] >= 0x80 && data[1] <= 0xBF && data[2] >= 0x80 && data[2] <= 0xBF) | |
| { | |
| return 3; | |
| } | |
| } | |
| else if (c0 == 0xED) // U+D000..U+D7FF (excludes surrogates) | |
| { | |
| if (avail >= 3 && data[1] >= 0x80 && data[1] <= 0x9F && data[2] >= 0x80 && data[2] <= 0xBF) | |
| { | |
| return 3; | |
| } | |
| } | |
| else if (c0 == 0xF0) // U+10000..U+3FFFF | |
| { | |
| if (avail >= 4 && data[1] >= 0x90 && data[1] <= 0xBF && data[2] >= 0x80 && data[2] <= 0xBF && data[3] >= 0x80 && data[3] <= 0xBF) | |
| { | |
| return 4; | |
| } | |
| } | |
| else if (c0 >= 0xF1 && c0 <= 0xF3) // U+40000..U+FFFFF | |
| { | |
| if (avail >= 4 && data[1] >= 0x80 && data[1] <= 0xBF && data[2] >= 0x80 && data[2] <= 0xBF && data[3] >= 0x80 && data[3] <= 0xBF) | |
| { | |
| return 4; | |
| } | |
| } | |
| else if (c0 == 0xF4) // U+100000..U+10FFFF | |
| { | |
| if (avail >= 4 && data[1] >= 0x80 && data[1] <= 0x8F && data[2] >= 0x80 && data[2] <= 0xBF && data[3] >= 0x80 && data[3] <= 0xBF) | |
| { | |
| return 4; | |
| } | |
| } | |
| return 0; // invalid, incomplete, or must be diagnosed by the byte path | |
| } | |
| // Return the length of the longest prefix of [data, data+n) that consists of | |
| // ASCII characters and complete well-formed UTF-8 sequences; n if all of it is | |
| // valid UTF-8. Unlike scalar_string_bulk_run(), quotes, escapes, and control | |
| // characters are ordinary characters here. ASCII is skipped 8 bytes at a time. | |
| inline std::size_t valid_utf8_prefix(const unsigned char* data, std::size_t n) noexcept | |
| { | |
| constexpr std::uint64_t high = 0x8080808080808080ull; | |
| std::size_t pos = 0; | |
| while (pos < n) | |
| { | |
| if (pos + 8 <= n) | |
| { | |
| std::uint64_t word = 0; | |
| std::memcpy(&word, data + pos, sizeof(word)); | |
| if ((word & high) == 0) | |
| { | |
| pos += 8; | |
| continue; | |
| } | |
| } | |
| if (data[pos] < 0x80u) | |
| { | |
| ++pos; | |
| continue; | |
| } | |
| const std::size_t seq = validate_one_utf8(data + pos, n - pos); | |
| if (seq == 0) | |
| { | |
| break; // ill-formed or truncated | |
| } | |
| pos += seq; | |
| } | |
| return pos; | |
| } | |
| #if JSON_SCAN_VECTOR_UTF8 | |
| /// the end of scan_string_vector from block, where the vector loop stopped | |
| /// (ill-formed UTF-8, or fewer than 16 bytes left): one byte or sequence at a | |
| /// time, from the start of a sequence that crosses into the block | |
| inline const unsigned char* scan_string_finish(const unsigned char* p, const unsigned char* block, const unsigned char* e) noexcept | |
| { | |
| for (int i = 1; i <= 3 && block - i >= p; ++i) | |
| { | |
| const unsigned char c = block[-i]; | |
| if (c < 0x80) | |
| { | |
| break; | |
| } | |
| if (c >= 0xC0) | |
| { | |
| const int len = 2 + static_cast<int>(c >= 0xE0) + static_cast<int>(c >= 0xF0); | |
| if (len > i) | |
| { | |
| block -= i; | |
| } | |
| break; | |
| } | |
| } | |
| for (p = block; p != e;) | |
| { | |
| if (*p < 0x80) | |
| { | |
| if (is_string_special(*p)) | |
| { | |
| return p; | |
| } | |
| ++p; | |
| continue; | |
| } | |
| const std::size_t n = validate_one_utf8(p, static_cast<std::size_t>(e - p)); | |
| if (n == 0) | |
| { | |
| return p; | |
| } | |
| p += n; | |
| } | |
| return p; | |
| } | |
| /// the rest of a string from p (a character boundary), with the vector UTF-8 | |
| /// check and the scalar check for the end of the block where it stopped | |
| inline const unsigned char* scan_string_vector(const unsigned char* p, const unsigned char* e) noexcept | |
| { | |
| const unsigned char* block = p; | |
| if (vector_utf8_run(p, e, block)) | |
| { | |
| return block; | |
| } | |
| return scan_string_finish(p, block, e); | |
| } | |
| #endif | |
| #if JSON_SCAN_VECTOR | |
| /// the end of the run of plain string characters at @a p: the first quote, | |
| /// backslash, control character, or non-ASCII byte, or @a e. The first words | |
| /// are checked with SWAR (one; four with NEON, where the vector mask costs | |
| /// more), as most keys and short values end there; longer runs continue 16 | |
| /// bytes at a time. | |
| JSON_HEDLEY_ALWAYS_INLINE const unsigned char* plain_run_end(const unsigned char* p, const unsigned char* e) noexcept | |
| { | |
| constexpr int prefix_words = JSON_SCAN_NEON ? 4 : 1; | |
| for (int words = prefix_words; words > 0 && e - p >= 8; --words) | |
| { | |
| const std::uint64_t special = swar_string_special(read_eight_bytes(p)); | |
| if (special != 0) | |
| { | |
| return p + (static_cast<std::size_t>(count_trailing_zeros(special)) / 8); | |
| } | |
| p += 8; | |
| } | |
| // the vector loop only for 16 bytes or more: the serializer passes a | |
| // string without its closing quote, so most of its runs end at e, and a | |
| // call of the out-of-line NEON loop for a shorter rest made dump() up to | |
| // 10% slower | |
| if (e - p >= 16) | |
| { | |
| p = vector_plain_run_long(p, e); | |
| if (e - p >= 16) | |
| { | |
| return p; // the vector loop stopped at a special byte | |
| } | |
| } | |
| return p + find_string_special(p, static_cast<std::size_t>(e - p)); | |
| } | |
| #endif | |
| // Computation of the bulk run length: the number of leading bytes in | |
| // [data, data+n) that are ordinary ASCII or complete well-formed UTF-8 | |
| // sequences, stopping before the first byte that needs individual handling (the | |
| // closing quote, an escape, a control character, or an ill-formed/truncated | |
| // sequence). ASCII is skipped 16 bytes at a time with SSE2 and 8 bytes at a | |
| // time otherwise; runs of non-ASCII text use the vector UTF-8 check where | |
| // available. | |
| JSON_HEDLEY_ALWAYS_INLINE std::size_t scalar_string_bulk_run(const unsigned char* data, std::size_t n) noexcept | |
| { | |
| const unsigned char* const e = data + n; | |
| const unsigned char* p = data; | |
| while (p != e) | |
| { | |
| #if JSON_SCAN_VECTOR | |
| p = plain_run_end(p, e); | |
| #else | |
| p += find_string_special(p, static_cast<std::size_t>(e - p)); | |
| #endif | |
| if (p == e || *p < 0x80u) | |
| { | |
| break; // end of buffer, or a quote/escape/control byte | |
| } | |
| #if JSON_SCAN_VECTOR_UTF8 | |
| #if JSON_SCAN_SSSE3_DISPATCH | |
| if (JSON_HEDLEY_LIKELY(cpu_has_ssse3())) | |
| #endif | |
| { | |
| return static_cast<std::size_t>(scan_string_vector(p, e) - data); | |
| } | |
| #endif | |
| #if !JSON_SCAN_VECTOR_UTF8 || JSON_SCAN_SSSE3_DISPATCH | |
| // a run of multi-byte sequences (e.g. CJK text) is validated sequence | |
| // by sequence without searching for the next special byte in between | |
| do | |
| { | |
| const std::size_t seq = validate_one_utf8(p, static_cast<std::size_t>(e - p)); | |
| if (seq == 0) | |
| { | |
| return static_cast<std::size_t>(p - data); // ill-formed or truncated: let the byte path diagnose it | |
| } | |
| p += seq; | |
| } | |
| while (p != e && *p >= 0x80u); | |
| #endif | |
| } | |
| return static_cast<std::size_t>(p - data); | |
| } | |
| #if defined(JSON_USE_SIMDUTF) && defined(JSON_HAS_CPP_17) | |
| // Index of the first quote/escape/control byte in [data, data+n) (non-ASCII | |
| // bytes are *not* stops here - the whole run is handed to simdutf), or n. | |
| inline std::size_t find_string_delimiter(const unsigned char* data, std::size_t n) noexcept | |
| { | |
| constexpr std::uint64_t ones = 0x0101010101010101ull; | |
| constexpr std::uint64_t high = 0x8080808080808080ull; | |
| std::size_t i = 0; | |
| for (; i + 8 <= n; i += 8) | |
| { | |
| const std::uint64_t v = read_eight_bytes(data + i); | |
| const std::uint64_t q = v ^ 0x2222222222222222ull; | |
| const std::uint64_t b = v ^ 0x5C5C5C5C5C5C5C5Cull; | |
| const std::uint64_t hit = ((q - ones) & ~q & high) | |
| | ((b - ones) & ~b & high) | |
| | ((v - 0x2020202020202020ull) & ~v & high); | |
| if (hit != 0) | |
| { | |
| // the lowest flagged byte is the first delimiter (see find_string_special()) | |
| return i + (static_cast<std::size_t>(count_trailing_zeros(hit)) / 8); | |
| } | |
| } | |
| for (; i < n; ++i) | |
| { | |
| const unsigned char c = data[i]; | |
| if (c == '\"' || c == '\\' || c < 0x20u) | |
| { | |
| return i; | |
| } | |
| } | |
| return n; | |
| } | |
| #endif | |
| // Backend-dispatched bulk run length. With JSON_USE_SIMDUTF the run up to the | |
| // next delimiter is validated in one shot by simdutf; on the rare failure the | |
| // scalar helper recomputes the exact valid prefix so the byte path still | |
| // produces the precise diagnostic. Without it, the pure scalar path is used. | |
| JSON_HEDLEY_ALWAYS_INLINE std::size_t string_bulk_run(const unsigned char* data, std::size_t n) noexcept | |
| { | |
| #if defined(JSON_USE_SIMDUTF) && defined(JSON_HAS_CPP_17) | |
| const std::size_t run = find_string_delimiter(data, n); | |
| if (run != 0 && simdutf::validate_utf8(reinterpret_cast<const char*>(data), run)) | |
| { | |
| return run; | |
| } | |
| #endif | |
| return scalar_string_bulk_run(data, n); | |
| } | |
| #if JSON_SCAN_NEON && !(defined(JSON_USE_SIMDUTF) && defined(JSON_HAS_CPP_17)) | |
| /// scalar_string_bulk_run() from @a start on, out of line (see | |
| /// lexer_string_bulk_run()) | |
| JSON_HEDLEY_NEVER_INLINE inline std::size_t string_bulk_run_from(const unsigned char* data, std::size_t start, std::size_t n) noexcept | |
| { | |
| return start + scalar_string_bulk_run(data + start, n - start); | |
| } | |
| #endif | |
| // string_bulk_run() for the lexer. With NEON, only the first four words are | |
| // checked inline (most keys and short values end there), and longer runs and | |
| // non-ASCII text continue out of line. The lexer's scan function runs once per | |
| // token, and the vector code inlined into it needs more registers, which every | |
| // token pays for: 5% of json::accept() on jeopardy.json with Apple Clang on | |
| // Apple M1, even though no string of that file reaches the vector code. The | |
| // serializer keeps string_bulk_run() inline, which is faster there. | |
| JSON_HEDLEY_ALWAYS_INLINE std::size_t lexer_string_bulk_run(const unsigned char* data, std::size_t n) noexcept | |
| { | |
| #if JSON_SCAN_NEON && !(defined(JSON_USE_SIMDUTF) && defined(JSON_HAS_CPP_17)) | |
| std::size_t i = 0; | |
| for (int words = 4; words > 0 && n - i >= 8; --words) | |
| { | |
| const std::uint64_t special = swar_string_special(read_eight_bytes(data + i)); | |
| if (special != 0) | |
| { | |
| const std::size_t pos = i + (static_cast<std::size_t>(count_trailing_zeros(special)) / 8); | |
| return data[pos] < 0x80u ? pos : string_bulk_run_from(data, pos, n); | |
| } | |
| i += 8; | |
| } | |
| return string_bulk_run_from(data, i, n); | |
| #else | |
| return string_bulk_run(data, n); | |
| #endif | |
| } | |
| // Decode the 4 hex digits at [data, data+4) - the digits following a `\u` | |
| // escape - into a codepoint 0x0000..0xFFFF via one table lookup per byte | |
| // (after yyjson's read_hex_u16), or return -1 if any of the 4 bytes is not a | |
| // hex digit ('0'..'9', 'A'..'F', 'a'..'f'). The caller must already have | |
| // checked that 4 bytes are available; used by lexer::get_codepoint()'s | |
| // contiguous fast path. On -1 it falls back to the byte-at-a-time loop, which | |
| // stops at the first invalid digit, so the reported error and position are | |
| // unaffected by this fast path. | |
| inline int hex_codepoint(const unsigned char* data) noexcept | |
| { | |
| static const std::array<std::uint8_t, 256> hex_digit_table = // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) | |
| { | |
| { | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 00..0F | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 10..1F | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 20..2F | |
| 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 30..3F ('0'..'9') | |
| 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 40..4F ('A'..'F') | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 50..5F | |
| 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 60..6F ('a'..'f') | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 70..7F | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 80..8F | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 90..9F | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // A0..AF | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // B0..BF | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // C0..CF | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // D0..DF | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // E0..EF | |
| 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // F0..FF | |
| } | |
| }; | |
| const std::uint8_t d0 = hex_digit_table[data[0]]; | |
| const std::uint8_t d1 = hex_digit_table[data[1]]; | |
| const std::uint8_t d2 = hex_digit_table[data[2]]; | |
| const std::uint8_t d3 = hex_digit_table[data[3]]; | |
| // every valid digit is <= 0xF; the combined OR only exceeds it if at | |
| // least one of the four bytes was not a hex digit (looked up as 0xFF) | |
| if ((d0 | d1 | d2 | d3) > 0x0F) | |
| { | |
| return -1; | |
| } | |
| return (d0 << 12) | (d1 << 8) | (d2 << 4) | d3; | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| // #include <nlohmann/detail/string_utils.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /////////// | |
| // lexer // | |
| /////////// | |
| template<typename BasicJsonType> | |
| class lexer_base | |
| { | |
| public: | |
| /// token types for the parser | |
| enum class token_type | |
| { | |
| uninitialized, ///< indicating the scanner is uninitialized | |
| literal_true, ///< the `true` literal | |
| literal_false, ///< the `false` literal | |
| literal_null, ///< the `null` literal | |
| value_string, ///< a string -- use get_string() for actual value | |
| value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value | |
| value_integer, ///< a signed integer -- use get_number_integer() for actual value | |
| value_float, ///< an floating point number -- use get_number_float() for actual value | |
| begin_array, ///< the character for array begin `[` | |
| begin_object, ///< the character for object begin `{` | |
| end_array, ///< the character for array end `]` | |
| end_object, ///< the character for object end `}` | |
| name_separator, ///< the name separator `:` | |
| value_separator, ///< the value separator `,` | |
| parse_error, ///< indicating a parse error | |
| end_of_input, ///< indicating the end of the input buffer | |
| literal_or_value ///< a literal or the begin of a value (only for diagnostics) | |
| }; | |
| /// return name of values of type token_type (only used for errors) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| JSON_HEDLEY_CONST | |
| static const char* token_type_name(const token_type t) noexcept | |
| { | |
| switch (t) | |
| { | |
| case token_type::uninitialized: | |
| return "<uninitialized>"; | |
| case token_type::literal_true: | |
| return "true literal"; | |
| case token_type::literal_false: | |
| return "false literal"; | |
| case token_type::literal_null: | |
| return "null literal"; | |
| case token_type::value_string: | |
| return "string literal"; | |
| case token_type::value_unsigned: | |
| case token_type::value_integer: | |
| case token_type::value_float: | |
| return "number literal"; | |
| case token_type::begin_array: | |
| return "'['"; | |
| case token_type::begin_object: | |
| return "'{'"; | |
| case token_type::end_array: | |
| return "']'"; | |
| case token_type::end_object: | |
| return "'}'"; | |
| case token_type::name_separator: | |
| return "':'"; | |
| case token_type::value_separator: | |
| return "','"; | |
| case token_type::parse_error: | |
| return "<parse error>"; | |
| case token_type::end_of_input: | |
| return "end of input"; | |
| case token_type::literal_or_value: | |
| return "'[', '{', or a literal"; | |
| // LCOV_EXCL_START | |
| default: // catch non-enum values | |
| return "unknown token"; | |
| // LCOV_EXCL_STOP | |
| } | |
| } | |
| }; | |
| // Detect whether an input adapter can reconstruct already-consumed input on | |
| // demand (see iterator_input_adapter::supports_seek). Adapters that do not | |
| // expose the flag - e.g. file, stream, wide-string, and user-defined adapters - | |
| // are treated as non-seekable streaming input, for which the lexer keeps | |
| // copying every scanned character eagerly. The value is read via tag dispatch | |
| // on is_detected so the flag is only referenced for adapters that provide it. | |
| template<typename InputAdapterType> | |
| using detect_supports_seek = decltype(InputAdapterType::supports_seek); | |
| template<typename InputAdapterType> | |
| constexpr bool input_adapter_supports_seek(std::true_type /*detected*/) | |
| { | |
| return InputAdapterType::supports_seek; | |
| } | |
| template<typename InputAdapterType> | |
| constexpr bool input_adapter_supports_seek(std::false_type /*detected*/) | |
| { | |
| return false; | |
| } | |
| // Detect whether an input adapter reads with one character of lookahead that | |
| // can be left in the input (see input_stream_adapter::supports_lookahead, | |
| // which is only defined with JSON_PRECISE_STREAM_POSITION), detected like | |
| // supports_seek above. | |
| template<typename InputAdapterType> | |
| using detect_supports_lookahead = decltype(InputAdapterType::supports_lookahead); | |
| template<typename InputAdapterType> | |
| constexpr bool input_adapter_supports_lookahead(std::true_type /*detected*/) | |
| { | |
| return InputAdapterType::supports_lookahead; | |
| } | |
| template<typename InputAdapterType> | |
| constexpr bool input_adapter_supports_lookahead(std::false_type /*detected*/) | |
| { | |
| return false; | |
| } | |
| // Detect whether an input adapter exposes a contiguous byte block that the | |
| // lexer can scan directly (see iterator_input_adapter::supports_bulk_scan). | |
| // Adapters without the flag - file, stream, wide-string, user-defined - fall | |
| // back to the character-at-a-time string scanner. | |
| template<typename InputAdapterType> | |
| using detect_supports_bulk_scan = decltype(InputAdapterType::supports_bulk_scan); | |
| template<typename InputAdapterType> | |
| constexpr bool input_adapter_supports_bulk_scan(std::true_type /*detected*/) | |
| { | |
| return InputAdapterType::supports_bulk_scan; | |
| } | |
| template<typename InputAdapterType> | |
| constexpr bool input_adapter_supports_bulk_scan(std::false_type /*detected*/) | |
| { | |
| return false; | |
| } | |
| // Detect whether an input adapter keeps the current token itself and can | |
| // hand it out on demand (see input_stream_adapter::supports_token_tracking), | |
| // so the lexer need not copy every scanned character into token_string. | |
| template<typename InputAdapterType> | |
| using detect_supports_token_tracking = decltype(InputAdapterType::supports_token_tracking); | |
| template<typename InputAdapterType> | |
| constexpr bool input_adapter_supports_token_tracking(std::true_type /*detected*/) | |
| { | |
| return InputAdapterType::supports_token_tracking; | |
| } | |
| template<typename InputAdapterType> | |
| constexpr bool input_adapter_supports_token_tracking(std::false_type /*detected*/) | |
| { | |
| return false; | |
| } | |
| // Detect whether the contiguous block of a bulk-scan adapter is only a window | |
| // into the input (see input_stream_adapter::bulk_window): its end is not the | |
| // end of the input, so a token that touches it must be finished character by | |
| // character. | |
| template<typename InputAdapterType> | |
| using detect_bulk_window = decltype(InputAdapterType::bulk_window); | |
| template<typename InputAdapterType> | |
| constexpr bool input_adapter_bulk_window(std::true_type /*detected*/) | |
| { | |
| return InputAdapterType::bulk_window; | |
| } | |
| template<typename InputAdapterType> | |
| constexpr bool input_adapter_bulk_window(std::false_type /*detected*/) | |
| { | |
| return false; | |
| } | |
| /*! | |
| @brief lexical analysis | |
| This class organizes the lexical analysis during JSON deserialization. | |
| */ | |
| template<typename BasicJsonType, typename InputAdapterType> | |
| class lexer : public lexer_base<BasicJsonType> | |
| { | |
| using number_integer_t = typename BasicJsonType::number_integer_t; | |
| using number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
| using number_float_t = typename BasicJsonType::number_float_t; | |
| using string_t = typename BasicJsonType::string_t; | |
| using char_type = typename InputAdapterType::char_type; | |
| using char_int_type = typename char_traits<char_type>::int_type; | |
| /// whether the last read token can be reconstructed from the input adapter | |
| /// on demand (in error paths) instead of being copied on every scanned | |
| /// character; see input_adapter_supports_seek | |
| static constexpr bool seekable = | |
| input_adapter_supports_seek<InputAdapterType>(is_detected<detect_supports_seek, InputAdapterType> {}); | |
| /// whether the adapter keeps the token itself (mark_token_start() / | |
| /// copy_token()); see input_adapter_supports_token_tracking | |
| static constexpr bool adapter_token = | |
| !seekable && input_adapter_supports_token_tracking<InputAdapterType>(is_detected<detect_supports_token_tracking, InputAdapterType> {}); | |
| /// whether the last read token is obtained from the input adapter on | |
| /// demand (in error paths) instead of being copied on every scanned | |
| /// character: seekable adapters reconstruct it from the consumed input, | |
| /// token-tracking adapters keep it themselves | |
| static constexpr bool lazy_token_string = seekable || adapter_token; | |
| /// whether the read position is derived from the input adapter on demand | |
| /// instead of being counted on every scanned character. Seekable adapters | |
| /// know how much input they consumed and can revisit it, so | |
| /// chars_read_total is the adapter's read count (minus a pending unget), | |
| /// and line and column are recomputed from the consumed input only when | |
| /// get_position() is called (errors). Counting per character kept two | |
| /// increments and a newline check in the hot path of every get(). | |
| static constexpr bool lazy_position = seekable; | |
| /// whether a simulated unget can be passed on to the input adapter, which | |
| /// then leaves the character in the input; see | |
| /// input_adapter_supports_lookahead | |
| static constexpr bool can_release_lookahead = | |
| input_adapter_supports_lookahead<InputAdapterType>(is_detected<detect_supports_lookahead, InputAdapterType> {}); | |
| /// whether string scanning may bulk-consume runs of ordinary characters | |
| /// directly from a contiguous input buffer (SWAR fast path). Without | |
| /// lazy_token_string / lazy_position, the bulk paths copy the consumed | |
| /// characters into token_string and advance the position counters | |
| /// themselves (see bulk_consume). | |
| static constexpr bool bulk_scan = | |
| input_adapter_supports_bulk_scan<InputAdapterType>(is_detected<detect_supports_bulk_scan, InputAdapterType> {}); | |
| /// whether the contiguous block is only a window into the input, so that | |
| /// its end does not end a token; see input_adapter_bulk_window | |
| static constexpr bool bulk_window = | |
| input_adapter_bulk_window<InputAdapterType>(is_detected<detect_bulk_window, InputAdapterType> {}); | |
| public: | |
| using token_type = typename lexer_base<BasicJsonType>::token_type; | |
| explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false, bool discard_number_values_ = false) noexcept | |
| : ia(std::move(adapter)) | |
| , ignore_comments(ignore_comments_) | |
| , discard_number_values(discard_number_values_) | |
| { | |
| // the token string of an error before the first token is everything | |
| // read so far | |
| begin_token(std::integral_constant<bool, adapter_token> {}); | |
| } | |
| // deleted because of pointer members | |
| lexer(const lexer&) = delete; | |
| lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) | |
| lexer& operator=(lexer&) = delete; | |
| lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) | |
| ~lexer() = default; | |
| private: | |
| ///////////////////// | |
| // scan functions | |
| ///////////////////// | |
| /// contiguous input: try to decode the 4 hex digits following `\\u` | |
| /// directly from the input buffer via hex_codepoint(), instead of 4 calls | |
| /// to get(). On success, advances the adapter exactly as those 4 get() | |
| /// calls would (including the position and token bookkeeping of a | |
| /// streaming adapter, see bulk_consume) and leaves @a current holding the last of | |
| /// the 4 digits, just as the last such get() would; the codepoint is | |
| /// written to @a out. Makes no state change and returns false for a | |
| /// pending unget, fewer than 4 remaining bytes, or any of the 4 bytes not | |
| /// being a hex digit, so the caller falls back unchanged to the | |
| /// per-character loop, which then reports the same diagnostic (stopping | |
| /// at the first invalid digit) as before this optimization. | |
| bool get_codepoint_bulk(std::true_type /*bulk*/, int& out) | |
| { | |
| if (next_unget || ia.bulk_remaining() < 4) | |
| { | |
| return false; | |
| } | |
| const char_type* const raw = ia.bulk_data(); | |
| const int codepoint = hex_codepoint(reinterpret_cast<const unsigned char*>(raw)); | |
| if (codepoint < 0) | |
| { | |
| return false; | |
| } | |
| bulk_consume(reinterpret_cast<const char*>(raw), 4); | |
| current = char_traits<char_type>::to_int_type(raw[3]); | |
| out = codepoint; | |
| return true; | |
| } | |
| /// streaming input: no bulk fast path | |
| bool get_codepoint_bulk(std::false_type /*bulk*/, int& /*out*/) const noexcept | |
| { | |
| return false; | |
| } | |
| /*! | |
| @brief get codepoint from 4 hex characters following `\\u` | |
| For input "\\u c1 c2 c3 c4" the codepoint is: | |
| (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 | |
| = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) | |
| Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' | |
| must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The | |
| conversion is done by subtracting the offset (0x30, 0x37, and 0x57) | |
| between the ASCII value of the character and the desired integer value. | |
| @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or | |
| non-hex character) | |
| */ | |
| int get_codepoint() | |
| { | |
| // this function only makes sense after reading `\u` | |
| JSON_ASSERT(current == 'u'); | |
| // contiguous input: decode all 4 hex digits directly from the buffer | |
| int fast_codepoint = 0; | |
| if (get_codepoint_bulk(std::integral_constant<bool, bulk_scan> {}, fast_codepoint)) | |
| { | |
| return fast_codepoint; | |
| } | |
| int codepoint = 0; | |
| const auto factors = { 12u, 8u, 4u, 0u }; | |
| for (const auto factor : factors) | |
| { | |
| get(); | |
| if (current >= '0' && current <= '9') | |
| { | |
| codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor); | |
| } | |
| else if (current >= 'A' && current <= 'F') | |
| { | |
| codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor); | |
| } | |
| else if (current >= 'a' && current <= 'f') | |
| { | |
| codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor); | |
| } | |
| else | |
| { | |
| return -1; | |
| } | |
| } | |
| JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF); | |
| return codepoint; | |
| } | |
| /*! | |
| @brief check if the next byte(s) are inside a given range | |
| Adds the current byte and, for each passed range, reads a new byte and | |
| checks if it is inside the range. If a violation was detected, set up an | |
| error message and return false. Otherwise, return true. | |
| @param[in] ranges list of integers; interpreted as list of pairs of | |
| inclusive lower and upper bound, respectively | |
| @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, | |
| 1, 2, or 3 pairs. This precondition is enforced by an assertion. | |
| @return true if and only if no range violation was detected | |
| */ | |
| bool next_byte_in_range(std::initializer_list<char_int_type> ranges) | |
| { | |
| JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6); | |
| add(current); | |
| for (auto range = ranges.begin(); range != ranges.end(); ++range) | |
| { | |
| get(); | |
| if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range))) // NOLINT(bugprone-inc-dec-in-conditions) | |
| { | |
| add(current); | |
| } | |
| else | |
| { | |
| error_message = "invalid string: ill-formed UTF-8 byte"; | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| /// contiguous input: bulk-append the run of ordinary characters and complete | |
| /// well-formed UTF-8 sequences starting at the current read position, then | |
| /// read the first byte that needs individual handling (the closing quote, an | |
| /// escape, a control character, or an ill-formed UTF-8 byte) like get(). | |
| /// That byte is taken from the buffer that was just scanned. Through get(), | |
| /// Apple Clang merged this read with the other get() calls of the scan | |
| /// function, which load the read position again right after it was stored | |
| /// (3% of json::accept() on jeopardy.json on Apple M1). | |
| char_int_type get_after_string_run(std::true_type /*bulk*/) | |
| { | |
| // a pending unget must be consumed through the normal path first | |
| if (next_unget) | |
| { | |
| return get(); | |
| } | |
| const std::size_t remaining = ia.bulk_remaining(); | |
| if (remaining == 0) | |
| { | |
| return get(); | |
| } | |
| const auto* const raw = ia.bulk_data(); | |
| const auto* const data = reinterpret_cast<const unsigned char*>(raw); | |
| const std::size_t pos = lexer_string_bulk_run(data, remaining); | |
| if (pos != 0) | |
| { | |
| token_buffer.append(reinterpret_cast<const typename string_t::value_type*>(data), pos); | |
| bulk_consume(reinterpret_cast<const char*>(data), pos); | |
| } | |
| if (pos == remaining) | |
| { | |
| return get(); // end of the contiguous input | |
| } | |
| // what get() does, with the byte at hand | |
| advance_position(); | |
| ia.bulk_skip(1); | |
| current = char_traits<char_type>::to_int_type(raw[pos]); | |
| return track_after_read(); | |
| } | |
| /// consume @a n characters at @a data (the adapter's bulk_data()) and do | |
| /// the bookkeeping get() would have done for them; the characters are | |
| /// never newlines | |
| void bulk_consume(const char* data, std::size_t n) | |
| { | |
| bulk_track_position(n, std::integral_constant<bool, lazy_position> {}); | |
| bulk_track_token(data, n, std::integral_constant<bool, lazy_token_string> {}); | |
| ia.bulk_skip(n); | |
| } | |
| /// seekable adapter: the position is derived from the adapter | |
| void bulk_track_position(std::size_t /*n*/, std::true_type /*lazy*/) const noexcept {} | |
| /// streaming adapter: count the characters | |
| void bulk_track_position(std::size_t n, std::false_type /*lazy*/) noexcept | |
| { | |
| position.chars_read_total += n; | |
| position.chars_read_current_line += n; | |
| } | |
| /// the token is obtained from the adapter | |
| void bulk_track_token(const char* /*data*/, std::size_t /*n*/, std::true_type /*lazy*/) const noexcept {} | |
| /// streaming adapter: capture the characters | |
| void bulk_track_token(const char* data, std::size_t n, std::false_type /*lazy*/) | |
| { | |
| token_string.insert(token_string.end(), data, data + n); | |
| } | |
| /// streaming input: no bulk fast path | |
| char_int_type get_after_string_run(std::false_type /*bulk*/) | |
| { | |
| return get(); | |
| } | |
| /*! | |
| @brief scan a string literal | |
| This function scans a string according to Sect. 7 of RFC 8259. While | |
| scanning, bytes are escaped and copied into buffer token_buffer. Then the | |
| function returns successfully, token_buffer is *not* null-terminated (as it | |
| may contain \0 bytes), and token_buffer.size() is the number of bytes in the | |
| string. | |
| @return token_type::value_string if string could be successfully scanned, | |
| token_type::parse_error otherwise | |
| @note In case of errors, variable error_message contains a textual | |
| description. | |
| */ | |
| token_type scan_string() | |
| { | |
| // reset token_buffer (ignore opening quote) | |
| reset(); | |
| // we entered the function by reading an open quote | |
| JSON_ASSERT(current == '\"'); | |
| while (true) | |
| { | |
| // bulk-consume ordinary characters from contiguous input, then | |
| // get the next character, the one that ends the run | |
| switch (get_after_string_run(std::integral_constant<bool, bulk_scan>())) | |
| { | |
| // end of file while parsing the string | |
| case char_traits<char_type>::eof(): | |
| { | |
| error_message = "invalid string: missing closing quote"; | |
| return token_type::parse_error; | |
| } | |
| // closing quote | |
| case '\"': | |
| { | |
| return token_type::value_string; | |
| } | |
| // escapes | |
| case '\\': | |
| { | |
| switch (get()) | |
| { | |
| // quotation mark | |
| case '\"': | |
| add('\"'); | |
| break; | |
| // reverse solidus | |
| case '\\': | |
| add('\\'); | |
| break; | |
| // solidus | |
| case '/': | |
| add('/'); | |
| break; | |
| // backspace | |
| case 'b': | |
| add('\b'); | |
| break; | |
| // form feed | |
| case 'f': | |
| add('\f'); | |
| break; | |
| // line feed | |
| case 'n': | |
| add('\n'); | |
| break; | |
| // carriage return | |
| case 'r': | |
| add('\r'); | |
| break; | |
| // tab | |
| case 't': | |
| add('\t'); | |
| break; | |
| // unicode escapes | |
| case 'u': | |
| { | |
| const int codepoint1 = get_codepoint(); | |
| int codepoint = codepoint1; // start with codepoint1 | |
| if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1)) | |
| { | |
| error_message = "invalid string: '\\u' must be followed by 4 hex digits"; | |
| return token_type::parse_error; | |
| } | |
| // check if code point is a high surrogate | |
| if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) | |
| { | |
| // expect next \uxxxx entry | |
| if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u')) | |
| { | |
| const int codepoint2 = get_codepoint(); | |
| if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1)) | |
| { | |
| error_message = "invalid string: '\\u' must be followed by 4 hex digits"; | |
| return token_type::parse_error; | |
| } | |
| // check if codepoint2 is a low surrogate | |
| if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) | |
| { | |
| // overwrite codepoint | |
| codepoint = static_cast<int>( | |
| // high surrogate occupies the most significant 22 bits | |
| (static_cast<unsigned int>(codepoint1) << 10u) | |
| // low surrogate occupies the least significant 15 bits | |
| + static_cast<unsigned int>(codepoint2) | |
| // there is still the 0xD800, 0xDC00, and 0x10000 noise | |
| // in the result, so we have to subtract with: | |
| // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 | |
| - 0x35FDC00u); | |
| } | |
| else | |
| { | |
| error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; | |
| return token_type::parse_error; | |
| } | |
| } | |
| else | |
| { | |
| error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; | |
| return token_type::parse_error; | |
| } | |
| } | |
| else | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) | |
| { | |
| error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; | |
| return token_type::parse_error; | |
| } | |
| } | |
| // the result of the above calculation yields a proper codepoint | |
| JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF); | |
| // translate codepoint into bytes | |
| encode_utf8(static_cast<std::uint32_t>(codepoint), [this](std::uint32_t byte) | |
| { | |
| add(static_cast<char_int_type>(byte)); | |
| }); | |
| break; | |
| } | |
| // other characters after escape | |
| default: | |
| error_message = "invalid string: forbidden character after backslash"; | |
| return token_type::parse_error; | |
| } | |
| break; | |
| } | |
| // invalid control characters | |
| case 0x00: | |
| case 0x01: | |
| case 0x02: | |
| case 0x03: | |
| case 0x04: | |
| case 0x05: | |
| case 0x06: | |
| case 0x07: | |
| case 0x08: | |
| case 0x09: | |
| case 0x0A: | |
| case 0x0B: | |
| case 0x0C: | |
| case 0x0D: | |
| case 0x0E: | |
| case 0x0F: | |
| case 0x10: | |
| case 0x11: | |
| case 0x12: | |
| case 0x13: | |
| case 0x14: | |
| case 0x15: | |
| case 0x16: | |
| case 0x17: | |
| case 0x18: | |
| case 0x19: | |
| case 0x1A: | |
| case 0x1B: | |
| case 0x1C: | |
| case 0x1D: | |
| case 0x1E: | |
| case 0x1F: | |
| { | |
| static const std::array<const char*, 32> control_character_messages = {{ | |
| "invalid string: control character U+0000 (NUL) must be escaped to \\u0000", | |
| "invalid string: control character U+0001 (SOH) must be escaped to \\u0001", | |
| "invalid string: control character U+0002 (STX) must be escaped to \\u0002", | |
| "invalid string: control character U+0003 (ETX) must be escaped to \\u0003", | |
| "invalid string: control character U+0004 (EOT) must be escaped to \\u0004", | |
| "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005", | |
| "invalid string: control character U+0006 (ACK) must be escaped to \\u0006", | |
| "invalid string: control character U+0007 (BEL) must be escaped to \\u0007", | |
| "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b", | |
| "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t", | |
| "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n", | |
| "invalid string: control character U+000B (VT) must be escaped to \\u000B", | |
| "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f", | |
| "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r", | |
| "invalid string: control character U+000E (SO) must be escaped to \\u000E", | |
| "invalid string: control character U+000F (SI) must be escaped to \\u000F", | |
| "invalid string: control character U+0010 (DLE) must be escaped to \\u0010", | |
| "invalid string: control character U+0011 (DC1) must be escaped to \\u0011", | |
| "invalid string: control character U+0012 (DC2) must be escaped to \\u0012", | |
| "invalid string: control character U+0013 (DC3) must be escaped to \\u0013", | |
| "invalid string: control character U+0014 (DC4) must be escaped to \\u0014", | |
| "invalid string: control character U+0015 (NAK) must be escaped to \\u0015", | |
| "invalid string: control character U+0016 (SYN) must be escaped to \\u0016", | |
| "invalid string: control character U+0017 (ETB) must be escaped to \\u0017", | |
| "invalid string: control character U+0018 (CAN) must be escaped to \\u0018", | |
| "invalid string: control character U+0019 (EM) must be escaped to \\u0019", | |
| "invalid string: control character U+001A (SUB) must be escaped to \\u001A", | |
| "invalid string: control character U+001B (ESC) must be escaped to \\u001B", | |
| "invalid string: control character U+001C (FS) must be escaped to \\u001C", | |
| "invalid string: control character U+001D (GS) must be escaped to \\u001D", | |
| "invalid string: control character U+001E (RS) must be escaped to \\u001E", | |
| "invalid string: control character U+001F (US) must be escaped to \\u001F" | |
| } | |
| }; | |
| error_message = control_character_messages[static_cast<std::size_t>(current)]; | |
| return token_type::parse_error; | |
| } | |
| // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) | |
| case 0x20: | |
| case 0x21: | |
| case 0x23: | |
| case 0x24: | |
| case 0x25: | |
| case 0x26: | |
| case 0x27: | |
| case 0x28: | |
| case 0x29: | |
| case 0x2A: | |
| case 0x2B: | |
| case 0x2C: | |
| case 0x2D: | |
| case 0x2E: | |
| case 0x2F: | |
| case 0x30: | |
| case 0x31: | |
| case 0x32: | |
| case 0x33: | |
| case 0x34: | |
| case 0x35: | |
| case 0x36: | |
| case 0x37: | |
| case 0x38: | |
| case 0x39: | |
| case 0x3A: | |
| case 0x3B: | |
| case 0x3C: | |
| case 0x3D: | |
| case 0x3E: | |
| case 0x3F: | |
| case 0x40: | |
| case 0x41: | |
| case 0x42: | |
| case 0x43: | |
| case 0x44: | |
| case 0x45: | |
| case 0x46: | |
| case 0x47: | |
| case 0x48: | |
| case 0x49: | |
| case 0x4A: | |
| case 0x4B: | |
| case 0x4C: | |
| case 0x4D: | |
| case 0x4E: | |
| case 0x4F: | |
| case 0x50: | |
| case 0x51: | |
| case 0x52: | |
| case 0x53: | |
| case 0x54: | |
| case 0x55: | |
| case 0x56: | |
| case 0x57: | |
| case 0x58: | |
| case 0x59: | |
| case 0x5A: | |
| case 0x5B: | |
| case 0x5D: | |
| case 0x5E: | |
| case 0x5F: | |
| case 0x60: | |
| case 0x61: | |
| case 0x62: | |
| case 0x63: | |
| case 0x64: | |
| case 0x65: | |
| case 0x66: | |
| case 0x67: | |
| case 0x68: | |
| case 0x69: | |
| case 0x6A: | |
| case 0x6B: | |
| case 0x6C: | |
| case 0x6D: | |
| case 0x6E: | |
| case 0x6F: | |
| case 0x70: | |
| case 0x71: | |
| case 0x72: | |
| case 0x73: | |
| case 0x74: | |
| case 0x75: | |
| case 0x76: | |
| case 0x77: | |
| case 0x78: | |
| case 0x79: | |
| case 0x7A: | |
| case 0x7B: | |
| case 0x7C: | |
| case 0x7D: | |
| case 0x7E: | |
| case 0x7F: | |
| { | |
| add(current); | |
| break; | |
| } | |
| // U+0080..U+07FF: bytes C2..DF 80..BF | |
| case 0xC2: | |
| case 0xC3: | |
| case 0xC4: | |
| case 0xC5: | |
| case 0xC6: | |
| case 0xC7: | |
| case 0xC8: | |
| case 0xC9: | |
| case 0xCA: | |
| case 0xCB: | |
| case 0xCC: | |
| case 0xCD: | |
| case 0xCE: | |
| case 0xCF: | |
| case 0xD0: | |
| case 0xD1: | |
| case 0xD2: | |
| case 0xD3: | |
| case 0xD4: | |
| case 0xD5: | |
| case 0xD6: | |
| case 0xD7: | |
| case 0xD8: | |
| case 0xD9: | |
| case 0xDA: | |
| case 0xDB: | |
| case 0xDC: | |
| case 0xDD: | |
| case 0xDE: | |
| case 0xDF: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF}))) | |
| { | |
| return token_type::parse_error; | |
| } | |
| break; | |
| } | |
| // U+0800..U+0FFF: bytes E0 A0..BF 80..BF | |
| case 0xE0: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) | |
| { | |
| return token_type::parse_error; | |
| } | |
| break; | |
| } | |
| // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF | |
| // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF | |
| case 0xE1: | |
| case 0xE2: | |
| case 0xE3: | |
| case 0xE4: | |
| case 0xE5: | |
| case 0xE6: | |
| case 0xE7: | |
| case 0xE8: | |
| case 0xE9: | |
| case 0xEA: | |
| case 0xEB: | |
| case 0xEC: | |
| case 0xEE: | |
| case 0xEF: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) | |
| { | |
| return token_type::parse_error; | |
| } | |
| break; | |
| } | |
| // U+D000..U+D7FF: bytes ED 80..9F 80..BF | |
| case 0xED: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) | |
| { | |
| return token_type::parse_error; | |
| } | |
| break; | |
| } | |
| // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF | |
| case 0xF0: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) | |
| { | |
| return token_type::parse_error; | |
| } | |
| break; | |
| } | |
| // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF | |
| case 0xF1: | |
| case 0xF2: | |
| case 0xF3: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) | |
| { | |
| return token_type::parse_error; | |
| } | |
| break; | |
| } | |
| // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF | |
| case 0xF4: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) | |
| { | |
| return token_type::parse_error; | |
| } | |
| break; | |
| } | |
| // the remaining bytes (80..C1 and F5..FF) are ill-formed | |
| default: | |
| { | |
| error_message = "invalid string: ill-formed UTF-8 byte"; | |
| return token_type::parse_error; | |
| } | |
| } | |
| } | |
| } | |
| /*! | |
| * @brief scan a comment | |
| * @return whether comment could be scanned successfully | |
| */ | |
| bool scan_comment() | |
| { | |
| switch (get()) | |
| { | |
| // single-line comments skip input until a newline or EOF is read | |
| case '/': | |
| { | |
| while (true) | |
| { | |
| switch (get()) | |
| { | |
| case '\n': | |
| case '\r': | |
| case char_traits<char_type>::eof(): | |
| return true; | |
| #if !JSON_STRICT_NUL_HANDLING | |
| case '\0': | |
| // a NUL byte is the end of the input (see scan()), | |
| // so leave it for scan() to see | |
| unget(); | |
| return true; | |
| #endif | |
| default: | |
| break; | |
| } | |
| } | |
| JSON_HEDLEY_UNREACHABLE(); | |
| } | |
| // multi-line comments skip input until */ is read | |
| case '*': | |
| { | |
| while (true) | |
| { | |
| switch (get()) | |
| { | |
| #if !JSON_STRICT_NUL_HANDLING | |
| case '\0': | |
| #endif | |
| case char_traits<char_type>::eof(): | |
| { | |
| error_message = "invalid comment; missing closing '*/'"; | |
| return false; | |
| } | |
| case '*': | |
| { | |
| switch (get()) | |
| { | |
| case '/': | |
| return true; | |
| default: | |
| { | |
| unget(); | |
| continue; | |
| } | |
| } | |
| } | |
| default: | |
| continue; | |
| } | |
| } | |
| JSON_HEDLEY_UNREACHABLE(); | |
| } | |
| // unexpected character after reading '/' | |
| default: | |
| { | |
| error_message = "invalid comment; expecting '/' or '*' after '/'"; | |
| return false; | |
| } | |
| } | |
| } | |
| /*! | |
| @brief scan a number literal | |
| This function scans a string according to Sect. 6 of RFC 8259. | |
| The function is realized with a deterministic finite state machine derived | |
| from the grammar described in RFC 8259. Starting in state "init", the | |
| input is read and used to determined the next state. Only state "done" | |
| accepts the number. State "error" is a trap state to model errors. In the | |
| table below, "anything" means any character but the ones listed before. | |
| state | 0 | 1-9 | e E | + | - | . | anything | |
| ---------|----------|----------|----------|---------|---------|----------|----------- | |
| init | zero | any1 | [error] | [error] | minus | [error] | [error] | |
| minus | zero | any1 | [error] | [error] | [error] | [error] | [error] | |
| zero | done | done | exponent | done | done | decimal1 | done | |
| any1 | any1 | any1 | exponent | done | done | decimal1 | done | |
| decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error] | |
| decimal2 | decimal2 | decimal2 | exponent | done | done | done | done | |
| exponent | any2 | any2 | [error] | sign | sign | [error] | [error] | |
| sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] | |
| any2 | any2 | any2 | done | done | done | done | done | |
| The state machine is realized with one label per state (prefixed with | |
| "scan_number_") and `goto` statements between them. The state machine | |
| contains cycles, but any cycle can be left when EOF is read. Therefore, | |
| the function is guaranteed to terminate. | |
| During scanning, the read bytes are stored in token_buffer. This string is | |
| then converted to a signed integer, an unsigned integer, or a | |
| floating-point number. | |
| @return token_type::value_unsigned, token_type::value_integer, or | |
| token_type::value_float if number could be successfully scanned, | |
| token_type::parse_error otherwise | |
| @note The scanner is independent of the current locale: token_buffer | |
| always holds `.`. The conversion of float and double does not use | |
| the locale either. Only the std::strtold fallback of | |
| convert_number() for long double formats other than binary64 | |
| depends on it, and it looks up the decimal point right before | |
| converting (see detail::convert_float_locale_aware()). | |
| */ | |
| token_type scan_number() // lgtm [cpp/use-of-goto] `goto` is used in this function to implement the number-parsing state machine described above. By design, any finite input will eventually reach the "done" state or return token_type::parse_error. In each intermediate state, 1 byte of the input is appended to the token_buffer vector, and only the already initialized variables token_buffer, number_type, and error_message are manipulated. | |
| { | |
| // reset token_buffer to store the number's bytes | |
| reset(); | |
| // the type of the parsed number; initially set to unsigned; will be | |
| // changed if minus sign, decimal point, or exponent is read | |
| token_type number_type = token_type::value_unsigned; | |
| // offset just past the last mantissa byte in token_buffer (i.e. the | |
| // index of 'e'/'E', or the whole token when there is no exponent). | |
| // convert_number() uses it to split the token; npos means | |
| // "not seen an exponent yet" and is resolved at scan_number_done | |
| std::size_t mantissa_end = std::string::npos; | |
| // state (init): we just found out we need to scan a number | |
| switch (current) | |
| { | |
| case '-': | |
| { | |
| add(current); | |
| goto scan_number_minus; | |
| } | |
| case '0': | |
| { | |
| add(current); | |
| goto scan_number_zero; | |
| } | |
| case '1': | |
| case '2': | |
| case '3': | |
| case '4': | |
| case '5': | |
| case '6': | |
| case '7': | |
| case '8': | |
| case '9': | |
| { | |
| add(current); | |
| goto scan_number_any1; | |
| } | |
| // all other characters are rejected outside scan_number() | |
| default: // LCOV_EXCL_LINE | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE | |
| } | |
| scan_number_minus: | |
| // state: we just parsed a leading minus sign | |
| number_type = token_type::value_integer; | |
| switch (get()) | |
| { | |
| case '0': | |
| { | |
| add(current); | |
| goto scan_number_zero; | |
| } | |
| case '1': | |
| case '2': | |
| case '3': | |
| case '4': | |
| case '5': | |
| case '6': | |
| case '7': | |
| case '8': | |
| case '9': | |
| { | |
| add(current); | |
| goto scan_number_any1; | |
| } | |
| default: | |
| { | |
| error_message = "invalid number; expected digit after '-'"; | |
| return token_type::parse_error; | |
| } | |
| } | |
| scan_number_zero: | |
| // state: we just parse a zero (maybe with a leading minus sign) | |
| switch (get()) | |
| { | |
| case '.': | |
| { | |
| add(current); | |
| decimal_point_position = token_buffer.size() - 1; | |
| goto scan_number_decimal1; | |
| } | |
| case 'e': | |
| case 'E': | |
| { | |
| add(current); | |
| goto scan_number_exponent; | |
| } | |
| default: | |
| goto scan_number_done; | |
| } | |
| scan_number_any1: | |
| // state: we just parsed a number 0-9 (maybe with a leading minus sign) | |
| switch (get()) | |
| { | |
| case '0': | |
| case '1': | |
| case '2': | |
| case '3': | |
| case '4': | |
| case '5': | |
| case '6': | |
| case '7': | |
| case '8': | |
| case '9': | |
| { | |
| add(current); | |
| goto scan_number_any1; | |
| } | |
| case '.': | |
| { | |
| add(current); | |
| decimal_point_position = token_buffer.size() - 1; | |
| goto scan_number_decimal1; | |
| } | |
| case 'e': | |
| case 'E': | |
| { | |
| add(current); | |
| goto scan_number_exponent; | |
| } | |
| default: | |
| goto scan_number_done; | |
| } | |
| scan_number_decimal1: | |
| // state: we just parsed a decimal point | |
| number_type = token_type::value_float; | |
| switch (get()) | |
| { | |
| case '0': | |
| case '1': | |
| case '2': | |
| case '3': | |
| case '4': | |
| case '5': | |
| case '6': | |
| case '7': | |
| case '8': | |
| case '9': | |
| { | |
| add(current); | |
| goto scan_number_decimal2; | |
| } | |
| default: | |
| { | |
| error_message = "invalid number; expected digit after '.'"; | |
| return token_type::parse_error; | |
| } | |
| } | |
| scan_number_decimal2: | |
| // we just parsed at least one number after a decimal point | |
| switch (get()) | |
| { | |
| case '0': | |
| case '1': | |
| case '2': | |
| case '3': | |
| case '4': | |
| case '5': | |
| case '6': | |
| case '7': | |
| case '8': | |
| case '9': | |
| { | |
| add(current); | |
| goto scan_number_decimal2; | |
| } | |
| case 'e': | |
| case 'E': | |
| { | |
| add(current); | |
| goto scan_number_exponent; | |
| } | |
| default: | |
| goto scan_number_done; | |
| } | |
| scan_number_exponent: | |
| // we just parsed an exponent | |
| number_type = token_type::value_float; | |
| // this label is reached only right after the 'e'/'E' was appended (from | |
| // the zero, any1, and decimal2 states), so the mantissa ends before it | |
| mantissa_end = token_buffer.size() - 1; | |
| switch (get()) | |
| { | |
| case '+': | |
| case '-': | |
| { | |
| add(current); | |
| goto scan_number_sign; | |
| } | |
| case '0': | |
| case '1': | |
| case '2': | |
| case '3': | |
| case '4': | |
| case '5': | |
| case '6': | |
| case '7': | |
| case '8': | |
| case '9': | |
| { | |
| add(current); | |
| goto scan_number_any2; | |
| } | |
| default: | |
| { | |
| error_message = | |
| "invalid number; expected '+', '-', or digit after exponent"; | |
| return token_type::parse_error; | |
| } | |
| } | |
| scan_number_sign: | |
| // we just parsed an exponent sign | |
| switch (get()) | |
| { | |
| case '0': | |
| case '1': | |
| case '2': | |
| case '3': | |
| case '4': | |
| case '5': | |
| case '6': | |
| case '7': | |
| case '8': | |
| case '9': | |
| { | |
| add(current); | |
| goto scan_number_any2; | |
| } | |
| default: | |
| { | |
| error_message = "invalid number; expected digit after exponent sign"; | |
| return token_type::parse_error; | |
| } | |
| } | |
| scan_number_any2: | |
| // we just parsed a number after the exponent or exponent sign | |
| switch (get()) | |
| { | |
| case '0': | |
| case '1': | |
| case '2': | |
| case '3': | |
| case '4': | |
| case '5': | |
| case '6': | |
| case '7': | |
| case '8': | |
| case '9': | |
| { | |
| add(current); | |
| goto scan_number_any2; | |
| } | |
| default: | |
| goto scan_number_done; | |
| } | |
| scan_number_done: | |
| // unget the character after the number (we only read it to know that | |
| // we are done scanning a number) | |
| unget(); | |
| // no exponent was scanned: the mantissa spans the whole token | |
| if (mantissa_end == std::string::npos) | |
| { | |
| mantissa_end = token_buffer.size(); | |
| } | |
| return convert_number(number_type, mantissa_end); | |
| } | |
| /*! | |
| @brief convert an already-validated integer token to its value | |
| The digit sequence in [first, last) has been validated by the caller, so a | |
| dedicated parser can avoid the locale/errno overhead of std::strtoull. | |
| @return the token type on success; token_type::uninitialized if @a | |
| number_type is not an integer type or the value does not fit, in | |
| which case the caller falls back to the floating-point conversion | |
| (matching the previous std::strtoull/std::strtoll behavior) | |
| */ | |
| token_type convert_integer(token_type number_type, const char* first, const char* last) | |
| { | |
| if (number_type == token_type::value_unsigned) | |
| { | |
| if (parse_integer_unsigned(first, last, value_unsigned)) | |
| { | |
| return token_type::value_unsigned; | |
| } | |
| } | |
| else if (number_type == token_type::value_integer) | |
| { | |
| if (parse_integer_signed(first, last, value_integer)) | |
| { | |
| return token_type::value_integer; | |
| } | |
| } | |
| return token_type::uninitialized; | |
| } | |
| /*! | |
| @brief convert the number text in token_buffer to its value and token type | |
| The digit sequence in token_buffer has already been validated (by the | |
| scan_number() state machine or by the contiguous fast path) and holds '.' | |
| as decimal point, independent of the locale. Integers are parsed first and fall | |
| back to floating point on overflow. This is shared so both scanners produce | |
| identical results. | |
| @param[in] mantissa_end offset just past the last mantissa byte in | |
| token_buffer (the index of 'e'/'E', or | |
| token_buffer.size() when there is no exponent); | |
| with decimal_point_position, it locates the parts | |
| of a float token without scanning it again | |
| */ | |
| token_type convert_number(token_type number_type, std::size_t mantissa_end) | |
| { | |
| // accept() only needs to know whether the input is valid, so it sets | |
| // discard_number_values (see json.hpp), and an integer token whose | |
| // digit count shows that it fits is reported without calling | |
| // convert_integer(). A number with up to 18 digits always fits into | |
| // both std::uint64_t and std::int64_t (18 nines is about 1e18, below | |
| // INT64_MAX, which is about 9.2e18). Longer tokens take the exact path | |
| // below, including the fallback to floating point when the value does | |
| // not fit. | |
| // | |
| // With a narrower number_unsigned_t/number_integer_t (e.g. | |
| // std::uint32_t), the exact path would reclassify some of these tokens | |
| // as (finite) floats, while this check reports integers. That does not | |
| // change the result of accept(): it always parses through | |
| // json_sax_acceptor, whose number callbacks discard their argument and | |
| // return true, and the parser rejects neither integers nor finite | |
| // floats. value_unsigned/value_integer are left unset here, so a caller | |
| // that reads the converted value must not set discard_number_values. | |
| // | |
| // On contiguous input, scan_number_bulk_contiguous() converts integer | |
| // tokens itself and does not pass them to this function, unless | |
| // JSON_DIAGNOSTIC_POSITIONS is enabled. This check is therefore only | |
| // reached for input without bulk access (e.g. streams), with | |
| // JSON_DIAGNOSTIC_POSITIONS, or when scan_number_bulk_contiguous() | |
| // falls back to scan_number(). | |
| if (discard_number_values) | |
| { | |
| constexpr std::size_t safe_digit_count = 18; | |
| if (number_type == token_type::value_unsigned && token_buffer.size() <= safe_digit_count) | |
| { | |
| return token_type::value_unsigned; | |
| } | |
| if (number_type == token_type::value_integer && token_buffer.size() - 1 <= safe_digit_count) | |
| { | |
| return token_type::value_integer; | |
| } | |
| } | |
| const char* const num_begin = token_buffer.data(); | |
| const char* const num_end = num_begin + token_buffer.size(); | |
| if (number_type != token_type::value_float) | |
| { | |
| const token_type integer_result = convert_integer(number_type, num_begin, num_end); | |
| if (integer_result != token_type::uninitialized) | |
| { | |
| return integer_result; | |
| } | |
| } | |
| // this code is reached if we parse a floating-point number or if an | |
| // integer conversion above overflowed. float and double (and long | |
| // double where it is binary64) are converted by the library itself, | |
| // correctly rounded and independent of the locale; other long double | |
| // formats use std::from_chars when available, otherwise the | |
| // locale-aware strtold. | |
| if (convert_float_fast(num_begin, num_end, decimal_point_position, mantissa_end, value_float)) | |
| { | |
| return token_type::value_float; | |
| } | |
| convert_float_locale_aware(token_buffer, decimal_point_position, value_float); | |
| return token_type::value_float; | |
| } | |
| /*! | |
| @brief contiguous fast path for scanning a number | |
| Parses the whole number token straight from the input buffer, avoiding the | |
| per-character get()/add() of scan_number(). On success it fills token_buffer | |
| (as scan_number() does) and | |
| returns the token type. On anything it does not fully recognize as a | |
| well-formed number it makes no state change and returns | |
| token_type::uninitialized, so the caller falls back to scan_number(), which | |
| then produces the exact diagnostic. @a current is the first digit or the | |
| leading minus (already read); the remaining bytes are taken from the adapter. | |
| */ | |
| token_type scan_number_bulk_contiguous() | |
| { | |
| // a pending unget offsets the buffer position from current; fall back | |
| if (next_unget) | |
| { | |
| return token_type::uninitialized; | |
| } | |
| const std::size_t rem = ia.bulk_remaining(); | |
| if (rem == 0) | |
| { | |
| // the first digit is the last input byte; let scan_number() finish | |
| return token_type::uninitialized; | |
| } | |
| // the byte before the next unread one is current (contiguous input) | |
| const char* const data = reinterpret_cast<const char*>(ia.bulk_data()) - 1; | |
| const std::size_t avail = rem + 1; | |
| // validate + classify the number extent (mirrors scan_number()'s grammar) | |
| // and accumulate the mantissa digits on the way, so that tokens with up | |
| // to 19 digits need no second pass for their value | |
| std::size_t i = 0; | |
| std::size_t dot_index = std::string::npos; | |
| token_type number_type = token_type::value_unsigned; | |
| std::uint64_t w = 0; | |
| if (data[0] == '-') | |
| { | |
| number_type = token_type::value_integer; | |
| i = 1; | |
| if (i >= avail) | |
| { | |
| return token_type::uninitialized; | |
| } | |
| } | |
| const std::size_t integer_begin = i; | |
| if (data[i] == '0') | |
| { | |
| ++i; | |
| } | |
| else if (data[i] >= '1' && data[i] <= '9') | |
| { | |
| i = accumulate_digits(data, i, avail, w); | |
| } | |
| else | |
| { | |
| return token_type::uninitialized; | |
| } | |
| std::size_t digit_count = i - integer_begin; | |
| std::size_t fraction_digits = 0; | |
| if (i < avail && data[i] == '.') | |
| { | |
| number_type = token_type::value_float; | |
| dot_index = i; | |
| ++i; | |
| if (i >= avail || !(data[i] >= '0' && data[i] <= '9')) | |
| { | |
| return token_type::uninitialized; | |
| } | |
| const std::size_t fraction_begin = i; | |
| i = accumulate_digits(data, i, avail, w); | |
| fraction_digits = i - fraction_begin; | |
| digit_count += fraction_digits; | |
| } | |
| // the mantissa ends here, whether or not an exponent part follows | |
| const std::size_t mantissa_end = i; | |
| std::int64_t exponent = 0; | |
| if (i < avail && (data[i] == 'e' || data[i] == 'E')) | |
| { | |
| number_type = token_type::value_float; | |
| ++i; | |
| bool negative_exponent = false; | |
| if (i < avail && (data[i] == '+' || data[i] == '-')) | |
| { | |
| negative_exponent = data[i] == '-'; | |
| ++i; | |
| } | |
| if (i >= avail || !(data[i] >= '0' && data[i] <= '9')) | |
| { | |
| return token_type::uninitialized; | |
| } | |
| // saturated far beyond every range, see parse_float_exponent() | |
| constexpr std::int64_t saturation = 100000000000000000; // 10^17 | |
| while (i < avail && data[i] >= '0' && data[i] <= '9') | |
| { | |
| if (exponent < saturation) | |
| { | |
| exponent = (exponent * 10) + (data[i] - '0'); | |
| } | |
| ++i; | |
| } | |
| exponent = negative_exponent ? -exponent : exponent; | |
| } | |
| const std::size_t len = i; | |
| if (number_may_continue(len == avail, std::integral_constant<bool, bulk_window> {})) | |
| { | |
| return token_type::uninitialized; | |
| } | |
| // reset() records where this token starts (for diagnostics), so it has | |
| // to run before the input position advances below | |
| reset(); | |
| // An integer token needs no token_buffer: the SAX callbacks for | |
| // number_integer/number_unsigned take only the value, and the overflow | |
| // diagnostic rebuilds the text from the input. Convert straight from the | |
| // input buffer and leave token_buffer empty. (JSON_DIAGNOSTIC_POSITIONS | |
| // derives a number's start position from get_string().size(), so there | |
| // the token still has to be materialized.) | |
| #if !JSON_DIAGNOSTIC_POSITIONS | |
| if (number_type != token_type::value_float) | |
| { | |
| // up to 18 digits always fit into std::uint64_t and std::int64_t | |
| const token_type integer_result = (digit_count <= 18) | |
| ? store_integer(number_type, w) | |
| : convert_integer(number_type, data, data + len); | |
| if (JSON_HEDLEY_LIKELY(integer_result != token_type::uninitialized)) | |
| { | |
| bulk_consume(data + 1, len - 1); | |
| read_number_terminator(std::integral_constant<bool, bulk_window> {}); | |
| return integer_result; | |
| } | |
| // The value does not fit an integer, so this token converts as a | |
| // float. Recording that here keeps convert_number() below from | |
| // repeating the integer attempt that just failed. | |
| number_type = token_type::value_float; | |
| } | |
| #endif | |
| decimal_point_position = dot_index; | |
| bulk_consume(data + 1, len - 1); | |
| read_number_terminator(std::integral_constant<bool, bulk_window> {}); | |
| // a float whose digits all fit into w converts from the accumulated | |
| // value; longer ones (and other float formats) take the general path | |
| if (number_type == token_type::value_float && digit_count <= 19) | |
| { | |
| float_significand s; | |
| s.w = w; | |
| s.exponent = exponent - static_cast<std::int64_t>(fraction_digits); | |
| s.negative = data[0] == '-'; | |
| if (convert_accumulated_float(s, std::integral_constant<bool, has_native_float_format<number_float_t>::value> {})) | |
| { | |
| // the token text is only copied into token_buffer when | |
| // get_string() asks for it; the library's own SAX handlers | |
| // ignore it. A window into a stream may be refilled by the | |
| // next read, so there the text is copied right away. | |
| if (bulk_window) | |
| { | |
| token_buffer.append(reinterpret_cast<const typename string_t::value_type*>(data), len); | |
| } | |
| else | |
| { | |
| pending_number_text = data; | |
| pending_number_length = len; | |
| } | |
| return token_type::value_float; | |
| } | |
| } | |
| // materialize the token exactly as scan_number() would. reset() already | |
| // cleared token_buffer, so append() fills it (assign() is avoided | |
| // because custom string_t types need not provide it) | |
| token_buffer.append(reinterpret_cast<const typename string_t::value_type*>(data), len); | |
| return convert_number(number_type, mantissa_end); | |
| } | |
| /// window adapter: a number that reaches the end of the window may continue | |
| /// after it, so scan_number() has to read it character by character | |
| static constexpr bool number_may_continue(bool at_end, std::true_type /*window*/) noexcept | |
| { | |
| return at_end; | |
| } | |
| /// the end of the block is the end of the input, which ends the number | |
| static constexpr bool number_may_continue(bool /*at_end*/, std::false_type /*window*/) noexcept | |
| { | |
| return false; | |
| } | |
| /// window adapter: read the character after a bulk-scanned number and unget | |
| /// it, as scan_number() does. The adapter is a stream that is handed back to | |
| /// the user, who must find the same input consumed either way. | |
| void read_number_terminator(std::true_type /*window*/) | |
| { | |
| get(); | |
| unget(); | |
| } | |
| /// the input is not handed back, so the terminator can stay unread | |
| void read_number_terminator(std::false_type /*window*/) const noexcept {} | |
| /// binary32/binary64: the value of a float token from its accumulated | |
| /// significand (see scan_number_bulk_contiguous()) | |
| bool convert_accumulated_float(const float_significand& s, std::true_type /*native*/) noexcept | |
| { | |
| // accept() only needs to know that the value is finite (see the parser): | |
| // w < 10^19, so a value below 10^max_exponent10 cannot overflow, and a | |
| // value that underflows is a finite number as well. Only a token that | |
| // may overflow has to be converted to find out. | |
| if (JSON_HEDLEY_UNLIKELY(discard_number_values && s.exponent + 19 <= std::numeric_limits<number_float_t>::max_exponent10)) | |
| { | |
| value_float = 0; | |
| return true; | |
| } | |
| value_float = decimal_to_float<number_float_t>(s); | |
| return true; | |
| } | |
| /// other formats (e.g. x87 long double): not instantiated for them, as | |
| /// decimal_to_float() only supports binary32/binary64 | |
| static bool convert_accumulated_float(const float_significand& /*s*/, std::false_type /*native*/) noexcept | |
| { | |
| return false; | |
| } | |
| /// the value of an integer token with at most 18 digits, accumulated in @a w | |
| token_type store_integer(token_type number_type, std::uint64_t w) noexcept | |
| { | |
| if (number_type == token_type::value_unsigned) | |
| { | |
| value_unsigned = static_cast<number_unsigned_t>(w); | |
| // reject values that do not round-trip into a narrower type | |
| return (static_cast<std::uint64_t>(value_unsigned) == w) ? token_type::value_unsigned : token_type::uninitialized; | |
| } | |
| const std::int64_t x = -static_cast<std::int64_t>(w); | |
| value_integer = static_cast<number_integer_t>(x); | |
| return (static_cast<std::int64_t>(value_integer) == x) ? token_type::value_integer : token_type::uninitialized; | |
| } | |
| /// contiguous input: try the number fast path, else the byte-path scanner | |
| token_type scan_number_dispatch(std::true_type /*bulk*/) | |
| { | |
| const token_type t = scan_number_bulk_contiguous(); | |
| return (t != token_type::uninitialized) ? t : scan_number(); | |
| } | |
| /// streaming input: always use the byte-path scanner | |
| token_type scan_number_dispatch(std::false_type /*bulk*/) | |
| { | |
| return scan_number(); | |
| } | |
| /*! | |
| @param[in] rest the literal text after its first character, which | |
| is current (its length is a template parameter, so | |
| that the comparison of the contiguous fast path is | |
| a fixed-size load, not a call of memcmp) | |
| @param[in] return_type the token type to return on success | |
| */ | |
| template<std::size_t N> | |
| JSON_HEDLEY_NEVER_INLINE token_type scan_literal(const char (&rest)[N], token_type return_type) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| { | |
| constexpr std::size_t length = N - 1; | |
| if (scan_literal_bulk(rest, length, std::integral_constant<bool, bulk_scan> {})) | |
| { | |
| return return_type; | |
| } | |
| for (std::size_t i = 0; i < length; ++i) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(char_traits<char_type>::to_char_type(get()) != static_cast<char_type>(rest[i]))) | |
| { | |
| error_message = "invalid literal"; | |
| return token_type::parse_error; | |
| } | |
| } | |
| return return_type; | |
| } | |
| /// contiguous input: compare the rest of a literal at once; false (and | |
| /// nothing consumed) if it does not match, so that the byte path reports | |
| /// the error at the right character | |
| JSON_HEDLEY_ALWAYS_INLINE bool scan_literal_bulk(const char* rest, const std::size_t length, std::true_type /*bulk*/) | |
| { | |
| if (next_unget || ia.bulk_remaining() < length | |
| || std::memcmp(ia.bulk_data(), rest, length) != 0) | |
| { | |
| return false; | |
| } | |
| bulk_consume(reinterpret_cast<const char*>(ia.bulk_data()), length); | |
| current = static_cast<char_int_type>(static_cast<unsigned char>(rest[length - 1])); | |
| return true; | |
| } | |
| /// streaming input: no bulk fast path | |
| bool scan_literal_bulk(const char* /*rest*/, const std::size_t /*length*/, std::false_type /*bulk*/) const noexcept | |
| { | |
| return false; | |
| } | |
| ///////////////////// | |
| // input management | |
| ///////////////////// | |
| /// reset token_buffer; current character is beginning of token | |
| void reset() noexcept | |
| { | |
| token_buffer.clear(); | |
| pending_number_text = nullptr; | |
| decimal_point_position = std::string::npos; | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| // the first character of the token has already been read, hence the -1 | |
| token_start_position = get_chars_read_total() - 1; | |
| #endif | |
| note_token_start(std::integral_constant<bool, lazy_token_string> {}); | |
| } | |
| /// seekable adapter: remember where the current token starts so it can be | |
| /// reconstructed from the input on error; current has already been | |
| /// consumed, hence the -1 | |
| void note_token_start(std::true_type /*lazy*/) | |
| { | |
| note_token_start_lazy(std::integral_constant<bool, adapter_token> {}); | |
| } | |
| void note_token_start_lazy(std::false_type /*adapter_token*/) noexcept | |
| { | |
| token_string_start = ia.get_consumed_count() - 1; | |
| } | |
| /// token-tracking adapter: start tracking the token at the first character | |
| void begin_token(std::true_type /*adapter_token*/) noexcept | |
| { | |
| ia.begin_token(); | |
| } | |
| void begin_token(std::false_type /*adapter_token*/) const noexcept {} | |
| /// token-tracking adapter: the token starts with the current character | |
| void note_token_start_lazy(std::true_type /*adapter_token*/) | |
| { | |
| ia.mark_token_start(current); | |
| } | |
| /// streaming adapter: start copying the token eagerly, beginning with the | |
| /// already-read first character | |
| void note_token_start(std::false_type /*lazy*/) noexcept | |
| { | |
| token_string.clear(); | |
| token_string.push_back(char_traits<char_type>::to_char_type(current)); | |
| } | |
| /* | |
| @brief get next character from the input | |
| This function provides the interface to the used input adapter. It does | |
| not throw in case the input reached EOF, but returns a | |
| `char_traits<char>::eof()` in that case. Stores the scanned characters | |
| for use in error messages. | |
| @return character read from the input | |
| */ | |
| char_int_type get() | |
| { | |
| advance_position(); | |
| if (next_unget) | |
| { | |
| // only reset the next_unget variable and work with current | |
| next_unget = false; | |
| } | |
| else | |
| { | |
| current = ia.get_character(); | |
| } | |
| return track_after_read(); | |
| } | |
| /// shared head of get() / get_ignoring_pending_unget(): bump the | |
| /// per-character position counters (line-count-on-'\n' bookkeeping is | |
| /// handled afterwards, in track_after_read(), once `current` is known) | |
| void advance_position() noexcept | |
| { | |
| advance_position_impl(std::integral_constant<bool, lazy_position> {}); | |
| } | |
| /// seekable adapter: the position is derived from the adapter on demand | |
| void advance_position_impl(std::true_type /*lazy*/) const noexcept {} | |
| /// streaming adapter: count the character | |
| void advance_position_impl(std::false_type /*lazy*/) noexcept | |
| { | |
| ++position.chars_read_total; | |
| ++position.chars_read_current_line; | |
| } | |
| /// shared tail of get() / get_ignoring_pending_unget(): capture the | |
| /// character for error messages (if needed) and update line/column | |
| /// bookkeeping for the character now in `current` | |
| char_int_type track_after_read() | |
| { | |
| // seekable adapters reconstruct the token lazily on error (see | |
| // get_token_string), so the eager per-character copy is skipped | |
| capture_char(std::integral_constant<bool, lazy_token_string> {}); | |
| track_newline(std::integral_constant<bool, lazy_position> {}); | |
| return current; | |
| } | |
| /// seekable adapter: lines are counted on demand in get_position() | |
| void track_newline(std::true_type /*lazy*/) const noexcept {} | |
| /// streaming adapter: start a new line after reading a newline | |
| void track_newline(std::false_type /*lazy*/) noexcept | |
| { | |
| if (current == '\n') | |
| { | |
| ++position.lines_read; | |
| // remember the column the newline was read at: chars_read_current_line | |
| // is about to be cleared, and a matching unget() cannot reconstruct it | |
| chars_read_before_newline = position.chars_read_current_line; | |
| position.chars_read_current_line = 0; | |
| } | |
| } | |
| /*! | |
| @brief like get(), but for call sites that can prove no unget() is pending | |
| get() has to check the `next_unget` flag on every call, because a | |
| previous token may have ended with unget() (e.g. scan_number() always | |
| ungets the character that terminated the number, so the next call to | |
| scan() can see it again). skip_whitespace() reads that first, | |
| possibly-ungotten character via a plain get(), but every further | |
| character it reads is guaranteed to be a fresh read: nothing between | |
| those calls invokes unget(). This variant skips the (otherwise always | |
| false) next_unget branch for those calls; it is not a general | |
| replacement for get(). | |
| */ | |
| char_int_type get_ignoring_pending_unget() | |
| { | |
| JSON_ASSERT(!next_unget); | |
| advance_position(); | |
| current = ia.get_character(); | |
| return track_after_read(); | |
| } | |
| /// seekable adapter: nothing to capture, the token is rebuilt on error | |
| void capture_char(std::true_type /*lazy*/) const noexcept {} | |
| /// streaming adapter: copy the scanned character into token_string | |
| void capture_char(std::false_type /*lazy*/) | |
| { | |
| if (JSON_HEDLEY_LIKELY(current != char_traits<char_type>::eof())) | |
| { | |
| token_string.push_back(char_traits<char_type>::to_char_type(current)); | |
| } | |
| } | |
| /*! | |
| @brief unget current character (read it again on next get) | |
| We implement unget by setting variable next_unget to true. The input is not | |
| changed - we just simulate ungetting by modifying chars_read_total, | |
| chars_read_current_line, and token_string. The next call to get() will | |
| behave as if the unget character is read again. With lazy_position, the | |
| pending next_unget is all get_chars_read_total() needs. | |
| */ | |
| void unget() | |
| { | |
| next_unget = true; | |
| unget_position(std::integral_constant<bool, lazy_position> {}); | |
| uncapture_char(std::integral_constant<bool, lazy_token_string> {}); | |
| } | |
| /// seekable adapter: get_chars_read_total() accounts for next_unget | |
| void unget_position(std::true_type /*lazy*/) const noexcept {} | |
| /// streaming adapter: step the counters back over the ungotten character | |
| void unget_position(std::false_type /*lazy*/) noexcept | |
| { | |
| --position.chars_read_total; | |
| // in case we "unget" a newline, we have to also decrement the lines_read | |
| // and restore the column that get() cleared when it saw the newline; | |
| // chars_read_current_line == 0 can only mean the last get() read one | |
| if (position.chars_read_current_line == 0) | |
| { | |
| if (position.lines_read > 0) | |
| { | |
| --position.lines_read; | |
| } | |
| // chars_read_before_newline counts the newline itself, which is the | |
| // character being ungotten, hence the -1 | |
| position.chars_read_current_line = (chars_read_before_newline > 0) | |
| ? chars_read_before_newline - 1 | |
| : 0; | |
| } | |
| else | |
| { | |
| --position.chars_read_current_line; | |
| } | |
| } | |
| /// adapter without lookahead: nothing to do (see release_lookahead) | |
| void release_lookahead_impl(std::false_type /*can_release*/) const noexcept {} | |
| /// adapter with lookahead: leave the character in the input instead | |
| void release_lookahead_impl(std::true_type /*can_release*/) | |
| { | |
| if (next_unget) | |
| { | |
| // the character is read from the input again rather than replayed | |
| // from current, so the adapter must not step over it | |
| next_unget = false; | |
| ia.release_lookahead(); | |
| } | |
| } | |
| /// seekable adapter: nothing was captured, so nothing to undo | |
| void uncapture_char(std::true_type /*lazy*/) const noexcept {} | |
| /// streaming adapter: drop the character copied by the matching get() | |
| void uncapture_char(std::false_type /*lazy*/) | |
| { | |
| if (JSON_HEDLEY_LIKELY(current != char_traits<char_type>::eof())) | |
| { | |
| JSON_ASSERT(!token_string.empty()); | |
| token_string.pop_back(); | |
| } | |
| } | |
| /// add a character to token_buffer | |
| void add(char_int_type c) | |
| { | |
| token_buffer.push_back(static_cast<typename string_t::value_type>(c)); | |
| } | |
| public: | |
| ///////////////////// | |
| // value getters | |
| ///////////////////// | |
| /// return integer value | |
| constexpr number_integer_t get_number_integer() const noexcept | |
| { | |
| return value_integer; | |
| } | |
| /// return unsigned integer value | |
| constexpr number_unsigned_t get_number_unsigned() const noexcept | |
| { | |
| return value_unsigned; | |
| } | |
| /// return floating-point value | |
| constexpr number_float_t get_number_float() const noexcept | |
| { | |
| return value_float; | |
| } | |
| /// return current string value | |
| string_t& get_string() | |
| { | |
| if (pending_number_text != nullptr) | |
| { | |
| token_buffer.append(reinterpret_cast<const typename string_t::value_type*>(pending_number_text), pending_number_length); | |
| pending_number_text = nullptr; | |
| } | |
| // a number token holds '.' regardless of the locale (#4084) | |
| return token_buffer; | |
| } | |
| /// the value of a string token (key or string), which never has pending | |
| /// number text, so get_string()'s check is not needed | |
| string_t& get_string_token() noexcept | |
| { | |
| JSON_ASSERT(pending_number_text == nullptr); | |
| return token_buffer; | |
| } | |
| /// the text of a float token for a SAX handler that ignores it (the | |
| /// library's own handlers): empty, without copying the token | |
| const string_t& get_ignored_number_text() const noexcept | |
| { | |
| return token_buffer; | |
| } | |
| ///////////////////// | |
| // diagnostics | |
| ///////////////////// | |
| /*! | |
| @brief return the number of characters read so far | |
| Unlike get_position(), this is O(1) for all adapters, so it may be called | |
| for every value (JSON_DIAGNOSTIC_POSITIONS). | |
| */ | |
| std::size_t get_chars_read_total() const noexcept | |
| { | |
| return get_chars_read_total_impl(std::integral_constant<bool, lazy_position> {}); | |
| } | |
| /// return position of last read token | |
| position_t get_position() const | |
| { | |
| return get_position_impl(std::integral_constant<bool, lazy_position> {}); | |
| } | |
| /*! | |
| @brief pass a pending simulated unget on to the input | |
| unget() only rewinds the lexer's own bookkeeping, so the character that | |
| terminated the last token (e.g. the character after a number) would still | |
| be stepped over when the input adapter is done. Callers that hand the | |
| input back to the user afterwards - operator>> and non-strict sax_parse - | |
| call this once when scanning is done, so that the input is positioned | |
| right after the value. | |
| Adapters without lookahead (see input_adapter_supports_lookahead) are not | |
| handed back to the user, so this is a no-op for them. Without | |
| JSON_PRECISE_STREAM_POSITION, no adapter has lookahead, so this is always a | |
| no-op and the terminating character stays consumed. | |
| Scanning may continue after this call: @a next_unget is cleared, and the | |
| character is read from the input again instead of being replayed from | |
| @a current. A pending unget of EOF needs no special case, because reaching | |
| EOF leaves no lookahead to release. | |
| */ | |
| void release_lookahead() | |
| { | |
| release_lookahead_impl(std::integral_constant<bool, can_release_lookahead> {}); | |
| } | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| /// return the offset of the first character of the last read token; unlike | |
| /// the token's parsed value, this accounts for escape sequences | |
| constexpr std::size_t get_token_start_position() const noexcept | |
| { | |
| return token_start_position; | |
| } | |
| #endif | |
| private: | |
| /// seekable adapter: every get() either read from the adapter (including | |
| /// reads at EOF, which get() counts as characters as well) or replayed an | |
| /// ungotten character, so the count is the adapter's read count minus a | |
| /// still pending unget | |
| std::size_t get_chars_read_total_impl(std::true_type /*lazy*/) const noexcept | |
| { | |
| return ia.get_read_count() - (next_unget ? 1u : 0u); | |
| } | |
| /// streaming adapter: the counter is maintained by get() and unget() | |
| std::size_t get_chars_read_total_impl(std::false_type /*lazy*/) const noexcept | |
| { | |
| return position.chars_read_total; | |
| } | |
| /// seekable adapter: count the lines in the consumed input; O(input read | |
| /// so far), but only called on errors | |
| position_t get_position_impl(std::true_type /*lazy*/) const | |
| { | |
| position_t result; | |
| result.chars_read_total = get_chars_read_total(); | |
| // reads at EOF count as characters but are not part of the input | |
| const std::size_t consumed = (std::min)(result.chars_read_total, ia.get_consumed_count()); | |
| std::size_t line_start = 0; | |
| result.lines_read = ia.count_consumed_lines(consumed, line_start); | |
| result.chars_read_current_line = result.chars_read_total - line_start; | |
| return result; | |
| } | |
| /// streaming adapter: the position is maintained by get() and unget() | |
| position_t get_position_impl(std::false_type /*lazy*/) const noexcept | |
| { | |
| return position; | |
| } | |
| public: | |
| /// seekable adapter: rebuild the last read token from the input on demand | |
| const std::vector<char_type>& collect_token_chars(std::vector<char_type>& out, std::true_type /*lazy*/) const | |
| { | |
| return collect_token_chars_lazy(out, std::integral_constant<bool, adapter_token> {}); | |
| } | |
| /// token-tracking adapter: the adapter hands out everything read since | |
| /// mark_token_start(), except a pending unget (see below) | |
| const std::vector<char_type>& collect_token_chars_lazy(std::vector<char_type>& out, std::true_type /*adapter_token*/) const | |
| { | |
| const bool pending_real_unget = next_unget && current != char_traits<char_type>::eof(); | |
| ia.copy_token(out, pending_real_unget); | |
| return out; | |
| } | |
| const std::vector<char_type>& collect_token_chars_lazy(std::vector<char_type>& out, std::false_type /*adapter_token*/) const | |
| { | |
| // a pending unget of a real (non-EOF) character means that character | |
| // was consumed from the input but is not part of the token; EOF is | |
| // never consumed, so it must not be subtracted (mirrors unget()) | |
| const bool pending_real_unget = next_unget && current != char_traits<char_type>::eof(); | |
| const std::size_t stop = ia.get_consumed_count() - (pending_real_unget ? 1u : 0u); | |
| if (JSON_HEDLEY_LIKELY(stop >= token_string_start)) | |
| { | |
| ia.copy_consumed_range(token_string_start, stop, out); | |
| } | |
| return out; | |
| } | |
| /// streaming adapter: the token was copied eagerly while scanning | |
| const std::vector<char_type>& collect_token_chars(std::vector<char_type>& /*out*/, std::false_type /*lazy*/) const | |
| { | |
| return token_string; | |
| } | |
| /// return the last read token (for errors only). Will never contain EOF | |
| /// (an arbitrary value that is not a valid char value, often -1), because | |
| /// 255 may legitimately occur. May contain NUL, which should be escaped. | |
| std::string get_token_string() const | |
| { | |
| std::vector<char_type> reconstructed; | |
| const std::vector<char_type>& chars = collect_token_chars(reconstructed, std::integral_constant<bool, lazy_token_string> {}); | |
| // escape control characters | |
| std::string result; | |
| for (const auto c : chars) | |
| { | |
| if (static_cast<unsigned char>(c) <= '\x1F') | |
| { | |
| // escape control characters | |
| std::array<char, 9> cs{{}}; | |
| static_cast<void>((std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) | |
| result += cs.data(); | |
| } | |
| else | |
| { | |
| // add character as is | |
| result.push_back(static_cast<std::string::value_type>(c)); | |
| } | |
| } | |
| return result; | |
| } | |
| /// return syntax error message | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| constexpr const char* get_error_message() const noexcept | |
| { | |
| return error_message; | |
| } | |
| ///////////////////// | |
| // actual scanner | |
| ///////////////////// | |
| /*! | |
| @brief skip the UTF-8 byte order mark | |
| @return true iff there is no BOM or the correct BOM has been skipped | |
| */ | |
| bool skip_bom() | |
| { | |
| if (get() == 0xEF) | |
| { | |
| // check if we completely parse the BOM | |
| return get() == 0xBB && get() == 0xBF; | |
| } | |
| // the first character is not the beginning of the BOM; unget it to | |
| // process is later | |
| unget(); | |
| return true; | |
| } | |
| /// whether `current` is one of the four JSON whitespace characters | |
| bool current_is_whitespace() const noexcept | |
| { | |
| return current == ' ' || current == '\t' || current == '\n' || current == '\r'; | |
| } | |
| void skip_whitespace() | |
| { | |
| // the first character may be a pending unget() left over from the | |
| // previous token (see get_ignoring_pending_unget()); every | |
| // subsequent character read by this loop is guaranteed fresh, since | |
| // nothing below calls unget() | |
| get(); | |
| if (!current_is_whitespace()) | |
| { | |
| return; | |
| } | |
| // this is written as an if-guarded do-while (rather than a plain | |
| // while loop) because that shape is what lets both GCC and Clang | |
| // keep the input adapter's read pointer in a register across | |
| // iterations; the equivalent while-loop measurably defeated that | |
| // optimization in testing, turning long whitespace runs (e.g. the | |
| // indentation of pretty-printed JSON) from a register-only loop | |
| // into one that reloads the pointer from memory every character | |
| do | |
| { | |
| if (current == '\n') | |
| { | |
| skip_indentation(std::integral_constant<bool, bulk_scan> {}); | |
| } | |
| get_ignoring_pending_unget(); | |
| } | |
| while (current_is_whitespace()); | |
| } | |
| /*! | |
| @brief contiguous input: skip the space indentation that follows a newline | |
| 8 bytes at a time | |
| Pretty-printed JSON indents every line with a run of spaces, which the loop | |
| in skip_whitespace() would otherwise read one character at a time. The | |
| spaces are skipped 8 bytes at a time; the last 7 bytes of the input and any | |
| other whitespace are left to that loop. Skipping bypasses get(); | |
| bulk_consume() does its bookkeeping. | |
| */ | |
| void skip_indentation(std::true_type /*bulk*/) | |
| { | |
| JSON_ASSERT(!next_unget); | |
| const std::size_t remaining = ia.bulk_remaining(); | |
| if (remaining < 8) | |
| { | |
| return; | |
| } | |
| const char* const data = reinterpret_cast<const char*>(ia.bulk_data()); | |
| std::size_t pos = 0; | |
| for (; pos + 8 <= remaining; pos += 8) | |
| { | |
| // little-endian, so the first byte is the lowest | |
| const std::uint64_t non_space = read_eight_bytes(data + pos) ^ 0x2020202020202020ull; | |
| if (non_space != 0) | |
| { | |
| // skip the spaces before the first other byte of this word | |
| pos += static_cast<std::size_t>(count_trailing_zeros(non_space)) / 8; | |
| break; | |
| } | |
| } | |
| bulk_consume(data, pos); | |
| } | |
| /// streaming input: no bulk fast path | |
| void skip_indentation(std::false_type /*bulk*/) const noexcept {} | |
| token_type scan() | |
| { | |
| // initially, skip the BOM | |
| if (get_chars_read_total() == 0 && !skip_bom()) | |
| { | |
| error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; | |
| return token_type::parse_error; | |
| } | |
| // read the next character and ignore whitespace | |
| skip_whitespace(); | |
| return scan_after_whitespace(); | |
| } | |
| /*! | |
| @brief scan the next token when the caller expects a separator (':' or | |
| ',') most of the time | |
| After an object key the next token is almost always ':', after a value | |
| inside an object or array almost always ','. Testing for that character | |
| first is a compare and a well-predicted branch, where the switch in | |
| scan_after_whitespace() is an indirect jump through a table. Anything else | |
| goes through the switch, so the result is the same as scan()'s. | |
| May only be called after scan() has run once (the BOM check is skipped). | |
| */ | |
| token_type scan_expecting(token_type expected_type) | |
| { | |
| JSON_ASSERT(expected_type == token_type::name_separator || expected_type == token_type::value_separator); | |
| JSON_ASSERT(get_chars_read_total() > 0); | |
| const char_int_type expected_char = static_cast<unsigned char>((expected_type == token_type::name_separator) ? ':' : ','); | |
| skip_whitespace(); | |
| if (JSON_HEDLEY_LIKELY(current == expected_char)) | |
| { | |
| return expected_type; | |
| } | |
| return scan_after_whitespace(); | |
| } | |
| private: | |
| /// the part of scan() after the leading whitespace: skip comments and | |
| /// scan the token that starts with current | |
| token_type scan_after_whitespace() | |
| { | |
| // ignore comments | |
| while (ignore_comments && current == '/') | |
| { | |
| if (!scan_comment()) | |
| { | |
| return token_type::parse_error; | |
| } | |
| // skip following whitespace | |
| skip_whitespace(); | |
| } | |
| switch (current) | |
| { | |
| // structural characters | |
| case '[': | |
| return token_type::begin_array; | |
| case ']': | |
| return token_type::end_array; | |
| case '{': | |
| return token_type::begin_object; | |
| case '}': | |
| return token_type::end_object; | |
| case ':': | |
| return token_type::name_separator; | |
| case ',': | |
| return token_type::value_separator; | |
| // literals | |
| // (the text after the first character; no local arrays, which | |
| // would give this function a stack canary on every token) | |
| case 't': | |
| return scan_literal("rue", token_type::literal_true); | |
| case 'f': | |
| return scan_literal("alse", token_type::literal_false); | |
| case 'n': | |
| return scan_literal("ull", token_type::literal_null); | |
| // string | |
| case '\"': | |
| return scan_string(); | |
| // number | |
| case '-': | |
| case '0': | |
| case '1': | |
| case '2': | |
| case '3': | |
| case '4': | |
| case '5': | |
| case '6': | |
| case '7': | |
| case '8': | |
| case '9': | |
| return scan_number_dispatch(std::integral_constant<bool, bulk_scan> {}); | |
| #if !JSON_STRICT_NUL_HANDLING | |
| case '\0': | |
| #endif | |
| // end of input; by default, a null byte is also treated as end of | |
| // input for backwards compatibility (see JSON_STRICT_NUL_HANDLING | |
| // to opt into rejecting a null byte in the input instead) | |
| case char_traits<char_type>::eof(): | |
| return token_type::end_of_input; | |
| // error | |
| default: | |
| error_message = "invalid literal"; | |
| return token_type::parse_error; | |
| } | |
| } | |
| /// input adapter | |
| InputAdapterType ia; | |
| /// whether comments should be ignored (true) or signaled as errors (false) | |
| const bool ignore_comments = false; | |
| /// the current character | |
| char_int_type current = char_traits<char_type>::eof(); | |
| /// whether the next get() call should just return current | |
| bool next_unget = false; | |
| /// the text of the current float token in the input, not yet copied into | |
| /// token_buffer (see get_string()), or nullptr | |
| const char* pending_number_text = nullptr; | |
| std::size_t pending_number_length = 0; | |
| /// the start position of the current token | |
| position_t position {}; | |
| /// the value chars_read_current_line had when the last newline was read, so | |
| /// that unget() can restore the column instead of leaving it at 0 | |
| std::size_t chars_read_before_newline = 0; | |
| /// raw input token string for error messages; only populated for streaming | |
| /// adapters (seekable adapters reconstruct it lazily via token_string_start) | |
| std::vector<char_type> token_string {}; | |
| /// start offset of the current token within the input, used to reconstruct | |
| /// the last read token on error for seekable adapters (see collect_token_chars) | |
| std::size_t token_string_start = 0; | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| /// start offset of the current token within the input, used to report | |
| /// diagnostic positions (see reset()) | |
| std::size_t token_start_position = 0; | |
| #endif | |
| /// buffer for variable-length tokens (numbers, strings) | |
| string_t token_buffer {}; | |
| /// a description of occurred lexer errors | |
| const char* error_message = ""; | |
| // number values | |
| number_integer_t value_integer = 0; | |
| number_unsigned_t value_unsigned = 0; | |
| number_float_t value_float = 0; | |
| /// the position of the decimal point in token_buffer | |
| std::size_t decimal_point_position = std::string::npos; | |
| /// whether the caller only needs the token types and never looks at the | |
| /// converted numeric values; set only by accept(), which parses through | |
| /// json_sax_acceptor. When set, convert_number() skips converting integer | |
| /// tokens whose digit count guarantees that they fit into 64 bits (see | |
| /// there) | |
| const bool discard_number_values = false; | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/json_custom_base_class.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <type_traits> // conditional, is_same | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| /*! | |
| @brief Default base class of the @ref basic_json class. | |
| So that the correct implementations of the copy / move ctors / assign operators | |
| of @ref basic_json do not require complex case distinctions | |
| (no base class / custom base class used as customization point), | |
| @ref basic_json always has a base class. | |
| By default, this class is used because it is empty and thus has no effect | |
| on the behavior of @ref basic_json. | |
| @note This class intentionally lives in namespace @ref nlohmann rather than | |
| @ref nlohmann::detail. Every @ref basic_json specialization derives from | |
| it (via @ref detail::json_base_class) unless a custom base class is | |
| supplied, which makes its namespace an associated namespace of | |
| @ref basic_json for the purpose of argument-dependent lookup (ADL). If | |
| it lived in `nlohmann::detail`, that namespace - and with it the | |
| library's internal `to_json`/`from_json` overloads - would leak into | |
| ADL for any unqualified `to_json`/`from_json` call a user makes | |
| involving a @ref basic_json argument, silently shadowing the user's own | |
| overloads in some cases. | |
| */ | |
| struct json_default_base {}; | |
| namespace detail | |
| { | |
| template<class T> | |
| using json_base_class = typename std::conditional < | |
| std::is_same<T, void>::value, | |
| ::nlohmann::json_default_base, | |
| T | |
| >::type; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/meta/cpp_future.hpp> | |
| // #include <nlohmann/detail/meta/detected.hpp> | |
| // #include <nlohmann/detail/string_concat.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| /*! | |
| @brief SAX interface | |
| This class describes the SAX interface used by @ref nlohmann::json::sax_parse. | |
| Each function is called in different situations while the input is parsed. The | |
| boolean return value informs the parser whether to continue processing the | |
| input. | |
| */ | |
| template<typename BasicJsonType> | |
| struct json_sax | |
| { | |
| using number_integer_t = typename BasicJsonType::number_integer_t; | |
| using number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
| using number_float_t = typename BasicJsonType::number_float_t; | |
| using string_t = typename BasicJsonType::string_t; | |
| using binary_t = typename BasicJsonType::binary_t; | |
| /*! | |
| @brief a null value was read | |
| @return whether parsing should proceed | |
| */ | |
| virtual bool null() = 0; | |
| /*! | |
| @brief a boolean value was read | |
| @param[in] val boolean value | |
| @return whether parsing should proceed | |
| */ | |
| virtual bool boolean(bool val) = 0; | |
| /*! | |
| @brief an integer number was read | |
| @param[in] val integer value | |
| @return whether parsing should proceed | |
| */ | |
| virtual bool number_integer(number_integer_t val) = 0; | |
| /*! | |
| @brief an unsigned integer number was read | |
| @param[in] val unsigned integer value | |
| @return whether parsing should proceed | |
| */ | |
| virtual bool number_unsigned(number_unsigned_t val) = 0; | |
| /*! | |
| @brief a floating-point number was read | |
| @param[in] val floating-point value | |
| @param[in] s raw token value | |
| @return whether parsing should proceed | |
| */ | |
| virtual bool number_float(number_float_t val, const string_t& s) = 0; | |
| /*! | |
| @brief a string value was read | |
| @param[in] val string value | |
| @return whether parsing should proceed | |
| @note It is safe to move the passed string value. | |
| */ | |
| virtual bool string(string_t& val) = 0; | |
| /*! | |
| @brief a binary value was read | |
| @param[in] val binary value | |
| @return whether parsing should proceed | |
| @note It is safe to move the passed binary value. | |
| */ | |
| virtual bool binary(binary_t& val) = 0; | |
| /*! | |
| @brief the beginning of an object was read | |
| @param[in] elements number of object elements or -1 if unknown | |
| @return whether parsing should proceed | |
| @note binary formats may report the number of elements | |
| */ | |
| virtual bool start_object(std::size_t elements) = 0; | |
| /*! | |
| @brief an object key was read | |
| @param[in] val object key | |
| @return whether parsing should proceed | |
| @note It is safe to move the passed string. | |
| */ | |
| virtual bool key(string_t& val) = 0; | |
| /*! | |
| @brief the end of an object was read | |
| @return whether parsing should proceed | |
| */ | |
| virtual bool end_object() = 0; | |
| /*! | |
| @brief the beginning of an array was read | |
| @param[in] elements number of array elements or -1 if unknown | |
| @return whether parsing should proceed | |
| @note binary formats may report the number of elements | |
| */ | |
| virtual bool start_array(std::size_t elements) = 0; | |
| /*! | |
| @brief the end of an array was read | |
| @return whether parsing should proceed | |
| */ | |
| virtual bool end_array() = 0; | |
| /*! | |
| @brief a parse error occurred | |
| @param[in] position the position in the input where the error occurs | |
| @param[in] last_token the last read token | |
| @param[in] ex an exception object describing the error | |
| @return whether parsing should proceed (must return false) | |
| */ | |
| virtual bool parse_error(std::size_t position, | |
| const std::string& last_token, | |
| const detail::exception& ex) = 0; | |
| json_sax() = default; | |
| json_sax(const json_sax&) = default; | |
| json_sax(json_sax&&) noexcept = default; | |
| json_sax& operator=(const json_sax&) = default; | |
| json_sax& operator=(json_sax&&) noexcept = default; | |
| virtual ~json_sax() = default; | |
| }; | |
| namespace detail | |
| { | |
| constexpr std::size_t unknown_size() | |
| { | |
| return (std::numeric_limits<std::size_t>::max)(); | |
| } | |
| /*! | |
| @brief reserve capacity for @a len elements in array @a arr | |
| Reserving upfront avoids repeated reallocations while the elements are added, | |
| but the reservation is capped so a bogus/hostile length (which is not bounded | |
| by max_size(), unlike e.g. std::vector) cannot trigger an oversized allocation | |
| for a small or truncated input. | |
| The overload below is selected for array types without reserve() (e.g., | |
| std::deque), which are then left untouched. | |
| */ | |
| template<typename ArrayType> | |
| auto reserve_array(ArrayType& arr, std::size_t len, priority_tag<1> /*unused*/) | |
| -> decltype(arr.reserve(len), void()) | |
| { | |
| constexpr std::size_t reserve_cap = 16384; | |
| arr.reserve((std::min)(len, reserve_cap)); | |
| } | |
| template<typename ArrayType> | |
| inline void reserve_array(ArrayType& /*arr*/, std::size_t /*len*/, priority_tag<0> /*unused*/) | |
| {} | |
| /*! | |
| @brief reports an object or array whose announced size exceeds max_size() | |
| Shared by json_sax_dom_parser and json_sax_dom_callback_parser. | |
| @param[in] sax the SAX parser to report the error to | |
| @param[in] len the number of elements announced by the input, or unknown_size() | |
| @param[in] kind "object" or "array" | |
| @param[in] ref the object or array that was just created | |
| @return whether parsing should continue (false after reporting out_of_range.408) | |
| */ | |
| template<typename SAX, typename BasicJsonType> | |
| JSON_HEDLEY_NEVER_INLINE | |
| bool container_too_large_error(SAX& sax, std::size_t len, const char* kind, BasicJsonType* ref) | |
| { | |
| return sax.parse_error(0, "", out_of_range::create(exception_id::container_too_large, concat("excessive ", kind, " size: ", std::to_string(len)), ref)); | |
| } | |
| template<typename SAX, typename BasicJsonType> | |
| bool check_container_size(SAX& sax, std::size_t len, const char* kind, BasicJsonType* ref) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(len != detail::unknown_size() && len > ref->max_size())) | |
| { | |
| return container_too_large_error(sax, len, kind, ref); | |
| } | |
| return true; | |
| } | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| /*! | |
| @brief set the diagnostic positions of a value the DOM SAX parsers just stored | |
| Shared by json_sax_dom_parser and json_sax_dom_callback_parser. basic_json | |
| befriends this struct, as the position members are private. | |
| */ | |
| struct diagnostic_positions | |
| { | |
| /*! | |
| @param[in,out] v the object or array whose opening brace or bracket was just read | |
| @param[in] lexer the lexer that read it, or nullptr to leave @a v alone | |
| */ | |
| template<typename BasicJsonType, typename LexerType> | |
| static void set_container_start(BasicJsonType& v, LexerType* lexer) | |
| { | |
| if (lexer) | |
| { | |
| // Lexer has read the first character of the container, so | |
| // subtract 1 from the position to get the correct start position. | |
| v.start_position = lexer->get_chars_read_total() - 1; | |
| } | |
| } | |
| /*! | |
| @param[in,out] v the object or array whose closing brace or bracket was just read | |
| @param[in] lexer the lexer that read it, or nullptr to leave @a v alone | |
| */ | |
| template<typename BasicJsonType, typename LexerType> | |
| static void set_container_end(BasicJsonType& v, LexerType* lexer) | |
| { | |
| if (lexer) | |
| { | |
| // Lexer's position is past the closing brace or bracket, so set that as the end position. | |
| v.end_position = lexer->get_chars_read_total(); | |
| } | |
| } | |
| /*! | |
| @param[in,out] v the value that was just parsed | |
| @param[in] lexer the lexer that read it, or nullptr to leave @a v alone | |
| */ | |
| template<typename BasicJsonType, typename LexerType> | |
| static void set_from_lexer(BasicJsonType& v, LexerType* lexer) | |
| { | |
| if (lexer) | |
| { | |
| // Lexer has read past the current field value, so set the end position to the current position. | |
| // The start position will be set below based on the length of the string representation | |
| // of the value. | |
| v.end_position = lexer->get_chars_read_total(); | |
| switch (v.type()) | |
| { | |
| case value_t::boolean: | |
| { | |
| // 4 and 5 are the string length of "true" and "false" | |
| v.start_position = v.end_position - (v.m_data.m_value.boolean ? 4 : 5); | |
| break; | |
| } | |
| case value_t::null: | |
| { | |
| // 4 is the string length of "null" | |
| v.start_position = v.end_position - 4; | |
| break; | |
| } | |
| case value_t::string: | |
| { | |
| // escape sequences make the token longer than the value it | |
| // parses to, so the start position cannot be derived from | |
| // the value; use the offset the lexer recorded instead | |
| v.start_position = lexer->get_token_start_position(); | |
| break; | |
| } | |
| case value_t::discarded: | |
| { | |
| // an object or array the callback of | |
| // json_sax_dom_callback_parser rejected has no position | |
| v.end_position = std::string::npos; | |
| v.start_position = v.end_position; | |
| break; | |
| } | |
| case value_t::binary: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| { | |
| v.start_position = v.end_position - lexer->get_string().size(); | |
| break; | |
| } | |
| case value_t::object: | |
| case value_t::array: | |
| { | |
| // object and array are handled in start_object() and start_array() handlers | |
| // skip setting the values here. | |
| break; | |
| } | |
| default: // LCOV_EXCL_LINE | |
| // Handle all possible types discretely, default handler should never be reached. | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE | |
| } | |
| } | |
| } | |
| }; | |
| #endif | |
| /*! | |
| @brief error state shared by the DOM-building SAX parsers | |
| Holds whether a parse error occurred and whether errors are thrown, and | |
| implements the parse_error() and is_errored() members of the SAX interface for | |
| json_sax_dom_parser and json_sax_dom_callback_parser. | |
| */ | |
| class json_sax_dom_error_state | |
| { | |
| public: | |
| explicit json_sax_dom_error_state(const bool allow_exceptions_) noexcept | |
| : allow_exceptions(allow_exceptions_) | |
| {} | |
| // make class move-only | |
| json_sax_dom_error_state(const json_sax_dom_error_state&) = delete; | |
| json_sax_dom_error_state(json_sax_dom_error_state&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) | |
| json_sax_dom_error_state& operator=(const json_sax_dom_error_state&) = delete; | |
| json_sax_dom_error_state& operator=(json_sax_dom_error_state&&) = delete; // the const member prevents assignment | |
| ~json_sax_dom_error_state() = default; | |
| template<class Exception> | |
| bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, | |
| const Exception& ex) | |
| { | |
| errored = true; | |
| static_cast<void>(ex); | |
| if (allow_exceptions) | |
| { | |
| JSON_THROW(ex); | |
| } | |
| return false; | |
| } | |
| bool is_errored() const | |
| { | |
| return errored; | |
| } | |
| private: | |
| /// whether a syntax error occurred | |
| bool errored = false; | |
| /// whether to throw exceptions in case of errors | |
| const bool allow_exceptions = true; | |
| }; | |
| /*! | |
| @brief a hash table that finds the position of a key in an object whose | |
| elements are kept in a vector (ordered_map) | |
| The elements stay where they are: the table only holds their hashes and | |
| positions, and the caller compares the keys. | |
| */ | |
| class object_key_index | |
| { | |
| public: | |
| static constexpr std::size_t npos = static_cast<std::size_t>(-1); | |
| /// @param[in] element_hashes the hashes of the keys of the elements that are there already | |
| explicit object_key_index(std::vector<std::size_t>&& element_hashes) | |
| : hashes(std::move(element_hashes)) | |
| { | |
| std::size_t size = 256; | |
| while (size < 4 * hashes.size()) | |
| { | |
| size *= 2; | |
| } | |
| rebuild(size); | |
| } | |
| /// @return the position of the element with @a hash for which @a matches(position) holds, or npos | |
| template<typename Matches> | |
| std::size_t find(const std::size_t hash, Matches matches) const | |
| { | |
| for (std::size_t slot = hash & mask;; slot = (slot + 1) & mask) | |
| { | |
| const std::size_t entry = table[slot]; | |
| if (entry == 0) | |
| { | |
| return npos; | |
| } | |
| if (hashes[entry - 1] == hash && matches(entry - 1)) | |
| { | |
| return entry - 1; | |
| } | |
| } | |
| } | |
| /// add the next element, whose position is the number of elements so far | |
| void add(const std::size_t hash) | |
| { | |
| hashes.push_back(hash); | |
| if (hashes.size() * 2 > table.size()) | |
| { | |
| rebuild(table.size() * 2); | |
| } | |
| else | |
| { | |
| place(hash, hashes.size()); | |
| } | |
| } | |
| private: | |
| void rebuild(const std::size_t size) | |
| { | |
| table.assign(size, 0); | |
| mask = size - 1; | |
| for (std::size_t i = 0; i < hashes.size(); ++i) | |
| { | |
| place(hashes[i], i + 1); | |
| } | |
| } | |
| void place(const std::size_t hash, const std::size_t entry) | |
| { | |
| std::size_t slot = hash & mask; | |
| while (table[slot] != 0) | |
| { | |
| slot = (slot + 1) & mask; | |
| } | |
| table[slot] = entry; | |
| } | |
| /// the hash of each element, by position | |
| std::vector<std::size_t> hashes; | |
| /// open addressing, a power of two in size: position + 1 of an element, or 0 for a free slot | |
| std::vector<std::size_t> table {}; // NOLINT(readability-redundant-member-init) | |
| std::size_t mask = 0; | |
| }; | |
| /*! | |
| @brief SAX implementation to create a JSON value from SAX events | |
| This class implements the @ref json_sax interface and processes the SAX events | |
| to create a JSON value which makes it basically a DOM parser. The structure or | |
| hierarchy of the JSON value is managed by the stack `frames` which contains | |
| an entry for each open array or object. The parser of the text formats, for | |
| which the size of a container is not known up front, collects the elements of | |
| an array and the members of an `ordered_json` object on a stack and moves them | |
| into a container of the exact size (with @a Collect, as basic_json's own parse | |
| functions use it); the binary readers use the plain | |
| @ref json_sax_dom_binary_parser instead. | |
| After successful parsing, the value that is passed by reference to the | |
| constructor contains the parsed value. Without @a Collect, every value is | |
| stored in place as it arrives, so after a parse error the value holds what was | |
| read up to it. | |
| @tparam BasicJsonType the JSON type | |
| @tparam Collect whether to collect the values of containers of unknown size on | |
| a stack (only for a caller that does not use the value after a | |
| parse error) | |
| */ | |
| template<typename BasicJsonType, typename InputAdapterType, bool Collect = false> | |
| class json_sax_dom_parser : public json_sax_dom_error_state | |
| { | |
| public: | |
| using number_integer_t = typename BasicJsonType::number_integer_t; | |
| using number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
| using number_float_t = typename BasicJsonType::number_float_t; | |
| using string_t = typename BasicJsonType::string_t; | |
| using binary_t = typename BasicJsonType::binary_t; | |
| using lexer_t = lexer<BasicJsonType, InputAdapterType>; | |
| /*! | |
| @param[in,out] r reference to a JSON value that is manipulated while | |
| parsing | |
| @param[in] allow_exceptions_ whether parse errors yield exceptions | |
| */ | |
| explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true, lexer_t* lexer_ = nullptr) | |
| : json_sax_dom_error_state(allow_exceptions_), root(r), m_lexer_ref(lexer_) | |
| {} | |
| // make class move-only | |
| json_sax_dom_parser(const json_sax_dom_parser&) = delete; | |
| json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) | |
| json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete; | |
| json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) | |
| ~json_sax_dom_parser() = default; | |
| bool null() | |
| { | |
| handle_value(nullptr); | |
| return true; | |
| } | |
| bool boolean(bool val) | |
| { | |
| handle_value(val); | |
| return true; | |
| } | |
| bool number_integer(number_integer_t val) | |
| { | |
| handle_value(val); | |
| return true; | |
| } | |
| bool number_unsigned(number_unsigned_t val) | |
| { | |
| handle_value(val); | |
| return true; | |
| } | |
| bool number_float(number_float_t val, const string_t& /*unused*/) | |
| { | |
| handle_value(val); | |
| return true; | |
| } | |
| bool string(string_t& val) | |
| { | |
| // json_sax documents that the passed value may be moved from, | |
| // so hand the buffer over instead of copying it | |
| handle_value(std::move(val)); | |
| return true; | |
| } | |
| bool binary(binary_t& val) | |
| { | |
| // json_sax documents that the passed value may be moved from, | |
| // so hand the buffer over instead of copying it | |
| handle_value(std::move(val)); | |
| return true; | |
| } | |
| bool start_object(std::size_t len) | |
| { | |
| #if JSON_DIAGNOSTICS || JSON_DIAGNOSTIC_POSITIONS | |
| // the values need their final place from the start (their parent | |
| // pointers and positions refer to it), so no buffering | |
| return start_stored_object(len); | |
| #else | |
| return start_object(len, std::integral_constant<bool, indexed_keys> {}); | |
| #endif | |
| } | |
| bool key(string_t& val) | |
| { | |
| JSON_ASSERT(!frames.empty()); | |
| return key(val, std::integral_constant<bool, indexed_keys> {}); | |
| } | |
| bool end_object() | |
| { | |
| JSON_ASSERT(!frames.empty()); | |
| return end_object(std::integral_constant<bool, indexed_keys> {}); | |
| } | |
| bool start_array(std::size_t len) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(len != detail::unknown_size() && len > array_t().max_size())) | |
| { | |
| // the array does not exist yet: report with an empty one | |
| BasicJsonType too_large(BasicJsonType::value_t::array); | |
| return container_too_large_error(*this, len, "array", &too_large); | |
| } | |
| #if JSON_DIAGNOSTICS || JSON_DIAGNOSTIC_POSITIONS | |
| // the values need their final place from the start (their parent | |
| // pointers and positions refer to it), so no buffering | |
| start_stored_array(len); | |
| #else | |
| if (!collects(len)) | |
| { | |
| // the number of elements is known (or the elements must be in | |
| // place as they arrive): store them directly | |
| start_stored_array(len); | |
| } | |
| else | |
| { | |
| // the number of elements is not known, so growing the array | |
| // would reallocate it (and, being a vector, move its elements) | |
| // again and again. Collect the elements on a stack shared by all | |
| // arrays instead, and copy them to an array of the exact size | |
| // when the closing bracket arrives. | |
| BasicJsonType* slot = nullptr; | |
| std::size_t dest_member = 0; | |
| container_destination(slot, dest_member); | |
| reserve_elements(); | |
| frames.push_back(frame{nullptr, nullptr, slot, elements.size(), ordered_state(dest_member, false)}); | |
| in_object = false; | |
| stored_array = nullptr; | |
| } | |
| #endif | |
| return true; | |
| } | |
| bool end_array() | |
| { | |
| JSON_ASSERT(!frames.empty()); | |
| JSON_ASSERT(frames.back().object == nullptr); | |
| const frame f = frames.back(); | |
| frames.pop_back(); | |
| reenter_enclosing_container(); | |
| if (f.array == nullptr) | |
| { | |
| // the elements are the top of the shared elements stack, from | |
| // f.start on (the elements below belong to enclosing arrays that | |
| // are still open): move them into the array and pop them | |
| const auto first = elements.begin() + static_cast<std::ptrdiff_t>(f.start); | |
| auto* const arr = BasicJsonType::template create<array_t>(std::make_move_iterator(first), std::make_move_iterator(elements.end())); | |
| BasicJsonType value; | |
| value.m_data.m_value.array = arr; | |
| value.m_data.m_type = BasicJsonType::value_t::array; | |
| elements.erase(first, elements.end()); | |
| place_container(f, frames.empty() ? nullptr : &frames.back(), std::move(value), true); | |
| return true; | |
| } | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| diagnostic_positions::set_container_end(*f.slot, m_lexer_ref); | |
| #endif | |
| #if JSON_DIAGNOSTICS | |
| f.slot->set_parents(); | |
| #endif | |
| return true; | |
| } | |
| private: | |
| using object_t = typename BasicJsonType::object_t; | |
| using array_t = typename BasicJsonType::array_t; | |
| /// whether objects keep their elements in a vector and a key can be hashed, | |
| /// so that a big object can find the keys it has in a hash table instead of | |
| /// searching all of them | |
| template<typename ObjectType, typename StringType> | |
| using detect_emplace_new_key = decltype(std::declval<ObjectType&>().emplace_new_key(std::declval<const StringType&>(), std::declval<typename ObjectType::mapped_type>())); | |
| template<typename StringType> | |
| using detect_hash = decltype(std::hash<StringType>()(std::declval<const StringType&>())); | |
| // std::hash is only named once the object can hold the keys in a vector: | |
| // VS 2015 static-asserts on std::hash of a type without one instead of | |
| // reporting a substitution failure | |
| template<typename ObjectType, typename StringType, bool = is_detected<detect_emplace_new_key, ObjectType, StringType>::value> | |
| struct detect_indexable_keys : std::false_type {}; | |
| template<typename ObjectType, typename StringType> | |
| struct detect_indexable_keys<ObjectType, StringType, true> : is_detected<detect_hash, StringType> {}; | |
| static constexpr bool indexed_keys = detect_indexable_keys<object_t, string_t>::value; | |
| /// what a frame holds for objects that are kept in a vector: the key index | |
| /// of an object with many keys, and for an object that is collected on the | |
| /// stack the member of the enclosing object it will become | |
| struct ordered_frame | |
| { | |
| /// the entry of key_indexes of an object that has one, else nullptr | |
| object_key_index* index; | |
| /// object or array without a slot in an object collected on the stack: | |
| /// the index of the member in `members` it goes to | |
| std::size_t dest_member; | |
| /// whether this is an object collected on the stack | |
| bool buffered; | |
| }; | |
| struct no_ordered_frame {}; | |
| using ordered_frame_state = typename std::conditional<indexed_keys, ordered_frame, no_ordered_frame>::type; | |
| static ordered_frame make_ordered_state(const std::size_t dest_member, const bool buffered, std::true_type /*indexed*/) noexcept | |
| { | |
| ordered_frame state = {nullptr, dest_member, buffered}; | |
| return state; | |
| } | |
| static no_ordered_frame make_ordered_state(const std::size_t /*dest_member*/, const bool /*buffered*/, std::false_type /*indexed*/) noexcept | |
| { | |
| return no_ordered_frame(); | |
| } | |
| static ordered_frame_state ordered_state(const std::size_t dest_member, const bool buffered) noexcept | |
| { | |
| return make_ordered_state(dest_member, buffered, std::integral_constant<bool, indexed_keys> {}); | |
| } | |
| /// an array or object that is being read | |
| struct frame | |
| { | |
| /// the object, or nullptr for an array | |
| object_t* object; | |
| /// the array if its elements are stored in it as they arrive, or | |
| /// nullptr for an array and an object | |
| array_t* array; | |
| /// array without `array`: where the finished array goes (nullptr: it | |
| /// is an element of the enclosing array); otherwise: the value that | |
| /// holds the object or array | |
| BasicJsonType* slot; | |
| /// array without `array`: the index of its first element in `elements` | |
| std::size_t start; | |
| /// what objects in a vector add (see ordered_frame) | |
| ordered_frame_state ordered; | |
| }; | |
| /// the open arrays and objects; the first few live in the object itself, so | |
| /// that the common documents do not allocate for them | |
| class frame_stack | |
| { | |
| public: | |
| frame_stack() noexcept | |
| : local() // NOLINT(readability-redundant-member-init) | |
| {} | |
| frame_stack(const frame_stack&) = delete; | |
| frame_stack& operator=(const frame_stack&) = delete; | |
| frame_stack(frame_stack&& other) noexcept | |
| : local() // NOLINT(readability-redundant-member-init) | |
| { | |
| take(other); | |
| } | |
| frame_stack& operator=(frame_stack&& other) noexcept | |
| { | |
| if (this != &other) | |
| { | |
| release(); | |
| take(other); | |
| } | |
| return *this; | |
| } | |
| ~frame_stack() = default; | |
| bool empty() const noexcept | |
| { | |
| return count == 0; | |
| } | |
| std::size_t size() const noexcept | |
| { | |
| return count; | |
| } | |
| frame& back() noexcept | |
| { | |
| return data[count - 1]; | |
| } | |
| frame& operator[](const std::size_t i) noexcept | |
| { | |
| return data[i]; | |
| } | |
| void push_back(const frame& f) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(count == capacity)) | |
| { | |
| grow(); | |
| } | |
| data[count++] = f; | |
| } | |
| void pop_back() noexcept | |
| { | |
| JSON_ASSERT(count > 0); | |
| --count; | |
| } | |
| private: | |
| JSON_HEDLEY_NEVER_INLINE | |
| void grow() | |
| { | |
| const std::size_t new_capacity = capacity * 2; | |
| std::unique_ptr<frame[]> new_heap(new frame[new_capacity]); // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| for (std::size_t i = 0; i < count; ++i) | |
| { | |
| new_heap[i] = data[i]; | |
| } | |
| heap = std::move(new_heap); | |
| data = heap.get(); | |
| capacity = new_capacity; | |
| } | |
| void release() noexcept | |
| { | |
| heap.reset(); | |
| data = local.data(); | |
| capacity = local_capacity; | |
| } | |
| /// make the contents of @a other our own | |
| void take(frame_stack& other) noexcept | |
| { | |
| if (other.heap == nullptr) | |
| { | |
| for (std::size_t i = 0; i < other.count; ++i) | |
| { | |
| local[i] = other.local[i]; | |
| } | |
| data = local.data(); | |
| capacity = local_capacity; | |
| } | |
| else | |
| { | |
| heap = std::move(other.heap); | |
| data = heap.get(); | |
| capacity = other.capacity; | |
| other.data = other.local.data(); | |
| other.capacity = local_capacity; | |
| } | |
| count = other.count; | |
| other.count = 0; | |
| } | |
| static constexpr std::size_t local_capacity = 8; | |
| /// the first frames, left uninitialized: a frame is written before it is | |
| /// read (the user-provided constructor keeps the member initialization, | |
| /// which -Weffc++ asks for, from zeroing them) | |
| struct local_frames : std::array<frame, local_capacity> | |
| { | |
| local_frames() noexcept {} // NOLINT(modernize-use-equals-default,hicpp-use-equals-default,cppcoreguidelines-pro-type-member-init,hicpp-member-init): see above | |
| }; | |
| local_frames local; | |
| /// the frames once there are more than local_capacity of them | |
| std::unique_ptr<frame[]> heap {}; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays,readability-redundant-member-init) | |
| frame* data = local.data(); | |
| std::size_t count = 0; | |
| std::size_t capacity = local_capacity; | |
| }; | |
| void release_key_index(const frame& f, std::true_type /*indexed*/) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(f.ordered.index != nullptr)) | |
| { | |
| ordered_data.key_indexes.pop_back(); | |
| } | |
| } | |
| static void release_key_index(const frame& /*f*/, std::false_type /*indexed*/) noexcept {} | |
| /// the number of keys from which an object looks them up in a hash table | |
| static constexpr std::size_t key_index_threshold = 64; | |
| /// add @a key to the object of @a f (or find it, if it is there), searching it in std::map | |
| static BasicJsonType* insert_key(frame& f, string_t&& key, std::false_type /*indexed*/) | |
| { | |
| return &f.object->operator[](std::move(key)); | |
| } | |
| /// add @a key to the object of @a f (or find it, if it is there), searching it in a vector | |
| BasicJsonType* insert_key(frame& f, string_t&& key, std::true_type /*indexed*/) | |
| { | |
| object_t& obj = *f.object; | |
| if (JSON_HEDLEY_LIKELY(obj.size() < key_index_threshold)) | |
| { | |
| return &obj[std::move(key)]; | |
| } | |
| return insert_key_with_index(f, std::move(key)); | |
| } | |
| /// add @a key to the big object of @a f (or find it, if it is there), using its key index | |
| JSON_HEDLEY_NEVER_INLINE | |
| BasicJsonType* insert_key_with_index(frame& f, string_t&& key) | |
| { | |
| object_t& obj = *f.object; | |
| const std::hash<string_t> hasher {}; | |
| const std::size_t hash = hasher(key); | |
| if (JSON_HEDLEY_UNLIKELY(f.ordered.index == nullptr)) | |
| { | |
| std::vector<std::size_t> hashes; | |
| hashes.reserve(obj.size()); | |
| for (const auto& element : obj) | |
| { | |
| hashes.push_back(hasher(element.first)); | |
| } | |
| ordered_data.key_indexes.emplace_back(new object_key_index(std::move(hashes))); | |
| f.ordered.index = ordered_data.key_indexes.back().get(); | |
| } | |
| const std::size_t position = f.ordered.index->find(hash, [&obj, &key](std::size_t i) | |
| { | |
| return (obj.begin() + static_cast<std::ptrdiff_t>(i))->first == key; | |
| }); | |
| if (position != object_key_index::npos) | |
| { | |
| return &(obj.begin() + static_cast<std::ptrdiff_t>(position))->second; | |
| } | |
| obj.emplace_new_key(key, BasicJsonType()); | |
| f.ordered.index->add(hash); | |
| return &obj.back().second; | |
| } | |
| /// where an array or object that starts now will go when it is finished: | |
| /// @a slot is the value to assign it to (the root or a member of an object | |
| /// that is stored directly), or nullptr if it is an element of the | |
| /// enclosing array or a member of the enclosing object that is collected on | |
| /// the stack, in which case @a dest_member is the member | |
| void container_destination(BasicJsonType*& slot, std::size_t& dest_member) | |
| { | |
| if (frames.empty()) | |
| { | |
| slot = &root; | |
| } | |
| else if (frames.back().object != nullptr) | |
| { | |
| slot = object_element; | |
| } | |
| else | |
| { | |
| collected_object_member(frames.back(), dest_member, std::integral_constant<bool, indexed_keys> {}); | |
| } | |
| } | |
| void collected_object_member(const frame& enclosing, std::size_t& dest_member, std::true_type /*indexed*/) const noexcept | |
| { | |
| if (enclosing.ordered.buffered) | |
| { | |
| dest_member = ordered_data.member_index; | |
| } | |
| } | |
| static void collected_object_member(const frame& /*enclosing*/, std::size_t& /*dest_member*/, std::false_type /*indexed*/) noexcept {} | |
| static bool is_collected_object(const frame& f, std::true_type /*indexed*/) noexcept | |
| { | |
| return f.ordered.buffered; | |
| } | |
| static bool is_collected_object(const frame& /*f*/, std::false_type /*indexed*/) noexcept | |
| { | |
| return false; | |
| } | |
| /// put a finished array or object that was collected on the stack, or | |
| /// that outgrew it, where it belongs; @a enclosing is the container it is in. | |
| /// @a enclosing_is_innermost tells whether that is the container that gets | |
| /// the next value, so that it can be switched to storing its elements | |
| /// directly if the value was the one too many. | |
| void place_container(const frame& f, frame* enclosing, BasicJsonType&& value, const bool enclosing_is_innermost) | |
| { | |
| // only a container with a slot may have no enclosing container | |
| JSON_ASSERT(f.slot != nullptr || enclosing != nullptr); | |
| if (f.slot != nullptr) | |
| { | |
| *f.slot = std::move(value); | |
| } | |
| else if (is_collected_object(*enclosing, std::integral_constant<bool, indexed_keys> {})) | |
| { | |
| place_member(f, std::move(value), std::integral_constant<bool, indexed_keys> {}); | |
| } | |
| else if (enclosing->array != nullptr) | |
| { | |
| enclosing->array->emplace_back(std::move(value)); | |
| } | |
| else | |
| { | |
| elements.emplace_back(std::move(value)); | |
| if (JSON_HEDLEY_UNLIKELY(enclosing_is_innermost && elements.size() - enclosing->start > buffer_limit)) | |
| { | |
| spill(*enclosing); | |
| } | |
| } | |
| } | |
| void place_member(const frame& f, BasicJsonType&& value, std::true_type /*indexed*/) | |
| { | |
| ordered_data.members[f.ordered.dest_member].second = std::move(value); | |
| } | |
| static void place_member(const frame& /*f*/, BasicJsonType&& /*value*/, std::false_type /*indexed*/) noexcept {} | |
| /// store the members of a new object directly in it | |
| bool start_stored_object(std::size_t len) | |
| { | |
| BasicJsonType* const ref = store(BasicJsonType::value_t::object); | |
| frames.push_back(frame{ref->m_data.m_value.object, nullptr, ref, 0, ordered_state(0, false)}); | |
| in_object = true; | |
| stored_array = nullptr; | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| // Ensure this is after the call to store to ensure correct start position. | |
| diagnostic_positions::set_container_start(*ref, m_lexer_ref); | |
| #endif | |
| return check_container_size(*this, len, "object", ref); | |
| } | |
| /// objects in std::map and the like have no use for collecting their members | |
| bool start_object(std::size_t len, std::false_type /*indexed*/) | |
| { | |
| return start_stored_object(len); | |
| } | |
| /// An object in a vector of members adds a member by appending it to the | |
| /// vector, which grows it again and again (and copies the keys each time). | |
| /// Collect the members of an object of unknown size on a stack shared by | |
| /// all open objects instead, and move them into a vector of the exact size | |
| /// when the closing brace arrives. | |
| bool start_object(std::size_t len, std::true_type /*indexed*/) | |
| { | |
| if (!collects(len)) | |
| { | |
| return start_stored_object(len); | |
| } | |
| BasicJsonType* slot = nullptr; | |
| std::size_t dest_member = 0; | |
| container_destination(slot, dest_member); | |
| frames.push_back(frame{nullptr, nullptr, slot, ordered_data.members.size(), ordered_state(dest_member, true)}); | |
| in_object = false; | |
| stored_array = nullptr; | |
| return true; | |
| } | |
| bool key(string_t& val, std::false_type /*indexed*/) | |
| { | |
| JSON_ASSERT(frames.back().object != nullptr); | |
| // add null at the given key and store the reference for later; the | |
| // key is moved, as the lexer starts the next token with reset() | |
| object_element = insert_key(frames.back(), std::move(val), std::false_type {}); | |
| return true; | |
| } | |
| bool key(string_t& val, std::true_type /*indexed*/) | |
| { | |
| frame& f = frames.back(); | |
| if (JSON_HEDLEY_UNLIKELY(f.object == nullptr)) | |
| { | |
| JSON_ASSERT(f.ordered.buffered); | |
| if (collect_member(f, val)) | |
| { | |
| return true; | |
| } | |
| // the object has grown big: it is stored directly from here on | |
| } | |
| object_element = insert_key(f, std::move(val), std::true_type {}); | |
| return true; | |
| } | |
| /*! | |
| @brief add a member to the object that is collected on the stack, or find the one with the key | |
| @return false if the object has collected enough members to be stored | |
| directly, which is done and which leaves the key to be inserted | |
| */ | |
| bool collect_member(frame& f, string_t& key) | |
| { | |
| for (std::size_t i = f.start; i < ordered_data.members.size(); ++i) | |
| { | |
| if (ordered_data.members[i].first == key) | |
| { | |
| ordered_data.member_index = i; | |
| return true; | |
| } | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(ordered_data.members.size() - f.start >= object_buffer_limit)) | |
| { | |
| spill_object(f); | |
| return false; | |
| } | |
| reserve_members(); | |
| ordered_data.members.emplace_back(std::move(key), BasicJsonType()); | |
| ordered_data.member_index = ordered_data.members.size() - 1; | |
| return true; | |
| } | |
| /// the members of an object that is collected on the stack as an object; | |
| /// they are the top of the shared member stack, from f.start on (the | |
| /// members below belong to enclosing objects that are still open) | |
| object_t* members_to_object(const frame& f, BasicJsonType& value) | |
| { | |
| const auto first = ordered_data.members.begin() + static_cast<std::ptrdiff_t>(f.start); | |
| auto* const obj = BasicJsonType::template create<object_t>(std::make_move_iterator(first), std::make_move_iterator(ordered_data.members.end())); | |
| value.m_data.m_value.object = obj; | |
| value.m_data.m_type = BasicJsonType::value_t::object; | |
| ordered_data.members.erase(first, ordered_data.members.end()); | |
| return obj; | |
| } | |
| /// switch an object that collects its members on the stack to storing them directly | |
| JSON_HEDLEY_NEVER_INLINE | |
| void spill_object(frame& f) | |
| { | |
| BasicJsonType value; | |
| f.object = members_to_object(f, value); | |
| f.ordered.buffered = false; | |
| in_object = true; | |
| // false positive: an object without an enclosing container is the root, | |
| // which has a slot, so place_container() does not use the nullptr | |
| // @infer-ignore NULLPTR_DEREFERENCE | |
| place_container(f, frames.size() >= 2 ? &frames[frames.size() - 2] : nullptr, std::move(value), false); | |
| } | |
| bool end_object(std::false_type /*indexed*/) | |
| { | |
| return end_stored_object(); | |
| } | |
| bool end_object(std::true_type /*indexed*/) | |
| { | |
| if (JSON_HEDLEY_LIKELY(frames.back().object != nullptr)) | |
| { | |
| return end_stored_object(); | |
| } | |
| // the members are on the stack: make them the object | |
| const frame f = frames.back(); | |
| frames.pop_back(); | |
| reenter_enclosing_container(); | |
| BasicJsonType value; | |
| members_to_object(f, value); | |
| place_container(f, frames.empty() ? nullptr : &frames.back(), std::move(value), true); | |
| return true; | |
| } | |
| bool end_stored_object() | |
| { | |
| JSON_ASSERT(frames.back().object != nullptr); | |
| #if JSON_DIAGNOSTICS || JSON_DIAGNOSTIC_POSITIONS | |
| // objects are never collected, so their value is where it was stored | |
| BasicJsonType* const ref = frames.back().slot; | |
| #endif | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| diagnostic_positions::set_container_end(*ref, m_lexer_ref); | |
| #endif | |
| #if JSON_DIAGNOSTICS | |
| ref->set_parents(); | |
| #endif | |
| release_key_index(frames.back(), std::integral_constant<bool, indexed_keys> {}); | |
| frames.pop_back(); | |
| reenter_enclosing_container(); | |
| return true; | |
| } | |
| /// the number of members an object collects on the stack before it | |
| /// switches to storing them directly | |
| static constexpr std::size_t object_buffer_limit = 32; | |
| void reserve_members() | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(ordered_data.members.capacity() == 0)) | |
| { | |
| ordered_data.members.reserve(16); | |
| } | |
| } | |
| /// the number of elements an array collects on the stack before it | |
| /// switches to storing them directly, so that it does not hold up the | |
| /// stack with its elements (and move all of them in the end) | |
| static constexpr std::size_t buffer_limit = 16; | |
| void reserve_elements() | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(elements.capacity() == 0)) | |
| { | |
| elements.reserve(32); | |
| } | |
| } | |
| /// store the elements of a new array directly in it | |
| void start_stored_array(const std::size_t len) | |
| { | |
| BasicJsonType* const ref = store(BasicJsonType::value_t::array); | |
| frames.push_back(frame{nullptr, ref->m_data.m_value.array, ref, 0, ordered_state(0, false)}); | |
| in_object = false; | |
| stored_array = ref->m_data.m_value.array; | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| // Ensure this is after the call to store to ensure correct start position. | |
| diagnostic_positions::set_container_start(*ref, m_lexer_ref); | |
| #endif | |
| if (len != detail::unknown_size()) | |
| { | |
| reserve_array(*ref->m_data.m_value.array, len, priority_tag<1> {}); | |
| } | |
| } | |
| /*! | |
| @brief store a value as the next element of the open array or object (or | |
| as the root) | |
| @return the stored value | |
| */ | |
| template<typename Value> | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| BasicJsonType* store(Value&& v) | |
| { | |
| if (stored_array != nullptr) | |
| { | |
| stored_array->emplace_back(std::forward<Value>(v)); | |
| return &stored_array->back(); | |
| } | |
| if (in_object) | |
| { | |
| JSON_ASSERT(object_element); | |
| set_member(*object_element, std::forward<Value>(v), std::is_same<typename BasicJsonType::json_base_class_t, json_default_base> {}); | |
| return object_element; | |
| } | |
| return store_collected(std::forward<Value>(v), std::integral_constant<bool, indexed_keys> {}); | |
| } | |
| /// store a value that is the root, an element of an array that is collected | |
| /// on the stack, or (in a vector) a member of an object that is | |
| template<typename Value> | |
| BasicJsonType* store_collected(Value&& v, std::true_type /*indexed*/) | |
| { | |
| if (!frames.empty() && frames.back().ordered.buffered) | |
| { | |
| BasicJsonType& member = ordered_data.members[ordered_data.member_index].second; | |
| set_member(member, std::forward<Value>(v), std::is_same<typename BasicJsonType::json_base_class_t, json_default_base> {}); | |
| return &member; | |
| } | |
| return store_collected(std::forward<Value>(v), std::false_type {}); | |
| } | |
| template<typename Value> | |
| BasicJsonType* store_collected(Value&& v, std::false_type /*indexed*/) | |
| { | |
| if (frames.empty()) | |
| { | |
| root = BasicJsonType(std::forward<Value>(v)); | |
| return &root; | |
| } | |
| frame& f = frames.back(); | |
| elements.emplace_back(std::forward<Value>(v)); | |
| if (JSON_HEDLEY_UNLIKELY(elements.size() - f.start > buffer_limit)) | |
| { | |
| return spill(f); | |
| } | |
| return &elements.back(); | |
| } | |
| /*! | |
| @brief switch an array that collects its elements on the stack to storing | |
| them directly | |
| @return the last element of the array | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| BasicJsonType* spill(frame& f) | |
| { | |
| JSON_ASSERT(f.array == nullptr); | |
| const auto first = elements.begin() + static_cast<std::ptrdiff_t>(f.start); | |
| BasicJsonType value(BasicJsonType::value_t::array); | |
| array_t& arr = *value.m_data.m_value.array; | |
| // the capacity a vector that grew by itself has with this many elements | |
| reserve_array(arr, 2 * buffer_limit, priority_tag<1> {}); | |
| arr.insert(arr.end(), std::make_move_iterator(first), std::make_move_iterator(elements.end())); | |
| elements.erase(first, elements.end()); | |
| f.array = &arr; | |
| stored_array = &arr; | |
| // the array takes the place its first element had on the stack | |
| place_container(f, frames.size() >= 2 ? &frames[frames.size() - 2] : nullptr, std::move(value), false); | |
| return &arr.back(); | |
| } | |
| /// set the value of the member key() just added | |
| template<typename Value> | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| static void set_member(BasicJsonType& member, Value&& v, std::true_type /*default base*/) | |
| { | |
| if (JSON_HEDLEY_LIKELY(member.is_null())) | |
| { | |
| // a new member is null and holds nothing: construct the value | |
| // over it instead of destroying and swapping | |
| ::new (static_cast<void*>(&member)) BasicJsonType(std::forward<Value>(v)); | |
| } | |
| else | |
| { | |
| // the key occurred before | |
| member = BasicJsonType(std::forward<Value>(v)); | |
| } | |
| } | |
| /// a custom base class may care about the lifetime of the value | |
| template<typename Value> | |
| static void set_member(BasicJsonType& member, Value&& v, std::false_type /*custom base*/) | |
| { | |
| member = BasicJsonType(std::forward<Value>(v)); | |
| } | |
| /// whether the values of a container of @a len elements are collected on the stack | |
| static bool collects(const std::size_t len) noexcept | |
| { | |
| return collects(len, std::integral_constant<bool, Collect> {}); | |
| } | |
| static bool collects(const std::size_t len, std::true_type /*collect*/) noexcept | |
| { | |
| return len == detail::unknown_size(); | |
| } | |
| static bool collects(const std::size_t /*len*/, std::false_type /*collect*/) noexcept | |
| { | |
| return false; | |
| } | |
| /// after a container was closed: the one it was in is the one that gets the next value | |
| void reenter_enclosing_container() | |
| { | |
| if (frames.empty()) | |
| { | |
| in_object = false; | |
| stored_array = nullptr; | |
| } | |
| else | |
| { | |
| const frame& f = frames.back(); | |
| in_object = f.object != nullptr; | |
| stored_array = f.array; | |
| } | |
| } | |
| template<typename Value> | |
| void handle_value(Value&& v) | |
| { | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| BasicJsonType* const stored = store(std::forward<Value>(v)); | |
| diagnostic_positions::set_from_lexer(*stored, m_lexer_ref); | |
| #else | |
| store(std::forward<Value>(v)); | |
| #endif | |
| } | |
| /// the parsed JSON value | |
| BasicJsonType& root; | |
| /// the open arrays and objects | |
| frame_stack frames {}; | |
| /// the elements of the open arrays that are not stored in them yet | |
| std::vector<BasicJsonType> elements {}; | |
| /// what objects in a vector need besides the frames (std::map based objects | |
| /// need nothing, so they do not carry it) | |
| struct ordered_data_t | |
| { | |
| /// the members of the open objects in a vector that are not stored in them yet | |
| std::vector<std::pair<string_t, BasicJsonType>> members {}; | |
| /// the member of the innermost such object that key() added or found last | |
| std::size_t member_index = 0; | |
| /// the key indexes of the open objects that have one, innermost last | |
| std::vector<std::unique_ptr<object_key_index>> key_indexes {}; // NOLINT(readability-redundant-member-init) | |
| }; | |
| struct no_ordered_data_t {}; | |
| typename std::conditional<indexed_keys, ordered_data_t, no_ordered_data_t>::type ordered_data {}; | |
| /// helper to hold the reference for the next object element | |
| BasicJsonType* object_element = nullptr; | |
| /// whether the innermost container is an object (frames.back().object) | |
| bool in_object = false; | |
| /// the array that stores the elements of the innermost array as they | |
| /// arrive (frames.back().array), or nullptr | |
| array_t* stored_array = nullptr; | |
| /// the lexer reference to obtain the current position | |
| lexer_t* m_lexer_ref = nullptr; | |
| }; | |
| /*! | |
| @brief SAX implementation to create a JSON value from the events of a binary reader | |
| The DOM parser of the text formats (json_sax_dom_parser) collects the elements | |
| of arrays and the members of objects on a stack and builds them in one | |
| exact-size allocation, which pays off because a text parser does not know the | |
| number of elements up front. Binary formats announce the size of their | |
| containers (CBOR, MessagePack, BSON and BON8 do, and so do the optimized | |
| containers of UBJSON and BJData), so they store each value directly in its | |
| container, and the bookkeeping of the collecting parser would be pure | |
| overhead for them. This is the plain parser: the structure or hierarchy of the | |
| JSON value is managed by the stack `ref_stack` which contains a pointer to the | |
| respective array or object for each recursion depth. | |
| After successful parsing, the value that is passed by reference to the | |
| constructor contains the parsed value. | |
| @tparam BasicJsonType the JSON type | |
| */ | |
| template<typename BasicJsonType, typename InputAdapterType> | |
| class json_sax_dom_binary_parser : public json_sax_dom_error_state | |
| { | |
| public: | |
| using number_integer_t = typename BasicJsonType::number_integer_t; | |
| using number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
| using number_float_t = typename BasicJsonType::number_float_t; | |
| using string_t = typename BasicJsonType::string_t; | |
| using binary_t = typename BasicJsonType::binary_t; | |
| using lexer_t = lexer<BasicJsonType, InputAdapterType>; | |
| /*! | |
| @param[in,out] r reference to a JSON value that is manipulated while | |
| parsing | |
| @param[in] allow_exceptions_ whether parse errors yield exceptions | |
| */ | |
| explicit json_sax_dom_binary_parser(BasicJsonType& r, const bool allow_exceptions_ = true, lexer_t* lexer_ = nullptr) | |
| : json_sax_dom_error_state(allow_exceptions_), root(r), m_lexer_ref(lexer_) | |
| {} | |
| // make class move-only | |
| json_sax_dom_binary_parser(const json_sax_dom_binary_parser&) = delete; | |
| json_sax_dom_binary_parser(json_sax_dom_binary_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) | |
| json_sax_dom_binary_parser& operator=(const json_sax_dom_binary_parser&) = delete; | |
| json_sax_dom_binary_parser& operator=(json_sax_dom_binary_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) | |
| ~json_sax_dom_binary_parser() = default; | |
| bool null() | |
| { | |
| handle_value(nullptr); | |
| return true; | |
| } | |
| bool boolean(bool val) | |
| { | |
| handle_value(val); | |
| return true; | |
| } | |
| bool number_integer(number_integer_t val) | |
| { | |
| handle_value(val); | |
| return true; | |
| } | |
| bool number_unsigned(number_unsigned_t val) | |
| { | |
| handle_value(val); | |
| return true; | |
| } | |
| bool number_float(number_float_t val, const string_t& /*unused*/) | |
| { | |
| handle_value(val); | |
| return true; | |
| } | |
| bool string(string_t& val) | |
| { | |
| // json_sax documents that the passed value may be moved from, | |
| // so hand the buffer over instead of copying it | |
| handle_value(std::move(val)); | |
| return true; | |
| } | |
| bool binary(binary_t& val) | |
| { | |
| // json_sax documents that the passed value may be moved from, | |
| // so hand the buffer over instead of copying it | |
| handle_value(std::move(val)); | |
| return true; | |
| } | |
| bool start_object(std::size_t len) | |
| { | |
| ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| // Ensure this is after the call to handle_value to ensure correct start position. | |
| diagnostic_positions::set_container_start(*ref_stack.back(), m_lexer_ref); | |
| #endif | |
| return check_container_size(*this, len, "object", ref_stack.back()); | |
| } | |
| bool key(string_t& val) | |
| { | |
| JSON_ASSERT(!ref_stack.empty()); | |
| JSON_ASSERT(ref_stack.back()->is_object()); | |
| // add null at the given key and store the reference for later; the | |
| // key is moved, as the lexer starts the next token with reset() | |
| object_element = &(ref_stack.back()->m_data.m_value.object->operator[](std::move(val))); | |
| return true; | |
| } | |
| bool end_object() | |
| { | |
| JSON_ASSERT(!ref_stack.empty()); | |
| JSON_ASSERT(ref_stack.back()->is_object()); | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| diagnostic_positions::set_container_end(*ref_stack.back(), m_lexer_ref); | |
| #endif | |
| ref_stack.back()->set_parents(); | |
| ref_stack.pop_back(); | |
| return true; | |
| } | |
| bool start_array(std::size_t len) | |
| { | |
| ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| // Ensure this is after the call to handle_value to ensure correct start position. | |
| diagnostic_positions::set_container_start(*ref_stack.back(), m_lexer_ref); | |
| #endif | |
| if (JSON_HEDLEY_UNLIKELY(!check_container_size(*this, len, "array", ref_stack.back()))) | |
| { | |
| return false; | |
| } | |
| if (len != detail::unknown_size()) | |
| { | |
| reserve_array(*ref_stack.back()->m_data.m_value.array, len, priority_tag<1> {}); | |
| } | |
| return true; | |
| } | |
| bool end_array() | |
| { | |
| JSON_ASSERT(!ref_stack.empty()); | |
| JSON_ASSERT(ref_stack.back()->is_array()); | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| diagnostic_positions::set_container_end(*ref_stack.back(), m_lexer_ref); | |
| #endif | |
| ref_stack.back()->set_parents(); | |
| ref_stack.pop_back(); | |
| return true; | |
| } | |
| private: | |
| /*! | |
| @invariant If the ref stack is empty, then the passed value will be the new | |
| root. | |
| @invariant If the ref stack contains a value, then it is an array or an | |
| object to which we can add elements | |
| */ | |
| template<typename Value> | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| BasicJsonType* handle_value(Value&& v) | |
| { | |
| if (ref_stack.empty()) | |
| { | |
| root = BasicJsonType(std::forward<Value>(v)); | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| diagnostic_positions::set_from_lexer(root, m_lexer_ref); | |
| #endif | |
| return &root; | |
| } | |
| JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); | |
| if (ref_stack.back()->is_array()) | |
| { | |
| ref_stack.back()->m_data.m_value.array->emplace_back(std::forward<Value>(v)); | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| diagnostic_positions::set_from_lexer(ref_stack.back()->m_data.m_value.array->back(), m_lexer_ref); | |
| #endif | |
| return &(ref_stack.back()->m_data.m_value.array->back()); | |
| } | |
| JSON_ASSERT(ref_stack.back()->is_object()); | |
| JSON_ASSERT(object_element); | |
| *object_element = BasicJsonType(std::forward<Value>(v)); | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| diagnostic_positions::set_from_lexer(*object_element, m_lexer_ref); | |
| #endif | |
| return object_element; | |
| } | |
| /// the parsed JSON value | |
| BasicJsonType& root; | |
| /// stack to model hierarchy of values | |
| std::vector<BasicJsonType*> ref_stack {}; | |
| /// helper to hold the reference for the next object element | |
| BasicJsonType* object_element = nullptr; | |
| /// the lexer reference to obtain the current position | |
| lexer_t* m_lexer_ref = nullptr; | |
| }; | |
| template<typename BasicJsonType, typename InputAdapterType> | |
| class json_sax_dom_callback_parser : public json_sax_dom_error_state | |
| { | |
| public: | |
| using number_integer_t = typename BasicJsonType::number_integer_t; | |
| using number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
| using number_float_t = typename BasicJsonType::number_float_t; | |
| using string_t = typename BasicJsonType::string_t; | |
| using binary_t = typename BasicJsonType::binary_t; | |
| using parser_callback_t = typename BasicJsonType::parser_callback_t; | |
| using parse_event_t = typename BasicJsonType::parse_event_t; | |
| using lexer_t = lexer<BasicJsonType, InputAdapterType>; | |
| json_sax_dom_callback_parser(BasicJsonType& r, | |
| parser_callback_t cb, | |
| const bool allow_exceptions_ = true, | |
| lexer_t* lexer_ = nullptr) | |
| : json_sax_dom_error_state(allow_exceptions_), root(r), callback(std::move(cb)), m_lexer_ref(lexer_) | |
| { | |
| keep_stack.push_back(true); | |
| } | |
| // make class move-only | |
| json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete; | |
| json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) | |
| json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete; | |
| json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) | |
| ~json_sax_dom_callback_parser() = default; | |
| bool null() | |
| { | |
| handle_value(nullptr); | |
| return true; | |
| } | |
| bool boolean(bool val) | |
| { | |
| handle_value(val); | |
| return true; | |
| } | |
| bool number_integer(number_integer_t val) | |
| { | |
| handle_value(val); | |
| return true; | |
| } | |
| bool number_unsigned(number_unsigned_t val) | |
| { | |
| handle_value(val); | |
| return true; | |
| } | |
| bool number_float(number_float_t val, const string_t& /*unused*/) | |
| { | |
| handle_value(val); | |
| return true; | |
| } | |
| bool string(string_t& val) | |
| { | |
| // json_sax documents that the passed value may be moved from, | |
| // so hand the buffer over instead of copying it | |
| handle_value(std::move(val)); | |
| return true; | |
| } | |
| bool binary(binary_t& val) | |
| { | |
| // json_sax documents that the passed value may be moved from, | |
| // so hand the buffer over instead of copying it | |
| handle_value(std::move(val)); | |
| return true; | |
| } | |
| bool start_object(std::size_t len) | |
| { | |
| // check callback for object start; not called inside a discarded container | |
| const bool keep = keep_stack.back() && callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded); | |
| keep_stack.push_back(keep); | |
| // the key this object will be stored under, read before handle_value() | |
| // may consume it; kept in lockstep with ref_stack so end_object() can | |
| // find the object in its parent again | |
| container_key_stack.push_back(current_key()); | |
| auto val = handle_value(BasicJsonType::value_t::object, true); | |
| ref_stack.push_back(val.second); | |
| if (ref_stack.back()) | |
| { | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| // Ensure this is after the call to handle_value to ensure correct start position. | |
| diagnostic_positions::set_container_start(*ref_stack.back(), m_lexer_ref); | |
| #endif | |
| return check_container_size(*this, len, "object", ref_stack.back()); | |
| } | |
| return true; | |
| } | |
| bool key(string_t& val) | |
| { | |
| if (!keep_stack.back() || !ref_stack.back()) | |
| { | |
| // the object is not stored: the value of this key is dropped in | |
| // handle_value() without touching the key stacks | |
| if (keep_stack.back()) | |
| { | |
| static_cast<void>(callback(static_cast<int>(ref_stack.size()), parse_event_t::key, key_value(val))); | |
| } | |
| return true; | |
| } | |
| // check callback for the key | |
| const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, key_value(val)); | |
| key_keep_stack.push_back(keep); | |
| // remember the key so a rejected value can be erased without searching | |
| // the object for it (kept in lockstep with key_keep_stack) | |
| key_stack.push_back(val); | |
| // add discarded value at the given key and store the reference for later | |
| if (keep && ref_stack.back()) | |
| { | |
| auto& obj = *ref_stack.back()->m_data.m_value.object; | |
| // a single lookup: insert the placeholder, or find the existing member | |
| const auto inserted = obj.emplace(std::move(val), discarded); | |
| const auto it = inserted.first; | |
| if (!inserted.second) | |
| { | |
| // this is a duplicate key (legal in JSON); remember its | |
| // current value so it can be restored later if the new | |
| // value is rejected by the callback, instead of being | |
| // erased together with the discarded placeholder | |
| duplicate_key_stash.emplace_back(&(it->second), it->second); | |
| it->second = discarded; | |
| } | |
| object_element = &(it->second); | |
| } | |
| return true; | |
| } | |
| bool end_object() | |
| { | |
| if (ref_stack.back()) | |
| { | |
| if (!callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) | |
| { | |
| // discard object, unless this slot holds a duplicate key's | |
| // previous value pending restoration, in which case that | |
| // value is restored instead of being discarded | |
| if (!resolve_duplicate_key_stash(ref_stack.back(), true)) | |
| { | |
| *ref_stack.back() = discarded; | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| // Set start/end positions for discarded object. | |
| diagnostic_positions::set_from_lexer(*ref_stack.back(), m_lexer_ref); | |
| #endif | |
| } | |
| } | |
| else | |
| { | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| diagnostic_positions::set_container_end(*ref_stack.back(), m_lexer_ref); | |
| #endif | |
| ref_stack.back()->set_parents(); | |
| // this object is finally, definitively kept; drop any | |
| // pending duplicate-key stash entry for its slot since it | |
| // can no longer be restored | |
| resolve_duplicate_key_stash(ref_stack.back(), false); | |
| } | |
| } | |
| const string_t object_key = pop_container(); | |
| if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured()) | |
| { | |
| // remove discarded value | |
| remove_discarded_value(*ref_stack.back(), object_key); | |
| } | |
| return true; | |
| } | |
| bool start_array(std::size_t len) | |
| { | |
| const bool keep = keep_stack.back() && callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded); | |
| keep_stack.push_back(keep); | |
| // see start_object() | |
| container_key_stack.push_back(current_key()); | |
| auto val = handle_value(BasicJsonType::value_t::array, true); | |
| ref_stack.push_back(val.second); | |
| if (ref_stack.back()) | |
| { | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| // Ensure this is after the call to handle_value to ensure correct start position. | |
| diagnostic_positions::set_container_start(*ref_stack.back(), m_lexer_ref); | |
| #endif | |
| if (JSON_HEDLEY_UNLIKELY(!check_container_size(*this, len, "array", ref_stack.back()))) | |
| { | |
| return false; | |
| } | |
| if (len != detail::unknown_size()) | |
| { | |
| reserve_array(*ref_stack.back()->m_data.m_value.array, len, priority_tag<1> {}); | |
| } | |
| } | |
| return true; | |
| } | |
| bool end_array() | |
| { | |
| bool keep = true; | |
| const bool stored = ref_stack.back() != nullptr; | |
| if (stored) | |
| { | |
| keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); | |
| if (keep) | |
| { | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| diagnostic_positions::set_container_end(*ref_stack.back(), m_lexer_ref); | |
| #endif | |
| ref_stack.back()->set_parents(); | |
| // this array is finally, definitively kept; drop any | |
| // pending duplicate-key stash entry for its slot since it | |
| // can no longer be restored | |
| resolve_duplicate_key_stash(ref_stack.back(), false); | |
| } | |
| else | |
| { | |
| // discard array, unless this slot holds a duplicate key's | |
| // previous value pending restoration, in which case that | |
| // value is restored instead of being discarded | |
| if (!resolve_duplicate_key_stash(ref_stack.back(), true)) | |
| { | |
| *ref_stack.back() = discarded; | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| // Set start/end positions for discarded array. | |
| diagnostic_positions::set_from_lexer(*ref_stack.back(), m_lexer_ref); | |
| #endif | |
| } | |
| } | |
| } | |
| const string_t object_key = pop_container(); | |
| // remove discarded value | |
| if (!ref_stack.empty() && ref_stack.back()) | |
| { | |
| if (!keep && ref_stack.back()->is_array()) | |
| { | |
| ref_stack.back()->m_data.m_value.array->pop_back(); | |
| } | |
| else if ((!keep || !stored) && ref_stack.back()->is_object()) | |
| { | |
| // the array is either still stored under its key or was never | |
| // stored, leaving the placeholder key() wrote; both show up as | |
| // a discarded member of the parent object | |
| remove_discarded_value(*ref_stack.back(), object_key); | |
| } | |
| } | |
| return true; | |
| } | |
| private: | |
| /*! | |
| @brief the value of a key event for the callback | |
| A string value of its own for every key would allocate it every time, so | |
| one is kept and set to the key. A callback that changed or moved it gets a | |
| new one, as it would have got a new value for every key anyway. | |
| */ | |
| BasicJsonType& key_value(const string_t& key) | |
| { | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| // a callback may have left positions on the value | |
| key_scratch = BasicJsonType(key); | |
| #else | |
| if (JSON_HEDLEY_LIKELY(key_scratch.is_string())) | |
| { | |
| *key_scratch.m_data.m_value.string = key; | |
| } | |
| else | |
| { | |
| key_scratch = BasicJsonType(key); | |
| } | |
| #endif | |
| return key_scratch; | |
| } | |
| /// if there is a pending duplicate-key stash entry for this exact slot, | |
| /// remove it from the stash; if restore_value is true, the stashed | |
| /// previous value is moved back into the slot first (use this when the | |
| /// new value at that slot was rejected); otherwise the stash entry is | |
| /// simply dropped (use this when the new value was accepted, so it | |
| /// correctly supersedes the old one and no restore should ever happen | |
| /// for this slot again) | |
| /// @return whether a matching stash entry was found (and processed) | |
| bool resolve_duplicate_key_stash(BasicJsonType* slot, bool restore_value) | |
| { | |
| const auto it = std::find_if(duplicate_key_stash.begin(), duplicate_key_stash.end(), | |
| [slot](const std::pair<BasicJsonType*, BasicJsonType>& entry) | |
| { | |
| return entry.first == slot; | |
| }); | |
| if (it == duplicate_key_stash.end()) | |
| { | |
| return false; | |
| } | |
| if (restore_value) | |
| { | |
| *slot = std::move(it->second); | |
| } | |
| duplicate_key_stash.erase(it); | |
| return true; | |
| } | |
| /*! | |
| @brief the key the value now being handled will be stored under | |
| Empty unless the enclosing container is an object, in which case it is the | |
| key of the pending key() event. Read before handle_value() consumes that | |
| key, so it is also correct when the value never reaches its parent. | |
| */ | |
| string_t current_key() const | |
| { | |
| if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_object() | |
| && !key_stack.empty()) | |
| { | |
| return key_stack.back(); | |
| } | |
| return string_t{}; | |
| } | |
| /*! | |
| @brief leave the object or array that end_object()/end_array() just closed | |
| @return the key the container is stored under in its parent (see | |
| container_key_stack) | |
| */ | |
| string_t pop_container() | |
| { | |
| JSON_ASSERT(!ref_stack.empty()); | |
| JSON_ASSERT(!keep_stack.empty()); | |
| JSON_ASSERT(!container_key_stack.empty()); | |
| ref_stack.pop_back(); | |
| keep_stack.pop_back(); | |
| string_t object_key = std::move(container_key_stack.back()); | |
| container_key_stack.pop_back(); | |
| return object_key; | |
| } | |
| /*! | |
| @brief remove the discarded value the callback rejected from its parent, | |
| unless it is a duplicate key's slot with a stashed previous value, in | |
| which case that previous value is restored instead | |
| A rejected value can only ever be the one most recently added to @a parent: | |
| the last element of an array, or the placeholder key() stored under @a key | |
| in an object. Looking there directly makes this O(1) resp. O(log n), where | |
| searching @a parent for it made a filtering parse quadratic in the number of | |
| members of a single container. | |
| Finding no discarded value there means none was stored in the first place - | |
| the callback rejected the value before it reached its parent - so there is | |
| nothing to remove. | |
| @param[in,out] parent the container to remove the rejected value from | |
| @param[in] key the key the value was stored under; unused for arrays | |
| */ | |
| void remove_discarded_value(BasicJsonType& parent, const string_t& key) | |
| { | |
| if (parent.is_array()) | |
| { | |
| auto& array = *parent.m_data.m_value.array; | |
| if (!array.empty() && array.back().is_discarded()) | |
| { | |
| array.pop_back(); | |
| } | |
| } | |
| else if (parent.is_object()) | |
| { | |
| auto& object = *parent.m_data.m_value.object; | |
| const auto it = object.find(key); | |
| if (it != object.end() && it->second.is_discarded()) | |
| { | |
| // a duplicate key's slot has a stashed previous value that | |
| // must be restored instead of being erased | |
| if (!resolve_duplicate_key_stash(&it->second, true)) | |
| { | |
| object.erase(it); | |
| } | |
| } | |
| } | |
| } | |
| /*! | |
| @param[in] v value to add to the JSON value we build during parsing | |
| @param[in] skip_callback whether we should skip calling the callback | |
| function; this is required after start_array() and | |
| start_object() SAX events, because otherwise we would call the | |
| callback function with an empty array or object, respectively. | |
| @invariant If the ref stack is empty, then the passed value will be the new | |
| root. | |
| @invariant If the ref stack contains a value, then it is an array or an | |
| object to which we can add elements | |
| @return pair of boolean (whether value should be kept) and pointer (to the | |
| passed value in the ref_stack hierarchy; nullptr if not kept) | |
| */ | |
| template<typename Value> | |
| std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false) | |
| { | |
| JSON_ASSERT(!keep_stack.empty()); | |
| // do not handle this value if we know it would be added to a discarded | |
| // container | |
| if (!keep_stack.back()) | |
| { | |
| return {false, nullptr}; | |
| } | |
| // create value | |
| auto value = BasicJsonType(std::forward<Value>(v)); | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| diagnostic_positions::set_from_lexer(value, m_lexer_ref); | |
| #endif | |
| // check callback | |
| const bool keep = skip_callback || callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value); | |
| // do not handle this value if we just learnt it shall be discarded | |
| if (!keep) | |
| { | |
| // if the value was to become an object member, key() already | |
| // stored a placeholder for it that has to be removed again | |
| if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_object()) | |
| { | |
| JSON_ASSERT(!key_keep_stack.empty()); | |
| JSON_ASSERT(!key_stack.empty()); | |
| const bool placeholder_stored = key_keep_stack.back(); | |
| key_keep_stack.pop_back(); | |
| const string_t key = std::move(key_stack.back()); | |
| key_stack.pop_back(); | |
| if (placeholder_stored) | |
| { | |
| remove_discarded_value(*ref_stack.back(), key); | |
| } | |
| } | |
| return {false, nullptr}; | |
| } | |
| if (ref_stack.empty()) | |
| { | |
| root = std::move(value); | |
| return {true, & root}; | |
| } | |
| // skip this value if we already decided to skip the parent | |
| // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360) | |
| if (!ref_stack.back()) | |
| { | |
| return {false, nullptr}; | |
| } | |
| // we now only expect arrays and objects | |
| JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); | |
| // array | |
| if (ref_stack.back()->is_array()) | |
| { | |
| ref_stack.back()->m_data.m_value.array->emplace_back(std::move(value)); | |
| return {true, & (ref_stack.back()->m_data.m_value.array->back())}; | |
| } | |
| // object | |
| JSON_ASSERT(ref_stack.back()->is_object()); | |
| // check if we should store an element for the current key | |
| JSON_ASSERT(!key_keep_stack.empty()); | |
| JSON_ASSERT(!key_stack.empty()); | |
| const bool store_element = key_keep_stack.back(); | |
| key_keep_stack.pop_back(); | |
| key_stack.pop_back(); | |
| if (!store_element) | |
| { | |
| return {false, nullptr}; | |
| } | |
| JSON_ASSERT(object_element); | |
| *object_element = std::move(value); | |
| if (!skip_callback) | |
| { | |
| // this scalar value finally, definitively replaces whatever was | |
| // at this slot; drop any pending duplicate-key stash entry for | |
| // it since it can no longer be restored (a container value at | |
| // this slot is resolved later, in end_object()/end_array(), | |
| // since skip_callback is true for the placeholder handling that | |
| // happens here for those) | |
| resolve_duplicate_key_stash(object_element, false); | |
| } | |
| return {true, object_element}; | |
| } | |
| /// the parsed JSON value | |
| BasicJsonType& root; | |
| /// stack to model hierarchy of values | |
| std::vector<BasicJsonType*> ref_stack {}; | |
| /// stack to manage which values to keep | |
| std::vector<bool> keep_stack {}; // NOLINT(readability-redundant-member-init) | |
| /// stack to manage which object keys to keep | |
| std::vector<bool> key_keep_stack {}; // NOLINT(readability-redundant-member-init) | |
| /// the keys key() stored a placeholder for, in lockstep with key_keep_stack | |
| std::vector<string_t> key_stack {}; // NOLINT(readability-redundant-member-init) | |
| /// for each open container, the key it is stored under in its parent | |
| /// object, in lockstep with ref_stack; unused where the parent is not an | |
| /// object | |
| std::vector<string_t> container_key_stack {}; // NOLINT(readability-redundant-member-init) | |
| /// helper to hold the reference for the next object element | |
| BasicJsonType* object_element = nullptr; | |
| /// stash of (slot pointer, previous value) for object members that | |
| /// already existed when key() was called again for the same key | |
| /// (duplicate keys); used to restore the previous value if the new | |
| /// value is later rejected by the callback, instead of erasing the | |
| /// member entirely | |
| std::vector<std::pair<BasicJsonType*, BasicJsonType>> duplicate_key_stash {}; | |
| /// callback function | |
| const parser_callback_t callback = nullptr; | |
| /// a discarded value for the callback | |
| BasicJsonType discarded = BasicJsonType::value_t::discarded; | |
| /// the value of the key event for the callback (see key_value()) | |
| BasicJsonType key_scratch {}; | |
| /// the lexer reference to obtain the current position | |
| lexer_t* m_lexer_ref = nullptr; | |
| }; | |
| template<typename BasicJsonType> | |
| class json_sax_acceptor | |
| { | |
| public: | |
| using number_integer_t = typename BasicJsonType::number_integer_t; | |
| using number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
| using number_float_t = typename BasicJsonType::number_float_t; | |
| using string_t = typename BasicJsonType::string_t; | |
| using binary_t = typename BasicJsonType::binary_t; | |
| bool null() | |
| { | |
| return true; | |
| } | |
| bool boolean(bool /*unused*/) | |
| { | |
| return true; | |
| } | |
| bool number_integer(number_integer_t /*unused*/) | |
| { | |
| return true; | |
| } | |
| bool number_unsigned(number_unsigned_t /*unused*/) | |
| { | |
| return true; | |
| } | |
| bool number_float(number_float_t /*unused*/, const string_t& /*unused*/) | |
| { | |
| return true; | |
| } | |
| bool string(string_t& /*unused*/) | |
| { | |
| return true; | |
| } | |
| bool binary(binary_t& /*unused*/) | |
| { | |
| return true; | |
| } | |
| bool start_object(std::size_t /*unused*/ = detail::unknown_size()) | |
| { | |
| return true; | |
| } | |
| bool key(string_t& /*unused*/) | |
| { | |
| return true; | |
| } | |
| bool end_object() | |
| { | |
| return true; | |
| } | |
| bool start_array(std::size_t /*unused*/ = detail::unknown_size()) | |
| { | |
| return true; | |
| } | |
| bool end_array() | |
| { | |
| return true; | |
| } | |
| bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) | |
| { | |
| return false; | |
| } | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/input/lexer.hpp> | |
| // #include <nlohmann/detail/input/string_scan.hpp> | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/meta/is_sax.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cstddef> // size_t | |
| #include <utility> // declval | |
| #include <string> // string | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| // #include <nlohmann/detail/meta/detected.hpp> | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| template<typename T> | |
| using null_function_t = decltype(std::declval<T&>().null()); | |
| template<typename T> | |
| using boolean_function_t = | |
| decltype(std::declval<T&>().boolean(std::declval<bool>())); | |
| template<typename T, typename Integer> | |
| using number_integer_function_t = | |
| decltype(std::declval<T&>().number_integer(std::declval<Integer>())); | |
| template<typename T, typename Unsigned> | |
| using number_unsigned_function_t = | |
| decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>())); | |
| template<typename T, typename Float, typename String> | |
| using number_float_function_t = decltype(std::declval<T&>().number_float( | |
| std::declval<Float>(), std::declval<const String&>())); | |
| template<typename T, typename String> | |
| using string_function_t = | |
| decltype(std::declval<T&>().string(std::declval<String&>())); | |
| template<typename T, typename Binary> | |
| using binary_function_t = | |
| decltype(std::declval<T&>().binary(std::declval<Binary&>())); | |
| template<typename T> | |
| using start_object_function_t = | |
| decltype(std::declval<T&>().start_object(std::declval<std::size_t>())); | |
| template<typename T, typename String> | |
| using key_function_t = | |
| decltype(std::declval<T&>().key(std::declval<String&>())); | |
| template<typename T> | |
| using end_object_function_t = decltype(std::declval<T&>().end_object()); | |
| template<typename T> | |
| using start_array_function_t = | |
| decltype(std::declval<T&>().start_array(std::declval<std::size_t>())); | |
| template<typename T> | |
| using end_array_function_t = decltype(std::declval<T&>().end_array()); | |
| template<typename T, typename Exception> | |
| using parse_error_function_t = decltype(std::declval<T&>().parse_error( | |
| std::declval<std::size_t>(), std::declval<const std::string&>(), | |
| std::declval<const Exception&>())); | |
| template<typename SAX, typename BasicJsonType> | |
| struct is_sax_static_asserts | |
| { | |
| private: | |
| static_assert(is_basic_json<BasicJsonType>::value, | |
| "BasicJsonType must be of type basic_json<...>"); | |
| using number_integer_t = typename BasicJsonType::number_integer_t; | |
| using number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
| using number_float_t = typename BasicJsonType::number_float_t; | |
| using string_t = typename BasicJsonType::string_t; | |
| using binary_t = typename BasicJsonType::binary_t; | |
| using exception_t = typename BasicJsonType::exception; | |
| public: | |
| static_assert(is_detected_exact<bool, null_function_t, SAX>::value, | |
| "Missing/invalid function: bool null()"); | |
| static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value, | |
| "Missing/invalid function: bool boolean(bool)"); | |
| static_assert( | |
| is_detected_exact<bool, number_integer_function_t, SAX, | |
| number_integer_t>::value, | |
| "Missing/invalid function: bool number_integer(number_integer_t)"); | |
| static_assert( | |
| is_detected_exact<bool, number_unsigned_function_t, SAX, | |
| number_unsigned_t>::value, | |
| "Missing/invalid function: bool number_unsigned(number_unsigned_t)"); | |
| static_assert(is_detected_exact<bool, number_float_function_t, SAX, | |
| number_float_t, string_t>::value, | |
| "Missing/invalid function: bool number_float(number_float_t, const string_t&)"); | |
| static_assert( | |
| is_detected_exact<bool, string_function_t, SAX, string_t>::value, | |
| "Missing/invalid function: bool string(string_t&)"); | |
| static_assert( | |
| is_detected_exact<bool, binary_function_t, SAX, binary_t>::value, | |
| "Missing/invalid function: bool binary(binary_t&)"); | |
| static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value, | |
| "Missing/invalid function: bool start_object(std::size_t)"); | |
| static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value, | |
| "Missing/invalid function: bool key(string_t&)"); | |
| static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value, | |
| "Missing/invalid function: bool end_object()"); | |
| static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value, | |
| "Missing/invalid function: bool start_array(std::size_t)"); | |
| static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value, | |
| "Missing/invalid function: bool end_array()"); | |
| static_assert( | |
| is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value, | |
| "Missing/invalid function: bool parse_error(std::size_t, const " | |
| "std::string&, const exception&)"); | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| // #include <nlohmann/detail/output/error_handler.hpp> | |
| // #include <nlohmann/detail/string_concat.hpp> | |
| // #include <nlohmann/detail/string_utils.hpp> | |
| // #include <nlohmann/detail/value_t.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /// how to treat CBOR tags | |
| enum class cbor_tag_handler_t | |
| { | |
| error, ///< throw a parse_error exception in case of a tag | |
| ignore, ///< ignore tags | |
| store ///< store tagged byte strings (for bytes 0xd8..0xdb) as binary values with the tag as subtype; other tagged values are read as if the tag were ignored | |
| }; | |
| /*! | |
| @brief determine system byte order | |
| @return true if and only if system's byte order is little endian | |
| @note from https://stackoverflow.com/a/1001328/266378 | |
| */ | |
| inline bool little_endianness(int num = 1) noexcept | |
| { | |
| return *reinterpret_cast<char*>(&num) == 1; | |
| } | |
| /*! | |
| @brief largest element count accepted for a UBJSON container of a valueless type | |
| An element of type 'Z' (null), 'T' (true) or 'F' (false) is encoded by its | |
| type marker alone, so an optimized container of one of those types has no | |
| payload at all and its declared count is the only thing that decides how much | |
| is allocated: `[$Z#L` followed by a large count turns some ten bytes of input | |
| into that many values (see #2793, which reports 35 GB and 150 seconds). Every | |
| other type costs at least one byte per element and is bounded by the end of | |
| the input. | |
| This is a sanity bound rather than a security boundary, and it is far above | |
| any container met in practice. @ref binary_writer falls back to the | |
| unoptimized encoding for longer containers, so that a value serialized by | |
| this library can always be read back. | |
| @sa https://github.com/nlohmann/json/issues/2793 | |
| */ | |
| JSON_INLINE_VARIABLE constexpr std::size_t max_valueless_container_size = 1 << 20; | |
| /////////////////// | |
| // binary reader // | |
| /////////////////// | |
| /*! | |
| @brief deserialization of BJData, BON8, BSON, CBOR, MessagePack, and UBJSON values | |
| */ | |
| template<typename BasicJsonType, typename InputAdapterType, typename SAX = json_sax_dom_binary_parser<BasicJsonType, InputAdapterType>> | |
| class binary_reader | |
| { | |
| using number_integer_t = typename BasicJsonType::number_integer_t; | |
| using number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
| using number_float_t = typename BasicJsonType::number_float_t; | |
| using string_t = typename BasicJsonType::string_t; | |
| using binary_t = typename BasicJsonType::binary_t; | |
| using json_sax_t = SAX; | |
| using char_type = typename InputAdapterType::char_type; | |
| using char_int_type = typename char_traits<char_type>::int_type; | |
| /// whether the input is a contiguous block of bytes that can be inspected | |
| /// and consumed in bulk (as in the lexer); used by @ref get_bon8_string_bulk | |
| static constexpr bool bulk_scan = | |
| input_adapter_supports_bulk_scan<InputAdapterType>(is_detected<detect_supports_bulk_scan, InputAdapterType> {}); | |
| public: | |
| /*! | |
| @brief create a binary reader | |
| @param[in] adapter input adapter to read from | |
| @param[in] format the binary format to parse | |
| @param[in] error_handler_ how to treat text strings and object keys that | |
| are not well-formed UTF-8; none of the supported formats | |
| requires a decoder to reject those, so the default is to | |
| @ref error_handler_t::keep them unchanged, as every binary | |
| reader did before this parameter existed | |
| */ | |
| explicit binary_reader(InputAdapterType&& adapter, const input_format_t format = input_format_t::json, | |
| const error_handler_t error_handler_ = error_handler_t::keep) noexcept | |
| : ia(std::move(adapter)), input_format(format), error_handler(error_handler_) | |
| { | |
| (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {}; | |
| } | |
| // make class move-only | |
| binary_reader(const binary_reader&) = delete; | |
| binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) | |
| binary_reader& operator=(const binary_reader&) = delete; | |
| binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) | |
| ~binary_reader() = default; | |
| /*! | |
| @brief parse in the format the constructor was given | |
| @param[in] sax_ a SAX event processor | |
| @param[in] strict whether to expect the input to be consumed completed | |
| @param[in] tag_handler how to treat CBOR tags | |
| @return whether parsing was successful | |
| */ | |
| JSON_HEDLEY_NON_NULL(2) | |
| bool sax_parse(json_sax_t* sax_, | |
| const bool strict = true, | |
| const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) | |
| { | |
| sax = sax_; | |
| container_stack.clear(); | |
| bon8_pushback_size = 0; | |
| bool result = false; | |
| switch (input_format) | |
| { | |
| case input_format_t::bson: | |
| result = parse_bson_internal(); | |
| break; | |
| case input_format_t::cbor: | |
| result = parse_cbor_internal(tag_handler); | |
| break; | |
| case input_format_t::msgpack: | |
| result = parse_msgpack_internal(); | |
| break; | |
| case input_format_t::ubjson: | |
| case input_format_t::bjdata: | |
| result = parse_ubjson_internal(); | |
| break; | |
| case input_format_t::bon8: | |
| result = parse_bon8_internal(); | |
| break; | |
| case input_format_t::json: // LCOV_EXCL_LINE | |
| default: // LCOV_EXCL_LINE | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE | |
| } | |
| // strict mode: next byte must be EOF | |
| if (result && strict) | |
| { | |
| if (input_format == input_format_t::ubjson || input_format == input_format_t::bjdata) | |
| { | |
| get_ignore_noop(); | |
| } | |
| else if (input_format == input_format_t::bon8) | |
| { | |
| // a string that ends a container hands back the byte after it | |
| get_bon8(); | |
| } | |
| else | |
| { | |
| get(); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(current != char_traits<char_type>::eof())) | |
| { | |
| return last_byte_error(exception_id::unexpected_end_of_input, "expected end of input", "value", ""); | |
| } | |
| } | |
| return result; | |
| } | |
| private: | |
| //////////////////////// | |
| // nested containers // | |
| //////////////////////// | |
| /*! | |
| @brief a container that has been opened and not closed yet | |
| The binary readers do not call themselves once per nesting level. Like | |
| @ref parser::sax_parse_internal, which does the same for JSON text, they | |
| keep the containers they are inside of on a heap-allocated stack, so that | |
| the native call stack does not grow with the nesting depth of the input | |
| and a deeply nested value is bounded by memory rather than by the stack | |
| (see #5104). | |
| The members are ordered by decreasing alignment, which is the ordering that | |
| keeps a struct from growing as members are added to it. | |
| */ | |
| struct container_frame | |
| { | |
| container_frame(const std::size_t remaining_, const bool is_object_, | |
| const char_int_type type_marker_ = 0) noexcept | |
| : remaining(remaining_), type_marker(type_marker_), is_object(is_object_) {} | |
| /// number of elements that have not been read yet, or npos when the | |
| /// container is not sized and ends at a marker instead | |
| std::size_t remaining; | |
| /// BSON: value of chars_read before this document's size prefix, which | |
| /// check_bson_document_size() needs once the document has been read | |
| std::size_t start_position = 0; | |
| /// UBJSON/BJData: the type marker of an optimized container, so that | |
| /// its elements are read without one of their own; 0 otherwise | |
| char_int_type type_marker; | |
| /// BSON: the size this document declares, in bytes | |
| std::int32_t declared_size = 0; | |
| /// whether to close this container with end_object() or end_array() | |
| bool is_object; | |
| }; | |
| /*! | |
| @brief open a nested array or object | |
| Emits the SAX start event and records the container. This is the only | |
| place the binary readers start a container, so a check that rejects one | |
| can be made here and is then guaranteed to run before the start event. | |
| @param[in] is_object whether an object (true) or an array (false) begins | |
| @param[in] len number of elements the container declares | |
| @return whether the SAX parser accepted the start event | |
| */ | |
| bool enter_container(const bool is_object, const std::size_t len, | |
| const char_int_type type_marker = 0) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(is_object ? !sax->start_object(len) : !sax->start_array(len))) | |
| { | |
| return false; | |
| } | |
| container_stack.emplace_back(len, is_object, type_marker); | |
| return true; | |
| } | |
| /// @copydoc enter_container | |
| bool enter_array(const std::size_t len, const char_int_type type_marker = 0) | |
| { | |
| return enter_container(/*is_object*/false, len, type_marker); | |
| } | |
| /// @copydoc enter_container | |
| bool enter_object(const std::size_t len, const char_int_type type_marker = 0) | |
| { | |
| return enter_container(/*is_object*/true, len, type_marker); | |
| } | |
| /*! | |
| @brief close the innermost open array or object | |
| Pops the container opened by the matching @ref enter_container call and | |
| emits the SAX end event. Every format-specific driver otherwise repeated | |
| the same pop-then-dispatch sequence at its own close site. | |
| @return whether the SAX parser accepted the end event | |
| */ | |
| bool leave_container() | |
| { | |
| const bool is_object = container_stack.back().is_object; | |
| container_stack.pop_back(); | |
| return is_object ? sax->end_object() : sax->end_array(); | |
| } | |
| /*! | |
| @brief close the innermost open container and report whether that | |
| completed the value being read | |
| The value begun by the driver is complete once its container is not | |
| inside another one. | |
| @param[out] value_complete whether no container is left open | |
| @return whether the SAX parser accepted the end event | |
| */ | |
| bool leave_container_and_check(bool& value_complete) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!leave_container())) | |
| { | |
| return false; | |
| } | |
| value_complete = container_stack.empty(); | |
| return true; | |
| } | |
| /*! | |
| @brief read an object key and pass it to the SAX parser | |
| @tparam GetKey member function that reads the key into a string | |
| @param[in,out] key string the key is read into; cleared first | |
| @return whether reading the key and the SAX event succeeded | |
| */ | |
| template<bool (binary_reader::*GetKey)(string_t&)> | |
| bool read_object_key(string_t& key) | |
| { | |
| key.clear(); | |
| return (this->*GetKey)(key) && sax->key(key); | |
| } | |
| ////////// | |
| // BSON // | |
| ////////// | |
| /*! | |
| @brief Validate a BSON document's declared size against the bytes read. | |
| A BSON document starts with an int32 that counts its own total length in | |
| bytes, including that prefix and the trailing 0x00. The reader is driven | |
| by the terminator rather than the declared length, so without this check a | |
| nested document could declare a length that disagrees with where its | |
| terminator actually falls and quietly hand the bytes in between to the | |
| enclosing document. A well-formed document is at least 5 bytes (the prefix | |
| plus the terminator); the equality also rejects those impossible sizes, | |
| since at least 5 bytes are always consumed. | |
| @param[in] document_start value of chars_read before the size prefix | |
| @param[in] document_size the declared document size | |
| @return whether the declared size matches the number of bytes read | |
| */ | |
| bool check_bson_document_size(const std::size_t document_start, const std::int32_t document_size) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(document_size < 0 || static_cast<std::size_t>(document_size) != chars_read - document_start)) | |
| { | |
| return bson_document_size_error(document_size, chars_read - document_start); | |
| } | |
| return true; | |
| } | |
| /*! | |
| @brief Reads in a BSON-object and passes it to the SAX-parser. | |
| @return whether a valid BSON-value was passed to the SAX parser | |
| */ | |
| bool open_bson_document(const bool is_object) | |
| { | |
| // recorded before the size prefix is read, because | |
| // check_bson_document_size() measures the document from here | |
| const std::size_t document_start = chars_read; | |
| std::int32_t document_size{}; | |
| if (!get_number<std::int32_t, true>(document_size)) | |
| { | |
| return false; | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!enter_container(is_object, detail::unknown_size()))) | |
| { | |
| return false; | |
| } | |
| container_frame& frame = container_stack.back(); | |
| frame.start_position = document_start; | |
| frame.declared_size = document_size; | |
| return true; | |
| } | |
| /*! | |
| @brief read a BSON document and everything nested inside it | |
| Reads elements until the document that was begun here is complete, | |
| resuming the enclosing document each time an embedded one ends, so that | |
| the nesting depth of the input costs heap rather than native stack | |
| (see #5104). | |
| @return whether reading the document succeeded | |
| */ | |
| bool parse_bson_internal() | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!open_bson_document(/*is_object*/true))) | |
| { | |
| return false; | |
| } | |
| // the key currently being read; hoisted out of the loop so that its | |
| // capacity is reused across elements and across nesting levels | |
| string_t key; | |
| while (true) | |
| { | |
| const auto element_type = get(); | |
| if (element_type == 0) // end of the innermost document | |
| { | |
| // a copy, not a reference: it must stay valid across the | |
| // pop_back() inside leave_container() below, which destroys | |
| // the container_stack element it would otherwise alias | |
| const container_frame top = container_stack.back(); | |
| if (JSON_HEDLEY_UNLIKELY(!check_bson_document_size(top.start_position, top.declared_size))) | |
| { | |
| return false; | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!leave_container())) | |
| { | |
| return false; | |
| } | |
| // the document begun here is complete once it is not inside one | |
| if (container_stack.empty()) | |
| { | |
| return true; | |
| } | |
| continue; | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("element list"))) | |
| { | |
| return false; | |
| } | |
| const std::size_t element_type_parse_position = chars_read; | |
| key.clear(); | |
| if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key))) | |
| { | |
| return false; | |
| } | |
| // an array's elements are named "0", "1", ... in the wire format, | |
| // and those names are not passed on | |
| if (container_stack.back().is_object && !sax->key(key)) | |
| { | |
| return false; | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position))) | |
| { | |
| return false; | |
| } | |
| } | |
| } | |
| /*! | |
| @brief Parses a C-style string from the BSON input. | |
| @param[in,out] result A reference to the string variable where the read | |
| string is to be stored. | |
| @return `true` if the \\x00-byte indicating the end of the string was | |
| encountered before the EOF; false` indicates an unexpected EOF. | |
| */ | |
| bool get_bson_cstr(string_t& result) | |
| { | |
| if (get_bson_cstr_bulk(result, std::integral_constant<bool, bulk_scan> {})) | |
| { | |
| return check_string_utf8(result, "key"); | |
| } | |
| auto out = std::back_inserter(result); | |
| while (true) | |
| { | |
| get(); | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("cstring"))) | |
| { | |
| return false; | |
| } | |
| if (current == 0x00) | |
| { | |
| return check_string_utf8(result, "key"); | |
| } | |
| *out++ = static_cast<typename string_t::value_type>(current); | |
| } | |
| } | |
| /*! | |
| @brief read a C-style string from contiguous input in one step | |
| @param[in,out] result the string to append to | |
| @return whether the string was read; if the input has no \\x00-byte, nothing | |
| is read, and @ref get_bson_cstr reports the end of the input | |
| */ | |
| bool get_bson_cstr_bulk(string_t& result, std::true_type /*bulk*/) | |
| { | |
| const std::size_t remaining = ia.bulk_remaining(); | |
| if (remaining == 0) | |
| { | |
| return false; | |
| } | |
| const auto* const data = reinterpret_cast<const unsigned char*>(ia.bulk_data()); | |
| // a plain loop rather than std::memchr: most keys are short (array | |
| // indices are keys, too), and the call would cost more than it saves | |
| std::size_t length = 0; | |
| while (length < remaining && data[length] != 0x00) | |
| { | |
| ++length; | |
| } | |
| if (length == remaining) | |
| { | |
| return false; | |
| } | |
| result.append(reinterpret_cast<const typename string_t::value_type*>(data), length); | |
| // consume the string and its \x00-byte, as the byte-wise path does | |
| ia.bulk_skip(length + 1); | |
| chars_read += length + 1; | |
| current = 0x00; | |
| return true; | |
| } | |
| /// input that is not contiguous: C-style strings are read byte by byte | |
| bool get_bson_cstr_bulk(string_t& /*result*/, std::false_type /*bulk*/) const noexcept | |
| { | |
| return false; | |
| } | |
| /*! | |
| @brief Parses a zero-terminated string of length @a len from the BSON | |
| input. | |
| @param[in] len The length (including the zero-byte at the end) of the | |
| string to be read. | |
| @param[in,out] result A reference to the string variable where the read | |
| string is to be stored. | |
| @tparam NumberType The type of the length @a len | |
| @pre len >= 1 | |
| @return `true` if the string was successfully parsed | |
| */ | |
| template<typename NumberType> | |
| bool get_bson_string(const NumberType len, string_t& result) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(len < 1)) | |
| { | |
| return bson_length_error("string length must be at least 1, is ", len, "string"); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!get_string(len - static_cast<NumberType>(1), result))) | |
| { | |
| return false; | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(get() != 0x00)) | |
| { | |
| return last_byte_error(exception_id::unexpected_byte, "BSON string is not null-terminated", "string"); | |
| } | |
| return check_string_utf8(result, "string"); | |
| } | |
| /*! | |
| @brief Parses a byte array input of length @a len from the BSON input. | |
| @param[in] len The length of the byte array to be read. | |
| @param[in,out] result A reference to the binary variable where the read | |
| array is to be stored. | |
| @tparam NumberType The type of the length @a len | |
| @pre len >= 0 | |
| @return `true` if the byte array was successfully parsed | |
| */ | |
| template<typename NumberType> | |
| bool get_bson_binary(const NumberType len, binary_t& result) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(len < 0)) | |
| { | |
| return bson_length_error("byte array length cannot be negative, is ", len, "binary"); | |
| } | |
| // All BSON binary values have a subtype | |
| std::uint8_t subtype{}; | |
| if (JSON_HEDLEY_UNLIKELY(!get_number<std::uint8_t>(subtype))) | |
| { | |
| return false; | |
| } | |
| result.set_subtype(subtype); | |
| return get_binary(len, result); | |
| } | |
| /*! | |
| @brief Read a BSON document element of the given @a element_type. | |
| @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html | |
| @param[in] element_type_parse_position The position in the input stream, | |
| where the `element_type` was read. | |
| @warning Not all BSON element types are supported yet. An unsupported | |
| @a element_type will give rise to a parse_error.114: | |
| Unsupported BSON record type 0x... | |
| @return whether a valid BSON-object/array was passed to the SAX parser | |
| */ | |
| bool parse_bson_element_internal(const char_int_type element_type, | |
| const std::size_t element_type_parse_position) | |
| { | |
| switch (element_type) | |
| { | |
| case 0x01: // double | |
| { | |
| double number{}; | |
| return get_number<double, true>(number) && emit_float(number); | |
| } | |
| case 0x02: // string | |
| { | |
| std::int32_t len{}; | |
| string_t value; | |
| return get_number<std::int32_t, true>(len) && get_bson_string(len, value) && sax->string(value); | |
| } | |
| case 0x03: // object | |
| { | |
| return open_bson_document(/*is_object*/true); | |
| } | |
| case 0x04: // array | |
| { | |
| return open_bson_document(/*is_object*/false); | |
| } | |
| case 0x05: // binary | |
| { | |
| std::int32_t len{}; | |
| binary_t value; | |
| return get_number<std::int32_t, true>(len) && get_bson_binary(len, value) && sax->binary(value); | |
| } | |
| case 0x08: // boolean | |
| { | |
| std::uint8_t value{}; | |
| return get_number<std::uint8_t>(value) && sax->boolean(value != 0); | |
| } | |
| case 0x0A: // null | |
| { | |
| return sax->null(); | |
| } | |
| case 0x10: // int32 | |
| { | |
| std::int32_t value{}; | |
| return get_number<std::int32_t, true>(value) && emit_signed(value); | |
| } | |
| case 0x12: // int64 | |
| { | |
| std::int64_t value{}; | |
| return get_number<std::int64_t, true>(value) && emit_signed(value); | |
| } | |
| case 0x11: // uint64 | |
| { | |
| std::uint64_t value{}; | |
| return get_number<std::uint64_t, true>(value) && emit_unsigned(value); | |
| } | |
| default: // anything else is not supported (yet) | |
| { | |
| return bson_unsupported_type_error(element_type_parse_position, element_type); | |
| } | |
| } | |
| } | |
| ////////// | |
| // CBOR // | |
| ////////// | |
| template<typename NumberType> | |
| bool get_cbor_negative_integer() | |
| { | |
| NumberType number{}; | |
| if (JSON_HEDLEY_UNLIKELY(!get_number(number))) | |
| { | |
| return false; | |
| } | |
| // the value is -1 - number, which fits into number_integer_t | |
| // whenever number does; the outer cast undoes the integral promotion | |
| // for number_integer_t types narrower than int | |
| if (JSON_HEDLEY_LIKELY(value_in_range_of<number_integer_t>(number))) | |
| { | |
| return sax->number_integer(conditional_static_cast<number_integer_t>(static_cast<number_integer_t>(-1) - static_cast<number_integer_t>(number))); | |
| } | |
| // like the lexer does for JSON text, store a value too small for | |
| // number_integer_t as number_float_t; compute it as long double so | |
| // that emit_float sees a finite value and can detect an overflow of | |
| // number_float_t | |
| return emit_float(static_cast<long double>(-1) - static_cast<long double>(number)); | |
| } | |
| /*! | |
| @param[in] get_char whether a new character should be retrieved from the | |
| input (true) or whether the last read character should | |
| be considered instead (false) | |
| @param[in] tag_handler how CBOR tags should be treated | |
| @param[out] tag_pending whether a tag was parsed and its value follows | |
| @param[out] item_read whether the tagged value's initial byte is already in current | |
| @return whether a valid CBOR value was passed to the SAX parser | |
| */ | |
| bool parse_cbor_value(const bool get_char, | |
| const cbor_tag_handler_t tag_handler, | |
| bool& tag_pending, | |
| bool& item_read) | |
| { | |
| tag_pending = false; | |
| item_read = false; | |
| switch (get_char ? get() : current) | |
| { | |
| // EOF | |
| case char_traits<char_type>::eof(): | |
| return unexpect_eof("value"); | |
| // Integer 0x00..0x17 (0..23) | |
| case 0x00: | |
| case 0x01: | |
| case 0x02: | |
| case 0x03: | |
| case 0x04: | |
| case 0x05: | |
| case 0x06: | |
| case 0x07: | |
| case 0x08: | |
| case 0x09: | |
| case 0x0A: | |
| case 0x0B: | |
| case 0x0C: | |
| case 0x0D: | |
| case 0x0E: | |
| case 0x0F: | |
| case 0x10: | |
| case 0x11: | |
| case 0x12: | |
| case 0x13: | |
| case 0x14: | |
| case 0x15: | |
| case 0x16: | |
| case 0x17: | |
| return sax->number_unsigned(static_cast<number_unsigned_t>(current)); | |
| case 0x18: // Unsigned integer (one-byte uint8_t follows) | |
| { | |
| std::uint8_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| case 0x19: // Unsigned integer (two-byte uint16_t follows) | |
| { | |
| std::uint16_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| case 0x1A: // Unsigned integer (four-byte uint32_t follows) | |
| { | |
| std::uint32_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| case 0x1B: // Unsigned integer (eight-byte uint64_t follows) | |
| { | |
| std::uint64_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| // Negative integer -1-0x00..-1-0x17 (-1..-24) | |
| case 0x20: | |
| case 0x21: | |
| case 0x22: | |
| case 0x23: | |
| case 0x24: | |
| case 0x25: | |
| case 0x26: | |
| case 0x27: | |
| case 0x28: | |
| case 0x29: | |
| case 0x2A: | |
| case 0x2B: | |
| case 0x2C: | |
| case 0x2D: | |
| case 0x2E: | |
| case 0x2F: | |
| case 0x30: | |
| case 0x31: | |
| case 0x32: | |
| case 0x33: | |
| case 0x34: | |
| case 0x35: | |
| case 0x36: | |
| case 0x37: | |
| return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current)); | |
| case 0x38: // Negative integer (one-byte uint8_t follows) | |
| return get_cbor_negative_integer<std::uint8_t>(); | |
| case 0x39: // Negative integer -1-n (two-byte uint16_t follows) | |
| return get_cbor_negative_integer<std::uint16_t>(); | |
| case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) | |
| return get_cbor_negative_integer<std::uint32_t>(); | |
| case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) | |
| return get_cbor_negative_integer<std::uint64_t>(); | |
| // Binary data (0x00..0x17 bytes follow) | |
| case 0x40: | |
| case 0x41: | |
| case 0x42: | |
| case 0x43: | |
| case 0x44: | |
| case 0x45: | |
| case 0x46: | |
| case 0x47: | |
| case 0x48: | |
| case 0x49: | |
| case 0x4A: | |
| case 0x4B: | |
| case 0x4C: | |
| case 0x4D: | |
| case 0x4E: | |
| case 0x4F: | |
| case 0x50: | |
| case 0x51: | |
| case 0x52: | |
| case 0x53: | |
| case 0x54: | |
| case 0x55: | |
| case 0x56: | |
| case 0x57: | |
| case 0x58: // Binary data (one-byte uint8_t for n follows) | |
| case 0x59: // Binary data (two-byte uint16_t for n follow) | |
| case 0x5A: // Binary data (four-byte uint32_t for n follow) | |
| case 0x5B: // Binary data (eight-byte uint64_t for n follow) | |
| case 0x5F: // Binary data (indefinite length) | |
| { | |
| binary_t b; | |
| return get_cbor_binary(b) && sax->binary(b); | |
| } | |
| // UTF-8 string (0x00..0x17 bytes follow) | |
| case 0x60: | |
| case 0x61: | |
| case 0x62: | |
| case 0x63: | |
| case 0x64: | |
| case 0x65: | |
| case 0x66: | |
| case 0x67: | |
| case 0x68: | |
| case 0x69: | |
| case 0x6A: | |
| case 0x6B: | |
| case 0x6C: | |
| case 0x6D: | |
| case 0x6E: | |
| case 0x6F: | |
| case 0x70: | |
| case 0x71: | |
| case 0x72: | |
| case 0x73: | |
| case 0x74: | |
| case 0x75: | |
| case 0x76: | |
| case 0x77: | |
| case 0x78: // UTF-8 string (one-byte uint8_t for n follows) | |
| case 0x79: // UTF-8 string (two-byte uint16_t for n follow) | |
| case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) | |
| case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) | |
| case 0x7F: // UTF-8 string (indefinite length) | |
| { | |
| string_t s; | |
| return get_cbor_string(s) && sax->string(s); | |
| } | |
| // array (0x00..0x17 data items follow) | |
| case 0x80: | |
| case 0x81: | |
| case 0x82: | |
| case 0x83: | |
| case 0x84: | |
| case 0x85: | |
| case 0x86: | |
| case 0x87: | |
| case 0x88: | |
| case 0x89: | |
| case 0x8A: | |
| case 0x8B: | |
| case 0x8C: | |
| case 0x8D: | |
| case 0x8E: | |
| case 0x8F: | |
| case 0x90: | |
| case 0x91: | |
| case 0x92: | |
| case 0x93: | |
| case 0x94: | |
| case 0x95: | |
| case 0x96: | |
| case 0x97: | |
| return enter_array(conditional_static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu)); | |
| case 0x98: // array (one-byte uint8_t for n follows) | |
| case 0x99: // array (two-byte uint16_t for n follow) | |
| case 0x9A: // array (four-byte uint32_t for n follow) | |
| case 0x9B: // array (eight-byte uint64_t for n follow) | |
| { | |
| std::uint64_t len{}; | |
| std::size_t size{}; | |
| return get_cbor_argument(len) && get_cbor_container_size(len, size, "array") && enter_array(size); | |
| } | |
| case 0x9F: // array (indefinite length) | |
| return enter_array(detail::unknown_size()); | |
| // map (0x00..0x17 pairs of data items follow) | |
| case 0xA0: | |
| case 0xA1: | |
| case 0xA2: | |
| case 0xA3: | |
| case 0xA4: | |
| case 0xA5: | |
| case 0xA6: | |
| case 0xA7: | |
| case 0xA8: | |
| case 0xA9: | |
| case 0xAA: | |
| case 0xAB: | |
| case 0xAC: | |
| case 0xAD: | |
| case 0xAE: | |
| case 0xAF: | |
| case 0xB0: | |
| case 0xB1: | |
| case 0xB2: | |
| case 0xB3: | |
| case 0xB4: | |
| case 0xB5: | |
| case 0xB6: | |
| case 0xB7: | |
| return enter_object(conditional_static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu)); | |
| case 0xB8: // map (one-byte uint8_t for n follows) | |
| case 0xB9: // map (two-byte uint16_t for n follow) | |
| case 0xBA: // map (four-byte uint32_t for n follow) | |
| case 0xBB: // map (eight-byte uint64_t for n follow) | |
| { | |
| std::uint64_t len{}; | |
| std::size_t size{}; | |
| return get_cbor_argument(len) && get_cbor_container_size(len, size, "map") && enter_object(size); | |
| } | |
| case 0xBF: // map (indefinite length) | |
| return enter_object(detail::unknown_size()); | |
| case 0xC0: // tagged item (tag value 0-23, in the head itself) | |
| case 0xC1: | |
| case 0xC2: | |
| case 0xC3: | |
| case 0xC4: | |
| case 0xC5: | |
| case 0xC6: | |
| case 0xC7: | |
| case 0xC8: | |
| case 0xC9: | |
| case 0xCA: | |
| case 0xCB: | |
| case 0xCC: | |
| case 0xCD: | |
| case 0xCE: | |
| case 0xCF: | |
| case 0xD0: | |
| case 0xD1: | |
| case 0xD2: | |
| case 0xD3: | |
| case 0xD4: | |
| case 0xD5: | |
| case 0xD6: | |
| case 0xD7: | |
| { | |
| if (tag_handler == cbor_tag_handler_t::error) | |
| { | |
| return unexpected_byte("invalid byte", "value"); | |
| } | |
| // ignore and store: the tag value is already in the head, so | |
| // there is nothing left to read here; the tagged value that | |
| // follows is read by the loop in parse_cbor_internal() rather | |
| // than by recursing here | |
| tag_pending = true; | |
| return true; | |
| } | |
| case 0xD8: // tagged item (1 byte follows) | |
| case 0xD9: // tagged item (2 bytes follow) | |
| case 0xDA: // tagged item (4 bytes follow) | |
| case 0xDB: // tagged item (8 bytes follow) | |
| { | |
| switch (tag_handler) | |
| { | |
| case cbor_tag_handler_t::error: | |
| { | |
| return unexpected_byte("invalid byte", "value"); | |
| } | |
| case cbor_tag_handler_t::ignore: | |
| { | |
| // ignore the tag's binary subtype argument | |
| std::uint64_t subtype_to_ignore{}; | |
| if (!get_cbor_argument(subtype_to_ignore)) | |
| { | |
| return false; | |
| } | |
| // the tagged value follows; it is read by the loop in | |
| // parse_cbor_internal() rather than by recursing here | |
| tag_pending = true; | |
| return true; | |
| } | |
| case cbor_tag_handler_t::store: | |
| { | |
| // use binary subtype and store in a binary container | |
| std::uint64_t subtype{}; | |
| if (!get_cbor_argument(subtype)) | |
| { | |
| return false; | |
| } | |
| binary_t b; | |
| b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype)); | |
| get(); | |
| // a byte string (the heads accepted by get_cbor_binary) keeps the tag as subtype | |
| if ((current >= 0x40 && current <= 0x5B) || current == 0x5F) | |
| { | |
| return get_cbor_binary(b) && sax->binary(b); | |
| } | |
| // not a byte string: the tagged value, whose first byte | |
| // was just read, is read by the caller like for ignore | |
| tag_pending = true; | |
| item_read = true; | |
| return true; | |
| } | |
| default: // LCOV_EXCL_LINE | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE | |
| return false; // LCOV_EXCL_LINE | |
| } | |
| } | |
| case 0xF4: // false | |
| return sax->boolean(false); | |
| case 0xF5: // true | |
| return sax->boolean(true); | |
| case 0xF6: // null | |
| return sax->null(); | |
| case 0xF9: // Half-Precision Float (two-byte IEEE 754) | |
| return get_half_float(false); | |
| case 0xFA: // Single-Precision Float (four-byte IEEE 754) | |
| { | |
| float number{}; | |
| return get_number(number) && emit_float(number); | |
| } | |
| case 0xFB: // Double-Precision Float (eight-byte IEEE 754) | |
| { | |
| double number{}; | |
| return get_number(number) && emit_float(number); | |
| } | |
| default: // anything else (0xFF is handled inside the other types) | |
| { | |
| return unexpected_byte("invalid byte", "value"); | |
| } | |
| } | |
| } | |
| /*! | |
| @brief reports a nested indefinite-length CBOR string or byte array | |
| @param[in] type_name name of the rejected string type | |
| @param[in] context parsing context for the error message | |
| @return whether the SAX consumer accepts the parse error | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| bool cbor_indefinite_string_error(const char* type_name, const char* context) | |
| { | |
| return last_byte_error(exception_id::invalid_string_or_size, concat("indefinite-length ", type_name, " is not allowed inside indefinite-length ", type_name, "; last byte: 0x", get_token_string()), context); | |
| } | |
| /*! | |
| @brief report an object key that is not a string | |
| @param[in] found description of what was found instead of a string key | |
| @return false | |
| */ | |
| bool unsupported_key_type(const char* found) const | |
| { | |
| return last_byte_error(exception_id::invalid_string_or_size, "only string keys are supported, but found ", "object key", found); | |
| } | |
| /*! | |
| @brief read the length of a CBOR string or byte array and then its bytes | |
| @tparam NumberType the type of the length field | |
| @tparam ContainerType the destination container (string_t or binary_t) | |
| @param[in] context further context information (for diagnostics) | |
| @param[out] result container the bytes are appended to | |
| @return whether reading completed | |
| */ | |
| template<typename NumberType, typename ContainerType> | |
| bool get_cbor_sized_bytes(const char* context, ContainerType& result) | |
| { | |
| NumberType len{}; | |
| return get_number(len) && get_bytes(len, context, result); | |
| } | |
| /*! | |
| @brief reads a definite-length CBOR string | |
| Reads everything @ref get_cbor_string accepts except the indefinite-length | |
| form, which that function handles itself. The bytes are appended to @a | |
| result, so consecutive chunks of an indefinite-length string can be read | |
| into the same string. | |
| @param[out] result string the bytes are appended to | |
| @param[in] inside_indefinite whether the bytes belong to an indefinite-length string | |
| @return whether string creation completed | |
| @pre @a current is not EOF | |
| */ | |
| bool get_cbor_string_chunk(string_t& result, const bool inside_indefinite) | |
| { | |
| switch (current) | |
| { | |
| // UTF-8 string (0x00..0x17 bytes follow) | |
| case 0x60: | |
| case 0x61: | |
| case 0x62: | |
| case 0x63: | |
| case 0x64: | |
| case 0x65: | |
| case 0x66: | |
| case 0x67: | |
| case 0x68: | |
| case 0x69: | |
| case 0x6A: | |
| case 0x6B: | |
| case 0x6C: | |
| case 0x6D: | |
| case 0x6E: | |
| case 0x6F: | |
| case 0x70: | |
| case 0x71: | |
| case 0x72: | |
| case 0x73: | |
| case 0x74: | |
| case 0x75: | |
| case 0x76: | |
| case 0x77: | |
| { | |
| return get_string(static_cast<unsigned int>(current) & 0x1Fu, result); | |
| } | |
| case 0x78: // UTF-8 string (one-byte uint8_t for n follows) | |
| { | |
| return get_cbor_sized_bytes<std::uint8_t>("string", result); | |
| } | |
| case 0x79: // UTF-8 string (two-byte uint16_t for n follow) | |
| { | |
| return get_cbor_sized_bytes<std::uint16_t>("string", result); | |
| } | |
| case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) | |
| { | |
| return get_cbor_sized_bytes<std::uint32_t>("string", result); | |
| } | |
| case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) | |
| { | |
| return get_cbor_sized_bytes<std::uint64_t>("string", result); | |
| } | |
| default: | |
| { | |
| return last_byte_error(exception_id::invalid_string_or_size, "expected length specification (0x60-0x7B)", "string", inside_indefinite ? "" : " or indefinite string type (0x7F)"); | |
| } | |
| } | |
| } | |
| /*! | |
| @brief reads a CBOR string | |
| This function first reads starting bytes to determine the expected | |
| string length and then copies this number of bytes into a string. | |
| Additionally, CBOR's strings with indefinite lengths are supported. | |
| @param[out] result created string | |
| @return whether string creation completed | |
| */ | |
| bool get_cbor_string(string_t& result, const char* context = "string") | |
| { | |
| // read chunks iteratively, but reject a second indefinite-length | |
| // level as required by RFC 8949, Section 3.2.3 | |
| bool indefinite = false; | |
| while (true) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("string"))) | |
| { | |
| return false; | |
| } | |
| if (current == 0x7F) // UTF-8 string (indefinite length) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(indefinite)) | |
| { | |
| return cbor_indefinite_string_error("string", "string"); | |
| } | |
| indefinite = true; | |
| get(); | |
| continue; | |
| } | |
| // a break marker closes the indefinite-length string; outside | |
| // of one it falls through to the error below | |
| if (indefinite && current == 0xFF) | |
| { | |
| return check_string_utf8(result, context); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!get_cbor_string_chunk(result, indefinite))) | |
| { | |
| return false; | |
| } | |
| if (!indefinite) | |
| { | |
| return check_string_utf8(result, context); | |
| } | |
| get(); | |
| } | |
| } | |
| /*! | |
| @brief reads a CBOR object key | |
| RFC 8949 allows any data item as a map key, but only strings have a | |
| counterpart in JSON. A key of any other type is rejected with a message | |
| naming that type, rather than the one @ref get_cbor_string gives for a | |
| malformed string. | |
| @param[out] result created key | |
| @return whether key creation completed | |
| */ | |
| bool get_cbor_object_key(string_t& result) | |
| { | |
| // EOF and major type 3 (text string) are left to get_cbor_string | |
| if (current == char_traits<char_type>::eof() || (static_cast<unsigned int>(current) & 0xE0u) == 0x60u) | |
| { | |
| return get_cbor_string(result, "key"); | |
| } | |
| const char* found = nullptr; | |
| switch (static_cast<unsigned int>(current) >> 5u) | |
| { | |
| case 0: | |
| found = "an unsigned integer"; | |
| break; | |
| case 1: | |
| found = "a negative integer"; | |
| break; | |
| case 2: | |
| found = "a byte string"; | |
| break; | |
| case 4: | |
| found = "an array"; | |
| break; | |
| case 5: | |
| found = "a map"; | |
| break; | |
| case 6: | |
| found = "a tag"; | |
| break; | |
| default: // major type 7 | |
| switch (current) | |
| { | |
| case 0xF4: | |
| case 0xF5: | |
| found = "a boolean"; | |
| break; | |
| case 0xF6: | |
| found = "null"; | |
| break; | |
| case 0xF7: | |
| found = "undefined"; | |
| break; | |
| case 0xF9: | |
| case 0xFA: | |
| case 0xFB: | |
| found = "a floating-point number"; | |
| break; | |
| case 0xFF: | |
| found = "a break stop code"; | |
| break; | |
| default: | |
| found = "a simple value"; | |
| break; | |
| } | |
| break; | |
| } | |
| return unsupported_key_type(found); | |
| } | |
| /*! | |
| @brief reads a definite-length CBOR byte array | |
| Reads everything @ref get_cbor_binary accepts except the indefinite-length | |
| form, which that function handles itself. The bytes are appended to @a | |
| result, so consecutive chunks of an indefinite-length byte array can be | |
| read into the same byte array. | |
| @param[out] result byte array the bytes are appended to | |
| @param[in] inside_indefinite whether the bytes belong to an indefinite-length string | |
| @return whether byte array creation completed | |
| @pre @a current is not EOF | |
| */ | |
| bool get_cbor_binary_chunk(binary_t& result, const bool inside_indefinite) | |
| { | |
| switch (current) | |
| { | |
| // Binary data (0x00..0x17 bytes follow) | |
| case 0x40: | |
| case 0x41: | |
| case 0x42: | |
| case 0x43: | |
| case 0x44: | |
| case 0x45: | |
| case 0x46: | |
| case 0x47: | |
| case 0x48: | |
| case 0x49: | |
| case 0x4A: | |
| case 0x4B: | |
| case 0x4C: | |
| case 0x4D: | |
| case 0x4E: | |
| case 0x4F: | |
| case 0x50: | |
| case 0x51: | |
| case 0x52: | |
| case 0x53: | |
| case 0x54: | |
| case 0x55: | |
| case 0x56: | |
| case 0x57: | |
| { | |
| return get_binary(static_cast<unsigned int>(current) & 0x1Fu, result); | |
| } | |
| case 0x58: // Binary data (one-byte uint8_t for n follows) | |
| { | |
| return get_cbor_sized_bytes<std::uint8_t>("binary", result); | |
| } | |
| case 0x59: // Binary data (two-byte uint16_t for n follow) | |
| { | |
| return get_cbor_sized_bytes<std::uint16_t>("binary", result); | |
| } | |
| case 0x5A: // Binary data (four-byte uint32_t for n follow) | |
| { | |
| return get_cbor_sized_bytes<std::uint32_t>("binary", result); | |
| } | |
| case 0x5B: // Binary data (eight-byte uint64_t for n follow) | |
| { | |
| return get_cbor_sized_bytes<std::uint64_t>("binary", result); | |
| } | |
| default: | |
| { | |
| return last_byte_error(exception_id::invalid_string_or_size, "expected length specification (0x40-0x5B)", "binary", inside_indefinite ? "" : " or indefinite binary array type (0x5F)"); | |
| } | |
| } | |
| } | |
| /*! | |
| @brief reads a CBOR byte array | |
| This function first reads starting bytes to determine the expected | |
| byte array length and then copies this number of bytes into the byte array. | |
| Additionally, CBOR's byte arrays with indefinite lengths are supported. | |
| @param[out] result created byte array | |
| @return whether byte array creation completed | |
| */ | |
| bool get_cbor_binary(binary_t& result) | |
| { | |
| // read chunks iteratively, but reject a second indefinite-length | |
| // level as required by RFC 8949, Section 3.2.3 | |
| bool indefinite = false; | |
| while (true) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("binary"))) | |
| { | |
| return false; | |
| } | |
| if (current == 0x5F) // Binary data (indefinite length) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(indefinite)) | |
| { | |
| return cbor_indefinite_string_error("binary array", "binary"); | |
| } | |
| indefinite = true; | |
| get(); | |
| continue; | |
| } | |
| // a break marker closes the indefinite-length string; outside | |
| // of one it falls through to the error below | |
| if (indefinite && current == 0xFF) | |
| { | |
| return true; | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!get_cbor_binary_chunk(result, indefinite))) | |
| { | |
| return false; | |
| } | |
| if (!indefinite) | |
| { | |
| return true; | |
| } | |
| get(); | |
| } | |
| } | |
| /*! | |
| @brief read a CBOR argument (additional information 24-27) of the width | |
| @ref current announces | |
| The lower 5 bits of @a current (0x18-0x1B) select a 1/2/4/8-byte | |
| big-endian unsigned integer that follows the head byte; this is shared by | |
| every major type that uses this encoding (unsigned/negative integers, | |
| strings, arrays, maps, tags). Reading always goes through @ref get_number, | |
| so EOF is reported the same way as before this helper existed. | |
| @param[out] value the decoded argument | |
| @return whether reading succeeded | |
| */ | |
| bool get_cbor_argument(std::uint64_t& value) | |
| { | |
| switch (current & 0x1F) | |
| { | |
| case 0x18: // 1 byte | |
| { | |
| std::uint8_t n{}; | |
| if (JSON_HEDLEY_UNLIKELY(!get_number(n))) | |
| { | |
| return false; | |
| } | |
| value = n; | |
| return true; | |
| } | |
| case 0x19: // 2 bytes | |
| { | |
| std::uint16_t n{}; | |
| if (JSON_HEDLEY_UNLIKELY(!get_number(n))) | |
| { | |
| return false; | |
| } | |
| value = n; | |
| return true; | |
| } | |
| case 0x1A: // 4 bytes | |
| { | |
| std::uint32_t n{}; | |
| if (JSON_HEDLEY_UNLIKELY(!get_number(n))) | |
| { | |
| return false; | |
| } | |
| value = n; | |
| return true; | |
| } | |
| case 0x1B: // 8 bytes | |
| { | |
| std::uint64_t n{}; | |
| if (JSON_HEDLEY_UNLIKELY(!get_number(n))) | |
| { | |
| return false; | |
| } | |
| value = n; | |
| return true; | |
| } | |
| default: // LCOV_EXCL_LINE | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE | |
| return false; // LCOV_EXCL_LINE | |
| } | |
| } | |
| /*! | |
| @brief narrow a definite CBOR array/map length to std::size_t | |
| A definite length is rejected if it does not fit in std::size_t or if it | |
| equals detail::unknown_size(), which is reserved to mark an indefinite- | |
| length container and would otherwise make the length read as indefinite. | |
| Both cases exceed any container's max_size(), so no representable input | |
| is affected. | |
| @param[in] len the declared length | |
| @param[out] result the length narrowed to std::size_t | |
| @param[in] context "array" or "map", for the error message | |
| @return whether the length is usable | |
| */ | |
| bool get_cbor_container_size(const std::uint64_t len, std::size_t& result, const char* context) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!value_in_range_of<std::size_t>(len) || len == detail::unknown_size())) | |
| { | |
| return container_size_error(context); | |
| } | |
| result = conditional_static_cast<std::size_t>(len); | |
| return true; | |
| } | |
| /*! | |
| @brief read a CBOR value and everything nested inside it | |
| Reads values until the one that was begun here is complete, resuming the | |
| enclosing container after each element, so that the nesting depth of the | |
| input costs heap rather than native stack (see #5104). | |
| @param[in] tag_handler how CBOR tags should be treated | |
| @return whether reading the value succeeded | |
| */ | |
| bool parse_cbor_internal(const cbor_tag_handler_t tag_handler) | |
| { | |
| // whether the next value starts at a fresh byte or at the one already | |
| // read into `current` | |
| bool fetch = true; | |
| // the key currently being read; hoisted out of the loop so that its | |
| // capacity is reused across elements and across nesting levels | |
| string_t key; | |
| while (true) | |
| { | |
| if (!container_stack.empty()) | |
| { | |
| // a copy, not a reference: it must stay valid across the | |
| // pop_back() below, which destroys the container_stack element | |
| // it would otherwise alias | |
| const container_frame top = container_stack.back(); | |
| bool at_end = false; | |
| if (top.remaining != npos) | |
| { | |
| // definite length: the container ends once its elements | |
| // have been read | |
| at_end = (top.remaining == 0); | |
| if (!at_end) | |
| { | |
| // claim the element about to be read | |
| --container_stack.back().remaining; | |
| if (top.is_object) | |
| { | |
| get(); | |
| } | |
| } | |
| fetch = true; | |
| } | |
| else | |
| { | |
| // indefinite length: the container ends at a break marker. | |
| // Testing for it consumes a byte, which is the first byte | |
| // of the next element when it is not one. | |
| at_end = (get() == 0xFF); | |
| fetch = top.is_object; | |
| } | |
| if (at_end) | |
| { | |
| bool value_complete = false; | |
| if (JSON_HEDLEY_UNLIKELY(!leave_container_and_check(value_complete))) | |
| { | |
| return false; | |
| } | |
| if (value_complete) | |
| { | |
| return true; | |
| } | |
| continue; | |
| } | |
| if (top.is_object) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!read_object_key<&binary_reader::get_cbor_object_key>(key))) | |
| { | |
| return false; | |
| } | |
| fetch = true; | |
| } | |
| } | |
| // a tag is not a value of its own: read on until the tagged value | |
| bool tag_pending = false; | |
| bool item_read = false; | |
| do | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!parse_cbor_value(fetch, tag_handler, tag_pending, item_read))) | |
| { | |
| return false; | |
| } | |
| fetch = !item_read; | |
| } | |
| while (tag_pending); | |
| // a value that opened a container left it on the stack; one that | |
| // did not, and that was not inside a container, was the whole value | |
| if (container_stack.empty()) | |
| { | |
| return true; | |
| } | |
| } | |
| } | |
| ///////////// | |
| // MsgPack // | |
| ///////////// | |
| /*! | |
| @brief read one MessagePack value | |
| Reads a single value and passes it to the SAX parser. A value that begins | |
| a container is not read to its end: the container is opened with | |
| @ref enter_container and its elements are read by | |
| @ref parse_msgpack_internal, so that nesting does not consume native stack. | |
| @return whether reading the value succeeded | |
| */ | |
| bool parse_msgpack_value() | |
| { | |
| switch (get()) | |
| { | |
| // EOF | |
| case char_traits<char_type>::eof(): | |
| return unexpect_eof("value"); | |
| // positive fixint | |
| case 0x00: | |
| case 0x01: | |
| case 0x02: | |
| case 0x03: | |
| case 0x04: | |
| case 0x05: | |
| case 0x06: | |
| case 0x07: | |
| case 0x08: | |
| case 0x09: | |
| case 0x0A: | |
| case 0x0B: | |
| case 0x0C: | |
| case 0x0D: | |
| case 0x0E: | |
| case 0x0F: | |
| case 0x10: | |
| case 0x11: | |
| case 0x12: | |
| case 0x13: | |
| case 0x14: | |
| case 0x15: | |
| case 0x16: | |
| case 0x17: | |
| case 0x18: | |
| case 0x19: | |
| case 0x1A: | |
| case 0x1B: | |
| case 0x1C: | |
| case 0x1D: | |
| case 0x1E: | |
| case 0x1F: | |
| case 0x20: | |
| case 0x21: | |
| case 0x22: | |
| case 0x23: | |
| case 0x24: | |
| case 0x25: | |
| case 0x26: | |
| case 0x27: | |
| case 0x28: | |
| case 0x29: | |
| case 0x2A: | |
| case 0x2B: | |
| case 0x2C: | |
| case 0x2D: | |
| case 0x2E: | |
| case 0x2F: | |
| case 0x30: | |
| case 0x31: | |
| case 0x32: | |
| case 0x33: | |
| case 0x34: | |
| case 0x35: | |
| case 0x36: | |
| case 0x37: | |
| case 0x38: | |
| case 0x39: | |
| case 0x3A: | |
| case 0x3B: | |
| case 0x3C: | |
| case 0x3D: | |
| case 0x3E: | |
| case 0x3F: | |
| case 0x40: | |
| case 0x41: | |
| case 0x42: | |
| case 0x43: | |
| case 0x44: | |
| case 0x45: | |
| case 0x46: | |
| case 0x47: | |
| case 0x48: | |
| case 0x49: | |
| case 0x4A: | |
| case 0x4B: | |
| case 0x4C: | |
| case 0x4D: | |
| case 0x4E: | |
| case 0x4F: | |
| case 0x50: | |
| case 0x51: | |
| case 0x52: | |
| case 0x53: | |
| case 0x54: | |
| case 0x55: | |
| case 0x56: | |
| case 0x57: | |
| case 0x58: | |
| case 0x59: | |
| case 0x5A: | |
| case 0x5B: | |
| case 0x5C: | |
| case 0x5D: | |
| case 0x5E: | |
| case 0x5F: | |
| case 0x60: | |
| case 0x61: | |
| case 0x62: | |
| case 0x63: | |
| case 0x64: | |
| case 0x65: | |
| case 0x66: | |
| case 0x67: | |
| case 0x68: | |
| case 0x69: | |
| case 0x6A: | |
| case 0x6B: | |
| case 0x6C: | |
| case 0x6D: | |
| case 0x6E: | |
| case 0x6F: | |
| case 0x70: | |
| case 0x71: | |
| case 0x72: | |
| case 0x73: | |
| case 0x74: | |
| case 0x75: | |
| case 0x76: | |
| case 0x77: | |
| case 0x78: | |
| case 0x79: | |
| case 0x7A: | |
| case 0x7B: | |
| case 0x7C: | |
| case 0x7D: | |
| case 0x7E: | |
| case 0x7F: | |
| return sax->number_unsigned(static_cast<number_unsigned_t>(current)); | |
| // fixmap | |
| case 0x80: | |
| case 0x81: | |
| case 0x82: | |
| case 0x83: | |
| case 0x84: | |
| case 0x85: | |
| case 0x86: | |
| case 0x87: | |
| case 0x88: | |
| case 0x89: | |
| case 0x8A: | |
| case 0x8B: | |
| case 0x8C: | |
| case 0x8D: | |
| case 0x8E: | |
| case 0x8F: | |
| return enter_object(conditional_static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu)); | |
| // fixarray | |
| case 0x90: | |
| case 0x91: | |
| case 0x92: | |
| case 0x93: | |
| case 0x94: | |
| case 0x95: | |
| case 0x96: | |
| case 0x97: | |
| case 0x98: | |
| case 0x99: | |
| case 0x9A: | |
| case 0x9B: | |
| case 0x9C: | |
| case 0x9D: | |
| case 0x9E: | |
| case 0x9F: | |
| return enter_array(conditional_static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu)); | |
| // fixstr | |
| case 0xA0: | |
| case 0xA1: | |
| case 0xA2: | |
| case 0xA3: | |
| case 0xA4: | |
| case 0xA5: | |
| case 0xA6: | |
| case 0xA7: | |
| case 0xA8: | |
| case 0xA9: | |
| case 0xAA: | |
| case 0xAB: | |
| case 0xAC: | |
| case 0xAD: | |
| case 0xAE: | |
| case 0xAF: | |
| case 0xB0: | |
| case 0xB1: | |
| case 0xB2: | |
| case 0xB3: | |
| case 0xB4: | |
| case 0xB5: | |
| case 0xB6: | |
| case 0xB7: | |
| case 0xB8: | |
| case 0xB9: | |
| case 0xBA: | |
| case 0xBB: | |
| case 0xBC: | |
| case 0xBD: | |
| case 0xBE: | |
| case 0xBF: | |
| case 0xD9: // str 8 | |
| case 0xDA: // str 16 | |
| case 0xDB: // str 32 | |
| { | |
| string_t s; | |
| return get_msgpack_string(s) && sax->string(s); | |
| } | |
| case 0xC0: // nil | |
| return sax->null(); | |
| case 0xC2: // false | |
| return sax->boolean(false); | |
| case 0xC3: // true | |
| return sax->boolean(true); | |
| case 0xC4: // bin 8 | |
| case 0xC5: // bin 16 | |
| case 0xC6: // bin 32 | |
| case 0xC7: // ext 8 | |
| case 0xC8: // ext 16 | |
| case 0xC9: // ext 32 | |
| case 0xD4: // fixext 1 | |
| case 0xD5: // fixext 2 | |
| case 0xD6: // fixext 4 | |
| case 0xD7: // fixext 8 | |
| case 0xD8: // fixext 16 | |
| { | |
| binary_t b; | |
| return get_msgpack_binary(b) && sax->binary(b); | |
| } | |
| case 0xCA: // float 32 | |
| { | |
| float number{}; | |
| return get_number(number) && emit_float(number); | |
| } | |
| case 0xCB: // float 64 | |
| { | |
| double number{}; | |
| return get_number(number) && emit_float(number); | |
| } | |
| case 0xCC: // uint 8 | |
| { | |
| std::uint8_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| case 0xCD: // uint 16 | |
| { | |
| std::uint16_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| case 0xCE: // uint 32 | |
| { | |
| std::uint32_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| case 0xCF: // uint 64 | |
| { | |
| std::uint64_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| case 0xD0: // int 8 | |
| { | |
| std::int8_t number{}; | |
| return get_number(number) && emit_signed(number); | |
| } | |
| case 0xD1: // int 16 | |
| { | |
| std::int16_t number{}; | |
| return get_number(number) && emit_signed(number); | |
| } | |
| case 0xD2: // int 32 | |
| { | |
| std::int32_t number{}; | |
| return get_number(number) && emit_signed(number); | |
| } | |
| case 0xD3: // int 64 | |
| { | |
| std::int64_t number{}; | |
| return get_number(number) && emit_signed(number); | |
| } | |
| case 0xDC: // array 16 | |
| { | |
| std::uint16_t len{}; | |
| return get_number(len) && enter_array(static_cast<std::size_t>(len)); | |
| } | |
| case 0xDD: // array 32 | |
| { | |
| std::uint32_t len{}; | |
| return get_number(len) && enter_array(conditional_static_cast<std::size_t>(len)); | |
| } | |
| case 0xDE: // map 16 | |
| { | |
| std::uint16_t len{}; | |
| return get_number(len) && enter_object(static_cast<std::size_t>(len)); | |
| } | |
| case 0xDF: // map 32 | |
| { | |
| std::uint32_t len{}; | |
| return get_number(len) && enter_object(conditional_static_cast<std::size_t>(len)); | |
| } | |
| // negative fixint | |
| case 0xE0: | |
| case 0xE1: | |
| case 0xE2: | |
| case 0xE3: | |
| case 0xE4: | |
| case 0xE5: | |
| case 0xE6: | |
| case 0xE7: | |
| case 0xE8: | |
| case 0xE9: | |
| case 0xEA: | |
| case 0xEB: | |
| case 0xEC: | |
| case 0xED: | |
| case 0xEE: | |
| case 0xEF: | |
| case 0xF0: | |
| case 0xF1: | |
| case 0xF2: | |
| case 0xF3: | |
| case 0xF4: | |
| case 0xF5: | |
| case 0xF6: | |
| case 0xF7: | |
| case 0xF8: | |
| case 0xF9: | |
| case 0xFA: | |
| case 0xFB: | |
| case 0xFC: | |
| case 0xFD: | |
| case 0xFE: | |
| case 0xFF: | |
| return sax->number_integer(static_cast<std::int8_t>(current)); | |
| default: // anything else | |
| { | |
| return unexpected_byte("invalid byte", "value"); | |
| } | |
| } | |
| } | |
| /*! | |
| @brief reads a MessagePack string | |
| This function first reads starting bytes to determine the expected | |
| string length and then copies this number of bytes into a string. | |
| @param[out] result created string | |
| @return whether string creation completed | |
| */ | |
| bool get_msgpack_string(string_t& result, const char* context = "string") | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("string"))) | |
| { | |
| return false; | |
| } | |
| switch (current) | |
| { | |
| // fixstr | |
| case 0xA0: | |
| case 0xA1: | |
| case 0xA2: | |
| case 0xA3: | |
| case 0xA4: | |
| case 0xA5: | |
| case 0xA6: | |
| case 0xA7: | |
| case 0xA8: | |
| case 0xA9: | |
| case 0xAA: | |
| case 0xAB: | |
| case 0xAC: | |
| case 0xAD: | |
| case 0xAE: | |
| case 0xAF: | |
| case 0xB0: | |
| case 0xB1: | |
| case 0xB2: | |
| case 0xB3: | |
| case 0xB4: | |
| case 0xB5: | |
| case 0xB6: | |
| case 0xB7: | |
| case 0xB8: | |
| case 0xB9: | |
| case 0xBA: | |
| case 0xBB: | |
| case 0xBC: | |
| case 0xBD: | |
| case 0xBE: | |
| case 0xBF: | |
| { | |
| return get_string(static_cast<unsigned int>(current) & 0x1Fu, result) && check_string_utf8(result, context); | |
| } | |
| case 0xD9: // str 8 | |
| { | |
| return get_string_with_length<std::uint8_t>(result, context); | |
| } | |
| case 0xDA: // str 16 | |
| { | |
| return get_string_with_length<std::uint16_t>(result, context); | |
| } | |
| case 0xDB: // str 32 | |
| { | |
| return get_string_with_length<std::uint32_t>(result, context); | |
| } | |
| default: | |
| { | |
| return last_byte_error(exception_id::invalid_string_or_size, "expected length specification (0xA0-0xBF, 0xD9-0xDB)", "string", ""); | |
| } | |
| } | |
| } | |
| /*! | |
| @brief reads a MessagePack object key | |
| The MessagePack specification allows any type as a map key, but only | |
| strings have a counterpart in JSON. A key of any other type is rejected | |
| with a message naming that type, rather than the one @ref | |
| get_msgpack_string gives for a malformed string. | |
| @param[out] result created key | |
| @return whether key creation completed | |
| */ | |
| bool get_msgpack_object_key(string_t& result) | |
| { | |
| const char* found = nullptr; | |
| switch (current) | |
| { | |
| case 0xC0: | |
| found = "nil"; | |
| break; | |
| case 0xC2: | |
| case 0xC3: | |
| found = "a boolean"; | |
| break; | |
| case 0xCA: | |
| case 0xCB: | |
| found = "a float"; | |
| break; | |
| case 0xC4: | |
| case 0xC5: | |
| case 0xC6: | |
| found = "a bin"; | |
| break; | |
| case 0xC7: | |
| case 0xC8: | |
| case 0xC9: | |
| case 0xD4: | |
| case 0xD5: | |
| case 0xD6: | |
| case 0xD7: | |
| case 0xD8: | |
| found = "an ext"; | |
| break; | |
| case 0xCC: | |
| case 0xCD: | |
| case 0xCE: | |
| case 0xCF: | |
| case 0xD0: | |
| case 0xD1: | |
| case 0xD2: | |
| case 0xD3: | |
| found = "an integer"; | |
| break; | |
| case 0xDC: | |
| case 0xDD: | |
| found = "an array"; | |
| break; | |
| case 0xDE: | |
| case 0xDF: | |
| found = "a map"; | |
| break; | |
| default: | |
| // fixint, fixmap, and fixarray; strings, EOF, and the unused | |
| // byte 0xC1 are left to get_msgpack_string | |
| if (current == char_traits<char_type>::eof()) | |
| { | |
| return get_msgpack_string(result, "key"); | |
| } | |
| if (current <= 0x7F || current >= 0xE0) | |
| { | |
| found = "an integer"; | |
| } | |
| else if (current <= 0x8F) | |
| { | |
| found = "a map"; | |
| } | |
| else if (current <= 0x9F) | |
| { | |
| found = "an array"; | |
| } | |
| else | |
| { | |
| return get_msgpack_string(result, "key"); | |
| } | |
| break; | |
| } | |
| return unsupported_key_type(found); | |
| } | |
| /*! | |
| @brief reads a MessagePack byte array | |
| This function first reads starting bytes to determine the expected | |
| byte array length and then copies this number of bytes into a byte array. | |
| @param[out] result created byte array | |
| @return whether byte array creation completed | |
| */ | |
| bool get_msgpack_binary(binary_t& result) | |
| { | |
| // helper function to set the subtype | |
| auto assign_and_return_true = [&result](std::int8_t subtype) | |
| { | |
| result.set_subtype(static_cast<std::uint8_t>(subtype)); | |
| return true; | |
| }; | |
| switch (current) | |
| { | |
| case 0xC4: // bin 8 | |
| { | |
| std::uint8_t len{}; | |
| return get_number(len) && | |
| get_binary(len, result); | |
| } | |
| case 0xC5: // bin 16 | |
| { | |
| std::uint16_t len{}; | |
| return get_number(len) && | |
| get_binary(len, result); | |
| } | |
| case 0xC6: // bin 32 | |
| { | |
| std::uint32_t len{}; | |
| return get_number(len) && | |
| get_binary(len, result); | |
| } | |
| case 0xC7: // ext 8 | |
| { | |
| std::uint8_t len{}; | |
| std::int8_t subtype{}; | |
| return get_number(len) && | |
| get_number(subtype) && | |
| get_binary(len, result) && | |
| assign_and_return_true(subtype); | |
| } | |
| case 0xC8: // ext 16 | |
| { | |
| std::uint16_t len{}; | |
| std::int8_t subtype{}; | |
| return get_number(len) && | |
| get_number(subtype) && | |
| get_binary(len, result) && | |
| assign_and_return_true(subtype); | |
| } | |
| case 0xC9: // ext 32 | |
| { | |
| std::uint32_t len{}; | |
| std::int8_t subtype{}; | |
| return get_number(len) && | |
| get_number(subtype) && | |
| get_binary(len, result) && | |
| assign_and_return_true(subtype); | |
| } | |
| case 0xD4: // fixext 1 | |
| { | |
| std::int8_t subtype{}; | |
| return get_number(subtype) && | |
| get_binary(1, result) && | |
| assign_and_return_true(subtype); | |
| } | |
| case 0xD5: // fixext 2 | |
| { | |
| std::int8_t subtype{}; | |
| return get_number(subtype) && | |
| get_binary(2, result) && | |
| assign_and_return_true(subtype); | |
| } | |
| case 0xD6: // fixext 4 | |
| { | |
| std::int8_t subtype{}; | |
| return get_number(subtype) && | |
| get_binary(4, result) && | |
| assign_and_return_true(subtype); | |
| } | |
| case 0xD7: // fixext 8 | |
| { | |
| std::int8_t subtype{}; | |
| return get_number(subtype) && | |
| get_binary(8, result) && | |
| assign_and_return_true(subtype); | |
| } | |
| case 0xD8: // fixext 16 | |
| { | |
| std::int8_t subtype{}; | |
| return get_number(subtype) && | |
| get_binary(16, result) && | |
| assign_and_return_true(subtype); | |
| } | |
| default: // LCOV_EXCL_LINE | |
| return false; // LCOV_EXCL_LINE | |
| } | |
| } | |
| /*! | |
| @brief read a MessagePack value and everything nested inside it | |
| Reads values until the one that was begun here is complete, resuming the | |
| enclosing container each time an element ends, so that the nesting depth | |
| of the input costs heap rather than native stack (see #5104). | |
| @return whether reading the value succeeded | |
| */ | |
| bool parse_msgpack_internal() | |
| { | |
| // the key currently being read; hoisted out of the loop so that its | |
| // capacity is reused across elements and across nesting levels | |
| string_t key; | |
| while (true) | |
| { | |
| if (!container_stack.empty()) | |
| { | |
| // copied out before anything can push onto the stack and | |
| // invalidate a reference into it | |
| const bool is_object = container_stack.back().is_object; | |
| if (container_stack.back().remaining == 0) | |
| { | |
| bool value_complete = false; | |
| if (JSON_HEDLEY_UNLIKELY(!leave_container_and_check(value_complete))) | |
| { | |
| return false; | |
| } | |
| if (value_complete) | |
| { | |
| return true; | |
| } | |
| continue; | |
| } | |
| // claim the element about to be read | |
| --container_stack.back().remaining; | |
| if (is_object) | |
| { | |
| get(); | |
| if (JSON_HEDLEY_UNLIKELY(!read_object_key<&binary_reader::get_msgpack_object_key>(key))) | |
| { | |
| return false; | |
| } | |
| } | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_value())) | |
| { | |
| return false; | |
| } | |
| // a value that opened a container left it on the stack; one that | |
| // did not, and that was not inside a container, was the whole value | |
| if (container_stack.empty()) | |
| { | |
| return true; | |
| } | |
| } | |
| } | |
| //////////// | |
| // UBJSON // | |
| //////////// | |
| /*! | |
| @return whether a valid UBJSON value was passed to the SAX parser | |
| */ | |
| bool parse_ubjson_internal() | |
| { | |
| // the key currently being read; hoisted out of the loop so that its | |
| // capacity is reused across elements and across nesting levels | |
| string_t key; | |
| // the type marker of the value to read next | |
| char_int_type prefix = get_ignore_noop(); | |
| while (true) | |
| { | |
| const std::size_t depth = container_stack.size(); | |
| if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(prefix))) | |
| { | |
| return false; | |
| } | |
| // the value begun here is complete once it is not inside anything | |
| if (container_stack.empty()) | |
| { | |
| return true; | |
| } | |
| // a value was completed rather than a container opened; a | |
| // container that ends at a marker needs the next byte to test | |
| if (container_stack.size() == depth && container_stack.back().remaining == npos) | |
| { | |
| get_ignore_noop(); | |
| } | |
| // advance to the next element, closing the containers that ended. | |
| // top is a copy, not a reference: it must stay valid across the | |
| // pop_back() below, which destroys the container_stack element it | |
| // would otherwise alias. | |
| for (;;) | |
| { | |
| const container_frame top = container_stack.back(); | |
| if (top.remaining != npos) | |
| { | |
| if (top.remaining != 0) | |
| { | |
| --container_stack.back().remaining; | |
| if (top.is_object) | |
| { | |
| key.clear(); | |
| if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, true, "key") || !sax->key(key))) | |
| { | |
| return false; | |
| } | |
| } | |
| // an optimized container gives its elements no marker | |
| prefix = (top.type_marker != 0) ? top.type_marker : get_ignore_noop(); | |
| break; | |
| } | |
| } | |
| // the end marker is compared against a literal rather than | |
| // against a conditional expression, because char_int_type is | |
| // unsigned for some input adapters and MSVC then reports the | |
| // comparison as a signed/unsigned mismatch | |
| else if (top.is_object ? (current != '}') : (current != ']')) | |
| { | |
| // a container that ends at a marker is never optimized, so | |
| // every element carries its own marker; for an object the | |
| // byte tested above is the first byte of the key | |
| if (top.is_object) | |
| { | |
| key.clear(); | |
| if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false, "key") || !sax->key(key))) | |
| { | |
| return false; | |
| } | |
| prefix = get_ignore_noop(); | |
| } | |
| else | |
| { | |
| prefix = current; | |
| } | |
| break; | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!leave_container())) | |
| { | |
| return false; | |
| } | |
| if (container_stack.empty()) | |
| { | |
| return true; | |
| } | |
| // the container that just ended was an element of the one | |
| // below it, which may need the next byte for its own test | |
| if (container_stack.back().remaining == npos) | |
| { | |
| get_ignore_noop(); | |
| } | |
| } | |
| } | |
| } | |
| /*! | |
| @brief reject a negative UBJSON/BJData string length | |
| String and key lengths are written with signed integer markers (i, I, l, | |
| L). A negative value is malformed; without this check get_string() would | |
| silently treat it as an empty string and leave the following bytes to be | |
| misread as the next value. This mirrors the non-negative check the | |
| optimized-container count path already performs in get_ubjson_size_value. | |
| @param[in] len the string length read from the input | |
| @return whether the length is valid (non-negative) | |
| */ | |
| template<typename NumberType> | |
| bool check_ubjson_string_length(const NumberType len) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(len < 0)) | |
| { | |
| return last_byte_error(exception_id::invalid_string_or_size, "string length must not be negative", "string"); | |
| } | |
| return true; | |
| } | |
| /*! | |
| @brief reads a UBJSON string | |
| This function is either called after reading the 'S' byte explicitly | |
| indicating a string, or in case of an object key where the 'S' byte can be | |
| left out. | |
| @param[out] result created string | |
| @param[in] get_char whether a new character should be retrieved from the | |
| input (true, default) or whether the last read | |
| character should be considered instead | |
| @return whether string creation completed | |
| */ | |
| bool get_ubjson_string(string_t& result, const bool get_char = true, const char* context = "string") | |
| { | |
| if (get_char) | |
| { | |
| // no get_ignore_noop() here: the byte read next must be a string | |
| // length type specification, and a no-op ('N') is not valid in | |
| // that position. No-ops at positions where a value may appear are | |
| // already consumed by the callers via get_ignore_noop(). | |
| get(); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("value"))) | |
| { | |
| return false; | |
| } | |
| switch (current) | |
| { | |
| case 'U': | |
| { | |
| return get_string_with_length<std::uint8_t>(result, context); | |
| } | |
| case 'i': | |
| { | |
| std::int8_t len{}; | |
| return get_number(len) && check_ubjson_string_length(len) && get_string(len, result) && check_string_utf8(result, context); | |
| } | |
| case 'I': | |
| { | |
| std::int16_t len{}; | |
| return get_number(len) && check_ubjson_string_length(len) && get_string(len, result) && check_string_utf8(result, context); | |
| } | |
| case 'l': | |
| { | |
| std::int32_t len{}; | |
| return get_number(len) && check_ubjson_string_length(len) && get_string(len, result) && check_string_utf8(result, context); | |
| } | |
| case 'L': | |
| { | |
| std::int64_t len{}; | |
| return get_number(len) && check_ubjson_string_length(len) && get_string(len, result) && check_string_utf8(result, context); | |
| } | |
| case 'u': | |
| { | |
| if (input_format != input_format_t::bjdata) | |
| { | |
| break; | |
| } | |
| return get_string_with_length<std::uint16_t>(result, context); | |
| } | |
| case 'm': | |
| { | |
| if (input_format != input_format_t::bjdata) | |
| { | |
| break; | |
| } | |
| return get_string_with_length<std::uint32_t>(result, context); | |
| } | |
| case 'M': | |
| { | |
| if (input_format != input_format_t::bjdata) | |
| { | |
| break; | |
| } | |
| return get_string_with_length<std::uint64_t>(result, context); | |
| } | |
| default: | |
| break; | |
| } | |
| return length_type_error("", "string"); | |
| } | |
| /*! | |
| @param[out] dim an integer vector storing the ND array dimensions | |
| @return whether reading ND array size vector is successful | |
| */ | |
| bool get_ubjson_ndarray_size(std::vector<size_t>& dim) | |
| { | |
| std::pair<std::size_t, char_int_type> size_and_type; | |
| size_t dimlen = 0; | |
| bool no_ndarray = true; | |
| if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type, no_ndarray))) | |
| { | |
| return false; | |
| } | |
| if (size_and_type.first != npos) | |
| { | |
| if (size_and_type.second != 0) | |
| { | |
| if (size_and_type.second != 'N') | |
| { | |
| for (std::size_t i = 0; i < size_and_type.first; ++i) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_value(dimlen, no_ndarray, size_and_type.second))) | |
| { | |
| return false; | |
| } | |
| dim.push_back(dimlen); | |
| } | |
| } | |
| } | |
| else | |
| { | |
| for (std::size_t i = 0; i < size_and_type.first; ++i) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_value(dimlen, no_ndarray))) | |
| { | |
| return false; | |
| } | |
| dim.push_back(dimlen); | |
| } | |
| } | |
| } | |
| else | |
| { | |
| while (current != ']') | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_value(dimlen, no_ndarray, current))) | |
| { | |
| return false; | |
| } | |
| dim.push_back(dimlen); | |
| get_ignore_noop(); | |
| } | |
| } | |
| return true; | |
| } | |
| /*! | |
| @brief read a UBJSON/BJData optimized-container count of a signed marker | |
| type ('i', 'I', 'l', 'L') and narrow it to std::size_t | |
| Every signed count marker rejects a negative value the same way (error | |
| 113); the value_in_range_of check additionally needed for 'L' is only | |
| ever live when @a SignedType is std::int64_t on a target where | |
| std::size_t is narrower (e.g. 32-bit), since 'i'/'I'/'l' can never exceed | |
| std::size_t there. | |
| @tparam SignedType std::int8_t, std::int16_t, std::int32_t or std::int64_t | |
| @param[out] result the count narrowed to std::size_t | |
| @return whether reading and validating succeeded | |
| */ | |
| template<typename SignedType> | |
| bool get_ubjson_signed_count(std::size_t& result) | |
| { | |
| SignedType number{}; | |
| if (JSON_HEDLEY_UNLIKELY(!get_number(number))) | |
| { | |
| return false; | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(number < 0)) | |
| { | |
| return last_byte_error(exception_id::invalid_string_or_size, "count in an optimized container must be positive", "size"); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!value_in_range_of<std::size_t>(number))) | |
| { | |
| return out_of_range_error(exception_id::container_too_large, "integer value overflow", "size"); | |
| } | |
| result = static_cast<std::size_t>(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char | |
| return true; | |
| } | |
| /*! | |
| @param[out] result determined size | |
| @param[in,out] is_ndarray for input, `true` means already inside an ndarray vector | |
| or ndarray dimension is not allowed; `false` means ndarray | |
| is allowed; for output, `true` means an ndarray is found; | |
| is_ndarray can only return `true` when its initial value | |
| is `false` | |
| @param[in] prefix type marker if already read, otherwise set to 0 | |
| @param[in] ndarray_dtype the element type marker of the enclosing bjdata ndarray if | |
| already known (it precedes the dimension vector read here), | |
| otherwise 0; used to emit the "_ArrayType_" annotation key | |
| before "_ArraySize_" if a dimension vector turns out to | |
| describe an ndarray | |
| @return whether size determination completed | |
| */ | |
| bool get_ubjson_size_value(std::size_t& result, bool& is_ndarray, char_int_type prefix = 0, char_int_type ndarray_dtype = 0) | |
| { | |
| if (prefix == 0) | |
| { | |
| prefix = get_ignore_noop(); | |
| } | |
| switch (prefix) | |
| { | |
| case 'U': | |
| { | |
| std::uint8_t number{}; | |
| if (JSON_HEDLEY_UNLIKELY(!get_number(number))) | |
| { | |
| return false; | |
| } | |
| result = static_cast<std::size_t>(number); | |
| return true; | |
| } | |
| case 'i': | |
| return get_ubjson_signed_count<std::int8_t>(result); | |
| case 'I': | |
| return get_ubjson_signed_count<std::int16_t>(result); | |
| case 'l': | |
| return get_ubjson_signed_count<std::int32_t>(result); | |
| case 'L': | |
| return get_ubjson_signed_count<std::int64_t>(result); | |
| case 'u': | |
| { | |
| if (input_format != input_format_t::bjdata) | |
| { | |
| break; | |
| } | |
| std::uint16_t number{}; | |
| if (JSON_HEDLEY_UNLIKELY(!get_number(number))) | |
| { | |
| return false; | |
| } | |
| result = static_cast<std::size_t>(number); | |
| return true; | |
| } | |
| case 'm': | |
| { | |
| if (input_format != input_format_t::bjdata) | |
| { | |
| break; | |
| } | |
| std::uint32_t number{}; | |
| if (JSON_HEDLEY_UNLIKELY(!get_number(number))) | |
| { | |
| return false; | |
| } | |
| result = conditional_static_cast<std::size_t>(number); | |
| return true; | |
| } | |
| case 'M': | |
| { | |
| if (input_format != input_format_t::bjdata) | |
| { | |
| break; | |
| } | |
| std::uint64_t number{}; | |
| if (JSON_HEDLEY_UNLIKELY(!get_number(number))) | |
| { | |
| return false; | |
| } | |
| if (!value_in_range_of<std::size_t>(number)) | |
| { | |
| return out_of_range_error(exception_id::container_too_large, "integer value overflow", "size"); | |
| } | |
| result = detail::conditional_static_cast<std::size_t>(number); | |
| return true; | |
| } | |
| case '[': | |
| { | |
| if (input_format != input_format_t::bjdata) | |
| { | |
| break; | |
| } | |
| if (is_ndarray) // ndarray dimensional vector can only contain integers and cannot embed another array | |
| { | |
| return last_byte_error(exception_id::invalid_string_or_size, "ndarray dimensional vector is not allowed", "size"); | |
| } | |
| std::vector<size_t> dim; | |
| if (JSON_HEDLEY_UNLIKELY(!get_ubjson_ndarray_size(dim))) | |
| { | |
| return false; | |
| } | |
| if (dim.size() == 1 || (dim.size() == 2 && dim.at(0) == 1)) // return normal array size if 1D row vector | |
| { | |
| result = dim.at(dim.size() - 1); | |
| return true; | |
| } | |
| if (!dim.empty()) // if ndarray, convert to an object in JData annotated array format | |
| { | |
| for (auto i : dim) // test if any dimension in an ndarray is 0, if so, return a 1D empty container | |
| { | |
| if ( i == 0 ) | |
| { | |
| result = 0; | |
| return true; | |
| } | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!sax->start_object(3))) | |
| { | |
| return false; | |
| } | |
| // the element type precedes the dimension vector (see get_ubjson_size_type) | |
| // and is passed down as ndarray_dtype; emit it here so the annotation keys | |
| // follow the documented _ArrayType_, _ArraySize_, _ArrayData_ order | |
| if (ndarray_dtype != 0) | |
| { | |
| const char* type_name = bjd_type_name(ndarray_dtype); | |
| if (JSON_HEDLEY_UNLIKELY(type_name == nullptr)) | |
| { | |
| return unexpected_byte("invalid byte", "type"); | |
| } | |
| string_t type_key = "_ArrayType_"; | |
| string_t type = type_name; // sax->string() takes a reference | |
| if (JSON_HEDLEY_UNLIKELY(!sax->key(type_key) || !sax->string(type))) | |
| { | |
| return false; | |
| } | |
| } | |
| string_t key = "_ArraySize_"; | |
| if (JSON_HEDLEY_UNLIKELY(!sax->key(key) || !sax->start_array(dim.size()))) | |
| { | |
| return false; | |
| } | |
| result = 1; | |
| for (auto i : dim) | |
| { | |
| // Pre-multiplication overflow check: since the loop above | |
| // already rejected any zero dimension, i is always > 0 | |
| // here, so result > SIZE_MAX/i means result*i would | |
| // overflow. This check must happen before multiplication | |
| // since overflow detection after the fact is unreliable, | |
| // as modular arithmetic can produce any value, not just 0 | |
| // or SIZE_MAX. | |
| if (JSON_HEDLEY_UNLIKELY(result > (std::numeric_limits<std::size_t>::max)() / i)) | |
| { | |
| return out_of_range_error(exception_id::container_too_large, "excessive ndarray size caused overflow", "size"); | |
| } | |
| result *= i; | |
| // the pre-check above already rules out result becoming 0 | |
| // by overflow; the only value it cannot rule out is an | |
| // exact match with npos, the sentinel reserved for an | |
| // unknown-size container (see get_ubjson_size_type()) | |
| if (result == npos) | |
| { | |
| return out_of_range_error(exception_id::container_too_large, "excessive ndarray size caused overflow", "size"); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!emit_unsigned(i))) | |
| { | |
| return false; | |
| } | |
| } | |
| is_ndarray = true; | |
| return sax->end_array(); | |
| } | |
| result = 0; | |
| return true; | |
| } | |
| default: | |
| break; | |
| } | |
| return length_type_error(" after '#'", "size"); | |
| } | |
| /*! | |
| @brief determine the type and size for a container | |
| In the optimized UBJSON format, a type and a size can be provided to allow | |
| for a more compact representation. | |
| @param[out] result pair of the size and the type | |
| @param[in] inside_ndarray whether the parser is parsing an ND array dimensional vector | |
| @return whether pair creation completed | |
| */ | |
| bool get_ubjson_size_type(std::pair<std::size_t, char_int_type>& result, bool inside_ndarray = false) | |
| { | |
| result.first = npos; // size | |
| result.second = 0; // type | |
| // seed the flag with the caller's context: inside an ndarray dimension | |
| // vector another ndarray is not allowed, and get_ubjson_size_value() | |
| // rejects it up front instead of reading it and reporting afterwards. | |
| // Seeding it with `false` made every '#' of a "[#[#[..." chain descend | |
| // another level, which overflowed the stack (see #5104). | |
| bool is_ndarray = inside_ndarray; | |
| get_ignore_noop(); | |
| if (current == '$') | |
| { | |
| result.second = get(); // must not ignore 'N', because 'N' maybe the type | |
| if (input_format == input_format_t::bjdata | |
| && JSON_HEDLEY_UNLIKELY(is_bjd_excluded_optimized_type(result.second))) | |
| { | |
| return optimized_type_error(); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("type"))) | |
| { | |
| return false; | |
| } | |
| get_ignore_noop(); | |
| if (JSON_HEDLEY_UNLIKELY(current != '#')) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("value"))) | |
| { | |
| return false; | |
| } | |
| return last_byte_error(exception_id::unexpected_byte, "expected '#' after type information", "size", ""); | |
| } | |
| const bool is_error = get_ubjson_size_value(result.first, is_ndarray, 0, result.second); | |
| // an ndarray was read here only if the flag flipped; when it was | |
| // seeded true, get_ubjson_size_value() already rejected the nested | |
| // dimension vector | |
| if (input_format == input_format_t::bjdata && is_ndarray && !inside_ndarray) | |
| { | |
| result.second |= (1 << 8); // use bit 8 to indicate ndarray, all UBJSON and BJData markers should be ASCII letters | |
| } | |
| return is_error; | |
| } | |
| if (current == '#') | |
| { | |
| const bool is_error = get_ubjson_size_value(result.first, is_ndarray); | |
| if (input_format == input_format_t::bjdata && is_ndarray && !inside_ndarray) | |
| { | |
| return last_byte_error(exception_id::unexpected_byte, "ndarray requires both type and size", "size"); | |
| } | |
| return is_error; | |
| } | |
| return true; | |
| } | |
| /*! | |
| @param prefix the previously read or set type prefix | |
| @return whether value creation completed | |
| */ | |
| bool get_ubjson_value(const char_int_type prefix) | |
| { | |
| switch (prefix) | |
| { | |
| case char_traits<char_type>::eof(): // EOF | |
| return unexpect_eof("value"); | |
| case 'T': // true | |
| return sax->boolean(true); | |
| case 'F': // false | |
| return sax->boolean(false); | |
| case 'Z': // null | |
| return sax->null(); | |
| case 'B': // byte | |
| { | |
| if (input_format != input_format_t::bjdata) | |
| { | |
| break; | |
| } | |
| std::uint8_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| case 'U': | |
| { | |
| std::uint8_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| case 'i': | |
| { | |
| std::int8_t number{}; | |
| return get_number(number) && emit_signed(number); | |
| } | |
| case 'I': | |
| { | |
| std::int16_t number{}; | |
| return get_number(number) && emit_signed(number); | |
| } | |
| case 'l': | |
| { | |
| std::int32_t number{}; | |
| return get_number(number) && emit_signed(number); | |
| } | |
| case 'L': | |
| { | |
| std::int64_t number{}; | |
| return get_number(number) && emit_signed(number); | |
| } | |
| case 'u': | |
| { | |
| if (input_format != input_format_t::bjdata) | |
| { | |
| break; | |
| } | |
| std::uint16_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| case 'm': | |
| { | |
| if (input_format != input_format_t::bjdata) | |
| { | |
| break; | |
| } | |
| std::uint32_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| case 'M': | |
| { | |
| if (input_format != input_format_t::bjdata) | |
| { | |
| break; | |
| } | |
| std::uint64_t number{}; | |
| return get_number(number) && emit_unsigned(number); | |
| } | |
| case 'h': | |
| { | |
| if (input_format != input_format_t::bjdata) | |
| { | |
| break; | |
| } | |
| return get_half_float(true); | |
| } | |
| case 'd': | |
| { | |
| float number{}; | |
| return get_number(number) && emit_float(number); | |
| } | |
| case 'D': | |
| { | |
| double number{}; | |
| return get_number(number) && emit_float(number); | |
| } | |
| case 'H': | |
| { | |
| return get_ubjson_high_precision_number(); | |
| } | |
| case 'C': // char | |
| { | |
| get(); | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("char"))) | |
| { | |
| return false; | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(current > 127)) | |
| { | |
| return last_byte_error(exception_id::invalid_string_or_size, "byte after 'C' must be in range 0x00..0x7F", "char", ""); | |
| } | |
| string_t s(1, static_cast<typename string_t::value_type>(current)); | |
| return sax->string(s); | |
| } | |
| case 'S': // string | |
| { | |
| string_t s; | |
| return get_ubjson_string(s) && sax->string(s); | |
| } | |
| case '[': // array | |
| return get_ubjson_array(); | |
| case '{': // object | |
| return get_ubjson_object(); | |
| default: // anything else | |
| break; | |
| } | |
| return unexpected_byte("invalid byte", "value"); | |
| } | |
| /*! | |
| @return whether array creation completed | |
| */ | |
| bool get_ubjson_array() | |
| { | |
| std::pair<std::size_t, char_int_type> size_and_type; | |
| if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) | |
| { | |
| return false; | |
| } | |
| // if bit-8 of size_and_type.second is set to 1, encode bjdata ndarray as an object in JData annotated array format (https://github.com/NeuroJSON/jdata): | |
| // {"_ArrayType_" : "typeid", "_ArraySize_" : [n1, n2, ...], "_ArrayData_" : [v1, v2, ...]} | |
| if (input_format == input_format_t::bjdata && size_and_type.first != npos && (size_and_type.second & (1 << 8)) != 0) | |
| { | |
| size_and_type.second &= ~(static_cast<char_int_type>(1) << 8); // use bit 8 to indicate ndarray, here we remove the bit to restore the type marker | |
| // the "_ArrayType_" and "_ArraySize_" annotation keys were already emitted by | |
| // get_ubjson_size_value() (the type marker is known before the dimension vector | |
| // that determines size_and_type.first is read, so it is emitted first there to | |
| // match the documented _ArrayType_, _ArraySize_, _ArrayData_ key order) | |
| if (size_and_type.second == 'C' || size_and_type.second == 'B') | |
| { | |
| size_and_type.second = 'U'; | |
| } | |
| string_t key = "_ArrayData_"; | |
| if (JSON_HEDLEY_UNLIKELY(!sax->key(key) || !sax->start_array(size_and_type.first) )) | |
| { | |
| return false; | |
| } | |
| for (std::size_t i = 0; i < size_and_type.first; ++i) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) | |
| { | |
| return false; | |
| } | |
| } | |
| return (sax->end_array() && sax->end_object()); | |
| } | |
| // If BJData type marker is 'B' decode as binary | |
| if (input_format == input_format_t::bjdata && size_and_type.first != npos && size_and_type.second == 'B') | |
| { | |
| binary_t result; | |
| return get_binary(size_and_type.first, result) && sax->binary(result); | |
| } | |
| if (size_and_type.first != npos) | |
| { | |
| // reading an element of a valueless type consumes no input, so the | |
| // declared count alone decides how much is allocated; the check is | |
| // made before the start event so that no container is opened that | |
| // is then abandoned. See @ref max_valueless_container_size. | |
| if (JSON_HEDLEY_UNLIKELY((size_and_type.second == 'Z' || size_and_type.second == 'T' || size_and_type.second == 'F') | |
| && size_and_type.first > max_valueless_container_size)) | |
| { | |
| return out_of_range_error(exception_id::container_too_large, "excessive array size", "size"); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!enter_array(size_and_type.first, size_and_type.second))) | |
| { | |
| return false; | |
| } | |
| if (size_and_type.second == 'N') | |
| { | |
| // a no-op is not a value, so a container of them holds none; | |
| // the declared size has already been passed to the SAX parser | |
| container_stack.back().remaining = 0; | |
| } | |
| return true; | |
| } | |
| return enter_array(detail::unknown_size()); | |
| } | |
| /*! | |
| @return whether object creation completed | |
| */ | |
| bool get_ubjson_object() | |
| { | |
| std::pair<std::size_t, char_int_type> size_and_type; | |
| if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) | |
| { | |
| return false; | |
| } | |
| // do not accept ND-array size in objects in BJData | |
| if (input_format == input_format_t::bjdata && size_and_type.first != npos && (size_and_type.second & (1 << 8)) != 0) | |
| { | |
| return last_byte_error(exception_id::unexpected_byte, "BJData object does not support ND-array size in optimized format", "object"); | |
| } | |
| if (size_and_type.first != npos) | |
| { | |
| return enter_object(size_and_type.first, size_and_type.second); | |
| } | |
| return enter_object(detail::unknown_size()); | |
| } | |
| // Note, UBJSON has no binary type of its own; BJData, which shares this | |
| // reader, decodes optimized 'B' arrays as binary in get_ubjson_array(). | |
| bool get_ubjson_high_precision_number() | |
| { | |
| // get the size of the following number string | |
| std::size_t size{}; | |
| bool no_ndarray = true; | |
| auto res = get_ubjson_size_value(size, no_ndarray); | |
| if (JSON_HEDLEY_UNLIKELY(!res)) | |
| { | |
| return res; | |
| } | |
| // get number string | |
| std::vector<char> number_vector; | |
| for (std::size_t i = 0; i < size; ++i) | |
| { | |
| get(); | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("number"))) | |
| { | |
| return false; | |
| } | |
| // the lexer would stop at a NUL and accept the digits before it | |
| if (JSON_HEDLEY_UNLIKELY(current == '\0')) | |
| { | |
| return sax->parse_error(chars_read, "00", parse_error::create(exception_id::invalid_high_precision_number, chars_read, | |
| exception_message("invalid number text; last byte: 0x00", "high-precision number"), nullptr)); | |
| } | |
| number_vector.push_back(static_cast<char>(current)); | |
| } | |
| // parse number string | |
| using ia_type = decltype(detail::input_adapter(number_vector)); | |
| auto number_lexer = detail::lexer<BasicJsonType, ia_type>(detail::input_adapter(number_vector), false); | |
| const auto result_number = number_lexer.scan(); | |
| const auto number_string = number_lexer.get_token_string(); | |
| const auto result_remainder = number_lexer.scan(); | |
| using token_type = typename detail::lexer_base<BasicJsonType>::token_type; | |
| if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input)) | |
| { | |
| return sax->parse_error(chars_read, number_string, parse_error::create(exception_id::invalid_high_precision_number, chars_read, | |
| exception_message(concat("invalid number text: ", number_lexer.get_token_string()), "high-precision number"), nullptr)); | |
| } | |
| switch (result_number) | |
| { | |
| case token_type::value_integer: | |
| return sax->number_integer(number_lexer.get_number_integer()); | |
| case token_type::value_unsigned: | |
| return sax->number_unsigned(number_lexer.get_number_unsigned()); | |
| case token_type::value_float: | |
| { | |
| const auto parsed_float = number_lexer.get_number_float(); | |
| if (JSON_HEDLEY_UNLIKELY(!std::isfinite(parsed_float))) | |
| { | |
| return sax->parse_error( | |
| chars_read, | |
| number_string, | |
| out_of_range::create(exception_id::number_overflow, concat("number overflow parsing '", number_string, '\''), nullptr)); | |
| } | |
| // number_string is a std::string, while the SAX interface takes a | |
| // string_t; convert explicitly, as the two are only implicitly | |
| // convertible for some string types | |
| return sax->number_float(parsed_float, string_t(number_string.data(), number_string.size())); | |
| } | |
| case token_type::uninitialized: | |
| case token_type::literal_true: | |
| case token_type::literal_false: | |
| case token_type::literal_null: | |
| case token_type::value_string: | |
| case token_type::begin_array: | |
| case token_type::begin_object: | |
| case token_type::end_array: | |
| case token_type::end_object: | |
| case token_type::name_separator: | |
| case token_type::value_separator: | |
| case token_type::parse_error: | |
| case token_type::end_of_input: | |
| case token_type::literal_or_value: | |
| default: | |
| return sax->parse_error(chars_read, number_string, parse_error::create(exception_id::invalid_high_precision_number, chars_read, | |
| exception_message(concat("invalid number text: ", number_lexer.get_token_string()), "high-precision number"), nullptr)); | |
| } | |
| } | |
| ////////// | |
| // BON8 // | |
| ////////// | |
| /*! | |
| @brief get the next byte of a BON8 value | |
| A BON8 string has no length prefix and no mandatory terminator: it ends at | |
| the first byte that cannot continue it, which is already the first byte (or, | |
| for an integer that begins with a UTF-8 lead byte, the first two bytes) of | |
| whatever follows. The string reader hands those bytes back with | |
| @ref unget_bon8, and every BON8 read goes through this function so that | |
| they are seen again. | |
| @return character read from the input | |
| */ | |
| char_int_type get_bon8() | |
| { | |
| if (bon8_pushback_size != 0) | |
| { | |
| ++chars_read; | |
| return current = bon8_pushback[--bon8_pushback_size]; | |
| } | |
| return get(); | |
| } | |
| /*! | |
| @brief hand a byte back so that the next @ref get_bon8 returns it again | |
| @param[in] c the byte to hand back; bytes handed back are returned in | |
| reverse order | |
| */ | |
| void unget_bon8(const char_int_type c) | |
| { | |
| // At most two bytes are ever handed back: a byte is only handed back | |
| // right after it was read with get_bon8(), and the only place that | |
| // hands back two bytes (a lead byte and the byte after it) read both | |
| // of them in a row, which emptied the buffer first. This is an | |
| // invariant of the reader rather than a property of the input, so | |
| // an assertion suffices (the fuzzers are built with assertions). | |
| JSON_ASSERT(bon8_pushback_size < bon8_pushback.size()); | |
| bon8_pushback[bon8_pushback_size++] = c; | |
| --chars_read; | |
| } | |
| /*! | |
| @param[in] c a byte | |
| @return whether @a c is a UTF-8 continuation byte (0x80..0xBF) | |
| */ | |
| static constexpr bool is_bon8_continuation(const char_int_type c) noexcept | |
| { | |
| return 0x80 <= c && c <= 0xBF; | |
| } | |
| /*! | |
| @brief read a BON8 value and everything nested inside it | |
| Reads values until the one that was begun here is complete, resuming the | |
| enclosing container after each element, so that the nesting depth of the | |
| input costs heap rather than native stack (see #5104). | |
| @return whether reading the value succeeded | |
| */ | |
| bool parse_bon8_internal() | |
| { | |
| // the key currently being read; hoisted out of the loop so that its | |
| // capacity is reused across elements and across nesting levels | |
| string_t key; | |
| while (true) | |
| { | |
| if (!container_stack.empty()) | |
| { | |
| // a copy, not a reference: it must stay valid across the | |
| // pop_back() below, which destroys the container_stack element | |
| // it would otherwise alias | |
| const container_frame top = container_stack.back(); | |
| bool at_end = false; | |
| if (top.remaining != npos) | |
| { | |
| // counted container (0x80..0x84, 0x86..0x8A): it ends once | |
| // its elements have been read | |
| at_end = (top.remaining == 0); | |
| if (!at_end) | |
| { | |
| // claim the element about to be read | |
| --container_stack.back().remaining; | |
| } | |
| } | |
| else | |
| { | |
| // container 0x85 or 0x8B: it ends at an end-of-container | |
| // marker (0xFE); any other byte begins the next element | |
| at_end = (get_bon8() == 0xFE); | |
| if (!at_end) | |
| { | |
| unget_bon8(current); | |
| } | |
| } | |
| if (at_end) | |
| { | |
| bool value_complete = false; | |
| if (JSON_HEDLEY_UNLIKELY(!leave_container_and_check(value_complete))) | |
| { | |
| return false; | |
| } | |
| if (value_complete) | |
| { | |
| return true; | |
| } | |
| continue; | |
| } | |
| if (top.is_object) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!read_object_key<&binary_reader::get_bon8_key>(key))) | |
| { | |
| return false; | |
| } | |
| } | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!parse_bon8_value())) | |
| { | |
| return false; | |
| } | |
| // a value that opened a container left it on the stack; one that | |
| // did not, and that was not inside a container, was the whole value | |
| if (container_stack.empty()) | |
| { | |
| return true; | |
| } | |
| } | |
| } | |
| /*! | |
| @brief read one BON8 value | |
| Reads a single value and passes it to the SAX parser. A value that begins | |
| a container is not read to its end: the container is opened with | |
| @ref enter_container and its elements are read by | |
| @ref parse_bon8_internal, so that nesting does not consume native stack. | |
| @return whether reading the value succeeded | |
| */ | |
| bool parse_bon8_value() | |
| { | |
| const auto byte = get_bon8(); | |
| if (byte == char_traits<char_type>::eof()) | |
| { | |
| return unexpect_eof("value"); | |
| } | |
| // string: ASCII character | |
| if (byte <= 0x7F) | |
| { | |
| string_t s; | |
| unget_bon8(byte); | |
| return get_bon8_string(s) && sax->string(s); | |
| } | |
| // array with 0..4 elements | |
| if (byte <= 0x84) | |
| { | |
| return enter_array(static_cast<std::size_t>(byte - 0x80)); | |
| } | |
| // array terminated by 0xFE | |
| if (byte == 0x85) | |
| { | |
| return enter_array(npos); | |
| } | |
| // object with 0..4 members | |
| if (byte <= 0x8A) | |
| { | |
| return enter_object(static_cast<std::size_t>(byte - 0x86)); | |
| } | |
| switch (byte) | |
| { | |
| case 0x8B: // object terminated by 0xFE | |
| return enter_object(npos); | |
| case 0x8C: // int32 | |
| { | |
| std::int32_t number{}; | |
| return get_number(number) && emit_bon8_integer(number); | |
| } | |
| case 0x8D: // int64 | |
| { | |
| std::int64_t number{}; | |
| return get_number(number) && emit_bon8_integer(number); | |
| } | |
| case 0x8E: // binary32 | |
| { | |
| float number{}; | |
| return get_number(number) && emit_float(number); | |
| } | |
| case 0x8F: // binary64 | |
| { | |
| double number{}; | |
| return get_number(number) && emit_float(number); | |
| } | |
| case 0xF8: | |
| return sax->boolean(false); | |
| case 0xF9: | |
| return sax->boolean(true); | |
| case 0xFA: | |
| return sax->null(); | |
| case 0xFB: | |
| return sax->number_float(static_cast<number_float_t>(-1.0), ""); | |
| case 0xFC: | |
| return sax->number_float(static_cast<number_float_t>(0.0), ""); | |
| case 0xFD: | |
| return sax->number_float(static_cast<number_float_t>(1.0), ""); | |
| case 0xFF: // empty string | |
| { | |
| string_t s; | |
| return sax->string(s); | |
| } | |
| default: | |
| break; | |
| } | |
| // integer 0..39 | |
| if (byte <= 0xB7) | |
| { | |
| return sax->number_unsigned(static_cast<number_unsigned_t>(byte - 0x90)); | |
| } | |
| // integer -1..-10 | |
| if (byte <= 0xC1) | |
| { | |
| return sax->number_integer(conditional_static_cast<number_integer_t>(-1 - static_cast<number_integer_t>(byte - 0xB8))); | |
| } | |
| // 0xC2..0xF7: a UTF-8 lead byte begins a string if a continuation | |
| // byte follows and an integer otherwise | |
| if (byte <= 0xF7) | |
| { | |
| const auto second = get_bon8(); | |
| if (is_bon8_continuation(second)) | |
| { | |
| string_t s; | |
| unget_bon8(second); | |
| unget_bon8(byte); | |
| return get_bon8_string(s) && sax->string(s); | |
| } | |
| return get_bon8_integer(byte, second); | |
| } | |
| // 0xFE: end of container where a value is expected | |
| return unexpected_byte("invalid byte", "value"); | |
| } | |
| /*! | |
| @brief pass an integer to the SAX parser | |
| Non-negative integers are passed as unsigned, negative integers as signed | |
| numbers, like the other binary formats do. A value that does not fit the | |
| number type is passed as described for @ref emit_unsigned and | |
| @ref emit_signed. | |
| @param[in] number the integer | |
| @return whether the SAX parser accepted the value | |
| */ | |
| bool emit_bon8_integer(const std::int64_t number) | |
| { | |
| if (number >= 0) | |
| { | |
| return emit_unsigned(static_cast<std::uint64_t>(number)); | |
| } | |
| return emit_signed(number); | |
| } | |
| /*! | |
| @brief read an integer encoded in 2..4 bytes | |
| The first byte is a UTF-8 lead byte (0xC2..0xF7) that is followed by a | |
| byte that is not a continuation byte: 0x00..0x7F for positive and | |
| 0xC0..0xFF for negative integers. The lead byte's low bits and the second | |
| byte's low 7 (positive) or 6 (negative) bits are the most significant bits | |
| of the value; 3- and 4-byte integers add one or two full bytes. Each range | |
| starts where the shorter one ends, so no value has two encodings of the | |
| same length. | |
| @param[in] lead the first byte (0xC2..0xF7) | |
| @param[in] second the second byte | |
| @return whether reading the integer succeeded | |
| */ | |
| bool get_bon8_integer(const char_int_type lead, const char_int_type second) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("number"))) | |
| { | |
| return false; | |
| } | |
| const bool negative = second >= 0xC0; | |
| auto value = static_cast<std::int64_t>(negative ? (second & 0x3F) : second); | |
| std::int64_t offset = 0; | |
| int extra_bytes = 0; | |
| if (lead <= 0xDF) | |
| { | |
| value |= static_cast<std::int64_t>(lead - 0xC2) << (negative ? 6 : 7); | |
| offset = negative ? 11 : 40; | |
| } | |
| else if (lead <= 0xEF) | |
| { | |
| value |= static_cast<std::int64_t>(lead & 0x0F) << (negative ? 6 : 7); | |
| offset = negative ? 1931 : 3880; | |
| extra_bytes = 1; | |
| } | |
| else | |
| { | |
| value |= static_cast<std::int64_t>(lead & 0x07) << (negative ? 6 : 7); | |
| offset = negative ? 264075 : 528168; | |
| extra_bytes = 2; | |
| } | |
| for (int i = 0; i < extra_bytes; ++i) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(get_bon8() == char_traits<char_type>::eof())) | |
| { | |
| return unexpect_eof("number"); | |
| } | |
| value = (value << 8) | static_cast<std::int64_t>(current); | |
| } | |
| return emit_bon8_integer(negative ? -(value + offset) : value + offset); | |
| } | |
| /*! | |
| @brief read an object key | |
| A key must be a string, so its first byte must be an ASCII character, a | |
| UTF-8 lead byte followed by a continuation byte, or 0xFF (empty string). | |
| @param[out] result the key | |
| @return whether reading the key succeeded | |
| */ | |
| bool get_bon8_key(string_t& result) | |
| { | |
| const auto byte = get_bon8(); | |
| if (byte == char_traits<char_type>::eof()) | |
| { | |
| return unexpect_eof("key"); | |
| } | |
| if (byte == 0xFF) | |
| { | |
| return true; | |
| } | |
| if (byte <= 0x7F) | |
| { | |
| unget_bon8(byte); | |
| return get_bon8_string(result); | |
| } | |
| if (0xC2 <= byte && byte <= 0xF7) | |
| { | |
| const auto second = get_bon8(); | |
| if (second == char_traits<char_type>::eof()) | |
| { | |
| // the input ends inside a character or an integer | |
| return unexpect_eof("key"); | |
| } | |
| unget_bon8(second); | |
| if (is_bon8_continuation(second)) | |
| { | |
| unget_bon8(byte); | |
| return get_bon8_string(result); | |
| } | |
| // an integer: report its first byte rather than the one after it | |
| current = byte; | |
| } | |
| return unexpected_byte("expected a string; last byte", "key"); | |
| } | |
| /*! | |
| @brief append the run of valid UTF-8 at the read position to a string | |
| For contiguous input, the ASCII characters and complete well-formed UTF-8 | |
| sequences at the read position are appended to @a result in one step. The | |
| byte that stops the run (an end-of-string marker, the first byte of the | |
| next value, or an ill-formed byte) is left for @ref get_bon8_string, so | |
| that strings end and errors are reported exactly as without this step. | |
| @param[in,out] result the string to append to | |
| */ | |
| void get_bon8_string_bulk(string_t& result, std::true_type /*bulk*/) | |
| { | |
| // bytes handed back must be read through get_bon8() first | |
| if (bon8_pushback_size != 0) | |
| { | |
| return; | |
| } | |
| const std::size_t remaining = ia.bulk_remaining(); | |
| if (remaining == 0) | |
| { | |
| return; | |
| } | |
| const auto* const data = reinterpret_cast<const unsigned char*>(ia.bulk_data()); | |
| const std::size_t length = valid_utf8_prefix(data, remaining); | |
| if (length != 0) | |
| { | |
| result.append(reinterpret_cast<const typename string_t::value_type*>(data), length); | |
| ia.bulk_skip(length); | |
| chars_read += length; | |
| } | |
| } | |
| /// input that is not contiguous: strings are read byte by byte | |
| void get_bon8_string_bulk(string_t& /*result*/, std::false_type /*bulk*/) const noexcept {} | |
| /*! | |
| @brief read a string | |
| Reads UTF-8 characters until an end-of-string marker (0xFF), which is | |
| consumed, or a byte that cannot continue the string, which is handed back | |
| to be read as the start of the next value. The string must be valid UTF-8, | |
| and it must not end at the end of the input: the last string of a message | |
| is always terminated by 0xFF. | |
| @param[out] result the string | |
| @return whether reading the string succeeded | |
| */ | |
| bool get_bon8_string(string_t& result) | |
| { | |
| while (true) | |
| { | |
| get_bon8_string_bulk(result, std::integral_constant<bool, bulk_scan> {}); | |
| const auto byte = get_bon8(); | |
| if (byte == char_traits<char_type>::eof()) | |
| { | |
| return unexpect_eof("string"); | |
| } | |
| // end of string | |
| if (byte == 0xFF) | |
| { | |
| return true; | |
| } | |
| // ASCII character | |
| if (byte <= 0x7F) | |
| { | |
| result.push_back(static_cast<typename string_t::value_type>(byte)); | |
| continue; | |
| } | |
| // a byte that cannot begin a character ends the string and begins | |
| // the next value | |
| if (byte < 0xC2 || byte > 0xF7) | |
| { | |
| unget_bon8(byte); | |
| return true; | |
| } | |
| // a lead byte ends the string if no continuation byte follows: it | |
| // is then the first byte of an integer | |
| const auto second = get_bon8(); | |
| if (second == char_traits<char_type>::eof()) | |
| { | |
| // the input ends inside a character or an integer: either | |
| // way, the message is incomplete | |
| return unexpect_eof("string"); | |
| } | |
| if (!is_bon8_continuation(second)) | |
| { | |
| unget_bon8(second); | |
| unget_bon8(byte); | |
| return true; | |
| } | |
| // the valid range of the second byte excludes overlong forms, | |
| // surrogates, and code points above U+10FFFF | |
| // (RFC 3629, section 4) | |
| int continuation_bytes = 0; | |
| bool valid_second = true; | |
| if (byte <= 0xDF) | |
| { | |
| continuation_bytes = 1; | |
| } | |
| else if (byte <= 0xEF) | |
| { | |
| continuation_bytes = 2; | |
| valid_second = (byte != 0xE0 || second >= 0xA0) && (byte != 0xED || second <= 0x9F); | |
| } | |
| else | |
| { | |
| continuation_bytes = 3; | |
| valid_second = byte <= 0xF4 && (byte != 0xF0 || second >= 0x90) && (byte != 0xF4 || second <= 0x8F); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!valid_second)) | |
| { | |
| return unexpected_byte("invalid UTF-8 byte", "string"); | |
| } | |
| result.push_back(static_cast<typename string_t::value_type>(byte)); | |
| result.push_back(static_cast<typename string_t::value_type>(second)); | |
| for (int i = 1; i < continuation_bytes; ++i) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(get_bon8() == char_traits<char_type>::eof())) | |
| { | |
| return unexpect_eof("string"); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!is_bon8_continuation(current))) | |
| { | |
| return unexpected_byte("invalid UTF-8 byte", "string"); | |
| } | |
| result.push_back(static_cast<typename string_t::value_type>(current)); | |
| } | |
| } | |
| } | |
| /////////////////////// | |
| // Utility functions // | |
| /////////////////////// | |
| /*! | |
| @brief get next character from the input | |
| This function provides the interface to the used input adapter. It does | |
| not throw in case the input reached EOF, but returns a -'ve valued | |
| `char_traits<char_type>::eof()` in that case. | |
| @return character read from the input | |
| */ | |
| char_int_type get() | |
| { | |
| ++chars_read; | |
| return current = ia.get_character(); | |
| } | |
| /*! | |
| @brief get_to read into a primitive type | |
| This function provides the interface to the used input adapter. It does | |
| not throw in case the input reached EOF, but returns false instead | |
| @return bool, whether the read was successful | |
| */ | |
| template<class T> | |
| bool get_to(T& dest, const char* context) | |
| { | |
| // false positive: new_chars_read is read on the next lines | |
| // @infer-ignore DEAD_STORE | |
| auto new_chars_read = ia.get_elements(&dest); | |
| chars_read += new_chars_read; | |
| if (JSON_HEDLEY_UNLIKELY(new_chars_read < sizeof(T))) | |
| { | |
| // in case of failure, advance position by 1 to report the failing location | |
| ++chars_read; | |
| static_cast<void>(report_eof(context)); | |
| return false; | |
| } | |
| return true; | |
| } | |
| /*! | |
| @return character read from the input after ignoring all 'N' entries | |
| */ | |
| char_int_type get_ignore_noop() | |
| { | |
| do | |
| { | |
| get(); | |
| } | |
| while (current == 'N'); | |
| return current; | |
| } | |
| template<class NumberType> | |
| static void byte_swap(NumberType& number) | |
| { | |
| constexpr std::size_t sz = sizeof(number); | |
| #ifdef __cpp_lib_byteswap | |
| if constexpr (sz == 1) | |
| { | |
| return; | |
| } | |
| else if constexpr(std::is_integral_v<NumberType>) | |
| { | |
| number = std::byteswap(number); | |
| return; | |
| } | |
| else | |
| { | |
| #endif | |
| auto* ptr = reinterpret_cast<std::uint8_t*>(&number); | |
| for (std::size_t i = 0; i < sz / 2; ++i) | |
| { | |
| std::swap(ptr[i], ptr[sz - i - 1]); | |
| } | |
| #ifdef __cpp_lib_byteswap | |
| } | |
| #endif | |
| } | |
| /*! | |
| @brief read a number from the input | |
| @tparam NumberType the type of the number | |
| @param[out] result number of type @a NumberType | |
| @return whether conversion completed | |
| @note This function needs to respect the system's endianness, because | |
| bytes in CBOR, MessagePack, UBJSON, and BON8 are stored in network | |
| order (big endian) and therefore need reordering on little endian | |
| systems. On the other hand, BSON and BJData use little endian and | |
| should reorder on big endian systems. | |
| */ | |
| template<typename NumberType, bool InputIsLittleEndian = false> | |
| bool get_number(NumberType& result) | |
| { | |
| // read in the original format | |
| if (JSON_HEDLEY_UNLIKELY(!get_to(result, "number"))) | |
| { | |
| return false; | |
| } | |
| if (is_little_endian != (InputIsLittleEndian || input_format == input_format_t::bjdata)) | |
| { | |
| byte_swap(result); | |
| } | |
| return true; | |
| } | |
| /*! | |
| @brief pass a signed integer read from the input to the SAX parser | |
| Like the lexer does for JSON text, a value that does not fit into | |
| number_integer_t is passed as number_unsigned_t if it is non-negative and | |
| fits there, and as number_float_t otherwise. With the default number | |
| types, every integer the binary formats can encode fits, so this only | |
| matters for narrower custom number types. | |
| @tparam NumberType a signed integer type | |
| @param[in] number the integer | |
| @return whether the SAX parser accepted the value | |
| @throw out_of_range.406 if @a number overflows number_float_t (see | |
| @ref emit_float) | |
| */ | |
| template<typename NumberType> | |
| bool emit_signed(const NumberType number) | |
| { | |
| if (JSON_HEDLEY_LIKELY(value_in_range_of<number_integer_t>(number))) | |
| { | |
| return sax->number_integer(static_cast<number_integer_t>(number)); | |
| } | |
| if (value_in_range_of<number_unsigned_t>(number)) | |
| { | |
| return sax->number_unsigned(static_cast<number_unsigned_t>(number)); | |
| } | |
| // std::isfinite has no integer overloads in MSVC's <cmath> | |
| return emit_float(static_cast<long double>(number)); | |
| } | |
| /*! | |
| @brief pass an unsigned integer read from the input to the SAX parser | |
| Like the lexer does for JSON text, a value that does not fit into | |
| number_unsigned_t is passed as number_float_t. | |
| @tparam NumberType an unsigned integer type | |
| @param[in] number the integer | |
| @return whether the SAX parser accepted the value | |
| @throw out_of_range.406 if @a number overflows number_float_t (see | |
| @ref emit_float) | |
| */ | |
| template<typename NumberType> | |
| bool emit_unsigned(const NumberType number) | |
| { | |
| if (JSON_HEDLEY_LIKELY(value_in_range_of<number_unsigned_t>(number))) | |
| { | |
| return sax->number_unsigned(static_cast<number_unsigned_t>(number)); | |
| } | |
| // std::isfinite has no integer overloads in MSVC's <cmath> | |
| return emit_float(static_cast<long double>(number)); | |
| } | |
| /*! | |
| @brief pass a floating-point number read from the input to the SAX parser | |
| Like the lexer does for JSON text, a finite value that overflows | |
| number_float_t is rejected instead of silently becoming infinity. Infinity | |
| and NaN in the input are passed on unchanged. Integers only overflow if | |
| number_float_t cannot represent 2^64, e.g., a half-precision type. | |
| @tparam NumberType a floating-point type (emit_signed and emit_unsigned | |
| convert integers to long double first) | |
| @param[in] number the number | |
| @return whether the SAX parser accepted the value | |
| @throw out_of_range.406 if a finite @a number overflows number_float_t | |
| */ | |
| template<typename NumberType> | |
| bool emit_float(const NumberType number) | |
| { | |
| const auto result = static_cast<number_float_t>(number); | |
| if (JSON_HEDLEY_UNLIKELY(std::isfinite(number) && !std::isfinite(result))) | |
| { | |
| return out_of_range_error(exception_id::number_overflow, "number overflow", "value"); | |
| } | |
| return sax->number_float(result, ""); | |
| } | |
| /*! | |
| @brief read and decode an IEEE 754 half-precision (16-bit) float | |
| Used by CBOR (big endian) and BJData (little endian); the two formats | |
| only differ in the byte order of the two bytes that make up the half. | |
| @param[in] little_endian whether the two bytes are little endian (BJData) | |
| or big endian (CBOR) | |
| @return whether reading and decoding succeeded | |
| */ | |
| bool get_half_float(const bool little_endian) | |
| { | |
| const auto byte1_raw = get(); | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("number"))) | |
| { | |
| return false; | |
| } | |
| const auto byte2_raw = get(); | |
| if (JSON_HEDLEY_UNLIKELY(!unexpect_eof("number"))) | |
| { | |
| return false; | |
| } | |
| const auto byte1 = static_cast<unsigned char>(byte1_raw); | |
| const auto byte2 = static_cast<unsigned char>(byte2_raw); | |
| // Code from RFC 8949, Appendix D, Figure 3: | |
| // As half-precision floating-point numbers were only added | |
| // to IEEE 754 in 2008, today's programming platforms often | |
| // still only have limited support for them. It is very | |
| // easy to include at least decoding support for them even | |
| // without such support. An example of a small decoder for | |
| // half-precision floating-point numbers in the C language | |
| // is shown in Fig. 3. | |
| const auto half = little_endian | |
| ? static_cast<unsigned int>((byte2 << 8u) + byte1) | |
| : static_cast<unsigned int>((byte1 << 8u) + byte2); | |
| const double val = [&half] | |
| { | |
| const int exp = (half >> 10u) & 0x1Fu; | |
| const unsigned int mant = half & 0x3FFu; | |
| JSON_ASSERT(exp <= 31); | |
| JSON_ASSERT(mant <= 1023); | |
| switch (exp) | |
| { | |
| case 0: | |
| return std::ldexp(mant, -24); | |
| case 31: | |
| return (mant == 0) | |
| ? std::numeric_limits<double>::infinity() | |
| : std::numeric_limits<double>::quiet_NaN(); | |
| default: | |
| return std::ldexp(mant + 1024, exp - 25); | |
| } | |
| }(); | |
| return sax->number_float((half & 0x8000u) != 0 | |
| ? static_cast<number_float_t>(-val) | |
| : static_cast<number_float_t>(val), ""); | |
| } | |
| /*! | |
| @brief create a string by reading characters from the input | |
| @tparam NumberType the type of the number | |
| @param[in] len number of characters to read | |
| @param[out] result string created by reading @a len bytes | |
| @return whether string creation completed | |
| @note We can not reserve @a len bytes for the result, because @a len | |
| may be too large. Usually, @ref unexpect_eof() detects the end of | |
| the input before we run out of string memory. | |
| */ | |
| template<typename NumberType> | |
| bool get_string(const NumberType len, | |
| string_t& result) | |
| { | |
| // Strings are taken as is by default: none of CBOR (RFC 8949 §3.1 | |
| // leaves the choice to the decoder), MessagePack (whose spec | |
| // explicitly allows a str object to contain an invalid byte | |
| // sequence), UBJSON, BJData, or BSON requires a decoder to reject | |
| // ill-formed UTF-8. Checking (and, with @ref error_handler_t::strict, | |
| // rejecting, or with `replace`/`ignore`, sanitizing) is opt-in via | |
| // @ref error_handler, applied once the whole string (all chunks of | |
| // an indefinite-length CBOR string included) has been assembled, by | |
| // @ref check_string_utf8 at the call site. | |
| return get_bytes(len, "string", result); | |
| } | |
| /*! | |
| @brief validate a decoded text string (value or object key) against @ref error_handler | |
| None of the binary formats requires a decoder to reject ill-formed UTF-8 | |
| in a text string (see @ref get_string), so by default | |
| (@ref error_handler_t::keep) this does nothing. A stricter | |
| @ref error_handler opts into the same well-formedness check @ref | |
| serializer::dump_escaped_impl applies when dumping a string: | |
| @ref error_handler_t::strict rejects ill-formed input with | |
| parse_error.113 (honoring `allow_exceptions` via @a sax), while | |
| @ref error_handler_t::replace / @ref error_handler_t::ignore sanitize | |
| @a result in place, using the exact same rules. | |
| @param[in,out] result the already assembled string to check | |
| @param[in] context further context information (for diagnostics) | |
| @return whether @a result is acceptable (always true for `keep`) | |
| */ | |
| bool check_string_utf8(string_t& result, const char* context) | |
| { | |
| if (error_handler == error_handler_t::keep || is_valid_utf8(result)) | |
| { | |
| return true; | |
| } | |
| if (error_handler == error_handler_t::strict) | |
| { | |
| return last_byte_error(exception_id::invalid_string_or_size, "invalid string: ill-formed UTF-8 byte", context); | |
| } | |
| result = sanitize_utf8(result, error_handler); | |
| return true; | |
| } | |
| /*! | |
| @brief read a length of type @a NumberType, then a string of that many bytes | |
| @tparam NumberType the type of the length field | |
| @param[out] result string the bytes are appended to | |
| @param[in] context further context information (for diagnostics) | |
| @return whether reading and validating the string succeeded | |
| */ | |
| template<typename NumberType> | |
| bool get_string_with_length(string_t& result, const char* context) | |
| { | |
| NumberType len{}; | |
| return get_number(len) && get_string(len, result) && check_string_utf8(result, context); | |
| } | |
| /*! | |
| @brief create a byte array by reading bytes from the input | |
| @tparam NumberType the type of the number | |
| @param[in] len number of bytes to read | |
| @param[out] result byte array created by reading @a len bytes | |
| @return whether byte array creation completed | |
| @note We can not reserve @a len bytes for the result, because @a len | |
| may be too large. Usually, @ref unexpect_eof() detects the end of | |
| the input before we run out of memory. | |
| */ | |
| template<typename NumberType> | |
| bool get_binary(const NumberType len, | |
| binary_t& result) | |
| { | |
| return get_bytes(len, "binary", result); | |
| } | |
| /*! | |
| @brief read @a len bytes from the input into a string or byte container | |
| @tparam NumberType the type of the length | |
| @tparam ContainerType the destination container (string_t or binary_t) | |
| @param[in] len number of bytes to read | |
| @param[in] context further context information (for diagnostics) | |
| @param[out] result container the bytes are appended to | |
| @return whether reading completed | |
| @note We cannot reserve @a len bytes for the result up front, because | |
| @a len may be far larger than the actual input. Instead we read in | |
| bounded chunks, so the peak allocation is capped regardless of the | |
| claimed length while the per-byte loop is replaced by block copies | |
| (a std::memcpy for contiguous inputs). @ref unexpect_eof() still | |
| detects a premature end of input. | |
| */ | |
| template<typename NumberType, typename ContainerType> | |
| bool get_bytes(NumberType len, | |
| const char* context, | |
| ContainerType& result) | |
| { | |
| // upper bound on the number of bytes read (and allocated) per chunk | |
| constexpr std::size_t chunk_size = 4096; | |
| while (len > 0) | |
| { | |
| // number of bytes to read this iteration: min(chunk_size, len), | |
| // computed without truncating chunk_size to a narrow NumberType | |
| const std::size_t wanted = (static_cast<std::uintmax_t>(len) < static_cast<std::uintmax_t>(chunk_size)) | |
| ? static_cast<std::size_t>(len) | |
| : chunk_size; | |
| const std::size_t old_size = result.size(); | |
| result.resize(old_size + wanted); | |
| // resize() is required to make size() exactly old_size + wanted; | |
| // that is the room get_elements() is allowed to write into | |
| JSON_ASSERT(result.size() == old_size + wanted); | |
| // false positive: bytes_read is read on the next lines | |
| // @infer-ignore DEAD_STORE | |
| const std::size_t bytes_read = ia.get_elements(&result[old_size], wanted); | |
| chars_read += bytes_read; | |
| if (JSON_HEDLEY_UNLIKELY(bytes_read < wanted)) | |
| { | |
| // premature end of input: shrink to what was actually read and | |
| // report the failure at the first missing byte (same position | |
| // accounting as get_to() for partial number reads) | |
| result.resize(old_size + bytes_read); | |
| ++chars_read; | |
| current = char_traits<char_type>::eof(); | |
| return unexpect_eof(context); | |
| } | |
| // a full chunk was read; get_elements() never returns more than requested | |
| JSON_ASSERT(bytes_read == wanted); | |
| len = static_cast<NumberType>(len - static_cast<NumberType>(wanted)); | |
| } | |
| return true; | |
| } | |
| /*! | |
| @param[in] context further context information (for diagnostics) | |
| @return whether the last read character is not EOF | |
| */ | |
| JSON_HEDLEY_NON_NULL(2) | |
| bool unexpect_eof(const char* context) const | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(current == char_traits<char_type>::eof())) | |
| { | |
| return report_eof(context); | |
| } | |
| return true; | |
| } | |
| /*! | |
| @brief reports an unexpected end of input (out of line to keep the exception | |
| construction out of the hot reading functions) | |
| @param[in] context further context information (for diagnostics) | |
| @return the result of the SAX parser's parse_error() | |
| */ | |
| JSON_HEDLEY_NON_NULL(2) | |
| JSON_HEDLEY_NEVER_INLINE | |
| bool report_eof(const char* context) const | |
| { | |
| return sax->parse_error(chars_read, "<end of file>", | |
| parse_error::create(exception_id::unexpected_end_of_input, chars_read, exception_message("unexpected end of input", context), nullptr)); | |
| } | |
| /*! | |
| @brief reports an out_of_range error at the last read byte (out of line) | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| bool out_of_range_error(const exception_id id_, const char* detail, const char* context) const | |
| { | |
| return sax->parse_error(chars_read, get_token_string(), out_of_range::create(id_, exception_message(detail, context), nullptr)); | |
| } | |
| JSON_HEDLEY_NEVER_INLINE | |
| bool container_size_error(const char* what) const | |
| { | |
| return sax->parse_error(chars_read, get_token_string(), out_of_range::create(exception_id::container_too_large, | |
| exception_message(concat("excessive ", what, " size"), "size"), nullptr)); | |
| } | |
| JSON_HEDLEY_NEVER_INLINE | |
| bool optimized_type_error() const | |
| { | |
| return last_byte_error(exception_id::unexpected_byte, concat("marker 0x", get_token_string(), " is not a permitted optimized array type"), "type"); | |
| } | |
| template<typename NumberType> | |
| JSON_HEDLEY_NEVER_INLINE | |
| bool bson_length_error(const char* prefix, const NumberType len, const char* context) const | |
| { | |
| return last_byte_error(exception_id::unexpected_byte, concat(prefix, std::to_string(len)), context); | |
| } | |
| JSON_HEDLEY_NEVER_INLINE | |
| bool bson_document_size_error(const std::int32_t document_size, const std::size_t bytes_read) const | |
| { | |
| return last_byte_error(exception_id::unexpected_byte, concat("document size ", std::to_string(document_size), " does not match the number of bytes read (", std::to_string(bytes_read), ")"), "document"); | |
| } | |
| JSON_HEDLEY_NEVER_INLINE | |
| bool bson_unsupported_type_error(const std::size_t position, const char_int_type element_type) const | |
| { | |
| const std::string cr_str = hex_byte(static_cast<std::uint8_t>(element_type)); | |
| return sax->parse_error(position, cr_str, | |
| parse_error::create(exception_id::bson_unsupported_type, position, concat("Unsupported BSON record type 0x", cr_str), nullptr)); | |
| } | |
| /*! | |
| @brief reports a parse error at the last read byte | |
| @param[in] id_ the id of the parse_error exception | |
| @param[in] detail a detailed error message | |
| @param[in] context further context information | |
| @param[in] tail optional text appended to the detail, followed by "; last byte: 0x<token>" | |
| @return the result of the SAX parser's parse_error() | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| bool last_byte_error(const exception_id id_, const std::string& detail, const char* context, const char* tail = nullptr) const | |
| { | |
| // with a tail, the message reads "<detail><tail>; last byte: 0x<token>" | |
| return sax->parse_error(chars_read, get_token_string(), parse_error::create(id_, chars_read, | |
| exception_message(tail == nullptr ? detail : concat(detail, tail, "; last byte: 0x", get_token_string()), context), nullptr)); | |
| } | |
| /*! | |
| @brief reports the last read byte as unexpected (parse_error.112) | |
| @param[in] detail what is wrong with the byte, e.g. "invalid byte" | |
| @param[in] context further context information | |
| @return the result of the SAX parser's parse_error() | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| bool unexpected_byte(const char* detail, const char* context) const | |
| { | |
| return last_byte_error(exception_id::unexpected_byte, concat(detail, ": 0x", get_token_string()), context); | |
| } | |
| /*! | |
| @brief reports that the last read byte is not a UBJSON/BJData length type (parse_error.113) | |
| @param[in] position where the length type was expected, e.g. " after '#'" | |
| @param[in] context further context information | |
| @return the result of the SAX parser's parse_error() | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| bool length_type_error(const char* position, const char* context) const | |
| { | |
| const char* types = input_format == input_format_t::bjdata ? "U, i, u, I, m, l, M, L" : "U, i, I, l, L"; | |
| return last_byte_error(exception_id::invalid_string_or_size, | |
| concat("expected length type specification (", types, ")", position, "; last byte: 0x", get_token_string()), context); | |
| } | |
| /*! | |
| @return a string representation of the last read byte | |
| */ | |
| std::string get_token_string() const | |
| { | |
| return hex_byte(static_cast<std::uint8_t>(current)); | |
| } | |
| /*! | |
| @param[in] detail a detailed error message | |
| @param[in] context further context information | |
| @return a message string to use in the parse_error exceptions | |
| */ | |
| std::string exception_message(const std::string& detail, | |
| const std::string& context) const | |
| { | |
| std::string error_msg = "syntax error while parsing "; | |
| error_msg += input_format_name(input_format); | |
| return concat(error_msg, ' ', context, ": ", detail); | |
| } | |
| private: | |
| static JSON_INLINE_VARIABLE constexpr std::size_t npos = detail::unknown_size(); | |
| /// input adapter | |
| InputAdapterType ia; | |
| /// the current character | |
| char_int_type current = char_traits<char_type>::eof(); | |
| /// the number of characters read | |
| std::size_t chars_read = 0; | |
| /// whether we can assume little endianness | |
| const bool is_little_endian = little_endianness(); | |
| /// input format | |
| const input_format_t input_format = input_format_t::json; | |
| /// how to treat text strings/object keys that are not well-formed UTF-8 | |
| const error_handler_t error_handler = error_handler_t::keep; | |
| /// the SAX parser | |
| json_sax_t* sax = nullptr; | |
| /// the containers that have been opened and not closed yet; see @ref container_frame | |
| std::vector<container_frame> container_stack{}; | |
| /// BON8: bytes read past the end of a string, returned again by @ref get_bon8 | |
| std::array<char_int_type, 2> bon8_pushback{{}}; | |
| /// BON8: number of bytes in @ref bon8_pushback | |
| std::size_t bon8_pushback_size = 0; | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| /*! | |
| @brief whether @a marker is excluded from BJData's optimized ND-array types | |
| @return whether @a marker is one of 'F', 'H', 'N', 'S', 'T', 'Z', '[', '{' | |
| Mirrors binary_writer's @ref binary_writer::is_bjdata_excluded_type_marker | |
| "is_bjdata_excluded_type_marker()`, which encodes the same list the other | |
| way; keep the two in sync. | |
| */ | |
| static constexpr bool is_bjd_excluded_optimized_type(const char_int_type marker) noexcept | |
| { | |
| return marker == '[' || marker == '{' || marker == 'S' || marker == 'H' | |
| || marker == 'T' || marker == 'F' || marker == 'N' || marker == 'Z'; | |
| } | |
| /*! | |
| @brief look up the ND-array element type name for a BJData dtype marker | |
| @return the type name ("uint8", "int8", ...), or nullptr if @a marker does | |
| not name a known dtype | |
| A C++11 `constexpr` function cannot contain a `switch`, so this is a | |
| plain (non-constexpr) switch instead. | |
| */ | |
| static const char* bjd_type_name(const char_int_type marker) | |
| { | |
| switch (marker) | |
| { | |
| case 'B': | |
| return "byte"; | |
| case 'C': | |
| return "char"; | |
| case 'D': | |
| return "double"; | |
| case 'I': | |
| return "int16"; | |
| case 'L': | |
| return "int64"; | |
| case 'M': | |
| return "uint64"; | |
| case 'U': | |
| return "uint8"; | |
| case 'd': | |
| return "single"; | |
| case 'i': | |
| return "int8"; | |
| case 'l': | |
| return "int32"; | |
| case 'm': | |
| return "uint32"; | |
| case 'u': | |
| return "uint16"; | |
| default: | |
| return nullptr; | |
| } | |
| } | |
| }; | |
| #ifndef JSON_HAS_CPP_17 | |
| template<typename BasicJsonType, typename InputAdapterType, typename SAX> | |
| constexpr std::size_t binary_reader<BasicJsonType, InputAdapterType, SAX>::npos; | |
| #endif | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/input/input_adapters.hpp> | |
| // #include <nlohmann/detail/input/json_sax.hpp> | |
| // #include <nlohmann/detail/input/lexer.hpp> | |
| // #include <nlohmann/detail/input/parser.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cmath> // isfinite | |
| #include <cstdint> // uint8_t | |
| #include <functional> // function | |
| #include <string> // string | |
| #include <utility> // move | |
| #include <vector> // vector | |
| // #include <nlohmann/detail/exceptions.hpp> | |
| // #include <nlohmann/detail/input/input_adapters.hpp> | |
| // #include <nlohmann/detail/input/json_sax.hpp> | |
| // #include <nlohmann/detail/input/lexer.hpp> | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/meta/is_sax.hpp> | |
| // #include <nlohmann/detail/string_concat.hpp> | |
| // #include <nlohmann/detail/value_t.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| //////////// | |
| // parser // | |
| //////////// | |
| enum class parse_event_t : std::uint8_t | |
| { | |
| /// the parser read `{` and started to process a JSON object | |
| object_start, | |
| /// the parser read `}` and finished processing a JSON object | |
| object_end, | |
| /// the parser read `[` and started to process a JSON array | |
| array_start, | |
| /// the parser read `]` and finished processing a JSON array | |
| array_end, | |
| /// the parser read a key of a value in an object | |
| key, | |
| /// the parser finished reading a JSON value | |
| value | |
| }; | |
| template<typename BasicJsonType> | |
| using parser_callback_t = | |
| std::function<bool(int /*depth*/, parse_event_t /*event*/, BasicJsonType& /*parsed*/)>; | |
| /// whether a SAX handler ignores the text of float tokens (the library's own | |
| /// handlers do), so that the parser need not materialize it | |
| template<typename SAX> | |
| struct sax_ignores_number_text : std::false_type {}; | |
| template<typename BasicJsonType, typename InputAdapterType, bool Collect> | |
| struct sax_ignores_number_text<json_sax_dom_parser<BasicJsonType, InputAdapterType, Collect>> : std::true_type {}; | |
| template<typename BasicJsonType, typename InputAdapterType> | |
| struct sax_ignores_number_text<json_sax_dom_callback_parser<BasicJsonType, InputAdapterType>> : std::true_type {}; | |
| template<typename BasicJsonType> | |
| struct sax_ignores_number_text<json_sax_acceptor<BasicJsonType>> : std::true_type {}; | |
| /*! | |
| @brief syntax analysis | |
| This class implements a parser for JSON text. Nested arrays and objects are tracked with an explicit | |
| stack instead of recursion, so deeply nested input does not exhaust the call stack, and what is read | |
| is reported as SAX events. | |
| */ | |
| template<typename BasicJsonType, typename InputAdapterType> | |
| class parser | |
| { | |
| using number_integer_t = typename BasicJsonType::number_integer_t; | |
| using number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
| using number_float_t = typename BasicJsonType::number_float_t; | |
| using string_t = typename BasicJsonType::string_t; | |
| using lexer_t = lexer<BasicJsonType, InputAdapterType>; | |
| using token_type = typename lexer_t::token_type; | |
| public: | |
| /// a parser reading from an input adapter | |
| explicit parser(InputAdapterType&& adapter, | |
| parser_callback_t<BasicJsonType> cb = nullptr, | |
| const bool allow_exceptions_ = true, | |
| const bool ignore_comments = false, | |
| const bool ignore_trailing_commas_ = false, | |
| const bool discard_number_values_ = false) | |
| : callback(std::move(cb)) | |
| , m_lexer(std::move(adapter), ignore_comments, discard_number_values_) | |
| , allow_exceptions(allow_exceptions_) | |
| , ignore_trailing_commas(ignore_trailing_commas_) | |
| { | |
| // read first token | |
| get_token(); | |
| } | |
| /*! | |
| @brief public parser interface | |
| @param[in] strict whether to expect the last token to be EOF | |
| @param[in,out] result parsed JSON value | |
| @throw parse_error.101 in case of an unexpected token (including invalid | |
| unicode escapes and surrogate errors, which are reported with a | |
| detailed message) | |
| */ | |
| void parse(const bool strict, BasicJsonType& result) | |
| { | |
| if (callback) | |
| { | |
| json_sax_dom_callback_parser<BasicJsonType, InputAdapterType> sdp(result, callback, allow_exceptions, &m_lexer); | |
| // in case of an error, return a discarded value | |
| if (!parse_dom(sdp, strict)) | |
| { | |
| result = value_t::discarded; | |
| return; | |
| } | |
| // set top-level value to null if it was discarded by the callback | |
| // function | |
| if (result.is_discarded()) | |
| { | |
| result = nullptr; | |
| } | |
| } | |
| else | |
| { | |
| json_sax_dom_parser<BasicJsonType, InputAdapterType, true> sdp(result, allow_exceptions, &m_lexer); | |
| // in case of an error, return a discarded value | |
| if (!parse_dom(sdp, strict)) | |
| { | |
| result = value_t::discarded; | |
| return; | |
| } | |
| } | |
| result.assert_invariant(); | |
| } | |
| /*! | |
| @brief public accept interface | |
| @param[in] strict whether to expect the last token to be EOF | |
| @return whether the input is a proper JSON text | |
| */ | |
| bool accept(const bool strict = true) | |
| { | |
| json_sax_acceptor<BasicJsonType> sax_acceptor; | |
| return sax_parse(&sax_acceptor, strict); | |
| } | |
| template<typename SAX> | |
| JSON_HEDLEY_NON_NULL(2) | |
| bool sax_parse(SAX* sax, const bool strict = true) | |
| { | |
| (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {}; | |
| const bool result = sax_parse_internal(sax); | |
| if (result) | |
| { | |
| return finish_input(*sax, strict); | |
| } | |
| return false; | |
| } | |
| private: | |
| /// the text of the current float token for @a sax (see sax_ignores_number_text) | |
| template<typename SAX> | |
| const string_t& number_float_text(SAX* /*sax*/) | |
| { | |
| return number_float_text(std::integral_constant<bool, sax_ignores_number_text<SAX>::value> {}); | |
| } | |
| const string_t& number_float_text(std::true_type /*ignored*/) const noexcept | |
| { | |
| return m_lexer.get_ignored_number_text(); | |
| } | |
| string_t& number_float_text(std::false_type /*ignored*/) | |
| { | |
| return m_lexer.get_string(); | |
| } | |
| /*! | |
| @brief apply the end-of-input handling after a value was parsed | |
| In strict mode, the next token must be the end of the input; otherwise | |
| parse_error.101 is reported through @a sax. In non-strict mode, the | |
| lookahead is released so the caller can keep reading the input right after | |
| the parsed value. | |
| @param[in,out] sax the SAX parser to report an error to | |
| @param[in] strict whether to expect the last token to be EOF | |
| @return true, or what @a sax returned for the error | |
| */ | |
| template<typename SAX> | |
| bool finish_input(SAX& sax, const bool strict) | |
| { | |
| if (strict) | |
| { | |
| // strict mode: next byte must be EOF | |
| if (get_token() != token_type::end_of_input) | |
| { | |
| return syntax_error(sax, exception_message(token_type::end_of_input, "value")); | |
| } | |
| } | |
| else | |
| { | |
| // the caller keeps using the input: position it right after | |
| // the value by leaving the character that terminated it | |
| m_lexer.release_lookahead(); | |
| } | |
| return true; | |
| } | |
| /*! | |
| @brief run a DOM SAX parser to completion and position the lexer | |
| Shared by both branches of @ref parse(): builds no SAX parser itself, | |
| but drives an already-constructed @a json_sax_dom_parser or | |
| @ref json_sax_dom_callback_parser through @ref sax_parse_internal(), | |
| then applies the strict-EOF check (reporting parse_error.101 through | |
| @a sdp on failure) or, in non-strict mode, releases the lookahead so | |
| the caller can keep reading the input right after the parsed value. | |
| @param[in,out] sdp the DOM SAX parser to run | |
| @param[in] strict whether to expect the last token to be EOF | |
| @return whether @a sdp did not report an error | |
| */ | |
| template<typename DomSax> | |
| bool parse_dom(DomSax& sdp, const bool strict) | |
| { | |
| sax_parse_internal(&sdp); | |
| static_cast<void>(finish_input(sdp, strict)); | |
| return !sdp.is_errored(); | |
| } | |
| template<typename SAX> | |
| JSON_HEDLEY_NON_NULL(2) | |
| bool sax_parse_internal(SAX* sax) | |
| { | |
| // value to avoid a goto (see comment where set to true) | |
| bool skip_to_state_evaluation = false; | |
| // stack to remember the hierarchy of structured values we are parsing | |
| // true = array; false = object (bytes, not std::vector<bool>, whose | |
| // push_back() is a call with GCC) | |
| std::vector<std::uint8_t> states; | |
| // a document that starts with a container pushes onto the stack at | |
| // once: allocate it in one step instead of growing it from 1 byte | |
| if (last_token == token_type::begin_object || last_token == token_type::begin_array) | |
| { | |
| states.reserve(32); | |
| } | |
| while (true) | |
| { | |
| if (!skip_to_state_evaluation) | |
| { | |
| // invariant: get_token() was called before each iteration | |
| switch (last_token) | |
| { | |
| case token_type::begin_object: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!sax->start_object(detail::unknown_size()))) | |
| { | |
| return false; | |
| } | |
| // closing } -> we are done | |
| if (get_token() == token_type::end_object) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) | |
| { | |
| return false; | |
| } | |
| break; | |
| } | |
| // parse key | |
| if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) | |
| { | |
| return syntax_error(*sax, exception_message(token_type::value_string, "object key")); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string_token()))) | |
| { | |
| return false; | |
| } | |
| // parse separator (:) | |
| if (JSON_HEDLEY_UNLIKELY(!get_token_expecting(token_type::name_separator))) | |
| { | |
| return syntax_error(*sax, exception_message(token_type::name_separator, "object separator")); | |
| } | |
| // remember we are now inside an object | |
| states.push_back(0); | |
| // parse values | |
| get_token(); | |
| continue; | |
| } | |
| case token_type::begin_array: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!sax->start_array(detail::unknown_size()))) | |
| { | |
| return false; | |
| } | |
| // closing ] -> we are done | |
| if (get_token() == token_type::end_array) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) | |
| { | |
| return false; | |
| } | |
| break; | |
| } | |
| // remember we are now inside an array | |
| states.push_back(1); | |
| // parse values (no need to call get_token) | |
| continue; | |
| } | |
| case token_type::value_float: | |
| { | |
| const auto res = m_lexer.get_number_float(); | |
| if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res))) | |
| { | |
| return sax->parse_error(m_lexer.get_position(), | |
| m_lexer.get_token_string(), | |
| out_of_range::create(exception_id::number_overflow, concat("number overflow parsing '", m_lexer.get_token_string(), '\''), nullptr)); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, number_float_text(sax)))) | |
| { | |
| return false; | |
| } | |
| break; | |
| } | |
| case token_type::literal_false: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false))) | |
| { | |
| return false; | |
| } | |
| break; | |
| } | |
| case token_type::literal_null: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!sax->null())) | |
| { | |
| return false; | |
| } | |
| break; | |
| } | |
| case token_type::literal_true: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true))) | |
| { | |
| return false; | |
| } | |
| break; | |
| } | |
| case token_type::value_integer: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer()))) | |
| { | |
| return false; | |
| } | |
| break; | |
| } | |
| case token_type::value_string: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string_token()))) | |
| { | |
| return false; | |
| } | |
| break; | |
| } | |
| case token_type::value_unsigned: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned()))) | |
| { | |
| return false; | |
| } | |
| break; | |
| } | |
| case token_type::parse_error: | |
| { | |
| // using "uninitialized" to avoid an "expected" message | |
| return syntax_error(*sax, exception_message(token_type::uninitialized, "value")); | |
| } | |
| case token_type::end_of_input: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(m_lexer.get_chars_read_total() == 1)) | |
| { | |
| return syntax_error(*sax, empty_input_message()); | |
| } | |
| return syntax_error(*sax, exception_message(token_type::literal_or_value, "value")); | |
| } | |
| case token_type::uninitialized: | |
| case token_type::end_array: | |
| case token_type::end_object: | |
| case token_type::name_separator: | |
| case token_type::value_separator: | |
| case token_type::literal_or_value: | |
| default: // the last token was unexpected | |
| { | |
| return syntax_error(*sax, exception_message(token_type::literal_or_value, "value")); | |
| } | |
| } | |
| } | |
| else | |
| { | |
| skip_to_state_evaluation = false; | |
| } | |
| // we reached this line after we successfully parsed a value | |
| if (states.empty()) | |
| { | |
| // empty stack: we reached the end of the hierarchy: done | |
| return true; | |
| } | |
| if (states.back() != 0) // array | |
| { | |
| // comma -> next value | |
| // or end of array (ignore_trailing_commas = true) | |
| if (get_token_expecting(token_type::value_separator)) | |
| { | |
| // parse a new value | |
| get_token(); | |
| // if ignore_trailing_commas and last_token is ], we can continue to "closing ]" | |
| if (!(ignore_trailing_commas && last_token == token_type::end_array)) | |
| { | |
| continue; | |
| } | |
| } | |
| // closing ] | |
| if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array)) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) | |
| { | |
| return false; | |
| } | |
| // We are done with this array. Before we can parse a | |
| // new value, we need to evaluate the new state first. | |
| // By setting skip_to_state_evaluation to true, the next | |
| // iteration skips parsing a value and evaluates the | |
| // enclosing state directly. | |
| JSON_ASSERT(!states.empty()); | |
| states.pop_back(); | |
| skip_to_state_evaluation = true; | |
| continue; | |
| } | |
| return syntax_error(*sax, exception_message(token_type::end_array, "array")); | |
| } | |
| // states.back() is false -> object | |
| // comma -> next value | |
| // or end of object (ignore_trailing_commas = true) | |
| if (get_token_expecting(token_type::value_separator)) | |
| { | |
| get_token(); | |
| // if ignore_trailing_commas and last_token is }, we can continue to "closing }" | |
| if (!(ignore_trailing_commas && last_token == token_type::end_object)) | |
| { | |
| // parse key | |
| if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) | |
| { | |
| return syntax_error(*sax, exception_message(token_type::value_string, "object key")); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string_token()))) | |
| { | |
| return false; | |
| } | |
| // parse separator (:) | |
| if (JSON_HEDLEY_UNLIKELY(!get_token_expecting(token_type::name_separator))) | |
| { | |
| return syntax_error(*sax, exception_message(token_type::name_separator, "object separator")); | |
| } | |
| // parse values | |
| get_token(); | |
| continue; | |
| } | |
| } | |
| // closing } | |
| if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object)) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) | |
| { | |
| return false; | |
| } | |
| // We are done with this object. Before we can parse a | |
| // new value, we need to evaluate the new state first. | |
| // By setting skip_to_state_evaluation to true, the next | |
| // iteration skips parsing a value and evaluates the | |
| // enclosing state directly. | |
| JSON_ASSERT(!states.empty()); | |
| states.pop_back(); | |
| skip_to_state_evaluation = true; | |
| continue; | |
| } | |
| return syntax_error(*sax, exception_message(token_type::end_object, "object")); | |
| } | |
| } | |
| /// get next token from lexer | |
| token_type get_token() | |
| { | |
| return last_token = m_lexer.scan(); | |
| } | |
| /// get next token from lexer; true if it is the separator @a expected_type | |
| /// (name_separator or value_separator), which it usually is | |
| bool get_token_expecting(token_type expected_type) | |
| { | |
| return (last_token = m_lexer.scan_expecting(expected_type)) == expected_type; | |
| } | |
| /*! | |
| @brief reports a syntax error at the current token (parse_error.101) | |
| @param[in] sax the SAX parser to report the error to | |
| @param[in] message the error message | |
| @return the result of the SAX parser's parse_error() | |
| */ | |
| template<typename SAX> | |
| bool syntax_error(SAX& sax, const std::string& message) | |
| { | |
| // MSVC 2015 reports C4100 (unreferenced parameter) when SAX::parse_error is static | |
| static_cast<void>(sax); | |
| // computing the position is O(input read so far) for seekable input | |
| const position_t position = m_lexer.get_position(); | |
| return sax.parse_error(position, m_lexer.get_token_string(), | |
| parse_error::create(exception_id::syntax_error, position, message, nullptr)); | |
| } | |
| std::string exception_message(const token_type expected, const std::string& context) | |
| { | |
| std::string error_msg = "syntax error "; | |
| if (!context.empty()) | |
| { | |
| error_msg += concat("while parsing ", context, ' '); | |
| } | |
| error_msg += "- "; | |
| if (last_token == token_type::parse_error) | |
| { | |
| error_msg += concat(m_lexer.get_error_message(), "; last read: '", | |
| m_lexer.get_token_string(), '\''); | |
| } | |
| else | |
| { | |
| error_msg += concat("unexpected ", lexer_t::token_type_name(last_token)); | |
| } | |
| if (expected != token_type::uninitialized) | |
| { | |
| error_msg += concat("; expected ", lexer_t::token_type_name(expected)); | |
| } | |
| return error_msg; | |
| } | |
| private: | |
| /// callback function | |
| const parser_callback_t<BasicJsonType> callback = nullptr; | |
| /// the type of the last read token | |
| token_type last_token = token_type::uninitialized; | |
| /// the lexer | |
| lexer_t m_lexer; | |
| /// whether to throw exceptions in case of errors | |
| const bool allow_exceptions = true; | |
| /// whether trailing commas in objects and arrays should be ignored (true) or signaled as errors (false) | |
| const bool ignore_trailing_commas = false; | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/iterators/internal_iterator.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| // #include <nlohmann/detail/iterators/primitive_iterator.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cstddef> // ptrdiff_t | |
| #include <limits> // numeric_limits | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /* | |
| @brief an iterator for primitive JSON types | |
| This class models an iterator for primitive JSON types (boolean, number, | |
| string). Its only purpose is to allow the iterator/const_iterator classes | |
| to "iterate" over primitive values. Internally, the iterator is modeled by | |
| a `difference_type` variable. Value begin_value (`0`) models the begin and | |
| end_value (`1`) models past the end. | |
| */ | |
| class primitive_iterator_t | |
| { | |
| private: | |
| using difference_type = std::ptrdiff_t; | |
| static constexpr difference_type begin_value = 0; | |
| static constexpr difference_type end_value = begin_value + 1; | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| /// iterator as signed integer type | |
| difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)(); | |
| public: | |
| constexpr difference_type get_value() const noexcept | |
| { | |
| return m_it; | |
| } | |
| /// set iterator to a defined beginning | |
| void set_begin() noexcept | |
| { | |
| m_it = begin_value; | |
| } | |
| /// set iterator to a defined past the end | |
| void set_end() noexcept | |
| { | |
| m_it = end_value; | |
| } | |
| /// return whether the iterator can be dereferenced | |
| constexpr bool is_begin() const noexcept | |
| { | |
| return m_it == begin_value; | |
| } | |
| /// return whether the iterator is at end | |
| constexpr bool is_end() const noexcept | |
| { | |
| return m_it == end_value; | |
| } | |
| friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept | |
| { | |
| return lhs.m_it == rhs.m_it; | |
| } | |
| friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept | |
| { | |
| return lhs.m_it < rhs.m_it; | |
| } | |
| primitive_iterator_t operator+(difference_type n) noexcept | |
| { | |
| auto result = *this; | |
| result += n; | |
| return result; | |
| } | |
| friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept | |
| { | |
| return lhs.m_it - rhs.m_it; | |
| } | |
| primitive_iterator_t& operator++() noexcept | |
| { | |
| ++m_it; | |
| return *this; | |
| } | |
| primitive_iterator_t operator++(int)& noexcept // NOLINT(cert-dcl21-cpp) | |
| { | |
| auto result = *this; | |
| ++m_it; | |
| return result; | |
| } | |
| primitive_iterator_t& operator--() noexcept | |
| { | |
| --m_it; | |
| return *this; | |
| } | |
| primitive_iterator_t operator--(int)& noexcept // NOLINT(cert-dcl21-cpp) | |
| { | |
| auto result = *this; | |
| --m_it; | |
| return result; | |
| } | |
| primitive_iterator_t& operator+=(difference_type n) noexcept | |
| { | |
| m_it += n; | |
| return *this; | |
| } | |
| primitive_iterator_t& operator-=(difference_type n) noexcept | |
| { | |
| m_it -= n; | |
| return *this; | |
| } | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /*! | |
| @brief an iterator value | |
| @note This structure could easily be a union, but MSVC currently does not allow | |
| unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. | |
| */ | |
| template<typename BasicJsonType> struct internal_iterator | |
| { | |
| /// iterator for JSON objects | |
| typename BasicJsonType::object_t::iterator object_iterator {}; | |
| /// iterator for JSON arrays | |
| typename BasicJsonType::array_t::iterator array_iterator {}; | |
| /// generic iterator for all other types | |
| primitive_iterator_t primitive_iterator {}; | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/iterators/iter_impl.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next | |
| #include <type_traits> // conditional, is_const, remove_const | |
| // #include <nlohmann/detail/exceptions.hpp> | |
| // #include <nlohmann/detail/iterators/internal_iterator.hpp> | |
| // #include <nlohmann/detail/iterators/primitive_iterator.hpp> | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/meta/cpp_future.hpp> | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| // #include <nlohmann/detail/value_t.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| // forward declare to be able to friend it later on | |
| template<typename IteratorType> class iteration_proxy; | |
| template<typename IteratorType> class iteration_proxy_value; | |
| /*! | |
| @brief a template for a bidirectional iterator for the @ref basic_json class | |
| This class implements a both iterators (iterator and const_iterator) for the | |
| @ref basic_json class. | |
| @note An iterator is called *initialized* when a pointer to a JSON value has | |
| been set (e.g., by a constructor or a copy assignment). If the iterator is | |
| default-constructed, it is *uninitialized* and most methods are undefined. | |
| **The library uses assertions to detect calls on uninitialized iterators.** | |
| This class satisfies the following concept requirements (REQ-JSON-01): | |
| - | |
| [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): | |
| The iterator that can be moved can be moved in both directions (i.e. | |
| incremented and decremented). | |
| @since version 1.0.0, simplified in version 2.0.9, change to bidirectional | |
| iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) | |
| */ | |
| template<typename BasicJsonType> | |
| class iter_impl // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) | |
| { | |
| /// the iterator with BasicJsonType of different const-ness | |
| using other_iter_impl = iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>; | |
| /// allow basic_json to access private members | |
| friend other_iter_impl; | |
| friend BasicJsonType; | |
| friend iteration_proxy<iter_impl>; | |
| friend iteration_proxy_value<iter_impl>; | |
| using object_t = typename BasicJsonType::object_t; | |
| using array_t = typename BasicJsonType::array_t; | |
| // make sure BasicJsonType is basic_json or const basic_json | |
| static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value, | |
| "iter_impl only accepts (const) basic_json"); | |
| // superficial check for the LegacyBidirectionalIterator named requirement | |
| // note: only array_t::iterator is checked here; object_t::iterator may be | |
| // a forward-only iterator as long as reverse iteration and operator-- | |
| // are never used on it | |
| static_assert(std::is_base_of<std::bidirectional_iterator_tag, typename std::iterator_traits<typename array_t::iterator>::iterator_category>::value, | |
| "basic_json iterator assumes array type iterators satisfy the LegacyBidirectionalIterator named requirement."); | |
| public: | |
| /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. | |
| /// The C++ Standard has never required user-defined iterators to derive from std::iterator. | |
| /// A user-defined iterator should provide publicly accessible typedefs named | |
| /// iterator_category, value_type, difference_type, pointer, and reference. | |
| /// Note that value_type is required to be non-const, even for constant iterators. | |
| using iterator_category = std::bidirectional_iterator_tag; | |
| /// the type of the values when the iterator is dereferenced | |
| using value_type = typename BasicJsonType::value_type; | |
| /// a type to represent differences between iterators | |
| using difference_type = typename BasicJsonType::difference_type; | |
| /// defines a pointer to the type iterated over (value_type) | |
| using pointer = typename std::conditional<std::is_const<BasicJsonType>::value, | |
| typename BasicJsonType::const_pointer, | |
| typename BasicJsonType::pointer>::type; | |
| /// defines a reference to the type iterated over (value_type) | |
| using reference = | |
| typename std::conditional<std::is_const<BasicJsonType>::value, | |
| typename BasicJsonType::const_reference, | |
| typename BasicJsonType::reference>::type; | |
| iter_impl() = default; | |
| ~iter_impl() = default; | |
| // the exception specification is left to be computed rather than declared: | |
| // an array or object type whose iterator is not nothrow move constructible | |
| // (std::deque's is not before libstdc++ 11) would make a declared noexcept | |
| // differ from the implicit one, which deletes the function -- and is an | |
| // error outright with older compilers | |
| iter_impl(iter_impl&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor,cppcoreguidelines-noexcept-move-operations) | |
| iter_impl& operator=(iter_impl&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor,cppcoreguidelines-noexcept-move-operations) | |
| /*! | |
| @brief constructor for a given JSON instance | |
| @param[in] object pointer to a JSON object for this iterator | |
| @pre object != nullptr | |
| @post The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| explicit iter_impl(pointer object) noexcept : m_object(object) | |
| { | |
| JSON_ASSERT(m_object != nullptr); | |
| if (m_object->is_object()) | |
| { | |
| m_it.object_iterator = typename object_t::iterator(); | |
| } | |
| else if (m_object->is_array()) | |
| { | |
| m_it.array_iterator = typename array_t::iterator(); | |
| } | |
| else | |
| { | |
| // primitive (is_primitive(), including discarded) | |
| m_it.primitive_iterator = primitive_iterator_t(); | |
| } | |
| } | |
| /*! | |
| @note The conventional copy constructor and copy assignment are implicitly | |
| defined. Combined with the following converting constructor and | |
| assignment, they support: (1) copy from iterator to iterator, (2) | |
| copy from const iterator to const iterator, and (3) conversion from | |
| iterator to const iterator. However conversion from const iterator | |
| to iterator is not defined. | |
| */ | |
| /*! | |
| @brief const copy constructor | |
| @param[in] other const iterator to copy from | |
| @note This copy constructor had to be defined explicitly to circumvent a bug | |
| occurring on msvc v19.0 compiler (VS 2015) debug build. For more | |
| information refer to: https://github.com/nlohmann/json/issues/1608 | |
| */ | |
| iter_impl(const iter_impl<const BasicJsonType>& other) noexcept | |
| : m_object(other.m_object), m_it(other.m_it) | |
| {} | |
| /*! | |
| @brief converting assignment | |
| @param[in] other const iterator to copy from | |
| @return const/non-const iterator | |
| @note It is not checked whether @a other is initialized. | |
| */ | |
| iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept | |
| { | |
| if (&other != this) | |
| { | |
| m_object = other.m_object; | |
| m_it = other.m_it; | |
| } | |
| return *this; | |
| } | |
| /*! | |
| @brief converting constructor | |
| @param[in] other non-const iterator to copy from | |
| @note It is not checked whether @a other is initialized. | |
| */ | |
| iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept | |
| : m_object(other.m_object), m_it(other.m_it) | |
| {} | |
| /*! | |
| @brief converting assignment | |
| @param[in] other non-const iterator to copy from | |
| @return const/non-const iterator | |
| @note It is not checked whether @a other is initialized. | |
| */ | |
| iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept // NOLINT(cert-oop54-cpp) | |
| { | |
| m_object = other.m_object; | |
| m_it = other.m_it; | |
| return *this; | |
| } | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| /*! | |
| @brief set the iterator to the first value | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| void set_begin() noexcept | |
| { | |
| JSON_ASSERT(m_object != nullptr); | |
| switch (m_object->m_data.m_type) | |
| { | |
| case value_t::object: | |
| { | |
| m_it.object_iterator = m_object->m_data.m_value.object->begin(); | |
| break; | |
| } | |
| case value_t::array: | |
| { | |
| m_it.array_iterator = m_object->m_data.m_value.array->begin(); | |
| break; | |
| } | |
| case value_t::null: | |
| { | |
| // set to end so begin()==end() is true: null is empty | |
| m_it.primitive_iterator.set_end(); | |
| break; | |
| } | |
| case value_t::string: | |
| case value_t::boolean: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| case value_t::binary: | |
| case value_t::discarded: | |
| default: | |
| { | |
| m_it.primitive_iterator.set_begin(); | |
| break; | |
| } | |
| } | |
| } | |
| /*! | |
| @brief set the iterator past the last value | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| void set_end() noexcept | |
| { | |
| JSON_ASSERT(m_object != nullptr); | |
| if (m_object->is_object()) | |
| { | |
| m_it.object_iterator = m_object->m_data.m_value.object->end(); | |
| } | |
| else if (m_object->is_array()) | |
| { | |
| m_it.array_iterator = m_object->m_data.m_value.array->end(); | |
| } | |
| else | |
| { | |
| // primitive (is_primitive(), including discarded) | |
| m_it.primitive_iterator.set_end(); | |
| } | |
| } | |
| /// @throw invalid_iterator.212 if @a other points to another container | |
| template<typename IterImpl> | |
| JSON_HEDLEY_ALWAYS_INLINE void check_same_container(const IterImpl& other) const | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) | |
| { | |
| throw_literal<invalid_iterator>(exception_id::iterators_compare_different_values, "cannot compare iterators of different containers", m_object); | |
| } | |
| } | |
| /// @throw invalid_iterator.214 always | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE void throw_cannot_get_value() const | |
| { | |
| JSON_THROW(invalid_iterator::create(exception_id::iterator_value_unavailable, "cannot get value", m_object)); | |
| } | |
| public: | |
| /*! | |
| @brief return a reference to the value pointed to by the iterator | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| reference operator*() const | |
| { | |
| JSON_ASSERT(m_object != nullptr); | |
| if (JSON_HEDLEY_LIKELY(m_object->m_data.m_type == value_t::array)) | |
| { | |
| JSON_ASSERT(m_it.array_iterator != m_object->m_data.m_value.array->end()); | |
| return *m_it.array_iterator; | |
| } | |
| if (JSON_HEDLEY_LIKELY(m_object->m_data.m_type == value_t::object)) | |
| { | |
| JSON_ASSERT(m_it.object_iterator != m_object->m_data.m_value.object->end()); | |
| return m_it.object_iterator->second; | |
| } | |
| // neither array nor object: a primitive value (null has no value to point to) | |
| if (JSON_HEDLEY_LIKELY(m_object->m_data.m_type != value_t::null && m_it.primitive_iterator.is_begin())) | |
| { | |
| return *m_object; | |
| } | |
| throw_cannot_get_value(); | |
| } | |
| /*! | |
| @brief dereference the iterator | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| pointer operator->() const | |
| { | |
| JSON_ASSERT(m_object != nullptr); | |
| if (JSON_HEDLEY_LIKELY(m_object->m_data.m_type == value_t::array)) | |
| { | |
| JSON_ASSERT(m_it.array_iterator != m_object->m_data.m_value.array->end()); | |
| return &*m_it.array_iterator; | |
| } | |
| if (JSON_HEDLEY_LIKELY(m_object->m_data.m_type == value_t::object)) | |
| { | |
| JSON_ASSERT(m_it.object_iterator != m_object->m_data.m_value.object->end()); | |
| return &(m_it.object_iterator->second); | |
| } | |
| // neither array nor object: a primitive value | |
| if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) | |
| { | |
| return m_object; | |
| } | |
| throw_cannot_get_value(); | |
| } | |
| /*! | |
| @brief post-increment (it++) | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| iter_impl operator++(int)& // NOLINT(cert-dcl21-cpp) | |
| { | |
| auto result = *this; | |
| ++(*this); | |
| return result; | |
| } | |
| /*! | |
| @brief pre-increment (++it) | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| iter_impl& operator++() | |
| { | |
| JSON_ASSERT(m_object != nullptr); | |
| if (JSON_HEDLEY_LIKELY(m_object->m_data.m_type == value_t::array)) | |
| { | |
| ++m_it.array_iterator; | |
| return *this; | |
| } | |
| if (JSON_HEDLEY_LIKELY(m_object->m_data.m_type == value_t::object)) | |
| { | |
| std::advance(m_it.object_iterator, 1); | |
| return *this; | |
| } | |
| // neither array nor object: a primitive value | |
| ++m_it.primitive_iterator; | |
| return *this; | |
| } | |
| /*! | |
| @brief post-decrement (it--) | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| iter_impl operator--(int)& // NOLINT(cert-dcl21-cpp) | |
| { | |
| auto result = *this; | |
| --(*this); | |
| return result; | |
| } | |
| /*! | |
| @brief pre-decrement (--it) | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| iter_impl& operator--() | |
| { | |
| JSON_ASSERT(m_object != nullptr); | |
| if (JSON_HEDLEY_LIKELY(m_object->m_data.m_type == value_t::array)) | |
| { | |
| --m_it.array_iterator; | |
| return *this; | |
| } | |
| if (JSON_HEDLEY_LIKELY(m_object->m_data.m_type == value_t::object)) | |
| { | |
| std::advance(m_it.object_iterator, -1); | |
| return *this; | |
| } | |
| // neither array nor object: a primitive value | |
| --m_it.primitive_iterator; | |
| return *this; | |
| } | |
| /*! | |
| @brief comparison: equal | |
| @pre (1) Both iterators are initialized to point to the same object, or (2) both iterators are value-initialized. | |
| */ | |
| template < typename IterImpl, detail::enable_if_t < (std::is_same<IterImpl, iter_impl>::value || std::is_same<IterImpl, other_iter_impl>::value), std::nullptr_t > = nullptr > | |
| bool operator==(const IterImpl& other) const | |
| { | |
| // if objects are not the same, the comparison is undefined | |
| check_same_container(other); | |
| // value-initialized forward iterators can be compared, and must compare equal to other value-initialized iterators of the same type #4493 | |
| if (m_object == nullptr) | |
| { | |
| return true; | |
| } | |
| if (JSON_HEDLEY_LIKELY(m_object->m_data.m_type == value_t::array)) | |
| { | |
| return (m_it.array_iterator == other.m_it.array_iterator); | |
| } | |
| if (JSON_HEDLEY_LIKELY(m_object->m_data.m_type == value_t::object)) | |
| { | |
| return (m_it.object_iterator == other.m_it.object_iterator); | |
| } | |
| // neither array nor object: a primitive value | |
| return (m_it.primitive_iterator == other.m_it.primitive_iterator); | |
| } | |
| /*! | |
| @brief comparison: not equal | |
| @pre (1) Both iterators are initialized to point to the same object, or (2) both iterators are value-initialized. | |
| */ | |
| template < typename IterImpl, detail::enable_if_t < (std::is_same<IterImpl, iter_impl>::value || std::is_same<IterImpl, other_iter_impl>::value), std::nullptr_t > = nullptr > | |
| bool operator!=(const IterImpl& other) const | |
| { | |
| return !operator==(other); | |
| } | |
| /*! | |
| @brief comparison: smaller | |
| @pre (1) Both iterators are initialized to point to the same object, or (2) both iterators are value-initialized. | |
| */ | |
| bool operator<(const iter_impl& other) const | |
| { | |
| // if objects are not the same, the comparison is undefined | |
| check_same_container(other); | |
| // value-initialized forward iterators can be compared, and must compare equal to other value-initialized iterators of the same type #4493 | |
| if (m_object == nullptr) | |
| { | |
| // the iterators are both value-initialized and are to be considered equal, but this function checks for smaller, so we return false | |
| return false; | |
| } | |
| if (m_object->is_object()) | |
| { | |
| throw_literal<invalid_iterator>(exception_id::iterator_order_on_object, "cannot compare order of object iterators", m_object); | |
| } | |
| if (m_object->is_array()) | |
| { | |
| return (m_it.array_iterator < other.m_it.array_iterator); | |
| } | |
| // primitive (is_primitive(), including discarded) | |
| return (m_it.primitive_iterator < other.m_it.primitive_iterator); | |
| } | |
| /*! | |
| @brief comparison: less than or equal | |
| @pre (1) Both iterators are initialized to point to the same object, or (2) both iterators are value-initialized. | |
| */ | |
| bool operator<=(const iter_impl& other) const | |
| { | |
| return !other.operator < (*this); | |
| } | |
| /*! | |
| @brief comparison: greater than | |
| @pre (1) Both iterators are initialized to point to the same object, or (2) both iterators are value-initialized. | |
| */ | |
| bool operator>(const iter_impl& other) const | |
| { | |
| return !operator<=(other); | |
| } | |
| /*! | |
| @brief comparison: greater than or equal | |
| @pre (1) The iterator is initialized; i.e. `m_object != nullptr`, or (2) both iterators are value-initialized. | |
| */ | |
| bool operator>=(const iter_impl& other) const | |
| { | |
| return !operator<(other); | |
| } | |
| /*! | |
| @brief add to iterator | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| iter_impl& operator+=(difference_type i) | |
| { | |
| JSON_ASSERT(m_object != nullptr); | |
| if (m_object->is_object()) | |
| { | |
| throw_literal<invalid_iterator>(exception_id::iterator_arithmetic_on_object, "cannot use offsets with object iterators", m_object); | |
| } | |
| if (m_object->is_array()) | |
| { | |
| std::advance(m_it.array_iterator, i); | |
| } | |
| else | |
| { | |
| // primitive (is_primitive(), including discarded) | |
| m_it.primitive_iterator += i; | |
| } | |
| return *this; | |
| } | |
| /*! | |
| @brief subtract from iterator | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| iter_impl& operator-=(difference_type i) | |
| { | |
| return operator+=(-i); | |
| } | |
| /*! | |
| @brief add to iterator | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| iter_impl operator+(difference_type i) const | |
| { | |
| auto result = *this; | |
| result += i; | |
| return result; | |
| } | |
| /*! | |
| @brief addition of distance and iterator | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| friend iter_impl operator+(difference_type i, const iter_impl& it) | |
| { | |
| auto result = it; | |
| result += i; | |
| return result; | |
| } | |
| /*! | |
| @brief subtract from iterator | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| iter_impl operator-(difference_type i) const | |
| { | |
| auto result = *this; | |
| result -= i; | |
| return result; | |
| } | |
| /*! | |
| @brief return difference | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| difference_type operator-(const iter_impl& other) const | |
| { | |
| JSON_ASSERT(m_object != nullptr); | |
| if (m_object->is_object()) | |
| { | |
| throw_literal<invalid_iterator>(exception_id::iterator_arithmetic_on_object, "cannot use offsets with object iterators", m_object); | |
| } | |
| if (m_object->is_array()) | |
| { | |
| return m_it.array_iterator - other.m_it.array_iterator; | |
| } | |
| // primitive (is_primitive(), including discarded) | |
| return m_it.primitive_iterator - other.m_it.primitive_iterator; | |
| } | |
| /*! | |
| @brief access to successor | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| reference operator[](difference_type n) const | |
| { | |
| JSON_ASSERT(m_object != nullptr); | |
| switch (m_object->m_data.m_type) | |
| { | |
| case value_t::object: | |
| throw_literal<invalid_iterator>(exception_id::iterator_subscript_on_object, "cannot use operator[] for object iterators", m_object); | |
| case value_t::array: | |
| return *std::next(m_it.array_iterator, n); | |
| case value_t::null: | |
| throw_cannot_get_value(); | |
| case value_t::string: | |
| case value_t::boolean: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| case value_t::binary: | |
| case value_t::discarded: | |
| default: | |
| { | |
| if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n)) | |
| { | |
| return *m_object; | |
| } | |
| throw_cannot_get_value(); | |
| } | |
| } | |
| } | |
| /*! | |
| @brief return the key of an object iterator | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| const typename object_t::key_type& key() const | |
| { | |
| JSON_ASSERT(m_object != nullptr); | |
| if (JSON_HEDLEY_UNLIKELY(!m_object->is_object())) | |
| { | |
| throw_literal<invalid_iterator>(exception_id::iterator_key_not_object, "cannot use key() for non-object iterators", m_object); | |
| } | |
| return m_it.object_iterator->first; | |
| } | |
| /*! | |
| @brief return the value of an iterator | |
| @pre The iterator is initialized; i.e. `m_object != nullptr`. | |
| */ | |
| reference value() const | |
| { | |
| return operator*(); | |
| } | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| /// associated JSON instance | |
| pointer m_object = nullptr; | |
| /// the actual iterator of the associated instance | |
| internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {}; | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/iterators/iteration_proxy.hpp> | |
| // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <cstddef> // ptrdiff_t | |
| #include <iterator> // reverse_iterator | |
| #include <utility> // declval | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| ////////////////////// | |
| // reverse_iterator // | |
| ////////////////////// | |
| /*! | |
| @brief a template for a reverse iterator class | |
| @tparam Base the base iterator type to reverse. Valid types are @ref | |
| iterator (to create @ref reverse_iterator) and @ref const_iterator (to | |
| create @ref const_reverse_iterator). | |
| This class satisfies the following concept requirements (REQ-JSON-02): | |
| - | |
| [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): | |
| The iterator that can be moved can be moved in both directions (i.e. | |
| incremented and decremented). | |
| - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): | |
| It is possible to write to the pointed-to element (only if @a Base is | |
| @ref iterator). | |
| @since version 1.0.0 | |
| */ | |
| template<typename Base> | |
| class json_reverse_iterator : public std::reverse_iterator<Base> | |
| { | |
| public: | |
| using difference_type = std::ptrdiff_t; | |
| /// shortcut to the reverse iterator adapter | |
| using base_iterator = std::reverse_iterator<Base>; | |
| /// the reference type for the pointed-to element | |
| using reference = typename Base::reference; | |
| /// create reverse iterator from iterator | |
| explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept | |
| : base_iterator(it) {} | |
| /// create reverse iterator from base class | |
| explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} | |
| /// post-increment (it++) | |
| json_reverse_iterator operator++(int)& // NOLINT(cert-dcl21-cpp) | |
| { | |
| return static_cast<json_reverse_iterator>(base_iterator::operator++(1)); | |
| } | |
| /// pre-increment (++it) | |
| json_reverse_iterator& operator++() | |
| { | |
| return static_cast<json_reverse_iterator&>(base_iterator::operator++()); | |
| } | |
| /// post-decrement (it--) | |
| json_reverse_iterator operator--(int)& // NOLINT(cert-dcl21-cpp) | |
| { | |
| return static_cast<json_reverse_iterator>(base_iterator::operator--(1)); | |
| } | |
| /// pre-decrement (--it) | |
| json_reverse_iterator& operator--() | |
| { | |
| return static_cast<json_reverse_iterator&>(base_iterator::operator--()); | |
| } | |
| /// add to iterator | |
| json_reverse_iterator& operator+=(difference_type i) | |
| { | |
| return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i)); | |
| } | |
| /// add to iterator | |
| json_reverse_iterator operator+(difference_type i) const | |
| { | |
| return static_cast<json_reverse_iterator>(base_iterator::operator+(i)); | |
| } | |
| /// subtract from iterator | |
| json_reverse_iterator operator-(difference_type i) const | |
| { | |
| return static_cast<json_reverse_iterator>(base_iterator::operator-(i)); | |
| } | |
| /// return difference | |
| difference_type operator-(const json_reverse_iterator& other) const | |
| { | |
| return base_iterator(*this) - base_iterator(other); | |
| } | |
| /// access to successor | |
| reference operator[](difference_type n) const | |
| { | |
| return *(this->operator+(n)); | |
| } | |
| /// return the key of an object iterator | |
| auto key() const -> decltype(std::declval<Base>().key()) | |
| { | |
| auto it = --this->base(); | |
| return it.key(); | |
| } | |
| /// return the value of an iterator | |
| reference value() const | |
| { | |
| auto it = --this->base(); | |
| return it.operator * (); | |
| } | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/iterators/primitive_iterator.hpp> | |
| // #include <nlohmann/detail/json_custom_base_class.hpp> | |
| // #include <nlohmann/detail/json_pointer.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <algorithm> // all_of, copy | |
| #include <array> // array | |
| #include <cctype> // isdigit | |
| #include <cerrno> // errno, ERANGE | |
| #include <cstddef> // size_t | |
| #include <cstdint> // uint64_t | |
| #include <cstdlib> // strtoull | |
| #include <cstring> // memchr, memcmp, memcpy | |
| #ifndef JSON_NO_IO | |
| #include <iosfwd> // ostream | |
| #endif // JSON_NO_IO | |
| #include <limits> // max | |
| #include <string> // string | |
| #include <utility> // move | |
| #include <vector> // vector | |
| // #include <nlohmann/detail/exceptions.hpp> | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/meta/cpp_future.hpp> | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| // #include <nlohmann/detail/string_concat.hpp> | |
| // #include <nlohmann/detail/string_escape.hpp> | |
| // #include <nlohmann/detail/string_utils.hpp> | |
| // #include <nlohmann/detail/value_t.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| struct json_pointer_access; | |
| /*! | |
| @brief result of parse_array_index() | |
| json_pointer::array_index() maps each value to the corresponding | |
| parse_error/out_of_range exception; json_pointer::contains() and | |
| get_checked_or_null(), which must not throw for an out-of-range or | |
| unrepresentable index, and the json_view pointer resolution switch on it | |
| directly instead. | |
| */ | |
| enum class array_index_status | |
| { | |
| ok, ///< @a s is a valid, representable array index | |
| leading_zero, ///< @a s begins with '0' but has more than one character | |
| not_a_number, ///< @a s is neither empty nor "-" and does not begin with a digit | |
| unresolved, ///< @a s could not be converted to an integer | |
| exceeds_size_type ///< @a s converts to an integer that exceeds SizeType | |
| }; | |
| /*! | |
| @brief convert a JSON Pointer reference token into an array index (RFC 6901, Sect. 4) | |
| @param[in] s reference token to be converted into an array index; its data() | |
| must be NUL-terminated | |
| @param[out] idx the integer representation of @a s if array_index_status::ok | |
| is returned; left unchanged otherwise | |
| @return whether @a s is a valid array index, and if not, why | |
| @note this function never throws; json_pointer::array_index(), the callers that | |
| must not throw, and the json_view pointer resolution build on it instead | |
| of each re-implementing the RFC 6901 digit rules and the range check | |
| @note force-inlined: as a free function template it is no longer inlined into | |
| the pointer resolution, which makes JsonPointerAt up to 17% slower (#5891) | |
| */ | |
| template<typename SizeType, typename StringType> | |
| JSON_HEDLEY_ALWAYS_INLINE array_index_status parse_array_index(const StringType& s, SizeType& idx) noexcept | |
| { | |
| // error condition (cf. RFC 6901, Sect. 4) | |
| if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0')) | |
| { | |
| return array_index_status::leading_zero; | |
| } | |
| // error condition (cf. RFC 6901, Sect. 4); this also covers single- | |
| // character tokens, so "/x" and "/xy" fail alike; "-" and the empty | |
| // token are left to the conversion below and are reported as unresolved | |
| if (JSON_HEDLEY_UNLIKELY(!s.empty() && !(s.size() == 1 && s[0] == '-') && !(s[0] >= '0' && s[0] <= '9'))) | |
| { | |
| return array_index_status::not_a_number; | |
| } | |
| // fast path: up to 18 decimal digits cannot overflow unsigned long long or | |
| // SizeType (9 digits for a 32-bit SizeType), so strtoull and errno are not needed | |
| constexpr std::size_t max_fast_digits = sizeof(SizeType) >= 8 ? 18 : 9; | |
| if (!s.empty() && s.size() <= max_fast_digits) | |
| { | |
| SizeType acc = 0; | |
| for (std::size_t i = 0; i < s.size(); ++i) | |
| { | |
| const char c = s[i]; | |
| if (JSON_HEDLEY_UNLIKELY(c < '0' || c > '9')) | |
| { | |
| break; // not a plain number: let strtoull decide | |
| } | |
| acc = static_cast<SizeType>((acc * 10) + static_cast<SizeType>(c - '0')); | |
| if (JSON_HEDLEY_UNLIKELY(i == s.size() - 1)) | |
| { | |
| idx = acc; | |
| return array_index_status::ok; | |
| } | |
| } | |
| } | |
| const char* p = s.data(); | |
| char* p_end = nullptr; // NOLINT(misc-const-correctness) | |
| errno = 0; // strtoull doesn't reset errno | |
| const unsigned long long res = std::strtoull(p, &p_end, 10); // NOLINT(runtime/int) | |
| if (p == p_end // invalid input or empty string | |
| || errno == ERANGE // out of range | |
| || JSON_HEDLEY_UNLIKELY(static_cast<std::size_t>(p_end - p) != s.size())) // incomplete read | |
| { | |
| return array_index_status::unresolved; | |
| } | |
| // the index does not fit into SizeType; on 64-bit platforms this is | |
| // only SIZE_MAX itself (see #2203 and #5395) | |
| if (res >= static_cast<unsigned long long>((std::numeric_limits<SizeType>::max)())) // NOLINT(runtime/int) | |
| { | |
| return array_index_status::exceeds_size_type; | |
| } | |
| idx = static_cast<SizeType>(res); | |
| return array_index_status::ok; | |
| } | |
| } // namespace detail | |
| /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document | |
| /// @sa https://json.nlohmann.me/api/json_pointer/ | |
| template<typename RefStringType> | |
| class json_pointer | |
| { | |
| // allow basic_json to access private members | |
| NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
| friend class basic_json; | |
| template<typename> | |
| friend class json_pointer; | |
| friend struct detail::json_pointer_access; | |
| template<typename T> | |
| struct string_t_helper | |
| { | |
| using type = T; | |
| }; | |
| NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
| struct string_t_helper<NLOHMANN_BASIC_JSON_TPL> | |
| { | |
| using type = StringType; | |
| }; | |
| public: | |
| // for backwards compatibility accept BasicJsonType | |
| using string_t = typename string_t_helper<RefStringType>::type; | |
| /// @brief create JSON pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/json_pointer/ | |
| explicit json_pointer(const string_t& s = "") | |
| : reference_tokens(split(s)) | |
| {} | |
| /// @brief return a string representation of the JSON pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/to_string/ | |
| string_t to_string() const | |
| { | |
| if (reference_tokens.empty()) | |
| { | |
| return string_t(); | |
| } | |
| // one buffer: every token adds its escaped form (at least its length) and a slash | |
| std::size_t length = 0; | |
| bool plain = true; | |
| for (const auto& reference_token : reference_tokens) | |
| { | |
| length += reference_token.size() + 1; | |
| const char* const data = reference_token.data(); | |
| for (std::size_t i = 0, size = reference_token.size(); plain && i < size; ++i) | |
| { | |
| plain = data[i] != '~' && data[i] != '/'; | |
| } | |
| } | |
| string_t result; | |
| if (JSON_HEDLEY_LIKELY(plain)) | |
| { | |
| // nothing to escape: the tokens are copied into the string | |
| result.resize(length); | |
| char* out = &result[0]; | |
| for (const auto& reference_token : reference_tokens) | |
| { | |
| *out++ = '/'; | |
| out = std::copy(reference_token.data(), reference_token.data() + reference_token.size(), out); | |
| } | |
| return result; | |
| } | |
| result.reserve(length); | |
| for (const auto& reference_token : reference_tokens) | |
| { | |
| result.append("/", 1); | |
| detail::escape_into(result, reference_token); | |
| } | |
| return result; | |
| } | |
| /// @brief return a string representation of the JSON pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_string_t/ | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.0, to_string()) | |
| operator string_t() const | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return to_string(); | |
| } | |
| #endif | |
| #ifndef JSON_NO_IO | |
| /// @brief write string representation of the JSON pointer to stream | |
| /// @sa https://json.nlohmann.me/api/operator_ltlt/ | |
| friend std::ostream& operator<<(std::ostream& o, const json_pointer& ptr) | |
| { | |
| o << ptr.to_string(); | |
| return o; | |
| } | |
| #endif | |
| /// @brief append another JSON pointer at the end of this JSON pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ | |
| json_pointer& operator/=(const json_pointer& ptr) | |
| { | |
| reference_tokens.insert(reference_tokens.end(), | |
| ptr.reference_tokens.begin(), | |
| ptr.reference_tokens.end()); | |
| return *this; | |
| } | |
| /// @brief append an unescaped reference token at the end of this JSON pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ | |
| json_pointer& operator/=(string_t token) | |
| { | |
| push_back(std::move(token)); | |
| return *this; | |
| } | |
| /// @brief append an array index at the end of this JSON pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ | |
| json_pointer& operator/=(std::size_t array_idx) | |
| { | |
| return *this /= detail::to_string<string_t>(array_idx); | |
| } | |
| /// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ | |
| friend json_pointer operator/(const json_pointer& lhs, | |
| const json_pointer& rhs) | |
| { | |
| json_pointer result; | |
| result.reference_tokens.reserve(lhs.reference_tokens.size() + rhs.reference_tokens.size()); | |
| result.reference_tokens.insert(result.reference_tokens.end(), lhs.reference_tokens.begin(), lhs.reference_tokens.end()); | |
| result.reference_tokens.insert(result.reference_tokens.end(), rhs.reference_tokens.begin(), rhs.reference_tokens.end()); | |
| return result; | |
| } | |
| /// @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ | |
| friend json_pointer operator/(const json_pointer& lhs, string_t token) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| json_pointer result; | |
| result.reference_tokens.reserve(lhs.reference_tokens.size() + 1); | |
| result.reference_tokens.insert(result.reference_tokens.end(), lhs.reference_tokens.begin(), lhs.reference_tokens.end()); | |
| result.reference_tokens.push_back(std::move(token)); | |
| return result; | |
| } | |
| /// @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ | |
| friend json_pointer operator/(const json_pointer& lhs, std::size_t array_idx) | |
| { | |
| return lhs / detail::to_string<string_t>(array_idx); | |
| } | |
| /// @brief returns the parent of this JSON pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/parent_pointer/ | |
| json_pointer parent_pointer() const | |
| { | |
| if (empty()) | |
| { | |
| return *this; | |
| } | |
| json_pointer res; | |
| res.reference_tokens = std::vector<string_t>(reference_tokens.begin(), reference_tokens.end() - 1); | |
| return res; | |
| } | |
| /// @brief remove first reference token | |
| /// @sa https://json.nlohmann.me/api/json_pointer/pop_front/ | |
| void pop_front() | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(empty())) | |
| { | |
| throw_no_parent(); | |
| } | |
| reference_tokens.erase(reference_tokens.begin()); | |
| } | |
| /// @brief return first reference token | |
| /// @sa https://json.nlohmann.me/api/json_pointer/front/ | |
| const string_t& front() const | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(empty())) | |
| { | |
| throw_no_parent(); | |
| } | |
| return reference_tokens.front(); | |
| } | |
| /// @brief append an unescaped token at the start of the reference pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/push_front/ | |
| void push_front(const string_t& token) | |
| { | |
| reference_tokens.insert(reference_tokens.begin(), token); | |
| } | |
| /// @brief append an unescaped token at the start of the reference pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/push_front/ | |
| void push_front(string_t&& token) | |
| { | |
| reference_tokens.insert(reference_tokens.begin(), std::move(token)); | |
| } | |
| /// @brief remove last reference token | |
| /// @sa https://json.nlohmann.me/api/json_pointer/pop_back/ | |
| void pop_back() | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(empty())) | |
| { | |
| throw_no_parent(); | |
| } | |
| reference_tokens.pop_back(); | |
| } | |
| /// @brief return last reference token | |
| /// @sa https://json.nlohmann.me/api/json_pointer/back/ | |
| const string_t& back() const | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(empty())) | |
| { | |
| throw_no_parent(); | |
| } | |
| return reference_tokens.back(); | |
| } | |
| /// @brief append an unescaped token at the end of the reference pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ | |
| void push_back(const string_t& token) | |
| { | |
| reference_tokens.push_back(token); | |
| } | |
| /// @brief append an unescaped token at the end of the reference pointer | |
| /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ | |
| void push_back(string_t&& token) | |
| { | |
| reference_tokens.push_back(std::move(token)); | |
| } | |
| /// @brief return whether pointer points to the root document | |
| /// @sa https://json.nlohmann.me/api/json_pointer/empty/ | |
| bool empty() const noexcept | |
| { | |
| return reference_tokens.empty(); | |
| } | |
| private: | |
| /// @throw out_of_range.405 always | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE static void throw_no_parent() | |
| { | |
| JSON_THROW(detail::out_of_range::create(detail::exception_id::patch_on_root, "JSON pointer has no parent", nullptr)); | |
| } | |
| /// whether the '~' at @a pos of @a s is not followed by '0' or '1' | |
| JSON_HEDLEY_ALWAYS_INLINE static bool is_invalid_escape(const string_t& s, std::size_t pos) | |
| { | |
| return pos == s.size() - 1 || (s[pos + 1] != '0' && s[pos + 1] != '1'); | |
| } | |
| /// @throw parse_error.107 always | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE static void throw_missing_slash(const string_t& pointer) | |
| { | |
| static_cast<void>(pointer); // unused when JSON_NOEXCEPTION is defined | |
| JSON_THROW(detail::parse_error::create(detail::exception_id::pointer_missing_slash, 1, detail::concat("JSON pointer must be empty or begin with '/' - was: '", pointer, "'"), nullptr)); | |
| } | |
| /// @throw parse_error.107 if a nonempty @a pointer does not begin with '/' | |
| JSON_HEDLEY_ALWAYS_INLINE static void check_begins_with_slash(const string_t& pointer) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(pointer[0] != '/')) | |
| { | |
| throw_missing_slash(pointer); | |
| } | |
| } | |
| /// @throw out_of_range.404 always | |
| template<typename BasicJsonContext> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE static void throw_unresolved(const string_t& reference_token, BasicJsonContext context) | |
| { | |
| static_cast<void>(reference_token); // unused when JSON_NOEXCEPTION is defined | |
| static_cast<void>(context); | |
| JSON_THROW(detail::out_of_range::create(detail::exception_id::pointer_unresolved, detail::concat("unresolved reference token '", reference_token, "'"), context)); | |
| } | |
| using array_index_status = detail::array_index_status; | |
| /// whether a reference token is "-" (a plain comparison with a string literal is not always inlined) | |
| static bool is_dash(const string_t& s) noexcept | |
| { | |
| return s.size() == 1 && s[0] == '-'; | |
| } | |
| /// detail::parse_array_index() for the size_type of @a BasicJsonType | |
| template<typename BasicJsonType> | |
| static array_index_status parse_array_index(const string_t& s, typename BasicJsonType::size_type& idx) noexcept | |
| { | |
| return detail::parse_array_index(s, idx); | |
| } | |
| /*! | |
| @param[in] s reference token to be converted into an array index | |
| @return integer representation of @a s | |
| @throw parse_error.106 if an array index begins with '0' | |
| @throw parse_error.109 if an array index begins not with a digit | |
| @throw out_of_range.404 if string @a s could not be converted to an integer | |
| @throw out_of_range.410 if an array index exceeds size_type | |
| */ | |
| template<typename BasicJsonType> | |
| static typename BasicJsonType::size_type array_index(const string_t& s) | |
| { | |
| typename BasicJsonType::size_type idx{}; | |
| switch (parse_array_index<BasicJsonType>(s, idx)) | |
| { | |
| // the branches differ in their messages, not after JSON_THROW's expansion | |
| // NOLINTNEXTLINE(bugprone-branch-clone) | |
| case array_index_status::leading_zero: | |
| JSON_THROW(detail::parse_error::create(detail::exception_id::pointer_index_leading_zero, 0, detail::concat("array index '", s, "' must not begin with '0'"), nullptr)); | |
| case array_index_status::not_a_number: | |
| JSON_THROW(detail::parse_error::create(detail::exception_id::pointer_index_not_a_number, 0, detail::concat("array index '", s, "' is not a number"), nullptr)); | |
| case array_index_status::unresolved: | |
| throw_unresolved(s, nullptr); | |
| case array_index_status::exceeds_size_type: | |
| JSON_THROW(detail::out_of_range::create(detail::exception_id::value_out_of_range, detail::concat("array index ", s, " exceeds size_type"), nullptr)); | |
| case array_index_status::ok: | |
| default: | |
| break; | |
| } | |
| return idx; | |
| } | |
| /*! | |
| @brief compare with a JSON pointer string without splitting it into tokens | |
| @throw parse_error.107 if the string is not empty or begins with '/' | |
| @throw parse_error.108 if character '~' is not followed by '0' or '1' | |
| */ | |
| bool equals_string(const string_t& reference_string) const | |
| { | |
| if (reference_string.empty()) | |
| { | |
| return reference_tokens.empty(); | |
| } | |
| check_begins_with_slash(reference_string); | |
| // the whole string is validated, whether or not it matches | |
| const std::size_t size = reference_string.size(); | |
| for (std::size_t pos = reference_string.find_first_of('~'); | |
| pos != string_t::npos; | |
| pos = reference_string.find_first_of('~', pos + 1)) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(is_invalid_escape(reference_string, pos))) | |
| { | |
| JSON_THROW(detail::parse_error::create(detail::exception_id::pointer_invalid_escape, 0, "escape character '~' must be followed with '0' or '1'", nullptr)); | |
| } | |
| } | |
| // compare token by token, unescaping the string on the fly | |
| std::size_t pos = 0; // the slash in front of the next token | |
| for (const auto& reference_token : reference_tokens) | |
| { | |
| if (pos >= size) | |
| { | |
| return false; | |
| } | |
| std::size_t i = pos + 1; | |
| std::size_t j = 0; | |
| const std::size_t token_size = reference_token.size(); | |
| while (i < size && reference_string[i] != '/') | |
| { | |
| char c = reference_string[i++]; | |
| if (c == '~') | |
| { | |
| c = (reference_string[i++] == '0') ? '~' : '/'; | |
| } | |
| if (j == token_size || reference_token[j] != c) | |
| { | |
| return false; | |
| } | |
| ++j; | |
| } | |
| if (j != token_size) | |
| { | |
| return false; | |
| } | |
| pos = i; | |
| } | |
| return pos == size; | |
| } | |
| /// reserve room for @a n elements of an array type that has reserve() | |
| template<typename ArrayType> | |
| static auto reserve_elements(ArrayType& array, const std::size_t n, detail::priority_tag<1> /*unused*/) | |
| -> decltype(array.reserve(n), void()) | |
| { | |
| array.reserve(n); | |
| } | |
| template<typename ArrayType> | |
| static void reserve_elements(ArrayType& /*array*/, const std::size_t /*n*/, detail::priority_tag<0> /*unused*/) | |
| {} | |
| /// @brief object member access with a key that is only copied if it is inserted | |
| /// | |
| /// Objects that can find the position of a key and insert there | |
| /// (std::map) search once, others look the key up and add it if it is missing. | |
| template<typename BasicJsonType> | |
| static auto object_member_impl(BasicJsonType& object, const string_t& key, detail::priority_tag<1> /*unused*/) | |
| -> decltype(object.m_data.m_value.object->emplace_hint(object.m_data.m_value.object->lower_bound(key), key, nullptr), std::declval<BasicJsonType&>()) | |
| { | |
| auto& members = *object.m_data.m_value.object; | |
| auto it = members.lower_bound(key); | |
| if (it != members.end() && !members.key_comp()(key, it->first)) | |
| { | |
| return it->second; | |
| } | |
| const auto old_capacity = object.container_capacity(); | |
| it = members.emplace_hint(it, key, nullptr); | |
| return object.set_parent_after_insert(it->second, old_capacity); | |
| } | |
| template<typename BasicJsonType> | |
| static BasicJsonType& object_member_impl(BasicJsonType& object, const string_t& key, detail::priority_tag<0> /*unused*/) | |
| { | |
| auto& members = *object.m_data.m_value.object; | |
| const auto it = members.find(key); | |
| if (it != members.end()) | |
| { | |
| return it->second; | |
| } | |
| return object.operator[](key); | |
| } | |
| template<typename BasicJsonType> | |
| static BasicJsonType& object_member(BasicJsonType& object, const string_t& key) | |
| { | |
| return object_member_impl(object, key, detail::priority_tag<1> {}); | |
| } | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| json_pointer top() const | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(empty())) | |
| { | |
| throw_no_parent(); | |
| } | |
| json_pointer result = *this; | |
| result.reference_tokens = {reference_tokens[0]}; | |
| return result; | |
| } | |
| private: | |
| /*! | |
| @brief the pointer prefixes of a flattened object that denote arrays | |
| @ref unflatten creates arrays exactly below the prefixes that have a | |
| reference token 0 among their children, and objects everywhere else. | |
| Deciding this up front keeps the result independent of the order in which | |
| the flattened object is iterated, which is unspecified for some object | |
| types. | |
| A prefix is identified by the text of the key it is the beginning of: | |
| escaping is unambiguous, so equal prefixes of valid keys are equal texts. | |
| The set refers to the keys, which must outlive it. | |
| */ | |
| class array_prefix_set | |
| { | |
| public: | |
| void insert(const char* data, std::size_t size) | |
| { | |
| // flattened objects are usually sorted, so most keys that have a | |
| // 0 yield the prefix of the previous one | |
| if (last_data != nullptr && last_size == size && std::memcmp(last_data, data, size) == 0) | |
| { | |
| return; | |
| } | |
| last_data = data; | |
| last_size = size; | |
| if (table.empty()) | |
| { | |
| table.resize(16); | |
| } | |
| const std::size_t hash = hash_of(data, size); | |
| const std::size_t mask = table.size() - 1; | |
| std::size_t i = hash & mask; | |
| while (table[i].data != nullptr) | |
| { | |
| if (table[i].hash == hash && table[i].size == size && std::memcmp(table[i].data, data, size) == 0) | |
| { | |
| return; | |
| } | |
| i = (i + 1) & mask; | |
| } | |
| table[i] = slot(hash, data, size); | |
| // keep the load factor below 1/2 | |
| if (++used * 2 > table.size()) | |
| { | |
| grow(); | |
| } | |
| } | |
| bool empty() const noexcept | |
| { | |
| return used == 0; | |
| } | |
| bool contains(const char* data, std::size_t size) const noexcept | |
| { | |
| if (used == 0) | |
| { | |
| return false; | |
| } | |
| const std::size_t hash = hash_of(data, size); | |
| const std::size_t mask = table.size() - 1; | |
| for (std::size_t i = hash & mask; table[i].data != nullptr; i = (i + 1) & mask) | |
| { | |
| if (table[i].hash == hash && table[i].size == size && std::memcmp(table[i].data, data, size) == 0) | |
| { | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| private: | |
| struct slot | |
| { | |
| slot() noexcept = default; | |
| slot(std::size_t h, const char* d, std::size_t s) noexcept | |
| : hash(h), data(d), size(s) | |
| {} | |
| std::size_t hash = 0; | |
| const char* data = nullptr; // nullptr: the slot is empty | |
| std::size_t size = 0; | |
| }; | |
| static std::size_t hash_of(const char* data, std::size_t size) noexcept | |
| { | |
| std::uint64_t h = 0x9E3779B97F4A7C15ULL ^ size; | |
| std::size_t i = 0; | |
| for (; i + 8 <= size; i += 8) | |
| { | |
| std::uint64_t w = 0; | |
| std::memcpy(&w, data + i, 8); | |
| h = (h ^ w) * 0x100000001B3ULL; | |
| h ^= h >> 32u; | |
| } | |
| std::uint64_t w = 0; | |
| if (i < size) | |
| { | |
| std::memcpy(&w, data + i, size - i); | |
| } | |
| h = (h ^ w) * 0x9E3779B97F4A7C15ULL; | |
| return detail::conditional_static_cast<std::size_t>(h ^ (h >> 29u)); | |
| } | |
| void grow() | |
| { | |
| std::vector<slot> old(table.size() * 2); | |
| old.swap(table); | |
| const std::size_t mask = table.size() - 1; | |
| for (const auto& s : old) | |
| { | |
| if (s.data != nullptr) | |
| { | |
| std::size_t i = s.hash & mask; | |
| while (table[i].data != nullptr) | |
| { | |
| i = (i + 1) & mask; | |
| } | |
| table[i] = s; | |
| } | |
| } | |
| } | |
| std::vector<slot> table{}; | |
| std::size_t used = 0; | |
| const char* last_data = nullptr; | |
| std::size_t last_size = 0; | |
| }; | |
| /// @brief the length of the longest common prefix of the first @a limit bytes of @a a and @a b | |
| static std::size_t common_prefix_length(const char* a, const char* b, const std::size_t limit) noexcept | |
| { | |
| std::size_t i = 0; | |
| for (; i + 8 <= limit; i += 8) | |
| { | |
| std::uint64_t x = 0; | |
| std::uint64_t y = 0; | |
| std::memcpy(&x, a + i, 8); | |
| std::memcpy(&y, b + i, 8); | |
| if (x != y) | |
| { | |
| break; | |
| } | |
| } | |
| while (i < limit && a[i] == b[i]) | |
| { | |
| ++i; | |
| } | |
| return i; | |
| } | |
| /*! | |
| @brief check that @a key is a valid JSON pointer, and add the prefixes of | |
| it that denote arrays to @a arrays | |
| @throw parse_error.107 if the key is not empty or begins with '/' | |
| @throw parse_error.108 if character '~' is not followed by '0' or '1' | |
| The same checks as @ref split, which throws the same exceptions, but | |
| without building the reference tokens. | |
| */ | |
| static void scan_key(const string_t& key, const string_t* previous, array_prefix_set& arrays) | |
| { | |
| const std::size_t size = key.size(); | |
| if (size == 0) | |
| { | |
| return; | |
| } | |
| const char* const data = key.data(); | |
| check_begins_with_slash(key); | |
| // The beginning of the key that it has in common with the previous | |
| // one, which was checked already, is skipped: the scan starts with | |
| // the token after the last slash in it. | |
| std::size_t begin = 1; | |
| if (previous != nullptr) | |
| { | |
| std::size_t same = common_prefix_length(data, previous->data(), (std::min)(size, previous->size())); | |
| while (same > 1 && data[same - 1] != '/') | |
| { | |
| --same; | |
| } | |
| if (same > 1) | |
| { | |
| begin = same; | |
| } | |
| } | |
| for (std::size_t i = begin; i <= size; ++i) | |
| { | |
| if (i == size || data[i] == '/') | |
| { | |
| // a token 0 makes the pointer before it an array | |
| if (i - begin == 1 && data[begin] == '0') | |
| { | |
| arrays.insert(data, begin - 1); | |
| } | |
| begin = i + 1; | |
| } | |
| else if (data[i] == '~') | |
| { | |
| // ~ must be followed by 0 or 1 | |
| if (JSON_HEDLEY_UNLIKELY(is_invalid_escape(key, i))) | |
| { | |
| JSON_THROW(detail::parse_error::create(detail::exception_id::pointer_invalid_escape, 0, "escape character '~' must be followed with '0' or '1'", nullptr)); | |
| } | |
| } | |
| } | |
| } | |
| /*! | |
| @brief the values along the pointer last resolved by @ref resolve_plain | |
| A patch from @ref basic_json::diff lists its operations in document order, | |
| so consecutive pointers share most of their reference tokens; the values | |
| along the previous pointer are kept to resume from the common prefix. | |
| `steps[k]` is the value after the first `k` reference tokens together with | |
| the length of the prefix of `*path` that holds them. A value stays valid as | |
| long as no operation changes its container: callers keep only values up to | |
| the parent of the pointer they modify, or call `reset()`. | |
| */ | |
| template<typename BasicJsonType> | |
| struct plain_steps | |
| { | |
| const string_t* path = nullptr; | |
| std::vector<std::pair<std::size_t, BasicJsonType*>> steps{}; | |
| void reset() noexcept | |
| { | |
| path = nullptr; | |
| steps.clear(); | |
| } | |
| }; | |
| /*! | |
| @brief resolve a plain JSON pointer without building its reference tokens | |
| @param[in] root the value the pointer starts at | |
| @param[in] path a JSON pointer string | |
| @param[in] length the number of leading bytes of @a path to resolve; 0 or | |
| the position of a slash | |
| @param[in,out] token a string to hold the reference tokens, to reuse its storage | |
| @param[in,out] cache the values along the previously resolved pointer; | |
| @a path must outlive the next call | |
| @return the pointed to value, or `nullptr` if the pointer does not denote | |
| an existing value, or does so in a way that is not plain: an array | |
| index that is malformed or out of range, or a "-", or a reference | |
| token with an escape. No exception is | |
| thrown for these; callers use @ref json_pointer instead, which | |
| handles them. | |
| */ | |
| template<typename BasicJsonType> | |
| static BasicJsonType* resolve_plain(BasicJsonType* root, const string_t& path, const std::size_t length, string_t& token, plain_steps<BasicJsonType>& cache) | |
| { | |
| auto& steps = cache.steps; | |
| // resume from the deepest step that is also a prefix of this path | |
| std::size_t depth = 1; | |
| if (cache.path != nullptr && !steps.empty() && steps[0].second == root) | |
| { | |
| const string_t& previous = *cache.path; | |
| for (depth = steps.size(); depth > 1; --depth) | |
| { | |
| // a step ends at a token boundary of the previous path | |
| const std::size_t prefix = steps[depth - 1].first; | |
| if (prefix <= length && (prefix == length || path[prefix] == '/') && std::memcmp(path.data(), previous.data(), prefix) == 0) | |
| { | |
| break; | |
| } | |
| } | |
| steps.resize(depth); | |
| } | |
| else | |
| { | |
| steps.assign(1, std::make_pair(std::size_t{0}, root)); | |
| } | |
| cache.path = &path; | |
| BasicJsonType* ptr = steps[depth - 1].second; | |
| for (std::size_t pos = steps[depth - 1].first; pos < length;) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(path[pos] != '/')) | |
| { | |
| return nullptr; | |
| } | |
| // the reference token between the slash at pos and the next one, | |
| // which must not have an escape | |
| const char* const begin = path.data() + pos + 1; | |
| const char* const limit = path.data() + length; | |
| const char* end = begin; | |
| while (end < limit && *end != '/') | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(*end == '~')) | |
| { | |
| return nullptr; | |
| } | |
| ++end; | |
| } | |
| if (ptr->is_object()) | |
| { | |
| token.clear(); | |
| token.append(begin, static_cast<std::size_t>(end - begin)); | |
| const auto it = ptr->m_data.m_value.object->find(token); | |
| if (JSON_HEDLEY_UNLIKELY(it == ptr->m_data.m_value.object->end())) | |
| { | |
| return nullptr; | |
| } | |
| ptr = &it->second; | |
| } | |
| else if (ptr->is_array()) | |
| { | |
| // an index of up to 18 digits without a leading zero fits into size_type | |
| // (9 digits for a 32-bit size_type); everything else is left to json_pointer | |
| constexpr std::size_t max_digits = sizeof(typename BasicJsonType::size_type) >= 8 ? 18 : 9; | |
| const auto digits = static_cast<std::size_t>(end - begin); | |
| if (JSON_HEDLEY_UNLIKELY(digits == 0 || digits > max_digits || (digits > 1 && *begin == '0'))) | |
| { | |
| return nullptr; | |
| } | |
| typename BasicJsonType::size_type idx = 0; | |
| for (const char* c = begin; c != end; ++c) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(*c < '0' || *c > '9')) | |
| { | |
| return nullptr; | |
| } | |
| idx = static_cast<typename BasicJsonType::size_type>((idx * 10) + static_cast<typename BasicJsonType::size_type>(*c - '0')); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(idx >= ptr->m_data.m_value.array->size())) | |
| { | |
| return nullptr; | |
| } | |
| ptr = &(*ptr->m_data.m_value.array)[idx]; | |
| } | |
| else | |
| { | |
| // primitive value with a reference token left | |
| return nullptr; | |
| } | |
| pos = static_cast<std::size_t>(end - path.data()); | |
| steps.emplace_back(pos, ptr); | |
| } | |
| return ptr; | |
| } | |
| /*! | |
| @brief return a reference to the pointed to value | |
| @note This version does not throw if a value is not present, but tries to | |
| create nested values instead. For instance, calling this function | |
| with pointer `"/this/that"` on a null value is equivalent to calling | |
| `operator[]("this").operator[]("that")` on that value, effectively | |
| changing the null value to an object. | |
| @param[in] ptr a JSON value | |
| @return reference to the JSON value pointed to by the JSON pointer | |
| Complexity: Linear in the length of the JSON pointer. | |
| @throw parse_error.106 if an array index begins with '0' | |
| @throw parse_error.109 if an array index was not a number | |
| @throw out_of_range.404 if the JSON pointer can not be resolved | |
| */ | |
| template<typename BasicJsonType> | |
| BasicJsonType& get_unchecked(BasicJsonType* ptr) const | |
| { | |
| for (const auto& reference_token : reference_tokens) | |
| { | |
| // convert null values to arrays or objects before continuing | |
| if (ptr->is_null()) | |
| { | |
| // check if the reference token is a number | |
| const bool nums = | |
| std::all_of(reference_token.begin(), reference_token.end(), | |
| [](const unsigned char x) | |
| { | |
| return std::isdigit(x); | |
| }); | |
| // change value to an array for numbers or "-" or to object otherwise | |
| *ptr = (nums || reference_token == "-") | |
| ? detail::value_t::array | |
| : detail::value_t::object; | |
| } | |
| if (ptr->is_object()) | |
| { | |
| // use unchecked object access | |
| ptr = &object_member(*ptr, reference_token); | |
| } | |
| else if (ptr->is_array()) | |
| { | |
| if (reference_token == "-") | |
| { | |
| // explicitly treat "-" as index beyond the end | |
| ptr = &ptr->operator[](ptr->m_data.m_value.array->size()); | |
| } | |
| else | |
| { | |
| // convert array index to number; unchecked access | |
| ptr = &ptr->operator[](array_index<BasicJsonType>(reference_token)); | |
| } | |
| } | |
| else | |
| { | |
| // primitive value with a reference token left | |
| throw_unresolved(reference_token, ptr); | |
| } | |
| } | |
| return *ptr; | |
| } | |
| /*! | |
| @throw parse_error.106 if an array index begins with '0' | |
| @throw parse_error.109 if an array index was not a number | |
| @throw out_of_range.402 if the array index '-' is used | |
| @throw out_of_range.404 if the JSON pointer can not be resolved | |
| */ | |
| template<typename BasicJsonType> | |
| BasicJsonType& get_checked(BasicJsonType* ptr) const | |
| { | |
| for (const auto& reference_token : reference_tokens) | |
| { | |
| if (ptr->is_object()) | |
| { | |
| const auto it = ptr->m_data.m_value.object->find(reference_token); | |
| if (JSON_HEDLEY_UNLIKELY(it == ptr->m_data.m_value.object->end())) | |
| { | |
| // at() throws out_of_range.403 with the usual message | |
| ptr->at(reference_token); | |
| } | |
| ptr = &it->second; | |
| } | |
| else if (ptr->is_array()) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(is_dash(reference_token))) | |
| { | |
| // "-" always fails the range check | |
| JSON_THROW(detail::out_of_range::create(detail::exception_id::pointer_past_the_end_index, detail::concat( | |
| "array index '-' (", std::to_string(ptr->m_data.m_value.array->size()), | |
| ") is out of range"), ptr)); | |
| } | |
| const auto idx = array_index<BasicJsonType>(reference_token); | |
| // Bounds check before access to avoid exception with JSON_NOEXCEPTION | |
| if (JSON_HEDLEY_UNLIKELY(idx >= ptr->m_data.m_value.array->size())) | |
| { | |
| JSON_THROW(detail::out_of_range::create(detail::exception_id::array_index_out_of_range, detail::concat( | |
| "array index ", std::to_string(idx), " is out of range"), ptr)); | |
| } | |
| ptr = &(*ptr->m_data.m_value.array)[idx]; | |
| } | |
| else | |
| { | |
| // primitive value with a reference token left | |
| throw_unresolved(reference_token, ptr); | |
| } | |
| } | |
| return *ptr; | |
| } | |
| /*! | |
| @brief return a const reference to the pointed to value | |
| @param[in] ptr a JSON value | |
| @return const reference to the JSON value pointed to by the JSON | |
| pointer | |
| @pre Every object key and array index the pointer refers to exists. | |
| Like the const operator[] for keys and indices, a missing one is | |
| undefined behavior, guarded by a runtime assertion. | |
| @throw parse_error.106 if an array index begins with '0' | |
| @throw parse_error.109 if an array index was not a number | |
| @throw out_of_range.402 if the array index '-' is used | |
| @throw out_of_range.404 if the JSON pointer can not be resolved | |
| */ | |
| template<typename BasicJsonType> | |
| const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const | |
| { | |
| for (const auto& reference_token : reference_tokens) | |
| { | |
| if (ptr->is_object()) | |
| { | |
| // use unchecked object access; the const operator[] | |
| // asserts that the key exists | |
| const auto it = ptr->m_data.m_value.object->find(reference_token); | |
| JSON_ASSERT(it != ptr->m_data.m_value.object->end()); | |
| ptr = &it->second; | |
| } | |
| else if (ptr->is_array()) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(is_dash(reference_token))) | |
| { | |
| // "-" cannot be used for const access | |
| JSON_THROW(detail::out_of_range::create(detail::exception_id::pointer_past_the_end_index, detail::concat("array index '-' (", std::to_string(ptr->m_data.m_value.array->size()), ") is out of range"), ptr)); | |
| } | |
| // use unchecked array access; the const operator[] | |
| // asserts that the index exists | |
| const auto idx = array_index<BasicJsonType>(reference_token); | |
| JSON_ASSERT(idx < ptr->m_data.m_value.array->size()); | |
| ptr = &(*ptr->m_data.m_value.array)[idx]; | |
| } | |
| else | |
| { | |
| // primitive value with a reference token left | |
| throw_unresolved(reference_token, ptr); | |
| } | |
| } | |
| return *ptr; | |
| } | |
| /*! | |
| @brief return a pointer to the pointed to value, or `nullptr` if the | |
| pointer cannot be resolved because a key is missing, an array | |
| index is out of range, or the array index is "-" | |
| @note unlike get_checked(), this never throws for those cases, so it | |
| can be used to implement a non-throwing fallback (e.g. value()) | |
| that also works when exceptions are disabled | |
| @throw parse_error.106 if an array index begins with '0' | |
| @throw parse_error.109 if an array index was not a number | |
| */ | |
| template<typename BasicJsonType> | |
| const BasicJsonType* get_checked_or_null(const BasicJsonType* ptr) const | |
| { | |
| for (const auto& reference_token : reference_tokens) | |
| { | |
| if (ptr->is_object()) | |
| { | |
| const auto it = ptr->m_data.m_value.object->find(reference_token); | |
| if (JSON_HEDLEY_UNLIKELY(it == ptr->m_data.m_value.object->end())) | |
| { | |
| return nullptr; | |
| } | |
| ptr = &it->second; | |
| } | |
| else if (ptr->is_array()) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(is_dash(reference_token))) | |
| { | |
| // "-" always fails the range check | |
| return nullptr; | |
| } | |
| // a malformed index throws parse_error.106/109; an | |
| // index that is syntactically valid but cannot be | |
| // represented (out_of_range.404/410) is treated like an | |
| // out-of-range index below | |
| typename BasicJsonType::size_type idx{}; | |
| switch (parse_array_index<BasicJsonType>(reference_token, idx)) | |
| { | |
| // the branches differ in their messages, not after JSON_THROW's expansion | |
| // NOLINTNEXTLINE(bugprone-branch-clone) | |
| case array_index_status::leading_zero: | |
| JSON_THROW(detail::parse_error::create(detail::exception_id::pointer_index_leading_zero, 0, detail::concat("array index '", reference_token, "' must not begin with '0'"), nullptr)); | |
| case array_index_status::not_a_number: | |
| JSON_THROW(detail::parse_error::create(detail::exception_id::pointer_index_not_a_number, 0, detail::concat("array index '", reference_token, "' is not a number"), nullptr)); | |
| case array_index_status::unresolved: | |
| case array_index_status::exceeds_size_type: | |
| return nullptr; | |
| case array_index_status::ok: | |
| default: | |
| break; | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(idx >= ptr->m_data.m_value.array->size())) | |
| { | |
| return nullptr; | |
| } | |
| ptr = &(*ptr->m_data.m_value.array)[idx]; | |
| } | |
| else | |
| { | |
| // primitive value with a reference token left | |
| return nullptr; | |
| } | |
| } | |
| return ptr; | |
| } | |
| /*! | |
| @note unlike array_index(), this never throws: a malformed or unrepresentable | |
| array index reference token is treated like a missing key (see #5395) | |
| */ | |
| template<typename BasicJsonType> | |
| bool contains(const BasicJsonType* ptr) const | |
| { | |
| for (const auto& reference_token : reference_tokens) | |
| { | |
| if (ptr->is_object()) | |
| { | |
| const auto it = ptr->m_data.m_value.object->find(reference_token); | |
| if (it == ptr->m_data.m_value.object->end()) | |
| { | |
| // we did not find the key in the object | |
| return false; | |
| } | |
| ptr = &it->second; | |
| } | |
| else if (ptr->is_array()) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(is_dash(reference_token))) | |
| { | |
| // "-" always fails the range check | |
| return false; | |
| } | |
| // any parse failure (malformed index, or one that is syntactically | |
| // valid but not representable as size_type) means the reference | |
| // token cannot denote an existing array element -- contains() must | |
| // not throw (see #5395), so it is treated as "not found" | |
| typename BasicJsonType::size_type idx{}; | |
| if (JSON_HEDLEY_UNLIKELY(parse_array_index<BasicJsonType>(reference_token, idx) != array_index_status::ok)) | |
| { | |
| return false; | |
| } | |
| if (idx >= ptr->m_data.m_value.array->size()) | |
| { | |
| // index out of range | |
| return false; | |
| } | |
| ptr = &(*ptr->m_data.m_value.array)[idx]; | |
| } | |
| else | |
| { | |
| // we do not expect primitive values if there is still a | |
| // reference token to process | |
| return false; | |
| } | |
| } | |
| // no reference token left means we found a primitive value | |
| return true; | |
| } | |
| /*! | |
| @brief split the string input to reference tokens | |
| @note This function is only called by the json_pointer constructor. | |
| All exceptions below are documented there. | |
| @throw parse_error.107 if the pointer is not empty or begins with '/' | |
| @throw parse_error.108 if character '~' is not followed by '0' or '1' | |
| */ | |
| static std::vector<string_t> split(const string_t& reference_string) | |
| { | |
| std::vector<string_t> result; | |
| // special case: empty reference string -> no reference tokens | |
| if (reference_string.empty()) | |
| { | |
| return result; | |
| } | |
| // check if a nonempty reference string begins with slash | |
| check_begins_with_slash(reference_string); | |
| // every slash starts a reference token | |
| const std::size_t size = reference_string.size(); | |
| std::size_t token_count = 0; | |
| for (std::size_t i = 0; i < size; ++i) | |
| { | |
| token_count += static_cast<std::size_t>(reference_string[i] == '/'); | |
| } | |
| result.reserve(token_count); | |
| // extract the reference tokens: every one runs from after a slash to | |
| // the next slash or the end of the string; a token without a '~' (the | |
| // common case) is stored as it is, others are checked and unescaped | |
| const char* const data = reference_string.data(); | |
| const char* const end = data + size; | |
| for (const char* start = data + 1;; ++start) | |
| { | |
| const char* slash = start; | |
| bool escaped = false; | |
| while (slash != end && *slash != '/') | |
| { | |
| escaped = escaped || *slash == '~'; | |
| ++slash; | |
| } | |
| const auto count = static_cast<std::size_t>(slash - start); | |
| if (JSON_HEDLEY_LIKELY(!escaped)) | |
| { | |
| result.emplace_back(start, count); | |
| } | |
| else | |
| { | |
| auto reference_token = string_t(start, count); | |
| // check reference tokens are properly escaped | |
| for (std::size_t pos = reference_token.find_first_of('~'); pos != string_t::npos; pos = reference_token.find_first_of('~', pos + 1)) | |
| { | |
| JSON_ASSERT(reference_token[pos] == '~'); | |
| // ~ must be followed by 0 or 1 | |
| if (JSON_HEDLEY_UNLIKELY(is_invalid_escape(reference_token, pos))) | |
| { | |
| JSON_THROW(detail::parse_error::create(detail::exception_id::pointer_invalid_escape, 0, "escape character '~' must be followed with '0' or '1'", nullptr)); | |
| } | |
| } | |
| detail::unescape(reference_token); | |
| result.push_back(std::move(reference_token)); | |
| } | |
| if (slash == end) | |
| { | |
| break; | |
| } | |
| start = slash; | |
| } | |
| return result; | |
| } | |
| private: | |
| // Add the entry (key, v) to the object `obj`. Flattened paths are pairwise | |
| // distinct, so objects that can append a key known to be absent | |
| // (ordered_map) skip the lookup, which is linear and would make flatten | |
| // quadratic. Objects with a positional insert (std::map) insert next to | |
| // the entry added last: paths come out in nearly sorted order, so the | |
| // position is usually right and no search from the root is needed. | |
| // All other object types use operator[]. | |
| template<typename ObjectType, typename ValueType> | |
| static auto add_flattened(ObjectType& obj, typename ObjectType::iterator& /*hint*/, const string_t& key, ValueType&& v, detail::priority_tag<2> /*unused*/) | |
| -> decltype(obj.emplace_new_key(key, std::forward<ValueType>(v)), void()) | |
| { | |
| obj.emplace_new_key(key, std::forward<ValueType>(v)); | |
| } | |
| template<typename ObjectType, typename ValueType> | |
| static auto add_flattened(ObjectType& obj, typename ObjectType::iterator& hint, const string_t& key, ValueType&& v, detail::priority_tag<1> /*unused*/) | |
| -> decltype(hint = obj.emplace_hint(hint, key, std::forward<ValueType>(v)), void()) | |
| { | |
| hint = obj.emplace_hint(hint, key, std::forward<ValueType>(v)); | |
| ++hint; | |
| } | |
| template<typename ObjectType, typename ValueType> | |
| static void add_flattened(ObjectType& obj, typename ObjectType::iterator& /*hint*/, const string_t& key, ValueType&& v, detail::priority_tag<0> /*unused*/) | |
| { | |
| obj[key] = std::forward<ValueType>(v); | |
| } | |
| /// the number of entries that flattening @a value adds: its primitive | |
| /// values and empty containers | |
| template<typename BasicJsonType> | |
| static std::size_t count_flattened(const BasicJsonType& value) | |
| { | |
| std::size_t count = 0; | |
| std::vector<const BasicJsonType*> pending(1, &value); | |
| while (!pending.empty()) | |
| { | |
| const BasicJsonType* const v = pending.back(); | |
| pending.pop_back(); | |
| if (v->is_array() && !v->m_data.m_value.array->empty()) | |
| { | |
| for (const auto& element : *v->m_data.m_value.array) | |
| { | |
| pending.push_back(&element); | |
| } | |
| } | |
| else if (v->is_object() && !v->m_data.m_value.object->empty()) | |
| { | |
| for (const auto& member : *v->m_data.m_value.object) | |
| { | |
| pending.push_back(&member.second); | |
| } | |
| } | |
| else | |
| { | |
| ++count; | |
| } | |
| } | |
| return count; | |
| } | |
| // Reserve the storage for @a value of objects that have a reserve(), so | |
| // that it does not have to be moved while it grows | |
| template<typename ObjectType, typename BasicJsonType> | |
| static auto reserve_flattened(ObjectType& obj, const BasicJsonType& value, detail::priority_tag<1> /*unused*/) | |
| -> decltype(obj.reserve(std::size_t {}), void()) | |
| { | |
| obj.reserve(count_flattened(value)); | |
| } | |
| template<typename ObjectType, typename BasicJsonType> | |
| static void reserve_flattened(ObjectType& /*obj*/, const BasicJsonType& /*value*/, detail::priority_tag<0> /*unused*/) | |
| {} | |
| /// append the decimal representation of @a i to @a out | |
| static void append_index(string_t& out, std::size_t i) | |
| { | |
| std::array<char, 24> buf{}; | |
| std::size_t pos = buf.size(); | |
| do | |
| { | |
| buf[--pos] = static_cast<char>('0' + (i % 10)); | |
| i /= 10; | |
| } | |
| while (i != 0); | |
| out.append(buf.data() + pos, buf.size() - pos); | |
| } | |
| /*! | |
| @param[in] reference_string the reference string to the current value | |
| @param[in] value the value to consider | |
| @param[in,out] result the result object to insert values to | |
| @note Empty objects or arrays are flattened to `null`. | |
| The value is walked with an explicit stack rather than the call stack, so | |
| arbitrarily deeply nested values can be flattened. | |
| @sa https://github.com/nlohmann/json/issues/5393 | |
| */ | |
| template<typename BasicJsonType> | |
| static void flatten(const string_t& reference_string, | |
| const BasicJsonType& value, | |
| BasicJsonType& result) | |
| { | |
| using object_const_iterator = typename BasicJsonType::object_t::const_iterator; | |
| // an array or object being walked: the container, the array index or | |
| // object iterator of the next child, and the length of the path of the | |
| // container itself | |
| struct frame | |
| { | |
| frame(const BasicJsonType* container_, object_const_iterator member_, const std::size_t path_length_) noexcept | |
| : container(container_), member(std::move(member_)), path_length(path_length_) | |
| {} | |
| const BasicJsonType* container; | |
| std::size_t index = 0; | |
| object_const_iterator member; | |
| std::size_t path_length; | |
| }; | |
| // The containers being flattened are kept on an explicit stack, and | |
| // every child is flattened completely before the next one, so the | |
| // entries come out in the same order as with a recursive walk. The | |
| // path of the value being flattened is kept in one buffer that grows | |
| // and shrinks with the stack, rather than in a new string per level. | |
| std::vector<frame> stack; | |
| string_t path = reference_string; | |
| // flatten `v`, whose path is `path`: primitives and empty containers | |
| // are added to the result right away; other containers get a frame | |
| auto& object = *result.m_data.m_value.object; | |
| auto hint = object.end(); | |
| const auto enter = [&stack, &path, &object, &hint](const BasicJsonType & v) | |
| { | |
| if (v.is_array()) | |
| { | |
| if (v.m_data.m_value.array->empty()) | |
| { | |
| // flatten empty array as null | |
| add_flattened(object, hint, path, nullptr, detail::priority_tag<2> {}); | |
| } | |
| else | |
| { | |
| stack.emplace_back(&v, object_const_iterator(), path.size()); | |
| } | |
| } | |
| else if (v.is_object()) | |
| { | |
| if (v.m_data.m_value.object->empty()) | |
| { | |
| // flatten empty object as null | |
| add_flattened(object, hint, path, nullptr, detail::priority_tag<2> {}); | |
| } | |
| else | |
| { | |
| stack.emplace_back(&v, v.m_data.m_value.object->begin(), path.size()); | |
| } | |
| } | |
| else | |
| { | |
| // add a primitive value with its reference string | |
| add_flattened(object, hint, path, v, detail::priority_tag<2> {}); | |
| } | |
| }; | |
| reserve_flattened(object, value, detail::priority_tag<1> {}); | |
| enter(value); | |
| while (!stack.empty()) | |
| { | |
| // the frame is changed through stack.back(): enter() may push a | |
| // frame, which would invalidate a reference to it | |
| const BasicJsonType* const container = stack.back().container; | |
| // the path of the previous child is replaced by the path of the | |
| // next one; for an array element in one resize | |
| const std::size_t path_length = stack.back().path_length; | |
| if (container->is_array()) | |
| { | |
| const auto& array = *container->m_data.m_value.array; | |
| const std::size_t i = stack.back().index; | |
| if (i == array.size()) | |
| { | |
| stack.pop_back(); | |
| continue; | |
| } | |
| // iterate array and use index as a reference string | |
| ++stack.back().index; | |
| std::array<char, 24> digits{}; | |
| std::size_t pos = digits.size(); | |
| std::size_t rest = i; | |
| do | |
| { | |
| digits[--pos] = static_cast<char>('0' + (rest % 10)); | |
| rest /= 10; | |
| } | |
| while (rest != 0); | |
| const std::size_t count = digits.size() - pos; | |
| path.resize(path_length + 1 + count); | |
| char* const out = &path[path_length]; | |
| out[0] = '/'; | |
| std::memcpy(out + 1, digits.data() + pos, count); | |
| enter(array[i]); | |
| } | |
| else | |
| { | |
| const object_const_iterator it = stack.back().member; | |
| if (it == container->m_data.m_value.object->end()) | |
| { | |
| stack.pop_back(); | |
| continue; | |
| } | |
| // iterate object and use keys as reference string | |
| ++stack.back().member; | |
| path.resize(path_length); | |
| path.push_back('/'); | |
| detail::escape_into(path, it->first); | |
| enter(it->second); | |
| } | |
| } | |
| // the entries were added without going through basic_json, so the | |
| // parent pointers (JSON_DIAGNOSTICS) have to be set now | |
| result.set_parents(); | |
| } | |
| /*! | |
| @param[in] value flattened JSON | |
| @return unflattened JSON | |
| @throw parse_error.109 if array index is not a number | |
| @throw type_error.314 if value is not an object | |
| @throw type_error.315 if object values are not primitive | |
| @throw type_error.313 if value cannot be unflattened | |
| */ | |
| template<typename BasicJsonType> | |
| static BasicJsonType | |
| unflatten(const BasicJsonType& value) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!value.is_object())) | |
| { | |
| JSON_THROW(detail::type_error::create(detail::exception_id::unflatten_not_object, "only objects can be unflattened", &value)); | |
| } | |
| BasicJsonType result; | |
| // check every key, and collect the prefixes that have a reference | |
| // token 0 among their children; the values below them are arrays, | |
| // all others are objects (see array_prefix_set) | |
| array_prefix_set arrays; | |
| const string_t* previous_key = nullptr; | |
| for (const auto& element : *value.m_data.m_value.object) | |
| { | |
| scan_key(element.first, previous_key, arrays); | |
| previous_key = &element.first; | |
| } | |
| // values[i] is the value after the first i reference tokens of the | |
| // previous key, ends[i] the length of that prefix of the key. Keys are | |
| // often sorted, so most of the path to the value of a key is the | |
| // same as for the previous key and need not be looked up again. Only | |
| // the values below the common prefix are dropped, and only they can | |
| // move when a value is added: the ones above are not inside the | |
| // container that grows. | |
| std::vector<BasicJsonType*> values(1, &result); | |
| std::vector<std::size_t> ends(1, 0); | |
| const string_t* previous = nullptr; | |
| string_t token; | |
| // iterate the JSON object values | |
| for (const auto& element : *value.m_data.m_value.object) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive())) | |
| { | |
| JSON_THROW(detail::type_error::create(detail::exception_id::unflatten_value_not_primitive, "values in object must be primitive", &element.second)); | |
| } | |
| const string_t& key = element.first; | |
| const char* const data = key.data(); | |
| // the number of reference tokens the key has in common with the | |
| // previous one | |
| std::size_t depth = 0; | |
| if (previous != nullptr) | |
| { | |
| const std::size_t same = common_prefix_length(data, previous->data(), (std::min)(key.size(), previous->size())); | |
| depth = ends.size() - 1; | |
| while (depth > 0 && (ends[depth] > same || (ends[depth] == same && same < key.size() && data[same] != '/'))) | |
| { | |
| --depth; | |
| } | |
| } | |
| values.resize(depth + 1); | |
| ends.resize(depth + 1); | |
| previous = &key; | |
| // Assign the value to the reference pointed to by JSON pointer. Note | |
| // that if the JSON pointer is "" (i.e., points to the whole value), | |
| // the value is the result itself. An assignment will then create a | |
| // primitive value. | |
| BasicJsonType* current = values.back(); | |
| for (std::size_t pos = ends.back(); pos < key.size();) | |
| { | |
| // the reference token between the slash at pos and the next | |
| std::size_t end = key.find_first_of('/', pos + 1); | |
| if (end == string_t::npos) | |
| { | |
| end = key.size(); | |
| } | |
| const std::size_t token_size = end - pos - 1; | |
| // a token that is a plain index of up to 9 digits, which is | |
| // the case for almost all array elements, is not copied | |
| std::size_t index = 0; | |
| bool plain_index = current->type() == detail::value_t::array && token_size != 0 && token_size <= 9 && (token_size == 1 || data[pos + 1] != '0'); | |
| for (std::size_t k = pos + 1; plain_index && k < end; ++k) | |
| { | |
| plain_index = data[k] >= '0' && data[k] <= '9'; | |
| index = (index * 10) + static_cast<std::size_t>(data[k] - '0'); | |
| } | |
| if (plain_index) | |
| { | |
| current = ¤t->operator[](static_cast<typename BasicJsonType::size_type>(index)); | |
| values.push_back(current); | |
| ends.push_back(end); | |
| pos = end; | |
| continue; | |
| } | |
| token.clear(); | |
| token.append(data + pos + 1, token_size); | |
| if (token.find_first_of('~') != string_t::npos) | |
| { | |
| detail::unescape(token); | |
| } | |
| switch (current->type()) | |
| { | |
| case detail::value_t::null: | |
| { | |
| // a first child 0 makes the value an array without a look-up | |
| if ((token_size == 1 && data[pos + 1] == '0') || arrays.contains(data, pos)) | |
| { | |
| // some reference token below this position is 0, so the | |
| // value is an array | |
| *current = BasicJsonType(detail::value_t::array); | |
| reserve_elements(*current->m_data.m_value.array, 2, detail::priority_tag<1> {}); | |
| current = ¤t->operator[](array_index<BasicJsonType>(token)); | |
| } | |
| else | |
| { | |
| // start a new object otherwise | |
| current = ¤t->operator[](token); | |
| } | |
| break; | |
| } | |
| case detail::value_t::object: | |
| { | |
| // create an entry in the object | |
| current = &object_member(*current, token); | |
| break; | |
| } | |
| case detail::value_t::array: | |
| { | |
| // create an entry in the array | |
| current = ¤t->operator[](array_index<BasicJsonType>(token)); | |
| break; | |
| } | |
| /* | |
| The following code is only reached if there exists a reference | |
| token _and_ the current value is primitive. In this case, we have | |
| an error situation, because primitive values may only occur as | |
| a single value; that is, with an empty list of reference tokens. | |
| */ | |
| case detail::value_t::string: | |
| case detail::value_t::boolean: | |
| case detail::value_t::number_integer: | |
| case detail::value_t::number_unsigned: | |
| case detail::value_t::number_float: | |
| case detail::value_t::binary: | |
| case detail::value_t::discarded: | |
| default: | |
| JSON_THROW(detail::type_error::create(detail::exception_id::unflatten_invalid_value, "invalid value to unflatten", &result)); | |
| } | |
| values.push_back(current); | |
| ends.push_back(end); | |
| pos = end; | |
| } | |
| *current = element.second; | |
| } | |
| return result; | |
| } | |
| // can't use the conversion operator because of ambiguity | |
| json_pointer<string_t> convert() const& | |
| { | |
| json_pointer<string_t> result; | |
| result.reference_tokens = reference_tokens; | |
| return result; | |
| } | |
| json_pointer<string_t> convert()&& | |
| { | |
| json_pointer<string_t> result; | |
| result.reference_tokens = std::move(reference_tokens); | |
| return result; | |
| } | |
| public: | |
| #if JSON_HAS_THREE_WAY_COMPARISON | |
| /// @brief compares two JSON pointers for equality | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/ | |
| template<typename RefStringTypeRhs> | |
| bool operator==(const json_pointer<RefStringTypeRhs>& rhs) const noexcept | |
| { | |
| return reference_tokens == rhs.reference_tokens; | |
| } | |
| /// @brief compares JSON pointer and string for equality | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/ | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator==(json_pointer)) | |
| bool operator==(const string_t& rhs) const | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return equals_string(rhs); | |
| } | |
| #endif | |
| /// @brief 3-way compares two JSON pointers | |
| template<typename RefStringTypeRhs> | |
| std::strong_ordering operator<=>(const json_pointer<RefStringTypeRhs>& rhs) const noexcept // *NOPAD* | |
| { | |
| return reference_tokens <=> rhs.reference_tokens; // *NOPAD* | |
| } | |
| #else | |
| /// @brief compares two JSON pointers for equality | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/ | |
| template<typename RefStringTypeLhs, typename RefStringTypeRhs> | |
| // NOLINTNEXTLINE(readability-redundant-declaration) | |
| friend bool operator==(const json_pointer<RefStringTypeLhs>& lhs, | |
| const json_pointer<RefStringTypeRhs>& rhs) noexcept; | |
| /// @brief compares JSON pointer and string for equality | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/ | |
| template<typename RefStringTypeLhs, typename StringType> | |
| // NOLINTNEXTLINE(readability-redundant-declaration) | |
| friend bool operator==(const json_pointer<RefStringTypeLhs>& lhs, | |
| const StringType& rhs); | |
| /// @brief compares string and JSON pointer for equality | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/ | |
| template<typename RefStringTypeRhs, typename StringType> | |
| // NOLINTNEXTLINE(readability-redundant-declaration) | |
| friend bool operator==(const StringType& lhs, | |
| const json_pointer<RefStringTypeRhs>& rhs); | |
| /// @brief compares two JSON pointers for inequality | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_ne/ | |
| template<typename RefStringTypeLhs, typename RefStringTypeRhs> | |
| // NOLINTNEXTLINE(readability-redundant-declaration) | |
| friend bool operator!=(const json_pointer<RefStringTypeLhs>& lhs, | |
| const json_pointer<RefStringTypeRhs>& rhs) noexcept; | |
| /// @brief compares JSON pointer and string for inequality | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_ne/ | |
| template<typename RefStringTypeLhs, typename StringType> | |
| // NOLINTNEXTLINE(readability-redundant-declaration) | |
| friend bool operator!=(const json_pointer<RefStringTypeLhs>& lhs, | |
| const StringType& rhs); | |
| /// @brief compares string and JSON pointer for inequality | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_ne/ | |
| template<typename RefStringTypeRhs, typename StringType> | |
| // NOLINTNEXTLINE(readability-redundant-declaration) | |
| friend bool operator!=(const StringType& lhs, | |
| const json_pointer<RefStringTypeRhs>& rhs); | |
| /// @brief compares two JSON pointers for less-than | |
| /// @sa https://json.nlohmann.me/api/json_pointer/operator_spaceship/ | |
| template<typename RefStringTypeLhs, typename RefStringTypeRhs> | |
| // NOLINTNEXTLINE(readability-redundant-declaration) | |
| friend bool operator<(const json_pointer<RefStringTypeLhs>& lhs, | |
| const json_pointer<RefStringTypeRhs>& rhs) noexcept; | |
| #endif | |
| private: | |
| /// the reference tokens | |
| std::vector<string_t> reference_tokens; | |
| }; | |
| #if !JSON_HAS_THREE_WAY_COMPARISON | |
| // functions cannot be defined inside the class due to ODR violations | |
| template<typename RefStringTypeLhs, typename RefStringTypeRhs> | |
| inline bool operator==(const json_pointer<RefStringTypeLhs>& lhs, | |
| const json_pointer<RefStringTypeRhs>& rhs) noexcept | |
| { | |
| return lhs.reference_tokens == rhs.reference_tokens; | |
| } | |
| template<typename RefStringTypeLhs, | |
| typename StringType = typename json_pointer<RefStringTypeLhs>::string_t> | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator==(json_pointer, json_pointer)) | |
| inline bool operator==(const json_pointer<RefStringTypeLhs>& lhs, | |
| const StringType& rhs) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return lhs.equals_string(rhs); | |
| } | |
| #endif | |
| template<typename RefStringTypeRhs, | |
| typename StringType = typename json_pointer<RefStringTypeRhs>::string_t> | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator==(json_pointer, json_pointer)) | |
| inline bool operator==(const StringType& lhs, | |
| const json_pointer<RefStringTypeRhs>& rhs) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return rhs.equals_string(lhs); | |
| } | |
| #endif | |
| template<typename RefStringTypeLhs, typename RefStringTypeRhs> | |
| inline bool operator!=(const json_pointer<RefStringTypeLhs>& lhs, | |
| const json_pointer<RefStringTypeRhs>& rhs) noexcept | |
| { | |
| return !(lhs == rhs); | |
| } | |
| template<typename RefStringTypeLhs, | |
| typename StringType = typename json_pointer<RefStringTypeLhs>::string_t> | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator!=(json_pointer, json_pointer)) | |
| inline bool operator!=(const json_pointer<RefStringTypeLhs>& lhs, | |
| const StringType& rhs) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return !(lhs == rhs); | |
| } | |
| #endif | |
| template<typename RefStringTypeRhs, | |
| typename StringType = typename json_pointer<RefStringTypeRhs>::string_t> | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator!=(json_pointer, json_pointer)) | |
| inline bool operator!=(const StringType& lhs, | |
| const json_pointer<RefStringTypeRhs>& rhs) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return !(lhs == rhs); | |
| } | |
| #endif | |
| template<typename RefStringTypeLhs, typename RefStringTypeRhs> | |
| inline bool operator<(const json_pointer<RefStringTypeLhs>& lhs, | |
| const json_pointer<RefStringTypeRhs>& rhs) noexcept | |
| { | |
| return lhs.reference_tokens < rhs.reference_tokens; | |
| } | |
| #endif | |
| namespace detail | |
| { | |
| /// the reference tokens of a json_pointer, for code that resolves pointers | |
| /// without a basic_json value (such as the zero-copy view) | |
| struct json_pointer_access | |
| { | |
| template<typename RefStringType> | |
| static const std::vector<typename json_pointer<RefStringType>::string_t>& reference_tokens(const json_pointer<RefStringType>& ptr) noexcept | |
| { | |
| return ptr.reference_tokens; | |
| } | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/json_ref.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <initializer_list> | |
| #include <utility> | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| template<typename BasicJsonType> | |
| class json_ref | |
| { | |
| public: | |
| using value_type = BasicJsonType; | |
| json_ref(value_type&& value) | |
| : owned_value(std::move(value)) | |
| {} | |
| json_ref(const value_type& value) | |
| : value_ref(&value) | |
| {} | |
| json_ref(std::initializer_list<json_ref> init) | |
| : owned_value(init) | |
| , braced_list(true) | |
| {} | |
| template < | |
| class... Args, | |
| enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 > | |
| json_ref(Args && ... args) | |
| : owned_value(std::forward<Args>(args)...) | |
| {} | |
| // class should be movable only | |
| json_ref(json_ref&&) noexcept = default; | |
| json_ref(const json_ref&) = delete; | |
| json_ref& operator=(const json_ref&) = delete; | |
| json_ref& operator=(json_ref&&) = delete; | |
| ~json_ref() = default; | |
| value_type moved_or_copied() const | |
| { | |
| if (value_ref == nullptr) | |
| { | |
| return std::move(owned_value); | |
| } | |
| return *value_ref; | |
| } | |
| value_type const& operator*() const | |
| { | |
| return value_ref ? *value_ref : owned_value; | |
| } | |
| value_type const* operator->() const | |
| { | |
| return &** this; | |
| } | |
| /// whether the value was written as a braced list, such as {"key", 1}, | |
| /// rather than given as a value | |
| bool is_braced_list() const noexcept | |
| { | |
| return braced_list; | |
| } | |
| private: | |
| mutable value_type owned_value = nullptr; | |
| value_type const* value_ref = nullptr; | |
| bool braced_list = false; | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // IWYU pragma: export | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // IWYU pragma: export | |
| // #include <nlohmann/detail/meta/detected.hpp> | |
| // #include <nlohmann/detail/string_concat.hpp> | |
| // #include <nlohmann/detail/string_escape.hpp> | |
| // #include <nlohmann/detail/string_utils.hpp> | |
| // #include <nlohmann/detail/meta/cpp_future.hpp> | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| // #include <nlohmann/detail/output/binary_writer.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <algorithm> // max, min, reverse | |
| #include <array> // array | |
| #include <cmath> // isnan, isinf | |
| #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t | |
| #include <cstring> // memcpy | |
| #include <limits> // numeric_limits | |
| #include <string> // string | |
| #include <type_traits> // enable_if, is_constructible | |
| #include <utility> // move | |
| #include <vector> // vector | |
| // #include <nlohmann/detail/bit_ops.hpp> | |
| // #include <nlohmann/detail/input/binary_reader.hpp> | |
| // #include <nlohmann/detail/input/input_adapters.hpp> | |
| // #include <nlohmann/detail/input/string_scan.hpp> | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/output/error_handler.hpp> | |
| // #include <nlohmann/detail/output/output_adapters.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <algorithm> // max | |
| #include <array> // array | |
| #include <cstddef> // size_t | |
| #include <cstring> // memcpy | |
| #include <memory> // shared_ptr, make_shared | |
| #include <string> // basic_string | |
| #include <type_traits> // conditional, integral_constant, is_same | |
| #include <utility> // move | |
| #include <vector> // vector | |
| #ifndef JSON_NO_IO | |
| #include <ios> // streamsize | |
| #include <ostream> // basic_ostream | |
| #endif // JSON_NO_IO | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /// abstract output adapter interface | |
| template<typename CharType> struct output_adapter_protocol | |
| { | |
| virtual void write_character(CharType c) = 0; | |
| /// @param[in] s pointer to the characters to write; binary_writer legitimately | |
| /// passes a null pointer together with length 0 for an empty | |
| /// string or binary value, so implementations must tolerate that | |
| /// @param[in] length number of characters at @a s | |
| virtual void write_characters(const CharType* s, std::size_t length) = 0; | |
| virtual ~output_adapter_protocol() = default; | |
| output_adapter_protocol() = default; | |
| output_adapter_protocol(const output_adapter_protocol&) = default; | |
| output_adapter_protocol(output_adapter_protocol&&) noexcept = default; | |
| output_adapter_protocol& operator=(const output_adapter_protocol&) = default; | |
| output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default; | |
| }; | |
| /// a type to simplify interfaces | |
| template<typename CharType> | |
| using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>; | |
| /// the largest number of characters a writer may reserve() from a sink at once; | |
| /// output_vector_sink also appends writes of at least this size with insert() | |
| constexpr std::size_t max_reserve_size = 256; | |
| /// @brief copy @a length characters, at most 32, without a call of memcpy() | |
| /// | |
| /// Short strings are the typical payload of a binary value, and a call of | |
| /// memcpy() costs more than copying them. A copy of 16 to 32 characters is two | |
| /// possibly overlapping 16-byte copies, one of 8 to 15 two 8-byte copies, and | |
| /// so on down to a single character; each is a fixed-size load and store. | |
| /// Nothing outside of [src, src + length) is read or written. | |
| template<typename CharType> | |
| inline void copy_short(CharType* dst, const CharType* src, const std::size_t length, std::true_type /*is_byte*/) noexcept | |
| { | |
| JSON_ASSERT(length <= 32); | |
| if (length >= 16) | |
| { | |
| std::array<char, 16> first; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read | |
| std::array<char, 16> last; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read | |
| std::memcpy(first.data(), src, 16); | |
| std::memcpy(last.data(), src + (length - 16), 16); | |
| std::memcpy(dst, first.data(), 16); | |
| std::memcpy(dst + (length - 16), last.data(), 16); | |
| } | |
| else if (length >= 8) | |
| { | |
| std::array<char, 8> first; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read | |
| std::array<char, 8> last; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read | |
| std::memcpy(first.data(), src, 8); | |
| std::memcpy(last.data(), src + (length - 8), 8); | |
| std::memcpy(dst, first.data(), 8); | |
| std::memcpy(dst + (length - 8), last.data(), 8); | |
| } | |
| else if (length >= 4) | |
| { | |
| std::array<char, 4> first; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read | |
| std::array<char, 4> last; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read | |
| std::memcpy(first.data(), src, 4); | |
| std::memcpy(last.data(), src + (length - 4), 4); | |
| std::memcpy(dst, first.data(), 4); | |
| std::memcpy(dst + (length - 4), last.data(), 4); | |
| } | |
| else if (length != 0) | |
| { | |
| // 1 to 3: the first, the middle, and the last character | |
| const CharType a = src[0]; | |
| const CharType b = src[length >> 1]; | |
| const CharType c = src[length - 1]; | |
| dst[0] = a; | |
| dst[length >> 1] = b; | |
| dst[length - 1] = c; | |
| } | |
| } | |
| /// @brief copy @a length characters, of a character type wider than a byte | |
| template<typename CharType> | |
| inline void copy_short(CharType* dst, const CharType* src, const std::size_t length, std::false_type /*is_byte*/) noexcept | |
| { | |
| std::memcpy(dst, src, length * sizeof(CharType)); | |
| } | |
| /// the number of characters an empty vector is grown to by output_vector_sink | |
| constexpr std::size_t min_vector_sink_capacity = 64; | |
| /// @brief non-virtual output sink writing into a std::vector | |
| /// | |
| /// This sink is not part of the virtual output_adapter_protocol hierarchy: it is | |
| /// passed to binary_writer by value as a template parameter, so | |
| /// write_character()/write_characters() are ordinary (inlinable) calls with no | |
| /// vtable lookup and no shared_ptr. It is used for the common | |
| /// `to_cbor`/`to_msgpack`/... into a std::vector. | |
| /// | |
| /// Most writes are a few bytes - a type marker, or a number of 1, 2, 4, or 8 | |
| /// bytes - and appending those with push_back() or insert() cost more than | |
| /// encoding them: insert() is an out-of-line call into a routine that can insert | |
| /// anywhere, and resize() is one as well with libstdc++. The sink therefore keeps | |
| /// its own write position: it grows the vector geometrically ahead of the | |
| /// position and copies each write to it, so a write is a capacity check and a | |
| /// short copy. The destructor shrinks the vector to the bytes actually written, | |
| /// also when a write throws; shrinking a vector never allocates. The sink owns | |
| /// that trim, so it can be moved but not copied, and the vector must not be used | |
| /// while the sink is alive. | |
| template<typename CharType, typename AllocatorType = std::allocator<CharType>> | |
| class output_vector_sink | |
| { | |
| public: | |
| explicit output_vector_sink(std::vector<CharType, AllocatorType>& vec) noexcept | |
| : v(&vec), cursor(vec.data() + vec.size()), limit(cursor) | |
| {} | |
| output_vector_sink(const output_vector_sink&) = delete; | |
| output_vector_sink& operator=(const output_vector_sink&) = delete; | |
| output_vector_sink& operator=(output_vector_sink&&) = delete; | |
| output_vector_sink(output_vector_sink&& other) noexcept | |
| : v(other.v), cursor(other.cursor), limit(other.limit) | |
| { | |
| other.v = nullptr; | |
| } | |
| ~output_vector_sink() | |
| { | |
| if (v != nullptr) | |
| { | |
| v->resize(position()); | |
| } | |
| } | |
| // always inlined: GCC otherwise keeps these out of line in a large | |
| // translation unit, and a call per byte or number costs more than the write | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| void write_character(CharType c) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(cursor == limit)) | |
| { | |
| grow(1); | |
| } | |
| *cursor++ = c; | |
| } | |
| // no JSON_HEDLEY_NON_NULL here: binary_writer legitimately passes a null | |
| // pointer with length 0 for empty strings/binary values; memcpy must not | |
| // see it. | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| void write_characters(const CharType* s, std::size_t length) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(space() < length)) | |
| { | |
| if (length >= max_reserve_size) | |
| { | |
| append(s, length); | |
| return; | |
| } | |
| grow(length); | |
| } | |
| if (length <= 32) | |
| { | |
| copy_short(cursor, s, length, std::integral_constant<bool, sizeof(CharType) == 1>()); | |
| cursor += length; | |
| } | |
| else | |
| { | |
| std::memcpy(cursor, s, length * sizeof(CharType)); | |
| cursor += length; | |
| } | |
| } | |
| /// @brief space for writing up to @a length characters directly | |
| /// | |
| /// Returns a pointer to at least @a length (at most @ref max_reserve_size) | |
| /// writable characters at the write position; @ref commit then keeps the | |
| /// first ones of them. A writer can store whole words there and keep only | |
| /// the bytes it needs, and keep its write pointer in a register across many | |
| /// values instead of updating the sink after each. | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| CharType* reserve(const std::size_t length) | |
| { | |
| JSON_ASSERT(length <= max_reserve_size); | |
| if (JSON_HEDLEY_UNLIKELY(space() < length)) | |
| { | |
| grow(length); | |
| } | |
| return cursor; | |
| } | |
| /// keep the first @a length characters written to the space from reserve() | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| void commit(const std::size_t length) noexcept | |
| { | |
| cursor += length; | |
| } | |
| /// nothing to pass on: the characters are in the vector (see output_adapter_sink) | |
| void flush() noexcept | |
| {} | |
| private: | |
| /// number of characters of *v written so far | |
| std::size_t position() const noexcept | |
| { | |
| return static_cast<std::size_t>(cursor - v->data()); | |
| } | |
| /// number of characters that fit the vector behind the write position | |
| std::size_t space() const noexcept | |
| { | |
| return static_cast<std::size_t>(limit - cursor); | |
| } | |
| /// make room for at least @a length more characters after the position; | |
| /// kept out of line so that the write functions stay small enough for | |
| /// GCC to inline them into the writer | |
| JSON_HEDLEY_NEVER_INLINE | |
| void grow(const std::size_t length) | |
| { | |
| // use the capacity the vector already has, else at least double it; | |
| // never less than min_vector_sink_capacity, so that a small value does not | |
| // reallocate for every few bytes | |
| const std::size_t written = position(); | |
| const std::size_t needed = written + length; | |
| v->resize((std::max)(min_vector_sink_capacity, needed <= v->capacity() | |
| ? v->capacity() | |
| : (std::max)(needed, v->capacity() * 2))); | |
| cursor = v->data() + written; | |
| limit = v->data() + v->size(); | |
| } | |
| /// append @a length (at least max_reserve_size) characters that do not fit | |
| /// the space ahead of the position: insert() copies them once into the | |
| /// grown vector, where grow() would first zero the new space and then copy | |
| /// over it - noticeable for a large string or binary value | |
| JSON_HEDLEY_NEVER_INLINE | |
| void append(const CharType* s, const std::size_t length) | |
| { | |
| const std::size_t written = position(); | |
| v->resize(written); | |
| if (v->capacity() - written < length) | |
| { | |
| // grow geometrically, with room for the writes that follow, so | |
| // that the next grow() need not reallocate right away | |
| v->reserve((std::max)(v->capacity() * 2, written + length + max_reserve_size)); | |
| } | |
| v->insert(v->end(), s, s + length); | |
| cursor = v->data() + v->size(); | |
| limit = cursor; | |
| } | |
| std::vector<CharType, AllocatorType>* v; | |
| /// the write position: in *v, at the number of characters written so far | |
| CharType* cursor; | |
| /// the end of *v | |
| CharType* limit; | |
| }; | |
| /// output adapter for byte vectors | |
| template<typename CharType, typename AllocatorType = std::allocator<CharType>> | |
| class output_vector_adapter : public output_adapter_protocol<CharType> | |
| { | |
| public: | |
| explicit output_vector_adapter(std::vector<CharType, AllocatorType>& vec) noexcept | |
| : v(vec) | |
| {} | |
| void write_character(CharType c) override | |
| { | |
| v.push_back(c); | |
| } | |
| // no JSON_HEDLEY_NON_NULL here: binary_writer legitimately passes a null | |
| // pointer with length 0 for empty strings/binary values; appending an empty | |
| // range is a no-op | |
| void write_characters(const CharType* s, std::size_t length) override | |
| { | |
| v.insert(v.end(), s, s + length); | |
| } | |
| private: | |
| std::vector<CharType, AllocatorType>& v; | |
| }; | |
| #ifndef JSON_NO_IO | |
| /// output adapter for output streams | |
| template<typename CharType> | |
| class output_stream_adapter : public output_adapter_protocol<CharType> | |
| { | |
| public: | |
| explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept | |
| : stream(s) | |
| {} | |
| // NOLINTNEXTLINE(portability-template-virtual-member-function) | |
| void write_character(CharType c) override | |
| { | |
| stream.put(c); | |
| } | |
| // NOLINTNEXTLINE(portability-template-virtual-member-function) | |
| void write_characters(const CharType* s, std::size_t length) override | |
| { | |
| stream.write(s, static_cast<std::streamsize>(length)); | |
| } | |
| private: | |
| std::basic_ostream<CharType>& stream; | |
| }; | |
| #endif // JSON_NO_IO | |
| /// output adapter for basic_string | |
| template<typename CharType, typename StringType = std::basic_string<CharType>> | |
| class output_string_adapter : public output_adapter_protocol<CharType> | |
| { | |
| public: | |
| explicit output_string_adapter(StringType& s) noexcept | |
| : str(s) | |
| {} | |
| void write_character(CharType c) override | |
| { | |
| str.push_back(c); | |
| } | |
| void write_characters(const CharType* s, std::size_t length) override | |
| { | |
| str.append(s, length); | |
| } | |
| private: | |
| StringType& str; | |
| }; | |
| /// @brief output sink forwarding to a type-erased output adapter | |
| /// | |
| /// Wraps the polymorphic output_adapter_t so the same binary_writer template can | |
| /// also target arbitrary adapters (output streams, strings, user-provided | |
| /// adapters) via the `output_adapter`-based overloads. | |
| /// | |
| /// A write through the adapter is a virtual call, and for a stream a call with | |
| /// a sentry on top, which costs more than encoding the few bytes of most values. | |
| /// The sink therefore collects what is written in a buffer and passes it on in | |
| /// one piece when it is full, a write is too large for it, or @ref flush is | |
| /// called. Everything written reaches the adapter in the same order and with | |
| /// the same bytes; the destructor passes on what is left, so that a write that | |
| /// throws leaves the adapter with exactly the bytes written before it. Only | |
| /// @ref flush can report an error of the adapter (the destructor must not | |
| /// throw), so it has to be called once the value is written. | |
| template<typename CharType> | |
| class output_adapter_sink | |
| { | |
| public: | |
| explicit output_adapter_sink(output_adapter_t<CharType> adapter) | |
| : oa(std::move(adapter)) | |
| { | |
| JSON_ASSERT(oa); | |
| } | |
| output_adapter_sink(const output_adapter_sink&) = delete; | |
| output_adapter_sink& operator=(const output_adapter_sink&) = delete; | |
| output_adapter_sink& operator=(output_adapter_sink&&) = delete; | |
| output_adapter_sink(output_adapter_sink&& other) noexcept | |
| : oa(std::move(other.oa)), used(other.used) | |
| { | |
| std::memcpy(buffer.data(), other.buffer.data(), other.used * sizeof(CharType)); | |
| other.used = 0; | |
| } | |
| ~output_adapter_sink() | |
| { | |
| // a normal return has flushed already, so this is for a write that threw | |
| if (used != 0) | |
| { | |
| JSON_TRY | |
| { | |
| flush(); | |
| } | |
| JSON_CATCH(...) | |
| { | |
| // nothing can be done about an adapter that throws here | |
| } | |
| } | |
| } | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| void write_character(CharType c) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(used == buffer_size)) | |
| { | |
| flush(); | |
| } | |
| buffer[used++] = c; | |
| } | |
| // no JSON_HEDLEY_NON_NULL: forwards (null, 0) for empty payloads, exactly as | |
| // the type-erased path already did before this sink existed | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| void write_characters(const CharType* s, std::size_t length) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(buffer_size - used < length)) | |
| { | |
| write_large(s, length); | |
| return; | |
| } | |
| if (length <= 32) | |
| { | |
| copy_short(buffer.data() + used, s, length, std::integral_constant<bool, sizeof(CharType) == 1>()); | |
| used += length; | |
| } | |
| else | |
| { | |
| std::memcpy(buffer.data() + used, s, length * sizeof(CharType)); | |
| used += length; | |
| } | |
| } | |
| /// space for writing up to @a length characters (see | |
| /// output_vector_sink::reserve) | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| CharType* reserve(const std::size_t length) | |
| { | |
| JSON_ASSERT(length <= max_reserve_size); | |
| if (JSON_HEDLEY_UNLIKELY(buffer_size - used < length)) | |
| { | |
| flush(); | |
| } | |
| return buffer.data() + used; | |
| } | |
| /// keep the first @a length characters written to the space from reserve() | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| void commit(const std::size_t length) noexcept | |
| { | |
| used += length; | |
| } | |
| /// pass everything written so far on to the adapter | |
| void flush() | |
| { | |
| if (used != 0) | |
| { | |
| // reset first: the characters count as written even if the adapter throws | |
| const std::size_t length = used; | |
| used = 0; | |
| oa->write_characters(buffer.data(), length); | |
| } | |
| } | |
| private: | |
| /// a write that does not fit the space left in the buffer | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_large(const CharType* s, const std::size_t length) | |
| { | |
| flush(); | |
| if (length >= buffer_size) | |
| { | |
| oa->write_characters(s, length); | |
| } | |
| else | |
| { | |
| std::memcpy(buffer.data(), s, length * sizeof(CharType)); | |
| used = length; | |
| } | |
| } | |
| /// large enough for reserve() at any time | |
| static constexpr std::size_t buffer_size = 4 * max_reserve_size; | |
| output_adapter_t<CharType> oa; | |
| /// number of characters of @ref buffer not yet passed on | |
| std::size_t used = 0; | |
| std::array<CharType, buffer_size> buffer{}; | |
| }; | |
| /// @brief whether std::basic_string<CharType> has a non-deprecated std::char_traits | |
| /// specialization, and is therefore usable as output_adapter's default StringType | |
| /// | |
| /// std::char_traits is only guaranteed (and, on some standard libraries, only | |
| /// implemented without a deprecation warning) for the character types listed | |
| /// below; std::char_traits<T> for any other T (e.g. std::uint8_t, as used by the | |
| /// binary writers) is a non-standard extension some standard libraries deprecate. | |
| /// See https://github.com/nlohmann/json/issues/5725 item 2. | |
| template<typename CharType> | |
| struct is_output_adapter_string_char_type : std::integral_constant < bool, | |
| std::is_same<CharType, char>::value || | |
| std::is_same<CharType, wchar_t>::value || | |
| std::is_same<CharType, char16_t>::value || | |
| std::is_same<CharType, char32_t>::value | |
| #if defined(__cpp_lib_char8_t) && (__cpp_lib_char8_t >= 201907L) | |
| || std::is_same<CharType, char8_t>::value | |
| #endif | |
| > {}; | |
| /// @brief placeholder type for output_adapter's StringType and (with JSON_NO_IO | |
| /// undefined) its std::basic_ostream constructor parameter, for CharType | |
| /// with no non-deprecated std::char_traits specialization | |
| /// | |
| /// Never actually used: the StringType- and std::basic_ostream-based | |
| /// output_adapter constructors are neither documented nor tested for such | |
| /// CharType (only the std::vector-based constructor is used for them, by the | |
| /// binary writers). Naming std::basic_string<CharType> or | |
| /// std::basic_ostream<CharType> anywhere such a constructor would otherwise be | |
| /// declared - even as an unused default template argument or an unused, | |
| /// never-called overload - instantiates std::char_traits<CharType> merely to | |
| /// name the type, which is exactly what triggers the deprecation warning this | |
| /// placeholder avoids. | |
| template<typename CharType> | |
| struct output_adapter_no_string_type {}; | |
| // Select output_adapter's default StringType (and, below, its ostream | |
| // constructor's parameter type) via partial specialization, not | |
| // std::conditional: std::conditional<B, T, F> requires both T and F to be named | |
| // as template arguments up front, which would still instantiate (and thus name) | |
| // std::basic_string<CharType> / std::basic_ostream<CharType> for every CharType, | |
| // defeating the point. A bool non-type parameter with two specializations only | |
| // ever names the type that is actually selected. | |
| template<typename CharType, bool = is_output_adapter_string_char_type<CharType>::value> | |
| struct output_adapter_default_string_type | |
| { | |
| using type = output_adapter_no_string_type<CharType>; | |
| }; | |
| template<typename CharType> | |
| struct output_adapter_default_string_type<CharType, true> | |
| { | |
| using type = std::basic_string<CharType>; | |
| }; | |
| #ifndef JSON_NO_IO | |
| /// distinct from output_adapter_no_string_type, so the placeholder overloads of | |
| /// output_adapter's constructor (used when CharType is not a character type) | |
| /// stay distinct overloads instead of colliding into a single redeclaration | |
| template<typename CharType> | |
| struct output_adapter_no_ostream_type {}; | |
| template<typename CharType, bool = is_output_adapter_string_char_type<CharType>::value> | |
| struct output_adapter_ostream_type | |
| { | |
| using type = output_adapter_no_ostream_type<CharType>; | |
| }; | |
| template<typename CharType> | |
| struct output_adapter_ostream_type<CharType, true> | |
| { | |
| using type = std::basic_ostream<CharType>; | |
| }; | |
| #endif // JSON_NO_IO | |
| template < typename CharType, typename StringType = | |
| typename output_adapter_default_string_type<CharType>::type > | |
| class output_adapter | |
| { | |
| public: | |
| template<typename AllocatorType = std::allocator<CharType>> | |
| output_adapter(std::vector<CharType, AllocatorType>& vec) | |
| : oa(std::make_shared<output_vector_adapter<CharType, AllocatorType>>(vec)) {} | |
| #ifndef JSON_NO_IO | |
| output_adapter(typename output_adapter_ostream_type<CharType>::type& s) | |
| : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {} | |
| #endif // JSON_NO_IO | |
| output_adapter(StringType& s) | |
| : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {} | |
| operator output_adapter_t<CharType>() | |
| { | |
| return oa; | |
| } | |
| private: | |
| output_adapter_t<CharType> oa = nullptr; | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/recursion_depth_limit.hpp> | |
| // #include <nlohmann/detail/string_concat.hpp> | |
| // #include <nlohmann/detail/string_utils.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /// how to encode BJData | |
| enum class bjdata_version_t | |
| { | |
| draft2, | |
| draft3, | |
| }; | |
| /////////////////// | |
| // binary writer // | |
| /////////////////// | |
| /*! | |
| @brief capacity hint for binary serialization into a std::vector | |
| Returns a *lower* bound on the number of bytes the serialization will produce, | |
| so that writing an array/object of many elements does not start reallocating | |
| from an empty buffer. Every array element occupies at least one byte in every | |
| supported binary format, and every object entry at least two (a key of at least | |
| one byte plus a value of at least one), plus one byte for the container header, | |
| so the hint can never exceed the final size and the returned vector is never | |
| left holding capacity the caller did not ask for. The buffer still grows | |
| geometrically past the hint, so under-reserving only costs a few later | |
| reallocations. Only the top-level element count is consulted (O(1), no walk of | |
| the DOM); a single scalar, string, or binary value is written in one shot and | |
| needs no hint. | |
| */ | |
| template<typename BasicJsonType> | |
| std::size_t binary_reserve_hint(const BasicJsonType& j) | |
| { | |
| if (j.is_array()) | |
| { | |
| return j.size() + 1; | |
| } | |
| if (j.is_object()) | |
| { | |
| return (j.size() * 2) + 1; | |
| } | |
| return 0; | |
| } | |
| /*! | |
| @brief the capacity to reserve for the result of a binary serialization into a | |
| std::vector | |
| The hint of @ref binary_reserve_hint, but not less than the 64 characters that | |
| output_vector_sink grows an empty vector to on its first write anyway. A small | |
| document then costs one allocation, instead of an allocation of a few bytes that | |
| the first write replaces with one of 64. | |
| */ | |
| template<typename BasicJsonType> | |
| std::size_t binary_initial_capacity(const BasicJsonType& j) | |
| { | |
| return (std::max)(binary_reserve_hint(j), min_vector_sink_capacity); | |
| } | |
| /*! | |
| @brief serialization to BJData, BON8, BSON, CBOR, MessagePack, and UBJSON values | |
| */ | |
| template<typename BasicJsonType, typename CharType, typename OutputSinkType = output_adapter_sink<CharType>> | |
| class binary_writer | |
| { | |
| using string_t = typename BasicJsonType::string_t; | |
| /// an object key as string_t: a reference when object_t::key_type already is | |
| /// string_t, otherwise a converted copy that outlives sanitize_utf8_for_write's result | |
| using object_key_string_t = typename std::conditional < | |
| std::is_same<typename BasicJsonType::object_t::key_type, string_t>::value, | |
| const string_t&, string_t >::type; | |
| using binary_t = typename BasicJsonType::binary_t; | |
| using number_float_t = typename BasicJsonType::number_float_t; | |
| public: | |
| /*! | |
| @brief create a binary writer | |
| @param[in] sink output sink to write to (a value-type sink such as | |
| output_vector_sink, or output_adapter_sink wrapping a | |
| type-erased output adapter) | |
| @param[in] error_handler_ how to treat a string value or object key that | |
| is not valid UTF-8 (CBOR, MessagePack, UBJSON, BJData, and BSON; | |
| never consulted by @ref write_bon8) | |
| */ | |
| explicit binary_writer(OutputSinkType sink, const error_handler_t error_handler_ = binary_writer_default_error_handler()) | |
| : oa(std::move(sink)), error_handler(error_handler_) | |
| {} | |
| /*! | |
| @brief create a binary writer from a type-erased output adapter | |
| Convenience constructor for the default (output_adapter_sink) sink so the | |
| `output_adapter`-based overloads keep constructing the writer directly from | |
| an adapter. Constrained to sinks that can actually be built from an adapter, | |
| so that a writer over some other sink type is not advertised as constructible | |
| from one. | |
| @param[in] adapter output adapter to write to | |
| @param[in] error_handler_ how to treat a string value or object key that | |
| is not valid UTF-8 (CBOR, MessagePack, UBJSON, BJData, and BSON; | |
| never consulted by @ref write_bon8) | |
| */ | |
| template < typename SinkType = OutputSinkType, | |
| typename std::enable_if < std::is_constructible<SinkType, output_adapter_t<CharType>>::value, int >::type = 0 > | |
| explicit binary_writer(output_adapter_t<CharType> adapter, const error_handler_t error_handler_ = binary_writer_default_error_handler()) | |
| : oa(std::move(adapter)), error_handler(error_handler_) | |
| {} | |
| /*! | |
| @brief pass on everything written so far to the output adapter | |
| A writer over an output_adapter_sink buffers what it writes; this has to | |
| be called after the last write, or the buffered end is only passed on, and | |
| an error of the adapter lost, when the writer is destroyed. A writer over | |
| an output_vector_sink writes straight into the vector. | |
| */ | |
| void flush() | |
| { | |
| oa.flush(); | |
| } | |
| /*! | |
| @param[in] j JSON value to serialize | |
| @throw type_error.316 if a string value or an object key is not valid | |
| UTF-8 | |
| @throw type_error.317 if @a j is not an object | |
| @throw type_error.321 if a value nested in @a j is discarded | |
| */ | |
| void write_bson(const BasicJsonType& j) | |
| { | |
| switch (j.type()) | |
| { | |
| case value_t::object: | |
| { | |
| write_bson_document(j); | |
| break; | |
| } | |
| case value_t::null: | |
| case value_t::array: | |
| case value_t::string: | |
| case value_t::boolean: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| case value_t::binary: | |
| case value_t::discarded: | |
| default: | |
| { | |
| JSON_THROW(type_error::create(exception_id::type_not_serializable, concat("to serialize to BSON, top-level type must be object, but is ", j.type_name()), &j)); | |
| } | |
| } | |
| } | |
| /*! | |
| @param[in] j JSON value to serialize | |
| @param[in] depth nesting level of @a j, counted from the top-level value | |
| passed to @ref basic_json::to_cbor | |
| @throw type_error.316 if a string value or an object key is not valid | |
| UTF-8 | |
| @throw type_error.321 if @a j or a value nested in it is discarded | |
| Serializing a container descends into its elements, so a value nested deeply | |
| enough used to exhaust the call stack and terminate the process with no | |
| exception to catch. The descent is bounded here: once @ref recursion_depth_limit | |
| levels have been entered, @ref write_cbor_iterative writes out what is left | |
| without the call stack. A value nested less deeply than that - all but a | |
| vanishing minority - is written by exactly the code that always wrote it. | |
| @sa https://github.com/nlohmann/json/issues/5392 | |
| */ | |
| void write_cbor(const BasicJsonType& j, const std::size_t depth = 0) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(depth >= recursion_depth_limit()) && (j.is_array() || j.is_object())) | |
| { | |
| write_cbor_iterative(j); | |
| return; | |
| } | |
| switch (j.type()) | |
| { | |
| case value_t::null: | |
| { | |
| oa.write_character(to_char_type(0xF6)); | |
| break; | |
| } | |
| case value_t::boolean: | |
| { | |
| oa.write_character(j.m_data.m_value.boolean | |
| ? to_char_type(0xF5) | |
| : to_char_type(0xF4)); | |
| break; | |
| } | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| { | |
| // one case for both, so that an array mixing negative | |
| // (number_integer) and non-negative (number_unsigned) values | |
| // does not mispredict the switch | |
| write_cbor_integer(j, std::integral_constant<bool, integers_fit_64_bits()>()); | |
| break; | |
| } | |
| case value_t::number_float: | |
| { | |
| if (std::isnan(j.m_data.m_value.number_float)) | |
| { | |
| // NaN is 0xf97e00 in CBOR | |
| oa.write_character(to_char_type(0xF9)); | |
| oa.write_character(to_char_type(0x7E)); | |
| oa.write_character(to_char_type(0x00)); | |
| } | |
| else if (std::isinf(j.m_data.m_value.number_float)) | |
| { | |
| // Infinity is 0xf97c00, -Infinity is 0xf9fc00 | |
| oa.write_character(to_char_type(0xf9)); | |
| oa.write_character(j.m_data.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC)); | |
| oa.write_character(to_char_type(0x00)); | |
| } | |
| else | |
| { | |
| write_compact_float(j.m_data.m_value.number_float, to_char_type(0xFA), to_char_type(0xFB)); | |
| } | |
| break; | |
| } | |
| case value_t::string: | |
| { | |
| write_cbor_string(*j.m_data.m_value.string, j); | |
| break; | |
| } | |
| case value_t::array: | |
| { | |
| write_cbor_array(j, depth); | |
| break; | |
| } | |
| case value_t::binary: | |
| { | |
| if (j.m_data.m_value.binary->has_subtype()) | |
| { | |
| // The subtype is always written as a tag with a 0xD8..0xDB | |
| // head, never in the one-byte form 0xC0..0xD7 that CBOR | |
| // allows for tags 0..23 (so this is not write_cbor_head). | |
| // binary_reader with cbor_tag_handler_t::store only turns | |
| // 0xD8..0xDB into a subtype and ignores the one-byte tags, | |
| // so the shorter form would lose subtypes 0..23 on a round | |
| // trip. | |
| if (j.m_data.m_value.binary->subtype() <= (std::numeric_limits<std::uint8_t>::max)()) | |
| { | |
| write_number(static_cast<std::uint8_t>(0xd8)); | |
| write_number(static_cast<std::uint8_t>(j.m_data.m_value.binary->subtype())); | |
| } | |
| else if (j.m_data.m_value.binary->subtype() <= (std::numeric_limits<std::uint16_t>::max)()) | |
| { | |
| write_number(static_cast<std::uint8_t>(0xd9)); | |
| write_number(static_cast<std::uint16_t>(j.m_data.m_value.binary->subtype())); | |
| } | |
| else if (j.m_data.m_value.binary->subtype() <= (std::numeric_limits<std::uint32_t>::max)()) | |
| { | |
| write_number(static_cast<std::uint8_t>(0xda)); | |
| write_number(static_cast<std::uint32_t>(j.m_data.m_value.binary->subtype())); | |
| } | |
| else | |
| { | |
| write_number(static_cast<std::uint8_t>(0xdb)); | |
| write_number(static_cast<std::uint64_t>(j.m_data.m_value.binary->subtype())); | |
| } | |
| } | |
| // step 1: write control byte and the binary array size | |
| const auto N = j.m_data.m_value.binary->size(); | |
| write_cbor_head(0x40, N); | |
| // step 2: write each element | |
| write_bytes(j.m_data.m_value.binary->data(), N); | |
| break; | |
| } | |
| case value_t::object: | |
| { | |
| write_cbor_object(j, depth); | |
| break; | |
| } | |
| case value_t::discarded: | |
| default: | |
| throw_on_discarded(j, input_format_t::cbor); | |
| } | |
| } | |
| /*! | |
| @brief check that @a length fits into the 32 bits that MessagePack stores | |
| the length of a string, binary value, array, or object in | |
| @return the length as an unsigned 32-bit integer | |
| @throw out_of_range.412 if @a length exceeds the range of std::uint32_t | |
| */ | |
| static std::uint32_t to_msgpack_length(const std::size_t length, const BasicJsonType& j) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!value_in_range_of<std::uint32_t>(length))) | |
| { | |
| throw_msgpack_length_too_large(length, j); | |
| } | |
| static_cast<void>(j); | |
| return static_cast<std::uint32_t>(length); | |
| } | |
| /*! | |
| @brief write a non-negative integer using the MessagePack fixint/uint ladder | |
| @param[in] n the value to write, already known to be non-negative | |
| */ | |
| void write_msgpack_unsigned(const std::uint64_t n) | |
| { | |
| if (n < 128) | |
| { | |
| // positive fixnum | |
| write_number(static_cast<std::uint8_t>(n)); | |
| } | |
| else if (n <= (std::numeric_limits<std::uint8_t>::max)()) | |
| { | |
| // uint 8 | |
| oa.write_character(to_char_type(0xCC)); | |
| write_number(static_cast<std::uint8_t>(n)); | |
| } | |
| else if (n <= (std::numeric_limits<std::uint16_t>::max)()) | |
| { | |
| // uint 16 | |
| oa.write_character(to_char_type(0xCD)); | |
| write_number(static_cast<std::uint16_t>(n)); | |
| } | |
| else if (n <= (std::numeric_limits<std::uint32_t>::max)()) | |
| { | |
| // uint 32 | |
| oa.write_character(to_char_type(0xCE)); | |
| write_number(static_cast<std::uint32_t>(n)); | |
| } | |
| else | |
| { | |
| // uint 64 | |
| oa.write_character(to_char_type(0xCF)); | |
| write_number(n); | |
| } | |
| } | |
| /*! | |
| @param[in] j JSON value to serialize | |
| @param[in] depth nesting level of @a j, counted from the top-level value | |
| passed to @ref basic_json::to_msgpack | |
| @throw type_error.321 if @a j or a value nested in it is discarded | |
| @sa @ref write_cbor | |
| @sa https://github.com/nlohmann/json/issues/5392 | |
| */ | |
| void write_msgpack(const BasicJsonType& j, const std::size_t depth = 0) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(depth >= recursion_depth_limit()) && (j.is_array() || j.is_object())) | |
| { | |
| write_msgpack_iterative(j); | |
| return; | |
| } | |
| switch (j.type()) | |
| { | |
| case value_t::null: // nil | |
| { | |
| oa.write_character(to_char_type(0xC0)); | |
| break; | |
| } | |
| case value_t::boolean: // true and false | |
| { | |
| oa.write_character(j.m_data.m_value.boolean | |
| ? to_char_type(0xC3) | |
| : to_char_type(0xC2)); | |
| break; | |
| } | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| { | |
| // one case for both, so that an array mixing negative | |
| // (number_integer) and non-negative (number_unsigned) values | |
| // does not mispredict the switch | |
| write_msgpack_integer(j, std::integral_constant<bool, integers_fit_64_bits()>()); | |
| break; | |
| } | |
| case value_t::number_float: | |
| { | |
| write_msgpack_float(j.m_data.m_value.number_float); | |
| break; | |
| } | |
| case value_t::string: | |
| { | |
| write_msgpack_string(*j.m_data.m_value.string, j); | |
| break; | |
| } | |
| case value_t::array: | |
| { | |
| write_msgpack_array(j, depth); | |
| break; | |
| } | |
| case value_t::binary: | |
| { | |
| // step 0: determine if the binary type has a set subtype to | |
| // determine whether to use the ext or fixext types | |
| const bool use_ext = j.m_data.m_value.binary->has_subtype(); | |
| // step 1: write control byte and the byte string length | |
| const auto N = to_msgpack_length(j.m_data.m_value.binary->size(), j); | |
| if (N <= (std::numeric_limits<std::uint8_t>::max)()) | |
| { | |
| std::uint8_t output_type{}; | |
| bool fixed = true; | |
| if (use_ext) | |
| { | |
| switch (N) | |
| { | |
| case 1: | |
| output_type = 0xD4; // fixext 1 | |
| break; | |
| case 2: | |
| output_type = 0xD5; // fixext 2 | |
| break; | |
| case 4: | |
| output_type = 0xD6; // fixext 4 | |
| break; | |
| case 8: | |
| output_type = 0xD7; // fixext 8 | |
| break; | |
| case 16: | |
| output_type = 0xD8; // fixext 16 | |
| break; | |
| default: | |
| output_type = 0xC7; // ext 8 | |
| fixed = false; | |
| break; | |
| } | |
| } | |
| else | |
| { | |
| output_type = 0xC4; // bin 8 | |
| fixed = false; | |
| } | |
| oa.write_character(to_char_type(output_type)); | |
| if (!fixed) | |
| { | |
| write_number(static_cast<std::uint8_t>(N)); | |
| } | |
| } | |
| else if (N <= (std::numeric_limits<std::uint16_t>::max)()) | |
| { | |
| const std::uint8_t output_type = use_ext | |
| ? 0xC8 // ext 16 | |
| : 0xC5; // bin 16 | |
| oa.write_character(to_char_type(output_type)); | |
| write_number(static_cast<std::uint16_t>(N)); | |
| } | |
| else | |
| { | |
| const std::uint8_t output_type = use_ext | |
| ? 0xC9 // ext 32 | |
| : 0xC6; // bin 32 | |
| oa.write_character(to_char_type(output_type)); | |
| write_number(static_cast<std::uint32_t>(N)); | |
| } | |
| // step 1.5: if this is an ext type, write the subtype | |
| if (use_ext) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(j.m_data.m_value.binary->subtype() > (std::numeric_limits<std::uint8_t>::max)())) | |
| { | |
| throw_subtype_out_of_range(j.m_data.m_value.binary->subtype(), "the MessagePack ext type", j); | |
| } | |
| write_number(static_cast<std::int8_t>(j.m_data.m_value.binary->subtype())); | |
| } | |
| // step 2: write the byte string | |
| write_bytes(j.m_data.m_value.binary->data(), N); | |
| break; | |
| } | |
| case value_t::object: | |
| { | |
| // step 1: write control byte and the object size | |
| write_msgpack_object(j, depth); | |
| break; | |
| } | |
| case value_t::discarded: | |
| default: | |
| throw_on_discarded(j, input_format_t::msgpack); | |
| } | |
| } | |
| /*! | |
| @param[in] j JSON value to serialize | |
| @param[in] use_count whether to use '#' prefixes (optimized format) | |
| @param[in] use_type whether to use '$' prefixes (optimized format) | |
| @param[in] add_prefix whether prefixes need to be used for this value | |
| @param[in] use_bjdata whether write in BJData format, default is false | |
| @param[in] bjdata_version which BJData version to use, default is draft2 | |
| @param[in] depth nesting level of @a j, counted from the top-level value | |
| passed to @ref basic_json::to_ubjson or @ref basic_json::to_bjdata | |
| @throw type_error.316 if a string value or an object key is not valid | |
| UTF-8 | |
| @throw type_error.321 if @a j or a value nested in it is discarded | |
| @sa @ref write_cbor | |
| @sa https://github.com/nlohmann/json/issues/5392 | |
| */ | |
| void write_ubjson(const BasicJsonType& j, const bool use_count, | |
| const bool use_type, const bool add_prefix = true, | |
| const bool use_bjdata = false, const bjdata_version_t bjdata_version = bjdata_version_t::draft2, | |
| const std::size_t depth = 0) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(depth >= recursion_depth_limit()) && (j.is_array() || j.is_object())) | |
| { | |
| write_ubjson_iterative(j, use_count, use_type, add_prefix, use_bjdata, bjdata_version); | |
| return; | |
| } | |
| const bool bjdata_draft3 = use_bjdata && bjdata_version == bjdata_version_t::draft3; | |
| switch (j.type()) | |
| { | |
| case value_t::null: | |
| { | |
| if (add_prefix) | |
| { | |
| oa.write_character(to_char_type('Z')); | |
| } | |
| break; | |
| } | |
| case value_t::boolean: | |
| { | |
| if (add_prefix) | |
| { | |
| oa.write_character(j.m_data.m_value.boolean | |
| ? to_char_type('T') | |
| : to_char_type('F')); | |
| } | |
| break; | |
| } | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| { | |
| if (j.m_data.m_type == value_t::number_integer) | |
| { | |
| write_number_with_ubjson_prefix(j.m_data.m_value.number_integer, add_prefix, use_bjdata); | |
| } | |
| else | |
| { | |
| write_number_with_ubjson_prefix(j.m_data.m_value.number_unsigned, add_prefix, use_bjdata); | |
| } | |
| break; | |
| } | |
| case value_t::number_float: | |
| { | |
| write_number_with_ubjson_prefix(j.m_data.m_value.number_float, add_prefix, use_bjdata); | |
| break; | |
| } | |
| case value_t::string: | |
| { | |
| write_ubjson_text(*j.m_data.m_value.string, j, add_prefix, use_bjdata); | |
| break; | |
| } | |
| case value_t::array: | |
| { | |
| bool prefix_required = true; | |
| const bool write_closer = write_ubjson_start_container<true>(j, use_count, use_type, add_prefix, use_bjdata, prefix_required); | |
| { | |
| const auto& array = *j.m_data.m_value.array; | |
| if (starts_with_ubjson_number(array, use_bjdata, std::integral_constant<bool, ubjson_integers_fit_64_bits()>())) | |
| { | |
| write_ubjson_array_elements(array, use_count, use_type, prefix_required, use_bjdata, bjdata_version, depth); | |
| } | |
| else | |
| { | |
| for (const auto& el : array) | |
| { | |
| write_ubjson(el, use_count, use_type, prefix_required, use_bjdata, bjdata_version, depth + 1); | |
| } | |
| } | |
| } | |
| if (write_closer) | |
| { | |
| oa.write_character(to_char_type(']')); | |
| } | |
| break; | |
| } | |
| case value_t::binary: | |
| { | |
| if (add_prefix) | |
| { | |
| oa.write_character(to_char_type('[')); | |
| } | |
| if (use_type && (bjdata_draft3 || !j.m_data.m_value.binary->empty())) | |
| { | |
| if (!use_count) | |
| { | |
| throw_size_marker_required(j); | |
| } | |
| oa.write_character(to_char_type('$')); | |
| oa.write_character(bjdata_draft3 ? 'B' : 'U'); | |
| } | |
| if (use_count) | |
| { | |
| oa.write_character(to_char_type('#')); | |
| write_number_with_ubjson_prefix(j.m_data.m_value.binary->size(), true, use_bjdata); | |
| } | |
| if (use_type) | |
| { | |
| write_bytes(j.m_data.m_value.binary->data(), j.m_data.m_value.binary->size()); | |
| } | |
| else | |
| { | |
| write_ubjson_binary_bytes(*j.m_data.m_value.binary, bjdata_draft3); | |
| } | |
| if (!use_count) | |
| { | |
| oa.write_character(to_char_type(']')); | |
| } | |
| break; | |
| } | |
| case value_t::object: | |
| { | |
| if (use_bjdata && is_bjdata_ndarray(j)) | |
| { | |
| if (!write_bjdata_ndarray(*j.m_data.m_value.object, use_count, use_type, bjdata_version)) // decode bjdata ndarray in the JData format (https://github.com/NeuroJSON/jdata) | |
| { | |
| break; | |
| } | |
| } | |
| bool prefix_required = true; | |
| const bool write_closer = write_ubjson_start_container<false>(j, use_count, use_type, add_prefix, use_bjdata, prefix_required); | |
| write_ubjson_members(j, use_count, use_type, prefix_required, use_bjdata, bjdata_version, depth); | |
| if (write_closer) | |
| { | |
| oa.write_character(to_char_type('}')); | |
| } | |
| break; | |
| } | |
| case value_t::discarded: | |
| default: | |
| throw_on_discarded(j, use_bjdata ? input_format_t::bjdata : input_format_t::ubjson); | |
| } | |
| } | |
| /*! | |
| @param[in] j JSON value to serialize | |
| @throw type_error.321 if @a j or a value nested in it is discarded | |
| */ | |
| void write_bon8(const BasicJsonType& j) | |
| { | |
| bool string_open = false; | |
| write_bon8_value(j, string_open); | |
| // the last string of a message must be terminated | |
| if (string_open) | |
| { | |
| oa.write_character(to_char_type(0xFF)); | |
| } | |
| } | |
| private: | |
| /*! | |
| @brief throws because @a j is discarded and cannot be serialized | |
| @throw type_error.321 always | |
| */ | |
| JSON_HEDLEY_NO_RETURN static void throw_on_discarded(const BasicJsonType& j, const input_format_t format) | |
| { | |
| static_cast<void>(j); // unused when JSON_NOEXCEPTION is defined | |
| static_cast<void>(format); | |
| JSON_THROW(type_error::create(exception_id::discarded_value_used, concat("cannot serialize discarded value to ", input_format_name(format)), &j)); | |
| } | |
| /// how the range of integer type @a NumberType relates to that of @a TargetType | |
| template<typename TargetType, typename NumberType> | |
| struct integer_range | |
| { | |
| /// whether NumberType can hold values above the maximum of TargetType | |
| static constexpr bool may_exceed_max = std::numeric_limits<NumberType>::digits > std::numeric_limits<TargetType>::digits; | |
| /// whether NumberType can hold values below the minimum of TargetType | |
| static constexpr bool may_fall_below_min = std::numeric_limits<NumberType>::is_signed | |
| && (!std::numeric_limits<TargetType>::is_signed || may_exceed_max); | |
| }; | |
| /*! | |
| @brief whether integer @a n does not exceed the maximum of @a TargetType | |
| The binary formats store integers in at most 64 bits, but number_integer_t | |
| and number_unsigned_t may be wider (e.g., __int128). The range of the | |
| integer is taken from std::numeric_limits, so a number type whose range | |
| fits into @a TargetType is never checked: the function is then constant | |
| true, and the default int64_t/uint64_t types pay nothing. | |
| */ | |
| template<typename TargetType, typename NumberType> | |
| static constexpr bool integer_fits_max(const NumberType n) noexcept | |
| { | |
| return integer_fits_max<TargetType>(n, std::integral_constant<bool, integer_range<TargetType, NumberType>::may_exceed_max>()); | |
| } | |
| template<typename TargetType, typename NumberType> | |
| static constexpr bool integer_fits_max(const NumberType /*unused*/, std::false_type /*may_exceed*/) noexcept | |
| { | |
| return true; | |
| } | |
| template<typename TargetType, typename NumberType> | |
| static constexpr bool integer_fits_max(const NumberType n, std::true_type /*may_exceed*/) noexcept | |
| { | |
| // NumberType has more digits than TargetType, so it can hold its maximum | |
| return n <= static_cast<NumberType>((std::numeric_limits<TargetType>::max)()); | |
| } | |
| /*! | |
| @brief whether integer @a n is not below the minimum of @a TargetType; | |
| constant true if NumberType cannot hold such a value | |
| */ | |
| template<typename TargetType, typename NumberType> | |
| static constexpr bool integer_fits_min(const NumberType n) noexcept | |
| { | |
| return integer_fits_min<TargetType>(n, std::integral_constant<bool, integer_range<TargetType, NumberType>::may_fall_below_min>()); | |
| } | |
| template<typename TargetType, typename NumberType> | |
| static constexpr bool integer_fits_min(const NumberType /*unused*/, std::false_type /*may_fall_below*/) noexcept | |
| { | |
| return true; | |
| } | |
| template<typename TargetType, typename NumberType> | |
| static constexpr bool integer_fits_min(const NumberType n, std::true_type /*may_fall_below*/) noexcept | |
| { | |
| // NumberType is signed and either TargetType is unsigned (minimum 0) | |
| // or NumberType has more digits, so it can hold the minimum | |
| return n >= static_cast<NumberType>((std::numeric_limits<TargetType>::min)()); | |
| } | |
| /*! | |
| @brief whether integer @a n lies in the range of @a TargetType | |
| */ | |
| template<typename TargetType, typename NumberType> | |
| static constexpr bool integer_fits(const NumberType n) noexcept | |
| { | |
| return integer_fits_min<TargetType>(n) && integer_fits_max<TargetType>(n); | |
| } | |
| /*! | |
| @brief the decimal digits of the non-negative integer @a n | |
| */ | |
| template<typename NumberType> | |
| static std::string integer_to_string(NumberType n, std::false_type /*is_signed*/) | |
| { | |
| std::string result; | |
| do | |
| { | |
| result.push_back(static_cast<char>('0' + (n % 10))); | |
| n = static_cast<NumberType>(n / 10); | |
| } | |
| while (n != 0); | |
| std::reverse(result.begin(), result.end()); | |
| return result; | |
| } | |
| /*! | |
| @brief the decimal digits of the integer @a n, with a leading '-' if it | |
| is negative | |
| */ | |
| template<typename NumberType> | |
| static std::string integer_to_string(NumberType n, std::true_type /*is_signed*/) | |
| { | |
| // the remainder of a negative n is not positive; each digit is | |
| // negated on its own, because negating the minimum of NumberType | |
| // as a whole would overflow | |
| const bool negative = n < 0; | |
| std::string result; | |
| do | |
| { | |
| const auto remainder = n % 10; | |
| result.push_back(static_cast<char>('0' + (remainder < 0 ? -remainder : remainder))); | |
| n = static_cast<NumberType>(n / 10); | |
| } | |
| while (n != 0); | |
| if (negative) | |
| { | |
| result.push_back('-'); | |
| } | |
| std::reverse(result.begin(), result.end()); | |
| return result; | |
| } | |
| /*! | |
| @brief throws because the integer @a j is too large for @a format | |
| @throw out_of_range.407 always | |
| */ | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_integer_out_of_range(const BasicJsonType& j, const input_format_t format, const char* range) | |
| { | |
| // neither std::to_string(), which has no overload for integer types | |
| // wider than 64 bits, nor dump(), which would also instantiate the | |
| // serializer for objects and fail for key types it cannot write | |
| using integer_limits = std::numeric_limits<typename BasicJsonType::number_integer_t>; | |
| using unsigned_limits = std::numeric_limits<typename BasicJsonType::number_unsigned_t>; | |
| const std::string number = j.is_number_unsigned() | |
| ? integer_to_string(j.m_data.m_value.number_unsigned, std::integral_constant<bool, unsigned_limits::is_signed>()) | |
| : integer_to_string(j.m_data.m_value.number_integer, std::integral_constant<bool, integer_limits::is_signed>()); | |
| static_cast<void>(number); // unused when JSON_NOEXCEPTION is defined | |
| static_cast<void>(format); | |
| static_cast<void>(range); | |
| JSON_THROW(out_of_range::create(exception_id::integer_too_large, concat("integer number ", number, " cannot be represented by ", input_format_name(format), " as it does not fit ", range), &j)); | |
| } | |
| // The exceptions below are thrown from functions of their own, out of line: | |
| // the code that builds a message (concat, std::to_string) would otherwise | |
| // make the frame of the function that checks, which most calls never throw. | |
| /// @throw out_of_range.412 always | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_msgpack_length_too_large(const std::size_t length, const BasicJsonType& j) | |
| { | |
| static_cast<void>(length); // unused when JSON_NOEXCEPTION is defined | |
| static_cast<void>(j); | |
| JSON_THROW(out_of_range::create(exception_id::length_too_large, concat("MessagePack length ", std::to_string(length), " exceeds maximum of ", std::to_string((std::numeric_limits<std::uint32_t>::max)())), &j)); | |
| } | |
| /// @throw out_of_range.412 always | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_bson_length_too_large(const std::size_t size) | |
| { | |
| static_cast<void>(size); // unused when JSON_NOEXCEPTION is defined | |
| JSON_THROW(out_of_range::create(exception_id::length_too_large, concat("BSON length ", std::to_string(size), " exceeds maximum of ", std::to_string((std::numeric_limits<std::int32_t>::max)())), nullptr)); | |
| } | |
| /// @throw out_of_range.415 always | |
| template<typename SubtypeType> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_subtype_out_of_range(const SubtypeType subtype, const char* what, const BasicJsonType& j) | |
| { | |
| static_cast<void>(subtype); // unused when JSON_NOEXCEPTION is defined | |
| static_cast<void>(what); | |
| static_cast<void>(j); | |
| JSON_THROW(out_of_range::create(exception_id::subtype_out_of_range, concat("subtype ", std::to_string(subtype), " is too large for ", what, " (max 255)"), &j)); | |
| } | |
| /// @throw other_error.407 always | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_size_marker_required(const BasicJsonType& j) | |
| { | |
| static_cast<void>(j); // unused when JSON_NOEXCEPTION is defined | |
| JSON_THROW(other_error::create(exception_id::size_marker_required, "use_type requires use_size = true", &j)); | |
| } | |
| /// @brief write @a size bytes starting at @a data to the output adapter | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| void write_bytes(const void* data, const std::size_t size) | |
| { | |
| oa.write_characters(static_cast<const CharType*>(data), size); | |
| } | |
| /// @brief write the MessagePack prefix of an array or object with @a N | |
| /// elements: the fix marker @a fix_marker | n, or @a marker_16 or | |
| /// @a marker_32 followed by the length | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| void write_msgpack_container_prefix(const std::size_t N, const BasicJsonType& j, | |
| const std::uint8_t fix_marker, const std::uint8_t marker_16, const std::uint8_t marker_32) | |
| { | |
| const auto n = to_msgpack_length(N, j); | |
| if (n <= 15) | |
| { | |
| // fixarray, fixmap | |
| oa.write_character(to_char_type(static_cast<std::uint8_t>(fix_marker | n))); | |
| } | |
| else if (n <= (std::numeric_limits<std::uint16_t>::max)()) | |
| { | |
| // array 16, map 16 | |
| oa.write_character(to_char_type(marker_16)); | |
| write_number(static_cast<std::uint16_t>(n)); | |
| } | |
| else | |
| { | |
| // array 32, map 32 | |
| oa.write_character(to_char_type(marker_32)); | |
| write_number(static_cast<std::uint32_t>(n)); | |
| } | |
| } | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| void write_msgpack_array_prefix(const std::size_t N, const BasicJsonType& j) | |
| { | |
| write_msgpack_container_prefix(N, j, 0x90, 0xDC, 0xDD); | |
| } | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| void write_msgpack_object_prefix(const std::size_t N, const BasicJsonType& j) | |
| { | |
| write_msgpack_container_prefix(N, j, 0x80, 0xDE, 0xDF); | |
| } | |
| /// @brief a CBOR, MessagePack, BON8, or (as the base of @ref ubjson_frame) | |
| /// UBJSON array or object whose elements @ref write_container_iterative, | |
| /// @ref write_bon8_iterative, or @ref write_ubjson_iterative is still | |
| /// writing | |
| struct binary_container_frame | |
| { | |
| explicit binary_container_frame(const BasicJsonType* value_) noexcept | |
| : value(value_) | |
| { | |
| if (value->is_object()) | |
| { | |
| object_it = value->m_data.m_value.object->cbegin(); | |
| } | |
| else | |
| { | |
| array_it = value->m_data.m_value.array->cbegin(); | |
| } | |
| } | |
| // declared for GCC's -Weffc++, which asks for them in a class with | |
| // pointer members and a non-trivial destructor; the exception | |
| // specifications are left implicit, as GCC 4.8 rejects explicit ones | |
| // that differ from them | |
| binary_container_frame(const binary_container_frame&) = default; | |
| binary_container_frame(binary_container_frame&&) = default; | |
| binary_container_frame& operator=(const binary_container_frame&) = default; | |
| binary_container_frame& operator=(binary_container_frame&&) = default; | |
| ~binary_container_frame() = default; | |
| /// the array or object being written | |
| const BasicJsonType* value; | |
| /// value's elements still to write; which of the two is live follows | |
| /// from the type of value. They are kept side by side rather than in | |
| /// a union, which would need its special members written out by | |
| /// hand, see detail/iterators/internal_iterator.hpp | |
| typename BasicJsonType::object_t::const_iterator object_it{}; | |
| typename BasicJsonType::array_t::const_iterator array_it{}; | |
| }; | |
| /// @brief the CBOR specifics of @ref write_container_iterative | |
| struct cbor_walk | |
| { | |
| static void array_head(binary_writer& w, const BasicJsonType& j) | |
| { | |
| w.write_cbor_head(0x80, j.m_data.m_value.array->size()); | |
| } | |
| static void object_head(binary_writer& w, const BasicJsonType& j) | |
| { | |
| w.write_cbor_head(0xA0, j.m_data.m_value.object->size()); | |
| } | |
| static void scalar(binary_writer& w, const BasicJsonType& j) | |
| { | |
| w.write_cbor(j); | |
| } | |
| static void string(binary_writer& w, const string_t& key, const BasicJsonType& context) | |
| { | |
| w.write_cbor_string(key, context); | |
| } | |
| template<typename KeyType> | |
| static void key(binary_writer& w, const KeyType& k, const BasicJsonType& object) | |
| { | |
| w.write_cbor_key(k, object); | |
| } | |
| }; | |
| /// @brief the MessagePack specifics of @ref write_container_iterative | |
| struct msgpack_walk | |
| { | |
| static void array_head(binary_writer& w, const BasicJsonType& j) | |
| { | |
| w.write_msgpack_array_prefix(j.m_data.m_value.array->size(), j); | |
| } | |
| static void object_head(binary_writer& w, const BasicJsonType& j) | |
| { | |
| w.write_msgpack_object_prefix(j.m_data.m_value.object->size(), j); | |
| } | |
| static void scalar(binary_writer& w, const BasicJsonType& j) | |
| { | |
| w.write_msgpack(j); | |
| } | |
| static void string(binary_writer& w, const string_t& key, const BasicJsonType& context) | |
| { | |
| w.write_msgpack_string(key, context); | |
| } | |
| template<typename KeyType> | |
| static void key(binary_writer& w, const KeyType& k, const BasicJsonType& object) | |
| { | |
| w.write_msgpack_key(k, object); | |
| } | |
| }; | |
| /*! | |
| @brief write @a j with @a Walk::scalar, or write its header and push a | |
| frame for @ref write_container_iterative to continue with its | |
| elements | |
| A scalar, and an empty array or object, are written out in full: there is | |
| nothing below them for @ref write_container_iterative to come back to, so | |
| nothing is pushed for them. | |
| */ | |
| template<typename Walk> | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| void write_container_value_or_push(const BasicJsonType& j, std::vector<binary_container_frame>& stack) | |
| { | |
| if (j.is_array()) | |
| { | |
| Walk::array_head(*this, j); | |
| if (!j.m_data.m_value.array->empty()) | |
| { | |
| stack.emplace_back(&j); | |
| } | |
| return; | |
| } | |
| if (j.is_object()) | |
| { | |
| Walk::object_head(*this, j); | |
| if (!j.m_data.m_value.object->empty()) | |
| { | |
| stack.emplace_back(&j); | |
| } | |
| return; | |
| } | |
| Walk::scalar(*this, j); | |
| } | |
| /*! | |
| @brief write out @a root and everything below it without the call stack | |
| Emits the same bytes as the recursive writer, keeping the containers it has | |
| entered on an explicit stack instead of descending into them. Only reached | |
| for values nested deeper than @ref recursion_depth_limit, which is why it | |
| is not written for speed. Shared by CBOR and MessagePack, which differ only | |
| in the @a Walk policy (@ref cbor_walk, @ref msgpack_walk); BON8 has its own | |
| walker, as it tracks an open string run and closes a container with a | |
| marker. | |
| */ | |
| template<typename Walk> | |
| void write_container_iterative(const BasicJsonType& root) | |
| { | |
| // only a container with elements is ever pushed; see write_container_value_or_push | |
| std::vector<binary_container_frame> stack; | |
| write_container_value_or_push<Walk>(root, stack); | |
| while (!stack.empty()) | |
| { | |
| const binary_container_frame current = stack.back(); | |
| if (current.value->is_array()) | |
| { | |
| const auto& array = *current.value->m_data.m_value.array; | |
| if (current.array_it == array.cend()) | |
| { | |
| stack.pop_back(); | |
| continue; | |
| } | |
| // read the child before pushing: entering it can move every frame | |
| const BasicJsonType* child = &(*current.array_it); | |
| ++stack.back().array_it; | |
| write_container_value_or_push<Walk>(*child, stack); | |
| } | |
| else | |
| { | |
| const auto& object = *current.value->m_data.m_value.object; | |
| if (current.object_it == object.cend()) | |
| { | |
| stack.pop_back(); | |
| continue; | |
| } | |
| // the key is written directly (not via a temporary basic_json), | |
| // with the object as diagnostics context, as in the recursive writer | |
| Walk::key(*this, current.object_it->first, *current.value); | |
| const BasicJsonType* child = &(current.object_it->second); | |
| ++stack.back().object_it; | |
| write_container_value_or_push<Walk>(*child, stack); | |
| } | |
| } | |
| } | |
| void write_cbor_iterative(const BasicJsonType& root) | |
| { | |
| write_container_iterative<cbor_walk>(root); | |
| } | |
| void write_msgpack_iterative(const BasicJsonType& root) | |
| { | |
| write_container_iterative<msgpack_walk>(root); | |
| } | |
| /*! | |
| @brief write the start of an array (@a IsArray) or object: its opening | |
| marker, the optimized type, and the count | |
| @return true when a closing ']' or '}' still has to be written after the | |
| elements | |
| */ | |
| template<bool IsArray> | |
| bool write_ubjson_start_container(const BasicJsonType& j, const bool use_count, const bool use_type, | |
| const bool add_prefix, const bool use_bjdata, bool& prefix_required) | |
| { | |
| prefix_required = true; | |
| if (add_prefix) | |
| { | |
| oa.write_character(to_char_type(IsArray ? '[' : '{')); | |
| } | |
| const std::size_t size = IsArray ? j.m_data.m_value.array->size() : j.m_data.m_value.object->size(); | |
| if (use_type && size != 0) | |
| { | |
| if (!use_count) | |
| { | |
| throw_size_marker_required(j); | |
| } | |
| const CharType first_prefix = ubjson_prefix(j.front(), use_bjdata); | |
| // the first element of an array has been compared with itself | |
| const bool same_prefix = std::all_of(IsArray ? j.begin() + 1 : j.begin(), j.end(), | |
| [this, first_prefix, use_bjdata](const BasicJsonType & v) | |
| { | |
| return ubjson_prefix(v, use_bjdata) == first_prefix; | |
| }); | |
| // an optimized array of a valueless type carries no payload, so a | |
| // reader has nothing but the declared count to bound the allocation | |
| // by and refuses an excessive one. Write the unoptimized form for | |
| // those, at one byte per element, so the result can be read back. | |
| // Objects are not affected: every element is preceded by its key. | |
| const bool valueless_type = (first_prefix == 'Z' || first_prefix == 'T' || first_prefix == 'F'); | |
| const bool excessive_valueless = IsArray | |
| && valueless_type | |
| && size > detail::max_valueless_container_size; | |
| if (same_prefix && !excessive_valueless | |
| && !(use_bjdata && is_bjdata_excluded_type_marker(first_prefix))) | |
| { | |
| prefix_required = false; | |
| oa.write_character(to_char_type('$')); | |
| oa.write_character(first_prefix); | |
| } | |
| } | |
| if (use_count) | |
| { | |
| write_ubjson_count(size, use_bjdata); | |
| } | |
| return !use_count; | |
| } | |
| /*! | |
| @brief whether @a j is a BJData ND-array annotation object | |
| (https://github.com/NeuroJSON/jdata) | |
| Used by both the recursive object case of @ref write_ubjson and | |
| @ref write_ubjson_value_or_push, which must agree on what counts as an | |
| ND-array: @a j is only actually written as one once @ref | |
| write_bjdata_ndarray has also accepted its contents. | |
| @pre @a j.is_object() | |
| */ | |
| static bool is_bjdata_ndarray(const BasicJsonType& j) | |
| { | |
| const auto& object = *j.m_data.m_value.object; | |
| return object.size() == 3 | |
| && object.find("_ArrayType_") != object.end() | |
| && object.find("_ArraySize_") != object.end() | |
| && object.find("_ArrayData_") != object.end(); | |
| } | |
| /// @brief an object or array @ref write_ubjson_iterative is still writing | |
| /// the elements of | |
| struct ubjson_frame : binary_container_frame | |
| { | |
| ubjson_frame(const BasicJsonType* value_, const bool prefix_required_) noexcept | |
| : binary_container_frame(value_) | |
| , prefix_required(prefix_required_) | |
| {} | |
| // declared for GCC's -Weffc++, which asks for them in a class with | |
| // pointer members and a non-trivial destructor; the exception | |
| // specifications are left implicit, as GCC 4.8 rejects explicit ones | |
| // that differ from them | |
| ubjson_frame(const ubjson_frame&) = default; | |
| ubjson_frame(ubjson_frame&&) = default; | |
| ubjson_frame& operator=(const ubjson_frame&) = default; | |
| ubjson_frame& operator=(ubjson_frame&&) = default; | |
| ~ubjson_frame() = default; | |
| /// whether value's elements each carry their own type marker; an | |
| /// optimized ($type) container writes it once for all of them instead | |
| bool prefix_required; | |
| }; | |
| /*! | |
| @brief write @a j with @ref write_ubjson, or write its header and push a | |
| frame for @ref write_ubjson_iterative to continue with its elements | |
| @param[in] add_prefix whether @a j's own type marker is written now (the | |
| elements of an optimized container, and everything below the | |
| top level, never repeat it) | |
| @sa @ref write_container_value_or_push | |
| */ | |
| void write_ubjson_value_or_push(const BasicJsonType& j, const bool add_prefix, const bool use_count, | |
| const bool use_type, const bool use_bjdata, const bjdata_version_t bjdata_version, | |
| std::vector<ubjson_frame>& stack) | |
| { | |
| if (!j.is_array() && !j.is_object()) | |
| { | |
| write_ubjson(j, use_count, use_type, add_prefix, use_bjdata, bjdata_version); | |
| return; | |
| } | |
| if (use_bjdata && j.is_object() && is_bjdata_ndarray(j) | |
| && !write_bjdata_ndarray(*j.m_data.m_value.object, use_count, use_type, bjdata_version)) | |
| { | |
| // fully written as an ND-array: nothing below it to come back to | |
| return; | |
| } | |
| const bool is_array = j.is_array(); | |
| bool prefix_required = true; | |
| if (is_array) | |
| { | |
| write_ubjson_start_container<true>(j, use_count, use_type, add_prefix, use_bjdata, prefix_required); | |
| } | |
| else | |
| { | |
| write_ubjson_start_container<false>(j, use_count, use_type, add_prefix, use_bjdata, prefix_required); | |
| } | |
| const bool empty = is_array ? j.m_data.m_value.array->empty() : j.m_data.m_value.object->empty(); | |
| if (!empty) | |
| { | |
| stack.emplace_back(&j, prefix_required); | |
| return; | |
| } | |
| // write_ubjson_start_container returns !use_count, i.e. whether a | |
| // closer still has to be written; use_count is constant for the whole | |
| // document, so that is recomputed here instead of being carried along | |
| if (!use_count) | |
| { | |
| oa.write_character(to_char_type(is_array ? ']' : '}')); | |
| } | |
| } | |
| /*! | |
| @brief write out @a root and everything below it without the call stack | |
| @sa @ref write_cbor_iterative | |
| */ | |
| void write_ubjson_iterative(const BasicJsonType& root, const bool use_count, const bool use_type, | |
| const bool add_prefix, const bool use_bjdata, const bjdata_version_t bjdata_version) | |
| { | |
| std::vector<ubjson_frame> stack; | |
| write_ubjson_value_or_push(root, add_prefix, use_count, use_type, use_bjdata, bjdata_version, stack); | |
| while (!stack.empty()) | |
| { | |
| const ubjson_frame current = stack.back(); | |
| const BasicJsonType& j = *current.value; | |
| if (j.is_array()) | |
| { | |
| const auto& array = *j.m_data.m_value.array; | |
| if (current.array_it == array.cend()) | |
| { | |
| if (!use_count) | |
| { | |
| oa.write_character(to_char_type(']')); | |
| } | |
| stack.pop_back(); | |
| continue; | |
| } | |
| const BasicJsonType* child = &(*current.array_it); | |
| const bool child_prefix = current.prefix_required; | |
| ++stack.back().array_it; | |
| write_ubjson_value_or_push(*child, child_prefix, use_count, use_type, use_bjdata, bjdata_version, stack); | |
| } | |
| else | |
| { | |
| const auto& object = *j.m_data.m_value.object; | |
| if (current.object_it == object.cend()) | |
| { | |
| if (!use_count) | |
| { | |
| oa.write_character(to_char_type('}')); | |
| } | |
| stack.pop_back(); | |
| continue; | |
| } | |
| // a converted key must outlive the reference returned by sanitize_utf8_for_write | |
| const object_key_string_t key_string = current.object_it->first; | |
| write_ubjson_text(key_string, j, false, use_bjdata); | |
| const BasicJsonType* child = &(current.object_it->second); | |
| const bool child_prefix = current.prefix_required; | |
| ++stack.back().object_it; | |
| write_ubjson_value_or_push(*child, child_prefix, use_count, use_type, use_bjdata, bjdata_version, stack); | |
| } | |
| } | |
| } | |
| ////////// | |
| // BSON // | |
| ////////// | |
| /*! | |
| @return The size of a BSON document entry header, including the id marker | |
| and the entry name size (and its null-terminator). | |
| @throw out_of_range.409 if @a name contains U+0000, before anything is | |
| written | |
| @throw type_error.316 if @a name is not valid UTF-8, before anything is | |
| written | |
| */ | |
| std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j) | |
| { | |
| const std::size_t it = find_nul(name); | |
| if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos)) | |
| { | |
| throw_bson_key_with_null(it, j); | |
| } | |
| if (JSON_HEDLEY_LIKELY(error_handler == error_handler_t::keep)) | |
| { | |
| return /*id*/ 1ul + name.size() + /*zero-terminator*/1u; | |
| } | |
| return calc_bson_checked_entry_header_size(name, j); | |
| } | |
| /// @brief throw out_of_range.409 for a name with U+0000 at byte @a index; | |
| /// out of line, so that the message does not burden the check | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_bson_key_with_null(const std::size_t index, const BasicJsonType& j) | |
| { | |
| static_cast<void>(index); // only used when exceptions are enabled | |
| static_cast<void>(j); | |
| JSON_THROW(out_of_range::create(exception_id::bson_key_with_null, concat("BSON key cannot contain code point U+0000 (at byte ", std::to_string(index), ")"), &j)); | |
| } | |
| /// @brief the size of a BSON document entry header for a name that the | |
| /// error handler checks or sanitizes; out of line, as the string_t | |
| /// for the sanitized copy would otherwise burden every call of | |
| /// @ref calc_bson_entry_header_size | |
| JSON_HEDLEY_NEVER_INLINE | |
| std::size_t calc_bson_checked_entry_header_size(const string_t& name, const BasicJsonType& j) | |
| { | |
| string_t storage; | |
| const string_t& sanitized = sanitize_utf8_for_write(name, j, storage); | |
| return /*id*/ 1ul + sanitized.size() + /*zero-terminator*/1u; | |
| } | |
| /*! | |
| @brief the position of the first U+0000 in @a name, or string_t::npos | |
| The same as `name.find(0)`, without the calls into the standard library for | |
| names of a few characters: it looks at eight characters at a time. | |
| */ | |
| static std::size_t find_nul(const string_t& name) noexcept | |
| { | |
| return find_nul(name, std::integral_constant<bool, sizeof(typename string_t::value_type) == 1>()); | |
| } | |
| static std::size_t find_nul(const string_t& name, std::true_type /*is_byte*/) noexcept | |
| { | |
| constexpr std::uint64_t ones = 0x0101010101010101ull; | |
| constexpr std::uint64_t high = 0x8080808080808080ull; | |
| const std::size_t size = name.size(); | |
| const char* const data = reinterpret_cast<const char*>(name.data()); | |
| std::size_t pos = 0; | |
| for (; pos + 8 <= size; pos += 8) | |
| { | |
| std::uint64_t word = 0; | |
| std::memcpy(&word, data + pos, sizeof(word)); | |
| if (((word - ones) & ~word & high) != 0) | |
| { | |
| break; | |
| } | |
| } | |
| for (; pos < size; ++pos) | |
| { | |
| if (data[pos] == '\0') | |
| { | |
| return pos; | |
| } | |
| } | |
| return BasicJsonType::string_t::npos; | |
| } | |
| static std::size_t find_nul(const string_t& name, std::false_type /*is_byte*/) noexcept | |
| { | |
| return name.find(static_cast<typename string_t::value_type>(0)); | |
| } | |
| /*! | |
| @brief Checks that @a size fits into the 32-bit length field used by BSON | |
| @return The size as a signed 32-bit integer | |
| @throw out_of_range.412 if @a size exceeds the range of std::int32_t | |
| */ | |
| static std::int32_t to_bson_length(const std::size_t size) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!value_in_range_of<std::int32_t>(size))) | |
| { | |
| throw_bson_length_too_large(size); | |
| } | |
| return static_cast<std::int32_t>(size); | |
| } | |
| /*! | |
| @brief Writes the given @a element_type and @a name to the output adapter | |
| @a name has already been validated (and, for @ref error_handler_t::strict, | |
| found well-formed) by @ref calc_bson_entry_header_size during the earlier | |
| size pass, so only @ref error_handler_t::replace / @ref | |
| error_handler_t::ignore need to sanitize it again here, to actually write | |
| the bytes that size was computed from. | |
| */ | |
| void write_bson_entry_header(const string_t& name, | |
| const std::uint8_t element_type) | |
| { | |
| oa.write_character(to_char_type(element_type)); | |
| if (JSON_HEDLEY_LIKELY(error_handler == error_handler_t::keep || error_handler == error_handler_t::strict)) | |
| { | |
| write_bytes(name.data(), name.size()); | |
| } | |
| else | |
| { | |
| string_t storage; | |
| const string_t& written = sanitize_utf8_for_bson_write(name, storage); | |
| write_bytes(written.data(), written.size()); | |
| } | |
| // the terminating null byte is written explicitly rather than taken | |
| // from the buffer, so that string_t::data() need not be null-terminated | |
| oa.write_character(to_char_type(0x00)); | |
| } | |
| /*! | |
| @brief Writes a BSON element with key @a name and boolean value @a value | |
| */ | |
| void write_bson_boolean(const string_t& name, | |
| const bool value) | |
| { | |
| write_bson_entry_header(name, 0x08); | |
| oa.write_character(value ? to_char_type(0x01) : to_char_type(0x00)); | |
| } | |
| /*! | |
| @brief Writes a BSON element with key @a name and double value @a value | |
| */ | |
| void write_bson_double(const string_t& name, | |
| const double value) | |
| { | |
| write_bson_entry_header(name, 0x01); | |
| write_number<double>(value, true); | |
| } | |
| /*! | |
| @return The size of the BSON-encoded string in @a value | |
| @throw type_error.316 if @a value is not valid UTF-8, before anything is | |
| written | |
| @note The UTF-8 check is skipped if @a value is already too long for the | |
| 32-bit BSON length field (@ref to_bson_length rejects it later, once | |
| the size of the whole document is known); this also keeps the check | |
| from reading past a StringType that reports a size larger than what | |
| it actually holds. | |
| */ | |
| std::size_t calc_bson_string_size(const string_t& value, const BasicJsonType& j) | |
| { | |
| if (JSON_HEDLEY_LIKELY(value_in_range_of<std::int32_t>(value.size()))) | |
| { | |
| if (JSON_HEDLEY_LIKELY(error_handler == error_handler_t::keep)) | |
| { | |
| return sizeof(std::int32_t) + value.size() + 1ul; | |
| } | |
| return calc_bson_checked_string_size(value, j); | |
| } | |
| return sizeof(std::int32_t) + value.size() + 1ul; | |
| } | |
| /// @brief the size of a BSON string that the error handler checks or | |
| /// sanitizes; out of line, like @ref calc_bson_checked_entry_header_size | |
| JSON_HEDLEY_NEVER_INLINE | |
| std::size_t calc_bson_checked_string_size(const string_t& value, const BasicJsonType& j) | |
| { | |
| string_t storage; | |
| const string_t& sanitized = sanitize_utf8_for_write(value, j, storage); | |
| return sizeof(std::int32_t) + sanitized.size() + 1ul; | |
| } | |
| /*! | |
| @brief Writes a BSON element with key @a name and string value @a value | |
| @a value has already been validated (and, for @ref error_handler_t::strict, | |
| found well-formed) by @ref calc_bson_string_size during the earlier size | |
| pass, so only @ref error_handler_t::replace / @ref error_handler_t::ignore | |
| need to sanitize it again here, to actually write the bytes that size was | |
| computed from. | |
| */ | |
| void write_bson_string(const string_t& name, | |
| const string_t& value) | |
| { | |
| write_bson_entry_header(name, 0x02); | |
| string_t storage; | |
| const string_t& written = sanitize_utf8_for_bson_write(value, storage); | |
| write_number<std::int32_t>(to_bson_length(written.size() + 1ul), true); | |
| write_bytes(written.data(), written.size()); | |
| // the terminating null byte is written explicitly rather than taken | |
| // from the buffer, so that string_t::data() need not be null-terminated | |
| oa.write_character(to_char_type(0x00)); | |
| } | |
| /*! | |
| @brief Writes a BSON element with key @a name and null value | |
| */ | |
| void write_bson_null(const string_t& name) | |
| { | |
| write_bson_entry_header(name, 0x0A); | |
| } | |
| /*! | |
| @return The size of the BSON-encoded integer @a value | |
| */ | |
| static std::size_t calc_bson_integer_size(const std::int64_t value) | |
| { | |
| return (std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)() | |
| ? sizeof(std::int32_t) | |
| : sizeof(std::int64_t); | |
| } | |
| /*! | |
| @brief Writes a BSON element with key @a name and integer @a value | |
| */ | |
| void write_bson_integer(const string_t& name, | |
| const std::int64_t value) | |
| { | |
| if ((std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)()) | |
| { | |
| write_bson_entry_header(name, 0x10); // int32 | |
| write_number<std::int32_t>(static_cast<std::int32_t>(value), true); | |
| } | |
| else | |
| { | |
| write_bson_entry_header(name, 0x12); // int64 | |
| write_number<std::int64_t>(static_cast<std::int64_t>(value), true); | |
| } | |
| } | |
| /*! | |
| @return The size of the BSON-encoded unsigned integer @a value | |
| */ | |
| static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept | |
| { | |
| return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) | |
| ? sizeof(std::int32_t) | |
| : sizeof(std::int64_t); | |
| } | |
| /*! | |
| @brief Writes a BSON element with key @a name and unsigned @a value | |
| */ | |
| void write_bson_unsigned(const string_t& name, | |
| const std::uint64_t value) | |
| { | |
| if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) | |
| { | |
| write_bson_entry_header(name, 0x10 /* int32 */); | |
| write_number<std::int32_t>(static_cast<std::int32_t>(value), true); | |
| } | |
| else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)())) | |
| { | |
| write_bson_entry_header(name, 0x12 /* int64 */); | |
| write_number<std::int64_t>(static_cast<std::int64_t>(value), true); | |
| } | |
| else | |
| { | |
| write_bson_entry_header(name, 0x11 /* uint64 */); | |
| write_number<std::uint64_t>(value, true); | |
| } | |
| } | |
| /*! | |
| @return The size of the BSON-encoded binary array in @a j | |
| @throw out_of_range.415 if the subtype of @a j does not fit into a byte, | |
| before anything is written | |
| */ | |
| static std::size_t calc_bson_binary_size(const BasicJsonType& j) | |
| { | |
| const auto& value = *j.m_data.m_value.binary; | |
| if (value.has_subtype() && JSON_HEDLEY_UNLIKELY(value.subtype() > (std::numeric_limits<std::uint8_t>::max)())) | |
| { | |
| throw_subtype_out_of_range(value.subtype(), "the BSON binary subtype", j); | |
| } | |
| return sizeof(std::int32_t) + value.size() + 1ul; | |
| } | |
| /*! | |
| @brief Writes a BSON element with key @a name and binary value @a value | |
| @pre @a value's subtype, if any, fits into a byte; @ref calc_bson_sizes | |
| checks this for every binary value in the document beforehand. | |
| */ | |
| void write_bson_binary(const string_t& name, | |
| const binary_t& value) | |
| { | |
| write_bson_entry_header(name, 0x05); | |
| write_number<std::int32_t>(to_bson_length(value.size()), true); | |
| write_number(value.has_subtype() ? static_cast<std::uint8_t>(value.subtype()) : static_cast<std::uint8_t>(0x00)); | |
| write_bytes(value.data(), value.size()); | |
| } | |
| /*! | |
| @return The size of the value of the BSON document entry for @a j, which | |
| is neither an object nor an array | |
| @throw out_of_range.415 if @a j is binary with a subtype that does not fit | |
| into a byte, before anything is written | |
| @throw out_of_range.407 if @a j is an integer that does not fit the 64 bits | |
| of a BSON integer, before anything is written | |
| @throw type_error.316 if @a j is a string that is not valid UTF-8, before | |
| anything is written | |
| @throw type_error.321 if @a j is discarded | |
| */ | |
| std::size_t calc_bson_value_size(const BasicJsonType& j) | |
| { | |
| switch (j.type()) | |
| { | |
| case value_t::binary: | |
| return calc_bson_binary_size(j); | |
| case value_t::boolean: | |
| return 1ul; | |
| case value_t::number_float: | |
| return 8ul; | |
| case value_t::number_integer: | |
| if (JSON_HEDLEY_UNLIKELY(!integer_fits<std::int64_t>(j.m_data.m_value.number_integer))) | |
| { | |
| throw_integer_out_of_range(j, input_format_t::bson, "int64"); | |
| } | |
| return calc_bson_integer_size(static_cast<std::int64_t>(j.m_data.m_value.number_integer)); | |
| case value_t::number_unsigned: | |
| if (JSON_HEDLEY_UNLIKELY(!integer_fits_max<std::uint64_t>(j.m_data.m_value.number_unsigned))) | |
| { | |
| throw_integer_out_of_range(j, input_format_t::bson, "uint64"); | |
| } | |
| return calc_bson_unsigned_size(conditional_static_cast<std::uint64_t>(j.m_data.m_value.number_unsigned)); | |
| case value_t::string: | |
| return calc_bson_string_size(*j.m_data.m_value.string, j); | |
| case value_t::null: | |
| return 0ul; | |
| case value_t::discarded: | |
| throw_on_discarded(j, input_format_t::bson); | |
| // LCOV_EXCL_START | |
| case value_t::object: | |
| case value_t::array: | |
| default: | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) | |
| return 0ul; | |
| // LCOV_EXCL_STOP | |
| } | |
| } | |
| /// the longest name for which write_bson_scalar() writes an entry through a | |
| /// single reservation: the type, name, terminating null byte, and the length | |
| /// of a string or binary value (4 bytes) or the largest fixed-size value (8 | |
| /// bytes, a double or a 64-bit integer) must fit max_reserve_size | |
| static constexpr std::size_t bson_scalar_max_name_size = max_reserve_size - 2 - 8 - 1; | |
| /*! | |
| @brief store @a n at @a out in little-endian byte order | |
| */ | |
| template<typename NumberType> | |
| void store_little_endian(CharType* out, const NumberType n) const noexcept | |
| { | |
| std::memcpy(out, &n, sizeof(NumberType)); | |
| if (!is_little_endian) | |
| { | |
| std::reverse(out, out + sizeof(NumberType)); | |
| } | |
| } | |
| /*! | |
| @brief encode the type and the value of the BSON document entry for @a j | |
| if it has a fixed size | |
| @param[in] out where the type byte goes | |
| @param[in] value_out where the value goes: the characters after the name | |
| and its terminating null byte | |
| @return the end of the entry, or nullptr (and nothing is written to | |
| @a out) if @a j is not a boolean, number, or null; at most 9 | |
| characters are written to @a out and @a value_out | |
| The entry is encoded as @ref write_bson_value does. | |
| */ | |
| CharType* encode_bson_fixed_entry(CharType* out, CharType* value_out, const BasicJsonType& j) const noexcept | |
| { | |
| switch (j.type()) | |
| { | |
| case value_t::boolean: | |
| out[0] = to_char_type(0x08); | |
| *value_out++ = j.m_data.m_value.boolean ? to_char_type(0x01) : to_char_type(0x00); | |
| return value_out; | |
| case value_t::number_float: | |
| out[0] = to_char_type(0x01); | |
| store_little_endian<double>(value_out, static_cast<double>(j.m_data.m_value.number_float)); | |
| return value_out + sizeof(double); | |
| case value_t::number_integer: | |
| { | |
| const auto value = static_cast<std::int64_t>(j.m_data.m_value.number_integer); | |
| if ((std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)()) | |
| { | |
| out[0] = to_char_type(0x10); // int32 | |
| store_little_endian<std::int32_t>(value_out, static_cast<std::int32_t>(value)); | |
| return value_out + sizeof(std::int32_t); | |
| } | |
| out[0] = to_char_type(0x12); // int64 | |
| store_little_endian<std::int64_t>(value_out, value); | |
| return value_out + sizeof(std::int64_t); | |
| } | |
| case value_t::number_unsigned: | |
| { | |
| const auto value = conditional_static_cast<std::uint64_t>(j.m_data.m_value.number_unsigned); | |
| if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) | |
| { | |
| out[0] = to_char_type(0x10); // int32 | |
| store_little_endian<std::int32_t>(value_out, static_cast<std::int32_t>(value)); | |
| return value_out + sizeof(std::int32_t); | |
| } | |
| if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)())) | |
| { | |
| out[0] = to_char_type(0x12); // int64 | |
| store_little_endian<std::int64_t>(value_out, static_cast<std::int64_t>(value)); | |
| return value_out + sizeof(std::int64_t); | |
| } | |
| out[0] = to_char_type(0x11); // uint64 | |
| store_little_endian<std::uint64_t>(value_out, value); | |
| return value_out + sizeof(std::uint64_t); | |
| } | |
| case value_t::null: | |
| out[0] = to_char_type(0x0A); | |
| return value_out; | |
| case value_t::string: | |
| case value_t::binary: | |
| case value_t::object: | |
| case value_t::array: | |
| case value_t::discarded: | |
| default: | |
| return nullptr; | |
| } | |
| } | |
| /*! | |
| @brief Writes the BSON document entry with key @a name for @a j, which is | |
| neither an object nor an array, with the key and a fixed-size value | |
| (or the header of a string or binary value) in one reservation | |
| @return whether the entry was written; false for a discarded value, a | |
| string or binary value whose length does not fit the length | |
| field, in which case nothing was written | |
| @pre @a name is at most bson_scalar_max_name_size characters long and is | |
| not changed by the error handler | |
| */ | |
| bool write_bson_scalar(const string_t& name, const BasicJsonType& j) | |
| { | |
| const std::size_t name_size = name.size(); | |
| // a short string is written whole: its type, the name and its null | |
| // byte, the length, the characters, and their null byte | |
| const bool whole_string = j.is_string() && j.m_data.m_value.string->size() <= max_reserve_size - name_size - 7; | |
| CharType* const out = oa.reserve(whole_string ? name_size + j.m_data.m_value.string->size() + 7 : name_size + 2 + 8); | |
| // the name and its terminating null byte follow the type byte | |
| CharType* p = out + 1; | |
| copy_characters(p, reinterpret_cast<const CharType*>(name.data()), name_size); | |
| p += name_size; | |
| *p++ = to_char_type(0x00); | |
| if (const CharType* const end = encode_bson_fixed_entry(out, p, j)) | |
| { | |
| oa.commit(static_cast<std::size_t>(end - out)); | |
| return true; | |
| } | |
| if (whole_string) | |
| { | |
| const string_t& value = *j.m_data.m_value.string; | |
| out[0] = to_char_type(0x02); | |
| store_little_endian<std::int32_t>(p, static_cast<std::int32_t>(value.size() + 1ul)); | |
| p += sizeof(std::int32_t); | |
| copy_characters(p, reinterpret_cast<const CharType*>(value.data()), value.size()); | |
| p += value.size(); | |
| // the terminating null byte is written explicitly rather than | |
| // taken from the buffer, so that string_t::data() need not be | |
| // null-terminated | |
| *p++ = to_char_type(0x00); | |
| oa.commit(static_cast<std::size_t>(p - out)); | |
| return true; | |
| } | |
| if (j.is_string()) | |
| { | |
| const string_t& value = *j.m_data.m_value.string; | |
| if (JSON_HEDLEY_UNLIKELY(!value_in_range_of<std::int32_t>(value.size() + 1ul))) | |
| { | |
| return false; | |
| } | |
| out[0] = to_char_type(0x02); | |
| store_little_endian<std::int32_t>(p, static_cast<std::int32_t>(value.size() + 1ul)); | |
| p += sizeof(std::int32_t); | |
| oa.commit(static_cast<std::size_t>(p - out)); | |
| // the terminating null byte is written explicitly rather than | |
| // taken from the buffer, so that string_t::data() need not be | |
| // null-terminated | |
| write_bytes(value.data(), value.size()); | |
| oa.write_character(to_char_type(0x00)); | |
| return true; | |
| } | |
| if (j.is_binary()) | |
| { | |
| const binary_t& value = *j.m_data.m_value.binary; | |
| if (JSON_HEDLEY_UNLIKELY(!value_in_range_of<std::int32_t>(value.size()))) | |
| { | |
| return false; | |
| } | |
| out[0] = to_char_type(0x05); | |
| store_little_endian<std::int32_t>(p, static_cast<std::int32_t>(value.size())); | |
| p += sizeof(std::int32_t); | |
| *p++ = value.has_subtype() ? to_char_type(static_cast<std::uint8_t>(value.subtype())) : to_char_type(0x00); | |
| oa.commit(static_cast<std::size_t>(p - out)); | |
| write_bytes(value.data(), value.size()); | |
| return true; | |
| } | |
| return false; | |
| } | |
| /*! | |
| @brief Writes the BSON document entry with key @a name for @a j, which is | |
| neither an object nor an array | |
| */ | |
| void write_bson_value(const string_t& name, const BasicJsonType& j) | |
| { | |
| // The strings are written as they are, as they are neither checked nor | |
| // sanitized again here by these two error handlers. The name has to leave | |
| // room for the larger payloads (see write_bson_scalar). | |
| if (name.size() <= bson_scalar_max_name_size | |
| && (error_handler == error_handler_t::keep || error_handler == error_handler_t::strict) | |
| && write_bson_scalar(name, j)) | |
| { | |
| return; | |
| } | |
| switch (j.type()) | |
| { | |
| case value_t::binary: | |
| return write_bson_binary(name, *j.m_data.m_value.binary); | |
| case value_t::boolean: | |
| return write_bson_boolean(name, j.m_data.m_value.boolean); | |
| case value_t::number_float: | |
| return write_bson_double(name, j.m_data.m_value.number_float); | |
| // calc_bson_value_size() checked that integers fit 64 bits | |
| case value_t::number_integer: | |
| return write_bson_integer(name, static_cast<std::int64_t>(j.m_data.m_value.number_integer)); | |
| case value_t::number_unsigned: | |
| return write_bson_unsigned(name, conditional_static_cast<std::uint64_t>(j.m_data.m_value.number_unsigned)); | |
| case value_t::string: | |
| return write_bson_string(name, *j.m_data.m_value.string); | |
| case value_t::null: | |
| return write_bson_null(name); | |
| case value_t::discarded: | |
| throw_on_discarded(j, input_format_t::bson); | |
| // LCOV_EXCL_START | |
| case value_t::object: | |
| case value_t::array: | |
| default: | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) | |
| return; | |
| // LCOV_EXCL_STOP | |
| } | |
| } | |
| /*! | |
| @brief Writes the head of a BSON element with key @a name whose value is | |
| the object or array @a j: its type, key, and @a size | |
| Called while the key is in scope: an object key is a key_type, which | |
| may only convert to a temporary string_t, so it cannot be kept by | |
| pointer until after the loop over the entries. | |
| */ | |
| void write_bson_nested_head(const string_t& name, const BasicJsonType& j, | |
| const std::size_t size) | |
| { | |
| write_bson_entry_header(name, j.is_object() ? 0x03 : 0x04); | |
| write_number<std::int32_t>(to_bson_length(size), true); | |
| } | |
| /// space for the name of an array element, the decimal index, in the frame | |
| static constexpr std::size_t bson_index_name_space = 24; | |
| /// @brief an object or array of the BSON document being sized or written | |
| struct bson_frame | |
| { | |
| explicit bson_frame(const BasicJsonType* value_, const std::size_t size_slot_ = 0) | |
| : value(value_) | |
| , size_slot(size_slot_) | |
| { | |
| if (value->is_object()) | |
| { | |
| member = value->m_data.m_value.object->cbegin(); | |
| } | |
| } | |
| /// @ref calc_bson_sizes only: make @ref index the next one and count the | |
| /// digits of its name | |
| void count_index() noexcept | |
| { | |
| if (++index == index_boundary) | |
| { | |
| ++index_name_size; | |
| index_boundary *= 10; | |
| } | |
| } | |
| /// @ref write_bson_document only: make @ref index the next one and | |
| /// update its decimal name | |
| void next_index() noexcept | |
| { | |
| ++index; | |
| std::size_t i = index_name_size; | |
| while (i > 0 && index_name[i - 1] == '9') | |
| { | |
| index_name[--i] = '0'; | |
| } | |
| if (i > 0) | |
| { | |
| ++index_name[i - 1]; | |
| } | |
| else | |
| { | |
| // all digits were 9: 10, 100, ... | |
| index_name[0] = '1'; | |
| index_name[index_name_size++] = '0'; | |
| } | |
| } | |
| /// the object or array | |
| const BasicJsonType* value; | |
| /// objects: the next member | |
| typename BasicJsonType::object_t::const_iterator member{}; | |
| /// arrays: the index of the next element | |
| std::size_t index = 0; | |
| /// arrays: the name BSON gives that element, its decimal index (at most | |
| /// 2^64 - 1, which has 20 digits), in space for copying a few characters | |
| /// more; only maintained by @ref write_bson_document | |
| std::array<char, bson_index_name_space> index_name{{'0'}}; | |
| /// arrays: the number of digits of the index | |
| std::size_t index_name_size = 1; | |
| /// arrays: the first index with one more digit; only maintained by | |
| /// @ref calc_bson_sizes | |
| std::uint64_t index_boundary = 10; | |
| /// @ref calc_bson_sizes only: where its size goes in the table | |
| std::size_t size_slot; | |
| /// @ref calc_bson_sizes only: the size of its entries seen so far | |
| std::size_t entries_size = 0; | |
| }; | |
| /// whether the BSON entry of @a j has a fixed size, which is the case for | |
| /// a boolean, a number, and null | |
| static bool is_bson_fixed_size(const BasicJsonType& j) noexcept | |
| { | |
| return j.is_number() || j.is_boolean() || j.is_null(); | |
| } | |
| /*! | |
| @brief Writes the entries of the array in @a frame that have a fixed size | |
| (booleans, numbers, and null), from its next element on, until it | |
| reaches another element or the end of the array | |
| The index of the element and its name are advanced in @a frame. | |
| The entries are encoded straight into space reserved from the sink for as | |
| many of them as fit, with the index, its digits, and the write pointer | |
| kept in local variables: stores of characters may alias the frame, and | |
| would force them to be loaded from it again for every element. | |
| */ | |
| void write_bson_array_fixed_entries(bson_frame& frame) | |
| { | |
| const auto& array = *frame.value->m_data.m_value.array; | |
| const std::size_t count = array.size(); | |
| std::size_t index = frame.index; | |
| std::size_t name_size = frame.index_name_size; | |
| std::array<char, bson_index_name_space> name = frame.index_name; | |
| // an entry is at most the type, 20 digits, the null byte, and 8 bytes | |
| constexpr std::size_t max_entry = 1 + 20 + 1 + 8; | |
| while (index < count) | |
| { | |
| CharType* const start = oa.reserve(max_reserve_size); | |
| CharType* out = start; | |
| const CharType* const limit = start + (max_reserve_size - max_entry); | |
| while (out <= limit && index < count) | |
| { | |
| CharType* p = out + 1; | |
| std::memcpy(p, name.data(), name.size()); | |
| p += name_size; | |
| *p++ = to_char_type(0x00); | |
| CharType* const end = encode_bson_fixed_entry(out, p, array[index]); | |
| if (end == nullptr) | |
| { | |
| break; | |
| } | |
| out = end; | |
| ++index; | |
| std::size_t i = name_size; | |
| while (i > 0 && name[i - 1] == '9') | |
| { | |
| name[--i] = '0'; | |
| } | |
| if (i > 0) | |
| { | |
| ++name[i - 1]; | |
| } | |
| else | |
| { | |
| // all digits were 9: 10, 100, ... | |
| name[0] = '1'; | |
| name[name_size++] = '0'; | |
| } | |
| } | |
| oa.commit(static_cast<std::size_t>(out - start)); | |
| if (out <= limit && index < count) | |
| { | |
| // stopped at an element that has no fixed size | |
| break; | |
| } | |
| } | |
| frame.index = index; | |
| frame.index_name_size = name_size; | |
| frame.index_name = name; | |
| } | |
| /*! | |
| @brief Calculates the size of the BSON array @a j if all its elements are | |
| booleans, numbers, or null | |
| @param[out] size the size of the array, including its own size field | |
| @return false (and nothing is known about @a size) if an element is not, | |
| or is an integer that does not fit 64 bits (which the generic | |
| path rejects), which is not looked at further | |
| */ | |
| bool calc_bson_fixed_array_size(const BasicJsonType& j, std::size_t& size) const noexcept | |
| { | |
| std::size_t total = sizeof(std::int32_t) + 1ul; | |
| std::size_t index_name_size = 1; | |
| std::uint64_t index_boundary = 10; | |
| std::uint64_t index = 0; | |
| for (const auto& el : *j.m_data.m_value.array) | |
| { | |
| // the type, the decimal index, and the terminating null byte | |
| total += 2ul + index_name_size; | |
| if (++index == index_boundary) | |
| { | |
| ++index_name_size; | |
| index_boundary *= 10; | |
| } | |
| switch (el.type()) | |
| { | |
| case value_t::boolean: | |
| total += 1ul; | |
| break; | |
| case value_t::number_float: | |
| total += 8ul; | |
| break; | |
| case value_t::number_integer: | |
| // an integer beyond 64 bits is left to the generic path, which throws | |
| if (JSON_HEDLEY_UNLIKELY(!integer_fits<std::int64_t>(el.m_data.m_value.number_integer))) | |
| { | |
| return false; | |
| } | |
| total += calc_bson_integer_size(static_cast<std::int64_t>(el.m_data.m_value.number_integer)); | |
| break; | |
| case value_t::number_unsigned: | |
| if (JSON_HEDLEY_UNLIKELY(!integer_fits_max<std::uint64_t>(el.m_data.m_value.number_unsigned))) | |
| { | |
| return false; | |
| } | |
| total += calc_bson_unsigned_size(conditional_static_cast<std::uint64_t>(el.m_data.m_value.number_unsigned)); | |
| break; | |
| case value_t::null: | |
| break; | |
| case value_t::string: | |
| case value_t::binary: | |
| case value_t::object: | |
| case value_t::array: | |
| case value_t::discarded: | |
| default: | |
| return false; | |
| } | |
| } | |
| size = total; | |
| return true; | |
| } | |
| /*! | |
| @brief Calculates the size of every object and array in the BSON document | |
| @a document, including the document itself. | |
| BSON prefixes every document and array with its size, so all of them have | |
| to be known before the first byte is written. They are computed in a | |
| single pass, each one from the sizes of its entries, which keeps | |
| serializing linear in the size of the document; computing each size by | |
| walking the entire value below it made it quadratic in the nesting depth. | |
| The pass keeps the objects and arrays it has entered on an explicit stack, | |
| so a deeply nested value cannot exhaust the call stack. | |
| @param[in] document the JSON object to serialize | |
| @param[out] nested_sizes the sizes of the objects and arrays in | |
| @a document, in the order they are written | |
| @return the size of @a document | |
| @throw out_of_range.409 if a key contains U+0000, before anything is | |
| written | |
| @throw out_of_range.415 if a binary value's subtype does not fit into a | |
| byte, before anything is written | |
| @throw type_error.316 if a string value or a key is not valid UTF-8, | |
| before anything is written | |
| @throw type_error.321 if a value nested in @a document is discarded, | |
| before anything is written | |
| */ | |
| std::size_t calc_bson_sizes(const BasicJsonType& document, std::vector<std::size_t>& nested_sizes) | |
| { | |
| // the object or array whose entries are being sized, and the ones it | |
| // is in; nothing is allocated unless the document nests | |
| bson_frame current(&document); | |
| std::vector<bson_frame> parents; | |
| while (true) | |
| { | |
| // size entries until the current object or array is done, or an | |
| // entry is an object or array itself | |
| const BasicJsonType* nested = nullptr; | |
| if (current.value->is_object()) | |
| { | |
| const auto& object = *current.value->m_data.m_value.object; | |
| while (nested == nullptr && current.member != object.cend()) | |
| { | |
| const auto& el = *current.member; | |
| ++current.member; | |
| current.entries_size += calc_bson_entry_header_size(el.first, el.second); | |
| if (el.second.is_structured()) | |
| { | |
| nested = &el.second; | |
| } | |
| else | |
| { | |
| current.entries_size += calc_bson_value_size(el.second); | |
| } | |
| } | |
| } | |
| else | |
| { | |
| const auto& array = *current.value->m_data.m_value.array; | |
| while (nested == nullptr && current.index < array.size()) | |
| { | |
| const BasicJsonType& el = array[current.index]; | |
| // the type, the decimal index (which is valid UTF-8 and | |
| // has no U+0000), and the terminating null byte | |
| current.entries_size += 2ul + current.index_name_size; | |
| current.count_index(); | |
| if (el.is_structured()) | |
| { | |
| nested = ⪙ | |
| } | |
| else | |
| { | |
| current.entries_size += calc_bson_value_size(el); | |
| } | |
| } | |
| } | |
| if (nested != nullptr) | |
| { | |
| // an array of booleans, numbers and null: sized without a frame | |
| std::size_t fixed_size = 0; | |
| if (nested->is_array() && calc_bson_fixed_array_size(*nested, fixed_size)) | |
| { | |
| nested_sizes.push_back(fixed_size); | |
| current.entries_size += fixed_size; | |
| continue; | |
| } | |
| // its size is added to the current one's once it is done | |
| nested_sizes.push_back(0); | |
| parents.push_back(std::move(current)); | |
| current = bson_frame(nested, nested_sizes.size() - 1); | |
| continue; | |
| } | |
| // the int32 size, the entries, and the terminating null byte | |
| const std::size_t size = sizeof(std::int32_t) + current.entries_size + 1ul; | |
| if (parents.empty()) | |
| { | |
| return size; | |
| } | |
| nested_sizes[current.size_slot] = size; | |
| current = std::move(parents.back()); | |
| parents.pop_back(); | |
| current.entries_size += size; | |
| } | |
| } | |
| /*! | |
| @brief Serializes the JSON object @a document as a BSON document | |
| Writes the objects and arrays in it without the call stack, keeping the | |
| ones it has entered on an explicit stack, so a deeply nested value | |
| cannot exhaust the call stack. | |
| @param[in] document the JSON object to serialize | |
| @pre document.type() == value_t::object | |
| */ | |
| void write_bson_document(const BasicJsonType& document) | |
| { | |
| std::vector<std::size_t> nested_sizes; | |
| const std::size_t document_size = calc_bson_sizes(document, nested_sizes); | |
| write_number<std::int32_t>(to_bson_length(document_size), true); | |
| // the object or array whose entries are being written, and the ones | |
| // it is in | |
| bson_frame current(&document); | |
| std::vector<bson_frame> parents; | |
| std::size_t next_size = 0; | |
| while (true) | |
| { | |
| // write entries until the current object or array is done, or an | |
| // entry is an object or array itself | |
| const BasicJsonType* nested = nullptr; | |
| if (current.value->is_object()) | |
| { | |
| const auto& object = *current.value->m_data.m_value.object; | |
| while (nested == nullptr && current.member != object.cend()) | |
| { | |
| const auto& el = *current.member; | |
| ++current.member; | |
| if (el.second.is_structured()) | |
| { | |
| write_bson_nested_head(el.first, el.second, nested_sizes[next_size++]); | |
| nested = &el.second; | |
| } | |
| else | |
| { | |
| write_bson_value(el.first, el.second); | |
| } | |
| } | |
| } | |
| else | |
| { | |
| const auto& array = *current.value->m_data.m_value.array; | |
| while (nested == nullptr && current.index < array.size()) | |
| { | |
| if (is_bson_fixed_size(array[current.index])) | |
| { | |
| write_bson_array_fixed_entries(current); | |
| if (current.index == array.size()) | |
| { | |
| break; | |
| } | |
| } | |
| // a string, binary value, object or array | |
| const BasicJsonType& el = array[current.index]; | |
| const string_t index_name(current.index_name.data(), current.index_name_size); | |
| current.next_index(); | |
| if (el.is_structured()) | |
| { | |
| write_bson_nested_head(index_name, el, nested_sizes[next_size++]); | |
| nested = ⪙ | |
| } | |
| else | |
| { | |
| write_bson_value(index_name, el); | |
| } | |
| } | |
| } | |
| if (nested != nullptr) | |
| { | |
| if (nested->is_array()) | |
| { | |
| // an array of booleans, numbers and null is written without a frame on the stack | |
| bson_frame leaf(nested); | |
| write_bson_array_fixed_entries(leaf); | |
| if (leaf.index == nested->m_data.m_value.array->size()) | |
| { | |
| oa.write_character(to_char_type(0x00)); | |
| continue; | |
| } | |
| parents.push_back(std::move(current)); | |
| current = std::move(leaf); | |
| continue; | |
| } | |
| parents.push_back(std::move(current)); | |
| current = bson_frame(nested); | |
| continue; | |
| } | |
| oa.write_character(to_char_type(0x00)); | |
| if (parents.empty()) | |
| { | |
| // calc_bson_sizes() and write_bson_document() are two | |
| // hand-synchronized passes over the same structure, linked | |
| // only by nested_sizes' visiting order; this checks that the | |
| // write pass consumed exactly the sizes the size pass | |
| // produced, so a future change that desyncs them (skips or | |
| // rejects an entry in only one pass) is caught immediately | |
| // instead of silently writing wrong length prefixes. | |
| JSON_ASSERT(next_size == nested_sizes.size()); | |
| return; | |
| } | |
| current = std::move(parents.back()); | |
| parents.pop_back(); | |
| } | |
| } | |
| ////////// | |
| // CBOR // | |
| ////////// | |
| /*! | |
| @brief write the head of a CBOR data item | |
| The head is the major type in the upper three bits of the first byte and | |
| an argument - an unsigned integer, the length of a string, the number of | |
| elements of a container - in the shortest of its encodings: in the lower | |
| five bits of the first byte itself if it is at most 23, otherwise in the | |
| 1, 2, 4, or 8 bytes that follow (RFC 8949, section 3). | |
| @param[in] major_type the major type, shifted into the upper three bits | |
| @param[in] argument the argument of the data item | |
| */ | |
| void write_cbor_head(const std::uint8_t major_type, const std::uint64_t argument) | |
| { | |
| if (argument <= 0x17) | |
| { | |
| write_number(static_cast<std::uint8_t>(major_type + argument)); | |
| } | |
| else if (argument <= (std::numeric_limits<std::uint8_t>::max)()) | |
| { | |
| oa.write_character(to_char_type(static_cast<std::uint8_t>(major_type + 0x18))); | |
| write_number(static_cast<std::uint8_t>(argument)); | |
| } | |
| else if (argument <= (std::numeric_limits<std::uint16_t>::max)()) | |
| { | |
| oa.write_character(to_char_type(static_cast<std::uint8_t>(major_type + 0x19))); | |
| write_number(static_cast<std::uint16_t>(argument)); | |
| } | |
| else if (argument <= (std::numeric_limits<std::uint32_t>::max)()) | |
| { | |
| oa.write_character(to_char_type(static_cast<std::uint8_t>(major_type + 0x1A))); | |
| write_number(static_cast<std::uint32_t>(argument)); | |
| } | |
| else | |
| { | |
| oa.write_character(to_char_type(static_cast<std::uint8_t>(major_type + 0x1B))); | |
| write_number(argument); | |
| } | |
| } | |
| /*! | |
| @brief size class of an unsigned integer from its bit length | |
| 1, 2, 3, or 4 if @a x fits 1, 2, 4, or 8 bytes. Looked up from the number | |
| of leading zero bits instead of found by branches: the sizes of a stream | |
| of numbers are hard to predict, and a mispredicted branch costs more than | |
| writing the number. (A table, as comparisons are vectorized by clang into | |
| slower code.) | |
| */ | |
| static unsigned integer_size_class(const std::uint64_t x) noexcept | |
| { | |
| static constexpr std::array<std::uint8_t, 64> size_class_by_leading_zeros = | |
| { | |
| { | |
| 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, | |
| 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, | |
| 2, 2, 2, 2, 2, 2, 2, 2, | |
| 1, 1, 1, 1, 1, 1, 1, 1 | |
| } | |
| }; | |
| // x | 1 keeps count_leading_zeros() away from 0 | |
| return size_class_by_leading_zeros[static_cast<std::size_t>(count_leading_zeros(x | 1u))]; | |
| } | |
| /*! | |
| @brief encode @a first_byte and the low-order bytes of @a value that | |
| @a size_class calls for (none, or 1, 2, 4, or 8) in network order | |
| to @a out | |
| @return the number of characters of the encoding; up to | |
| @ref integer_encoding_space characters at @a out are overwritten | |
| The bytes are written as one byte and one 8-byte word whose bytes after | |
| the value are scratch that the caller drops, so that writing them does not | |
| depend on the size class. For class 0 the word is all scratch; it is | |
| shifted by 60 bits rather than 64, which would be undefined. | |
| */ | |
| std::size_t encode_first_byte_and_tail(CharType* out, const std::uint8_t first_byte, const unsigned size_class, const std::uint64_t value) const noexcept | |
| { | |
| out[0] = to_char_type(first_byte); | |
| const unsigned unused_bits = 64u - ((8u << size_class) >> 1u); | |
| const std::uint64_t tail = is_little_endian ? byteswap(value) >> unused_bits : value << unused_bits; | |
| std::memcpy(out + 1, &tail, sizeof(tail)); | |
| return ((std::size_t{1} << size_class) >> 1u) + 1; | |
| } | |
| /// characters encode_first_byte_and_tail() may overwrite: the first byte | |
| /// and one 8-byte word | |
| static constexpr std::size_t integer_encoding_space = 9; | |
| /*! | |
| @brief the 64 bits of a number_integer or number_unsigned value, and a mask | |
| that is all ones if it is negative, else zero | |
| Selected through masks rather than branches, as the type and the sign of | |
| the values in an array of mixed signs alternate unpredictably (non-negative | |
| integers are number_unsigned after parsing). Up to 64 bits, the sign is bit | |
| 63 of the result (a narrower integer is sign-extended); computing it with | |
| masks keeps GCC from branching on the type. A wider integer has to be | |
| compared. | |
| */ | |
| static std::uint64_t integer_bits(const BasicJsonType& j, std::uint64_t& sign_mask) noexcept | |
| { | |
| const bool is_signed = j.m_data.m_type == value_t::number_integer; | |
| const std::uint64_t raw = is_signed | |
| ? static_cast<std::uint64_t>(j.m_data.m_value.number_integer) | |
| : static_cast<std::uint64_t>(j.m_data.m_value.number_unsigned); | |
| sign_mask = sizeof(typename BasicJsonType::number_integer_t) <= sizeof(std::uint64_t) | |
| ? (std::uint64_t{0} - static_cast<std::uint64_t>(is_signed)) & (std::uint64_t{0} - (raw >> 63u)) | |
| : std::uint64_t{0} - static_cast<std::uint64_t>(is_signed && j.m_data.m_value.number_integer < 0); | |
| return raw; | |
| } | |
| /*! | |
| @brief encode the head of a CBOR integer to @a out without branching on its | |
| size | |
| @return the number of characters of the head | |
| Same output as @ref write_cbor_head. The lengths of strings and containers | |
| are mostly predictable, so their heads keep the branches; the sizes of a | |
| run of integers are not, so an integer's head is assembled without them. | |
| */ | |
| std::size_t encode_cbor_integer_head(CharType* out, const std::uint8_t major_type, const std::uint64_t argument) const noexcept | |
| { | |
| // an argument of at most 23 is in size class 1 (one byte) and is moved | |
| // to class 0, the first byte, by subtracting 1 | |
| const auto is_immediate = static_cast<unsigned>(argument <= 0x17u); | |
| const unsigned size_class = integer_size_class(argument) - is_immediate; | |
| // the first byte: the argument itself if it is immediate, else | |
| // 0x17 + size_class, selected through a mask | |
| const std::uint64_t immediate_mask = std::uint64_t{0} - is_immediate; | |
| const auto first_byte = static_cast<std::uint8_t>(major_type + ((argument & immediate_mask) | ((0x17u + size_class) & ~immediate_mask))); | |
| return encode_first_byte_and_tail(out, first_byte, size_class, argument); | |
| } | |
| /// write the head of an array or object: one byte for a size of up to 23, else as | |
| /// @ref write_cbor_head | |
| void write_cbor_container_head(const std::uint8_t major_type, const std::uint64_t size) | |
| { | |
| if (JSON_HEDLEY_LIKELY(size <= 0x17)) | |
| { | |
| oa.write_character(to_char_type(static_cast<std::uint8_t>(major_type + size))); | |
| return; | |
| } | |
| write_cbor_head(major_type, size); | |
| } | |
| /*! | |
| @brief write an object value (head and members) as CBOR | |
| A member whose value is null, a boolean, an integer, or a string is written | |
| without a call of @ref write_cbor. Kept out of line, like @ref write_cbor_array. | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_cbor_object(const BasicJsonType& j, const std::size_t depth) | |
| { | |
| // step 1: write control byte and the object size | |
| write_cbor_container_head(0xA0, j.m_data.m_value.object->size()); | |
| for (const auto& el : *j.m_data.m_value.object) | |
| { | |
| // el.first is written directly (not via a temporary | |
| // basic_json), with the object as diagnostics context | |
| write_cbor_key(el.first, j); | |
| const BasicJsonType& value = el.second; | |
| switch (value.type()) | |
| { | |
| case value_t::null: | |
| oa.write_character(to_char_type(0xF6)); | |
| break; | |
| case value_t::boolean: | |
| oa.write_character(value.m_data.m_value.boolean ? to_char_type(0xF5) : to_char_type(0xF4)); | |
| break; | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| write_cbor_integer(value, std::integral_constant<bool, integers_fit_64_bits()>()); | |
| break; | |
| case value_t::string: | |
| write_cbor_string(*value.m_data.m_value.string, value); | |
| break; | |
| case value_t::object: | |
| case value_t::array: | |
| case value_t::binary: | |
| case value_t::number_float: | |
| case value_t::discarded: | |
| default: | |
| write_cbor(value, depth + 1); | |
| break; | |
| } | |
| } | |
| } | |
| /*! | |
| @brief write an array value (head and elements) as CBOR | |
| Integer elements, the most common scalar, are written without a call to | |
| @ref write_cbor. The loop is kept out of line: inlined into write_cbor, its | |
| registers would be saved and restored on every call of write_cbor, which | |
| is one call per value nested in an object. | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_cbor_array(const BasicJsonType& j, const std::size_t depth) | |
| { | |
| write_cbor_container_head(0x80, j.m_data.m_value.array->size()); | |
| if (!j.m_data.m_value.array->empty()) | |
| { | |
| write_cbor_array_elements(j, depth, std::integral_constant<bool, integers_fit_64_bits()>()); | |
| } | |
| } | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_cbor_array_elements(const BasicJsonType& j, const std::size_t depth, std::true_type /*fits_64_bits*/) | |
| { | |
| write_array_elements(j, [this](CharType * out, const BasicJsonType & el) | |
| { | |
| return encode_cbor_integer(out, el); | |
| }, [this](CharType * out, const number_float_t n) | |
| { | |
| return encode_cbor_float(out, n); | |
| }, [this, depth](const BasicJsonType & el) | |
| { | |
| write_cbor(el, depth + 1); | |
| }); | |
| } | |
| void write_cbor_array_elements(const BasicJsonType& j, const std::size_t depth, std::false_type /*fits_64_bits*/) | |
| { | |
| for (const auto& el : *j.m_data.m_value.array) | |
| { | |
| write_cbor(el, depth + 1); | |
| } | |
| } | |
| /*! | |
| @brief write the elements of the array @a j, runs of integers with | |
| @a encode_integer, runs of floats with @a encode_float, and all | |
| other values with @a write_value | |
| Runs of numbers are encoded straight into space reserved from the sink | |
| for a whole run: the write pointer stays a local, where it would otherwise | |
| be reloaded from the sink for every value, as a store of a character may | |
| alias it. | |
| */ | |
| template<typename EncodeInteger, typename EncodeFloat, typename WriteValue> | |
| void write_array_elements(const BasicJsonType& j, EncodeInteger encode_integer, EncodeFloat encode_float, WriteValue write_value) | |
| { | |
| constexpr std::size_t max_run = max_reserve_size / integer_encoding_space; | |
| auto it = j.m_data.m_value.array->begin(); | |
| const auto end = j.m_data.m_value.array->end(); | |
| while (it != end) | |
| { | |
| if (!it->is_number()) | |
| { | |
| write_value(*it); | |
| ++it; | |
| } | |
| else if (!it->is_number_float()) | |
| { | |
| CharType* const start = oa.reserve(max_run * integer_encoding_space); | |
| CharType* out = start; | |
| for (std::size_t n = 0; n < max_run && it != end && it->is_number_integer(); ++n, ++it) | |
| { | |
| out += encode_integer(out, *it); | |
| } | |
| oa.commit(static_cast<std::size_t>(out - start)); | |
| } | |
| else | |
| { | |
| it = write_float_elements(it, end, encode_float); | |
| } | |
| } | |
| } | |
| /*! | |
| @brief write the run of floats that starts at @a it with @a encode_float | |
| @return the first element after the run | |
| Out of line, so that the loop of integers in @ref write_array_elements is | |
| not changed by it. | |
| */ | |
| template<typename Iterator, typename EncodeFloat> | |
| JSON_HEDLEY_NEVER_INLINE | |
| Iterator write_float_elements(Iterator it, const Iterator end, EncodeFloat encode_float) // NOLINT(performance-unnecessary-value-param): iterators are passed by value | |
| { | |
| constexpr std::size_t max_run = max_reserve_size / integer_encoding_space; | |
| CharType* const start = oa.reserve(max_run * integer_encoding_space); | |
| CharType* out = start; | |
| for (std::size_t n = 0; n < max_run && it != end && it->is_number_float(); ++n, ++it) | |
| { | |
| out += encode_float(out, it->m_data.m_value.number_float); | |
| } | |
| oa.commit(static_cast<std::size_t>(out - start)); | |
| return it; | |
| } | |
| /*! | |
| @brief write a number_integer or number_unsigned value as a CBOR integer | |
| A negative integer n has major type 1 and the argument -1 - n, which is ~n. | |
| Kept out of line, like the other per-value paths, so that write_cbor stays | |
| small (runs of integers in an array are encoded inline instead). | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_cbor_integer(const BasicJsonType& j, std::true_type /*fits_64_bits*/) | |
| { | |
| oa.commit(encode_cbor_integer(oa.reserve(integer_encoding_space), j)); | |
| } | |
| /// write a number_integer or number_unsigned value of a number type wider | |
| /// than 64 bits as a CBOR integer, with range checks on the whole value | |
| void write_cbor_integer(const BasicJsonType& j, std::false_type /*fits_64_bits*/) | |
| { | |
| if (j.m_data.m_type == value_t::number_unsigned) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!integer_fits_max<std::uint64_t>(j.m_data.m_value.number_unsigned))) | |
| { | |
| throw_integer_out_of_range(j, input_format_t::cbor, "uint64"); | |
| } | |
| write_cbor_head(0x00, conditional_static_cast<std::uint64_t>(j.m_data.m_value.number_unsigned)); | |
| return; | |
| } | |
| if (j.m_data.m_value.number_integer >= 0) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!integer_fits_max<std::uint64_t>(j.m_data.m_value.number_integer))) | |
| { | |
| throw_integer_out_of_range(j, input_format_t::cbor, "[-2^64, 2^64-1]"); | |
| } | |
| // CBOR does not differentiate between positive signed | |
| // integers and unsigned integers | |
| write_cbor_head(0x00, static_cast<std::uint64_t>(j.m_data.m_value.number_integer)); | |
| } | |
| else | |
| { | |
| // a negative integer n is encoded as -1 - n | |
| if (JSON_HEDLEY_UNLIKELY(!integer_fits_max<std::uint64_t>(-1 - j.m_data.m_value.number_integer))) | |
| { | |
| throw_integer_out_of_range(j, input_format_t::cbor, "[-2^64, 2^64-1]"); | |
| } | |
| write_cbor_head(0x20, static_cast<std::uint64_t>(-1 - j.m_data.m_value.number_integer)); | |
| } | |
| } | |
| /// encode a number_integer or number_unsigned value to @a out (see | |
| /// @ref write_cbor_integer) and return the number of characters | |
| std::size_t encode_cbor_integer(CharType* out, const BasicJsonType& j) const noexcept | |
| { | |
| std::uint64_t sign_mask = 0; | |
| const std::uint64_t raw = integer_bits(j, sign_mask); | |
| // ~raw is -1 - n in the 64 bits that are written | |
| return encode_cbor_integer_head(out, static_cast<std::uint8_t>(sign_mask & 0x20u), raw ^ sign_mask); | |
| } | |
| /*! | |
| @brief whether the CBOR and MessagePack integers of BasicJsonType are | |
| written by @ref encode_cbor_integer and @ref encode_msgpack_integer | |
| These pick the format from the low 64 bits; a wider number type is written | |
| with range checks on the whole value instead. | |
| */ | |
| static constexpr bool integers_fit_64_bits() noexcept | |
| { | |
| return sizeof(typename BasicJsonType::number_integer_t) <= sizeof(std::uint64_t) | |
| && sizeof(typename BasicJsonType::number_unsigned_t) <= sizeof(std::uint64_t); | |
| } | |
| /*! | |
| @brief write a number_integer or number_unsigned value as a MessagePack | |
| integer without branching on its sign or size | |
| Same output as @ref write_msgpack: a non-negative integer as positive fixint | |
| (< 128) or uint 8/16/32/64, a negative one as negative fixint (>= -32) or | |
| int 8/16/32/64. Kept out of line (see @ref write_cbor_integer). | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_msgpack_integer(const BasicJsonType& j, std::true_type /*fits_64_bits*/) | |
| { | |
| oa.commit(encode_msgpack_integer(oa.reserve(integer_encoding_space), j)); | |
| } | |
| /// encode a number_integer or number_unsigned value to @a out (see | |
| /// @ref write_msgpack_integer) and return the number of characters | |
| std::size_t encode_msgpack_integer(CharType* out, const BasicJsonType& j) const noexcept | |
| { | |
| std::uint64_t sign_mask = 0; | |
| const std::uint64_t raw = integer_bits(j, sign_mask); | |
| // A negative n fits int 8/16/32 exactly if 2 * (-1 - n) + 1 fits | |
| // uint 8/16/32, so x gives the size class of either sign. | |
| const std::uint64_t is_negative = sign_mask & 1u; | |
| const std::uint64_t x = ((raw ^ sign_mask) << is_negative) | is_negative; | |
| // A fixint is at most 127, or at least -32 (x at most 63). It is in | |
| // size class 1 and is moved to class 0, the first byte, by subtracting 1. | |
| const auto is_fixint = static_cast<unsigned>(x <= (127u ^ (sign_mask & 64u))); | |
| const unsigned size_class = integer_size_class(x) - is_fixint; | |
| // the first byte: the low byte of the integer for a fixint, else the | |
| // marker 0xCC..0xCF (uint) or 0xD0..0xD3 (int), selected through a mask | |
| const std::uint64_t fixint_mask = std::uint64_t{0} - is_fixint; | |
| const std::uint64_t marker = 0xCBu + size_class + (sign_mask & 4u); | |
| const auto first_byte = static_cast<std::uint8_t>((raw & fixint_mask) | (marker & ~fixint_mask)); | |
| return encode_first_byte_and_tail(out, first_byte, size_class, raw); | |
| } | |
| /// write a number_integer or number_unsigned value of a number type wider | |
| /// than 64 bits as a MessagePack integer, with range checks on the whole value | |
| void write_msgpack_integer(const BasicJsonType& j, std::false_type /*fits_64_bits*/) | |
| { | |
| if (j.m_data.m_type == value_t::number_unsigned) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!integer_fits_max<std::uint64_t>(j.m_data.m_value.number_unsigned))) | |
| { | |
| throw_integer_out_of_range(j, input_format_t::msgpack, "uint64"); | |
| } | |
| write_msgpack_unsigned(static_cast<std::uint64_t>(j.m_data.m_value.number_unsigned)); | |
| return; | |
| } | |
| if (j.m_data.m_value.number_integer >= 0) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!integer_fits_max<std::uint64_t>(j.m_data.m_value.number_integer))) | |
| { | |
| throw_integer_out_of_range(j, input_format_t::msgpack, "[-2^63, 2^64-1]"); | |
| } | |
| // MessagePack does not differentiate between positive | |
| // signed integers and unsigned integers. | |
| write_msgpack_unsigned(static_cast<std::uint64_t>(j.m_data.m_value.number_integer)); | |
| } | |
| else | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!integer_fits_min<std::int64_t>(j.m_data.m_value.number_integer))) | |
| { | |
| throw_integer_out_of_range(j, input_format_t::msgpack, "[-2^63, 2^64-1]"); | |
| } | |
| if (j.m_data.m_value.number_integer >= -32) | |
| { | |
| // negative fixnum | |
| write_number(static_cast<std::int8_t>(j.m_data.m_value.number_integer)); | |
| } | |
| else if (j.m_data.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() && | |
| j.m_data.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)()) | |
| { | |
| // int 8 | |
| oa.write_character(to_char_type(0xD0)); | |
| write_number(static_cast<std::int8_t>(j.m_data.m_value.number_integer)); | |
| } | |
| else if (j.m_data.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() && | |
| j.m_data.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)()) | |
| { | |
| // int 16 | |
| oa.write_character(to_char_type(0xD1)); | |
| write_number(static_cast<std::int16_t>(j.m_data.m_value.number_integer)); | |
| } | |
| else if (j.m_data.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() && | |
| j.m_data.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)()) | |
| { | |
| // int 32 | |
| oa.write_character(to_char_type(0xD2)); | |
| write_number(static_cast<std::int32_t>(j.m_data.m_value.number_integer)); | |
| } | |
| else | |
| { | |
| // int 64 | |
| oa.write_character(to_char_type(0xD3)); | |
| write_number(static_cast<std::int64_t>(j.m_data.m_value.number_integer)); | |
| } | |
| } | |
| } | |
| /// write a float as MessagePack, into space reserved from the sink | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_msgpack_float(const number_float_t n) | |
| { | |
| oa.commit(encode_compact_float(oa.reserve(integer_encoding_space), n, to_char_type(0xCA), to_char_type(0xCB))); | |
| } | |
| /*! | |
| @brief write an object value (head and members) as MessagePack | |
| See @ref write_cbor_object. | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_msgpack_object(const BasicJsonType& j, const std::size_t depth) | |
| { | |
| write_msgpack_object_prefix(j.m_data.m_value.object->size(), j); | |
| for (const auto& el : *j.m_data.m_value.object) | |
| { | |
| // as in write_cbor, el.first is written directly with the | |
| // object as diagnostics context | |
| write_msgpack_key(el.first, j); | |
| const BasicJsonType& value = el.second; | |
| switch (value.type()) | |
| { | |
| case value_t::null: | |
| oa.write_character(to_char_type(0xC0)); | |
| break; | |
| case value_t::boolean: | |
| oa.write_character(value.m_data.m_value.boolean ? to_char_type(0xC3) : to_char_type(0xC2)); | |
| break; | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| write_msgpack_integer(value, std::integral_constant<bool, integers_fit_64_bits()>()); | |
| break; | |
| case value_t::number_float: | |
| write_msgpack_float(value.m_data.m_value.number_float); | |
| break; | |
| case value_t::string: | |
| write_msgpack_string(*value.m_data.m_value.string, value); | |
| break; | |
| case value_t::object: | |
| case value_t::array: | |
| case value_t::binary: | |
| case value_t::discarded: | |
| default: | |
| write_msgpack(value, depth + 1); | |
| break; | |
| } | |
| } | |
| } | |
| /*! | |
| @brief write an array value (head and elements) as MessagePack | |
| See @ref write_cbor_array. | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_msgpack_array(const BasicJsonType& j, const std::size_t depth) | |
| { | |
| write_msgpack_array_prefix(j.m_data.m_value.array->size(), j); | |
| if (!j.m_data.m_value.array->empty()) | |
| { | |
| write_msgpack_array_elements(j, depth, std::integral_constant<bool, integers_fit_64_bits()>()); | |
| } | |
| } | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_msgpack_array_elements(const BasicJsonType& j, const std::size_t depth, std::true_type /*fits_64_bits*/) | |
| { | |
| write_array_elements(j, [this](CharType * out, const BasicJsonType & el) | |
| { | |
| return encode_msgpack_integer(out, el); | |
| }, [this](CharType * out, const number_float_t n) | |
| { | |
| return encode_compact_float(out, n, to_char_type(0xCA), to_char_type(0xCB)); | |
| }, [this, depth](const BasicJsonType & el) | |
| { | |
| write_msgpack(el, depth + 1); | |
| }); | |
| } | |
| void write_msgpack_array_elements(const BasicJsonType& j, const std::size_t depth, std::false_type /*fits_64_bits*/) | |
| { | |
| for (const auto& el : *j.m_data.m_value.array) | |
| { | |
| write_msgpack(el, depth + 1); | |
| } | |
| } | |
| /*! | |
| @brief write an object key as a CBOR or MessagePack string (@a Walk) | |
| A key convertible to string_t is written directly. Other key types (only | |
| an explicit conversion, or only a to_json overload) go through a temporary | |
| basic_json, as in version 3.12.0; the temporary is then the diagnostics | |
| context for strict UTF-8 checks. | |
| */ | |
| template<typename Walk, typename Key = typename BasicJsonType::object_t::key_type, | |
| enable_if_t<std::is_convertible<Key, string_t>::value, int> = 0> | |
| void write_object_key(const typename BasicJsonType::object_t::key_type& key, const BasicJsonType& context) | |
| { | |
| Walk::string(*this, key, context); | |
| } | |
| template<typename Walk, typename Key = typename BasicJsonType::object_t::key_type, | |
| enable_if_t<negation<std::is_convertible<Key, string_t>>::value, int> = 0> | |
| void write_object_key(const typename BasicJsonType::object_t::key_type& key, const BasicJsonType& /*context*/) | |
| { | |
| Walk::scalar(*this, BasicJsonType(key)); | |
| } | |
| /// @brief write an object key as a CBOR text string | |
| void write_cbor_key(const typename BasicJsonType::object_t::key_type& key, const BasicJsonType& context) | |
| { | |
| write_object_key<cbor_walk>(key, context); | |
| } | |
| /// @brief write an object key as a MessagePack str | |
| void write_msgpack_key(const typename BasicJsonType::object_t::key_type& key, const BasicJsonType& context) | |
| { | |
| write_object_key<msgpack_walk>(key, context); | |
| } | |
| /// the longest string that is written, with its head of one or two | |
| /// characters, in a single reservation from the sink | |
| static constexpr std::size_t max_text_in_reservation = max_reserve_size - 2; | |
| /// copy the characters of a string to space in the sink; a short one | |
| /// without a call of memcpy() | |
| static void copy_characters(CharType* dst, const CharType* src, const std::size_t length) noexcept | |
| { | |
| if (length <= 32) | |
| { | |
| copy_short(dst, src, length, std::integral_constant<bool, sizeof(CharType) == 1>()); | |
| } | |
| else | |
| { | |
| std::memcpy(dst, src, length * sizeof(CharType)); | |
| } | |
| } | |
| /*! | |
| @brief write a CBOR text string | |
| @a value is checked or sanitized according to @ref error_handler, with | |
| @a context (the string value itself, or the object a key belongs to) used | |
| as diagnostics context; this avoids converting object keys to a temporary | |
| basic_json just to write them | |
| @note When object_t::key_type is not string_t, @a value is a temporary | |
| string_t converted from the key, which lives only until the end of | |
| the caller's statement. The reference returned by | |
| @ref sanitize_utf8_for_write may refer to it, so it must not escape | |
| this function. | |
| */ | |
| void write_cbor_string(const string_t& value, const BasicJsonType& context) | |
| { | |
| if (JSON_HEDLEY_LIKELY(error_handler == error_handler_t::keep)) | |
| { | |
| // the string is written as it is: head and characters in one reservation | |
| if (JSON_HEDLEY_LIKELY(value.size() <= max_text_in_reservation)) | |
| { | |
| CharType* const out = oa.reserve(value.size() + 2); | |
| CharType* p = out; | |
| if (value.size() <= 0x17) | |
| { | |
| *p++ = to_char_type(static_cast<std::uint8_t>(0x60 + value.size())); | |
| } | |
| else | |
| { | |
| *p++ = to_char_type(0x78); | |
| *p++ = to_char_type(static_cast<std::uint8_t>(value.size())); | |
| } | |
| copy_characters(p, reinterpret_cast<const CharType*>(value.data()), value.size()); | |
| oa.commit(static_cast<std::size_t>(p - out) + value.size()); | |
| return; | |
| } | |
| } | |
| write_cbor_checked_string(value, context); | |
| } | |
| /// @brief write a CBOR text string checked or sanitized by the error handler; | |
| /// out of line, as the string_t for the sanitized copy would make | |
| /// every call of @ref write_cbor_string set up a frame for it | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_cbor_checked_string(const string_t& value, const BasicJsonType& context) | |
| { | |
| string_t storage; | |
| const string_t& sanitized = sanitize_utf8_for_write(value, context, storage); | |
| // step 1: write control byte and the string length | |
| write_cbor_head(0x60, sanitized.size()); | |
| // step 2: write the string | |
| write_bytes(sanitized.data(), sanitized.size()); | |
| } | |
| ///////////// | |
| // MsgPack // | |
| ///////////// | |
| /*! | |
| @brief write a MessagePack str | |
| @a value is checked or sanitized according to @ref error_handler, with | |
| @a context used as diagnostics context, as in @ref write_cbor_string | |
| @note As in @ref write_cbor_string, @a value may be a temporary string_t | |
| converted from a key, so the reference returned by | |
| @ref sanitize_utf8_for_write must not escape this function. | |
| */ | |
| void write_msgpack_string(const string_t& value, const BasicJsonType& context) | |
| { | |
| if (JSON_HEDLEY_LIKELY(error_handler == error_handler_t::keep)) | |
| { | |
| // the string is written as it is: head and characters in one reservation | |
| if (JSON_HEDLEY_LIKELY(value.size() <= max_text_in_reservation)) | |
| { | |
| CharType* const out = oa.reserve(value.size() + 2); | |
| CharType* p = out; | |
| if (value.size() <= 31) | |
| { | |
| // fixstr | |
| *p++ = to_char_type(static_cast<std::uint8_t>(0xA0 | value.size())); | |
| } | |
| else | |
| { | |
| // str 8 | |
| *p++ = to_char_type(0xD9); | |
| *p++ = to_char_type(static_cast<std::uint8_t>(value.size())); | |
| } | |
| copy_characters(p, reinterpret_cast<const CharType*>(value.data()), value.size()); | |
| oa.commit(static_cast<std::size_t>(p - out) + value.size()); | |
| return; | |
| } | |
| } | |
| write_msgpack_checked_string(value, context); | |
| } | |
| /// @brief write a MessagePack str checked or sanitized by the error handler; | |
| /// out of line, like @ref write_cbor_checked_string | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_msgpack_checked_string(const string_t& value, const BasicJsonType& context) | |
| { | |
| string_t storage; | |
| const string_t& sanitized = sanitize_utf8_for_write(value, context, storage); | |
| // step 1: write control byte and the string length | |
| const auto N = to_msgpack_length(sanitized.size(), context); | |
| if (N <= 31) | |
| { | |
| // fixstr | |
| write_number(static_cast<std::uint8_t>(0xA0 | N)); | |
| } | |
| else if (N <= (std::numeric_limits<std::uint8_t>::max)()) | |
| { | |
| // str 8 | |
| oa.write_character(to_char_type(0xD9)); | |
| write_number(static_cast<std::uint8_t>(N)); | |
| } | |
| else if (N <= (std::numeric_limits<std::uint16_t>::max)()) | |
| { | |
| // str 16 | |
| oa.write_character(to_char_type(0xDA)); | |
| write_number(static_cast<std::uint16_t>(N)); | |
| } | |
| else | |
| { | |
| // str 32 | |
| oa.write_character(to_char_type(0xDB)); | |
| write_number(static_cast<std::uint32_t>(N)); | |
| } | |
| // step 2: write the string | |
| write_bytes(sanitized.data(), sanitized.size()); | |
| } | |
| //////////// | |
| // UBJSON // | |
| //////////// | |
| // UBJSON: write number (floating point) | |
| template<typename NumberType, typename std::enable_if< | |
| std::is_floating_point<NumberType>::value, int>::type = 0> | |
| void write_number_with_ubjson_prefix(const NumberType n, | |
| const bool add_prefix, | |
| const bool use_bjdata) | |
| { | |
| if (add_prefix) | |
| { | |
| oa.write_character(get_ubjson_float_prefix<NumberType>()); | |
| } | |
| write_number(n, use_bjdata); | |
| } | |
| // UBJSON: write number (integer) | |
| template<typename NumberType, typename std::enable_if< | |
| std::is_integral<NumberType>::value, int>::type = 0> | |
| void write_number_with_ubjson_prefix(const NumberType n, | |
| const bool add_prefix, | |
| const bool use_bjdata) | |
| { | |
| const CharType prefix = ubjson_integer_prefix(n, use_bjdata); | |
| if (add_prefix) | |
| { | |
| oa.write_character(prefix); | |
| } | |
| write_ubjson_integer_payload(prefix, n, use_bjdata); | |
| } | |
| /*! | |
| @brief markers and size classes of UBJSON/BJData integers, by the bit length | |
| of the magnitude | |
| A non-negative integer has the magnitude n, a negative one ~n = -1 - n; the | |
| bit length of the magnitude is 1 to 64. The first 130 characters of the | |
| table are the markers: 65 for a non-negative integer, then 65 for a negative | |
| one (index + 65). The marker is the first of `i`, `U`, `I`, `u` (BJData), | |
| `l`, `m` (BJData), `L`, `M` (BJData) whose range contains the integer; `H` | |
| (a high-precision number) is for a non-negative integer of 64 bits in | |
| UBJSON. The following 130 characters are the size classes at index + 130: | |
| the digit 0, 1, 2, or 3 for 1, 2, 4, or 8 bytes. Looked up, like | |
| @ref integer_size_class, instead of found by branches or comparisons. | |
| @sa ubjson_integer_prefix for the integers of types of more than 64 bits | |
| */ | |
| static const char* ubjson_integer_table(const bool use_bjdata) noexcept | |
| { | |
| // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays): initialized from string literals | |
| static constexpr char ubjson_table[] = | |
| // the markers for n >= 0, then n < 0 | |
| "i" "iiiiiii" "U" "IIIIIII" "llllllllllllllll" "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" "H" | |
| "i" "iiiiiii" "IIIIIIII" "llllllllllllllll" "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" "L" | |
| // the size classes | |
| "000000000" "1111111" "2222222222222222" "333333333333333333333333333333333" | |
| "00000000" "11111111" "2222222222222222" "333333333333333333333333333333333"; | |
| // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays): initialized from string literals | |
| static constexpr char bjdata_table[] = | |
| "i" "iiiiiii" "U" "IIIIIII" "u" "lllllllllllllll" "m" "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" "M" | |
| "i" "iiiiiii" "IIIIIIII" "llllllllllllllll" "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" "L" | |
| "000000000" "11111111" "2222222222222222" "33333333333333333333333333333333" | |
| "00000000" "11111111" "2222222222222222" "333333333333333333333333333333333"; | |
| static_assert(sizeof(ubjson_table) == 261 && sizeof(bjdata_table) == 261, "two tables of 130 markers and 130 size classes"); | |
| return use_bjdata ? bjdata_table : ubjson_table; | |
| } | |
| /// the index in ubjson_integer_table() of the integer with the 64 bits | |
| /// @a raw and the sign mask @a sign_mask (all ones if it is negative) | |
| static std::size_t ubjson_integer_index(const std::uint64_t raw, const std::uint64_t sign_mask) noexcept | |
| { | |
| const std::size_t sign_offset = sign_mask != 0 ? std::size_t{65} : | |
| std::size_t{0}; | |
| return static_cast<std::size_t>(64 - count_leading_zeros((raw ^ sign_mask) | 1u)) + sign_offset; | |
| } | |
| /*! | |
| @brief encode a UBJSON/BJData integer without branching on its size | |
| @param[in] out where the encoding goes; at most 9 characters are written | |
| @param[in] raw the 64 bits of the integer (two's complement) | |
| @param[in] sign_mask all ones if the integer is negative, else zero | |
| @param[in] table ubjson_integer_table(use_bjdata) | |
| @return the end of the encoding, or nullptr if the integer is a high-precision | |
| number (a non-negative one of 64 bits in UBJSON), which is not written | |
| */ | |
| CharType* encode_ubjson_integer(CharType* out, const std::uint64_t raw, const std::uint64_t sign_mask, | |
| const bool add_prefix, const bool use_bjdata, const char* table) const noexcept | |
| { | |
| const std::size_t index = ubjson_integer_index(raw, sign_mask); | |
| const char marker = table[index]; | |
| if (JSON_HEDLEY_UNLIKELY(marker == 'H')) | |
| { | |
| return nullptr; | |
| } | |
| const unsigned size_class = static_cast<unsigned>(table[index + 130]) & 3u; | |
| // the marker (or its place, if not written) and one 8-byte word, whose | |
| // bytes after the integer are scratch that the caller drops | |
| out[0] = to_char_type(static_cast<std::uint8_t>(marker)); | |
| out += add_prefix ? 1 : 0; | |
| const unsigned unused_bits = 64u - (8u << size_class); | |
| // UBJSON in network order, BJData in little-endian | |
| std::uint64_t tail = 0; | |
| if (use_bjdata) | |
| { | |
| tail = is_little_endian ? raw : byteswap(raw); | |
| } | |
| else | |
| { | |
| tail = is_little_endian ? byteswap(raw) >> unused_bits : raw << unused_bits; | |
| } | |
| std::memcpy(out, &tail, sizeof(tail)); | |
| return out + (std::size_t{1} << size_class); | |
| } | |
| /// @brief whether the integers of BasicJsonType are written by | |
| /// @ref encode_ubjson_integer | |
| static constexpr bool ubjson_integers_fit_64_bits() noexcept | |
| { | |
| return integers_fit_64_bits(); | |
| } | |
| /// space for the largest encoding of encode_ubjson_integer(): the marker and 8 bytes | |
| static constexpr std::size_t ubjson_integer_encoding_space = 9; | |
| /*! | |
| @brief write the bytes of a binary value as an array of UBJSON uint8 values | |
| Every byte is written with its marker, in blocks that fit the space reserved | |
| from the sink. Kept out of line, so that write_ubjson does not carry the | |
| registers of its loop. | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_ubjson_binary_bytes(const binary_t& binary, const bool bjdata_draft3) | |
| { | |
| const CharType marker = to_char_type(bjdata_draft3 ? 'B' : 'U'); | |
| const auto* const data = binary.data(); | |
| const std::size_t size = binary.size(); | |
| for (std::size_t i = 0; i < size;) | |
| { | |
| const std::size_t block = (std::min)(size - i, max_reserve_size / 2); | |
| CharType* const out = oa.reserve(2 * block); | |
| for (std::size_t k = 0; k < block; ++k) | |
| { | |
| out[2 * k] = marker; | |
| // the cast is needed for binary types whose value type | |
| // is not an integer (e.g., std::byte) | |
| out[(2 * k) + 1] = to_char_type(static_cast<std::uint8_t>(data[i + k])); | |
| } | |
| i += block; | |
| oa.commit(2 * block); | |
| } | |
| } | |
| /*! | |
| @brief write the members of the object @a j of a UBJSON/BJData container | |
| A member whose value is null, a boolean, an integer, a float, or a string is | |
| written without a call of @ref write_ubjson. Kept out of line, like | |
| @ref write_cbor_object. | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_ubjson_members(const BasicJsonType& j, const bool use_count, const bool use_type, | |
| const bool prefix_required, const bool use_bjdata, const bjdata_version_t bjdata_version, | |
| const std::size_t depth) | |
| { | |
| for (const auto& el : *j.m_data.m_value.object) | |
| { | |
| // a converted key must outlive the reference returned by sanitize_utf8_for_write | |
| const object_key_string_t key_string = el.first; | |
| write_ubjson_text(key_string, j, false, use_bjdata); | |
| const BasicJsonType& value = el.second; | |
| switch (value.type()) | |
| { | |
| case value_t::null: | |
| if (prefix_required) | |
| { | |
| oa.write_character(to_char_type('Z')); | |
| } | |
| break; | |
| case value_t::boolean: | |
| if (prefix_required) | |
| { | |
| oa.write_character(value.m_data.m_value.boolean ? to_char_type('T') : to_char_type('F')); | |
| } | |
| break; | |
| case value_t::number_integer: | |
| write_number_with_ubjson_prefix(value.m_data.m_value.number_integer, prefix_required, use_bjdata); | |
| break; | |
| case value_t::number_unsigned: | |
| write_number_with_ubjson_prefix(value.m_data.m_value.number_unsigned, prefix_required, use_bjdata); | |
| break; | |
| case value_t::number_float: | |
| write_number_with_ubjson_prefix(value.m_data.m_value.number_float, prefix_required, use_bjdata); | |
| break; | |
| case value_t::string: | |
| write_ubjson_text(*value.m_data.m_value.string, value, prefix_required, use_bjdata); | |
| break; | |
| case value_t::object: | |
| case value_t::array: | |
| case value_t::binary: | |
| case value_t::discarded: | |
| default: | |
| write_ubjson(value, use_count, use_type, prefix_required, use_bjdata, bjdata_version, depth + 1); | |
| break; | |
| } | |
| } | |
| } | |
| /// write the count marker `#` and the number of elements of a container as | |
| /// an integer; a count of up to 127, which is `i` and a byte, in one reservation | |
| void write_ubjson_count(const std::size_t count, const bool use_bjdata) | |
| { | |
| if (JSON_HEDLEY_LIKELY(count <= 127)) | |
| { | |
| CharType* const out = oa.reserve(3); | |
| out[0] = to_char_type('#'); | |
| out[1] = to_char_type('i'); | |
| out[2] = to_char_type(static_cast<std::uint8_t>(count)); | |
| oa.commit(3); | |
| return; | |
| } | |
| oa.write_character(to_char_type('#')); | |
| write_number_with_ubjson_prefix(count, true, use_bjdata); | |
| } | |
| /*! | |
| @brief write a UBJSON/BJData string or object key: the optional string | |
| marker `S`, the length as an integer with its marker, and the characters | |
| With the default error handler (keep) and a string of up to 253 characters, | |
| which has a length of the marker `i` or `U` and a single byte, everything is | |
| written into space reserved from the sink in one go. | |
| @param[in] value the string; checked or sanitized according to | |
| @ref error_handler, with @a context as diagnostics context | |
| @param[in] add_marker whether `S` is written first (not for an object key) | |
| */ | |
| void write_ubjson_text(const string_t& value, const BasicJsonType& context, const bool add_marker, const bool use_bjdata) | |
| { | |
| const std::size_t size = value.size(); | |
| if (JSON_HEDLEY_LIKELY(error_handler == error_handler_t::keep) && JSON_HEDLEY_LIKELY(size <= max_text_in_reservation - 1)) | |
| { | |
| CharType* const out = oa.reserve(size + 3); | |
| CharType* p = out; | |
| if (add_marker) | |
| { | |
| *p++ = to_char_type('S'); | |
| } | |
| *p++ = to_char_type(size <= 127 ? 'i' : 'U'); | |
| *p++ = to_char_type(static_cast<std::uint8_t>(size)); | |
| copy_characters(p, reinterpret_cast<const CharType*>(value.data()), size); | |
| oa.commit(static_cast<std::size_t>(p - out) + size); | |
| return; | |
| } | |
| write_ubjson_checked_text(value, context, add_marker, use_bjdata); | |
| } | |
| /// @brief write a UBJSON/BJData string checked or sanitized by the error | |
| /// handler; out of line, like @ref write_cbor_checked_string | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_ubjson_checked_text(const string_t& value, const BasicJsonType& context, const bool add_marker, const bool use_bjdata) | |
| { | |
| string_t storage; | |
| const string_t& sanitized = sanitize_utf8_for_write(value, context, storage); | |
| if (add_marker) | |
| { | |
| oa.write_character(to_char_type('S')); | |
| } | |
| write_number_with_ubjson_prefix(sanitized.size(), true, use_bjdata); | |
| write_bytes(sanitized.data(), sanitized.size()); | |
| } | |
| /*! | |
| @brief encode a UBJSON/BJData float, with its marker if @a add_prefix | |
| @param[in] out where the encoding goes; at most 9 characters are written | |
| @return the end of the encoding | |
| */ | |
| CharType* encode_ubjson_float(CharType* out, const number_float_t n, const bool add_prefix, const bool use_bjdata) const noexcept | |
| { | |
| if (add_prefix) | |
| { | |
| *out++ = get_ubjson_float_prefix<number_float_t>(); | |
| } | |
| return store_number(out, n, use_bjdata); | |
| } | |
| /// whether @a array starts with a number that @ref write_ubjson_array_elements | |
| /// can encode (all but an integer that UBJSON writes as a high-precision | |
| /// number); an array that does not is written by write_ubjson one element at a time | |
| template<typename ArrayType> | |
| static bool starts_with_ubjson_number(const ArrayType& array, const bool use_bjdata, std::true_type /*fits_64_bits*/) noexcept | |
| { | |
| if (array.empty() || !array.front().is_number()) | |
| { | |
| return false; | |
| } | |
| const BasicJsonType& first = array.front(); | |
| return use_bjdata || first.m_data.m_type != value_t::number_unsigned | |
| || (static_cast<std::uint64_t>(first.m_data.m_value.number_unsigned) >> 63u) == 0; | |
| } | |
| template<typename ArrayType> | |
| static bool starts_with_ubjson_number(const ArrayType& /*array*/, const bool /*use_bjdata*/, std::false_type /*fits_64_bits*/) noexcept | |
| { | |
| return false; | |
| } | |
| /*! | |
| @brief write the elements of an array of a UBJSON/BJData container that | |
| starts with a number, with runs of numbers encoded without a call of | |
| @ref write_ubjson for each | |
| Same output as calling write_ubjson for each element. The numbers of a | |
| run are encoded straight into space reserved from the sink, as in | |
| @ref write_array_elements; all other values, and an integer that UBJSON | |
| writes as a high-precision number, are written with write_ubjson. Kept out | |
| of line, like @ref write_cbor_array. | |
| */ | |
| template<typename ArrayType> | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_ubjson_array_elements(const ArrayType& array, const bool use_count, const bool use_type, | |
| const bool prefix_required, const bool use_bjdata, const bjdata_version_t bjdata_version, | |
| const std::size_t depth) | |
| { | |
| constexpr std::size_t max_run = max_reserve_size / ubjson_integer_encoding_space; | |
| const char* const table = ubjson_integer_table(use_bjdata); | |
| auto it = array.begin(); | |
| const auto end = array.end(); | |
| while (it != end) | |
| { | |
| if (!it->is_number()) | |
| { | |
| write_ubjson(*it, use_count, use_type, prefix_required, use_bjdata, bjdata_version, depth + 1); | |
| ++it; | |
| continue; | |
| } | |
| CharType* const start = oa.reserve(max_run * ubjson_integer_encoding_space); | |
| CharType* out = start; | |
| bool unencodable = false; | |
| for (std::size_t n = 0; n < max_run && it != end && it->is_number(); ++n) | |
| { | |
| CharType* next = nullptr; | |
| if (it->is_number_float()) | |
| { | |
| next = encode_ubjson_float(out, it->m_data.m_value.number_float, prefix_required, use_bjdata); | |
| } | |
| else | |
| { | |
| std::uint64_t sign_mask = 0; | |
| const std::uint64_t raw = integer_bits(*it, sign_mask); | |
| next = encode_ubjson_integer(out, raw, sign_mask, prefix_required, use_bjdata, table); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(next == nullptr)) | |
| { | |
| unencodable = true; | |
| break; | |
| } | |
| out = next; | |
| ++it; | |
| } | |
| oa.commit(static_cast<std::size_t>(out - start)); | |
| if (unencodable) | |
| { | |
| write_ubjson(*it, use_count, use_type, prefix_required, use_bjdata, bjdata_version, depth + 1); | |
| ++it; | |
| } | |
| } | |
| } | |
| /*! | |
| @brief store @a n at @a out in the byte order of the output | |
| @param[in] output_little_endian whether the output is little-endian | |
| @return the end of the number | |
| */ | |
| template<typename NumberType> | |
| CharType* store_number(CharType* out, const NumberType n, const bool output_little_endian) const noexcept | |
| { | |
| std::array<CharType, sizeof(NumberType)> vec{}; | |
| std::memcpy(vec.data(), &n, sizeof(NumberType)); | |
| if (is_little_endian != output_little_endian) | |
| { | |
| reverse_bytes(vec); | |
| } | |
| std::memcpy(out, vec.data(), sizeof(NumberType)); | |
| return out + sizeof(NumberType); | |
| } | |
| /*! | |
| @brief determine the UBJSON/BJData type marker of an integer | |
| This is the only place that picks the marker of an integer: both | |
| write_number_with_ubjson_prefix() and ubjson_prefix() use it. An optimized | |
| container announces the marker of its first value after `$` and then | |
| writes every value without a marker, so the two must never disagree. | |
| @param[in] n the integer | |
| @param[in] use_bjdata whether the BJData-only markers `u`, `m`, and `M` | |
| may be used | |
| @return the first marker of `i`, `U`, `I`, `u` (BJData), `l`, `m` (BJData), | |
| `L`, `M` (BJData, unsigned types only), and `H` (high-precision | |
| number) whose range contains @a n | |
| */ | |
| template<typename NumberType> | |
| static CharType ubjson_integer_prefix(const NumberType n, const bool use_bjdata) noexcept | |
| { | |
| if (value_in_range_of<std::int8_t>(n)) | |
| { | |
| return 'i'; | |
| } | |
| if (value_in_range_of<std::uint8_t>(n)) | |
| { | |
| return 'U'; | |
| } | |
| if (value_in_range_of<std::int16_t>(n)) | |
| { | |
| return 'I'; | |
| } | |
| if (use_bjdata && value_in_range_of<std::uint16_t>(n)) | |
| { | |
| return 'u'; | |
| } | |
| if (value_in_range_of<std::int32_t>(n)) | |
| { | |
| return 'l'; | |
| } | |
| if (use_bjdata && value_in_range_of<std::uint32_t>(n)) | |
| { | |
| return 'm'; | |
| } | |
| if (value_in_range_of<std::int64_t>(n)) | |
| { | |
| return 'L'; | |
| } | |
| if (use_bjdata && std::is_unsigned<NumberType>::value && integer_fits_max<std::uint64_t>(n)) | |
| { | |
| return 'M'; | |
| } | |
| // anything else is treated as a high-precision number | |
| return 'H'; | |
| } | |
| /*! | |
| @brief write the value of an integer for the marker chosen by | |
| ubjson_integer_prefix() | |
| */ | |
| template<typename NumberType> | |
| void write_ubjson_integer_payload(const CharType prefix, const NumberType n, const bool use_bjdata) | |
| { | |
| switch (prefix) | |
| { | |
| case 'i': | |
| write_number(static_cast<std::int8_t>(n), use_bjdata); | |
| break; | |
| case 'U': | |
| write_number(static_cast<std::uint8_t>(n), use_bjdata); | |
| break; | |
| case 'I': | |
| write_number(static_cast<std::int16_t>(n), use_bjdata); | |
| break; | |
| case 'u': | |
| write_number(static_cast<std::uint16_t>(n), use_bjdata); | |
| break; | |
| case 'l': | |
| write_number(static_cast<std::int32_t>(n), use_bjdata); | |
| break; | |
| case 'm': | |
| write_number(static_cast<std::uint32_t>(n), use_bjdata); | |
| break; | |
| case 'L': | |
| write_number(static_cast<std::int64_t>(n), use_bjdata); | |
| break; | |
| case 'M': | |
| write_number(static_cast<std::uint64_t>(n), use_bjdata); | |
| break; | |
| default: | |
| { | |
| JSON_ASSERT(prefix == 'H'); | |
| write_ubjson_high_precision(n, use_bjdata); | |
| break; | |
| } | |
| } | |
| } | |
| /// @brief write an integer as a high-precision number: its decimal digits as | |
| /// a string; out of line, as the string would otherwise burden | |
| /// @ref write_ubjson_integer_payload for every integer | |
| template<typename NumberType> | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_ubjson_high_precision(const NumberType n, const bool use_bjdata) | |
| { | |
| write_ubjson_high_precision(n, use_bjdata, std::integral_constant < bool, std::is_unsigned<NumberType>::value && sizeof(NumberType) <= sizeof(std::uint64_t) > ()); | |
| } | |
| /// an unsigned integer of at most 64 bits: its decimal digits are written directly | |
| template<typename NumberType> | |
| void write_ubjson_high_precision(const NumberType n, const bool use_bjdata, std::true_type /*is_unsigned_64_bits*/) | |
| { | |
| std::array<char, 20> digits; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read | |
| std::size_t first = digits.size(); | |
| auto value = static_cast<std::uint64_t>(n); | |
| do | |
| { | |
| digits[--first] = static_cast<char>('0' + (value % 10)); | |
| value /= 10; | |
| } | |
| while (value != 0); | |
| const std::size_t length = digits.size() - first; | |
| write_number_with_ubjson_prefix(length, true, use_bjdata); | |
| CharType* const out = oa.reserve(digits.size()); | |
| for (std::size_t i = 0; i < length; ++i) | |
| { | |
| out[i] = to_char_type(static_cast<std::uint8_t>(digits[first + i])); | |
| } | |
| oa.commit(length); | |
| } | |
| /// any other integer: its decimal digits from basic_json::dump() | |
| template<typename NumberType> | |
| void write_ubjson_high_precision(const NumberType n, const bool use_bjdata, std::false_type /*is_unsigned_64_bits*/) | |
| { | |
| const auto number = BasicJsonType(n).dump(); | |
| write_number_with_ubjson_prefix(number.size(), true, use_bjdata); | |
| for (std::size_t i = 0; i < number.size(); ++i) | |
| { | |
| oa.write_character(to_char_type(static_cast<std::uint8_t>(number[i]))); | |
| } | |
| } | |
| /*! | |
| @brief determine the type prefix of container values | |
| */ | |
| CharType ubjson_prefix(const BasicJsonType& j, const bool use_bjdata) const noexcept | |
| { | |
| switch (j.type()) | |
| { | |
| case value_t::null: | |
| return 'Z'; | |
| case value_t::boolean: | |
| return j.m_data.m_value.boolean ? 'T' : 'F'; | |
| case value_t::number_integer: | |
| return ubjson_integer_prefix(j.m_data.m_value.number_integer, use_bjdata); | |
| case value_t::number_unsigned: | |
| return ubjson_integer_prefix(j.m_data.m_value.number_unsigned, use_bjdata); | |
| case value_t::number_float: | |
| return get_ubjson_float_prefix<number_float_t>(); | |
| case value_t::string: | |
| return 'S'; | |
| case value_t::array: // fallthrough | |
| case value_t::binary: | |
| return '['; | |
| case value_t::object: | |
| return '{'; | |
| case value_t::discarded: | |
| default: // discarded values | |
| return 'N'; | |
| } | |
| } | |
| /*! | |
| @brief whether BJData forbids @a marker as the type of an optimized array | |
| or object | |
| Containers, strings, high-precision numbers, booleans and null cannot be | |
| declared as the single type of an optimized container in BJData; such a | |
| container is written unoptimized. The reader rejects them with the same | |
| list (binary_reader::is_bjd_excluded_optimized_type()). | |
| */ | |
| static constexpr bool is_bjdata_excluded_type_marker(const CharType marker) noexcept | |
| { | |
| return marker == '[' || marker == '{' || marker == 'S' || marker == 'H' | |
| || marker == 'T' || marker == 'F' || marker == 'N' || marker == 'Z'; | |
| } | |
| /// @return the UBJSON/BJData type marker for a float or double value | |
| /// | |
| /// number_float_t must be float or double; a static_assert (rather than | |
| /// an ambiguous overload) reports an unsupported number_float_t clearly. | |
| template<typename FloatType> | |
| static constexpr CharType get_ubjson_float_prefix() | |
| { | |
| static_assert(std::is_same<FloatType, float>::value || std::is_same<FloatType, double>::value, | |
| "number_float_t must be float or double for the UBJSON/BJData writer"); | |
| return std::is_same<FloatType, float>::value ? 'd' : 'D'; // float 32 / float 64 | |
| } | |
| /*! | |
| @brief checks whether a JSON number fits into @a TargetType | |
| @param[in] el a JSON number of either the signed or unsigned integer kind | |
| @return whether @a el's value can be represented by @a TargetType without | |
| wrapping, regardless of which of the two kinds it is stored as; | |
| false for a value that does not even fit the 64-bit type it is | |
| read as (possible for number types wider than 64 bits) | |
| */ | |
| template<typename TargetType> | |
| static bool bjdata_ndarray_value_in_range(const BasicJsonType& el) | |
| { | |
| return el.is_number_unsigned() | |
| ? integer_fits_max<std::uint64_t>(el.m_data.m_value.number_unsigned) && value_in_range_of<TargetType>(static_cast<std::uint64_t>(el.m_data.m_value.number_unsigned)) | |
| : integer_fits<std::int64_t>(el.m_data.m_value.number_integer) && value_in_range_of<TargetType>(static_cast<std::int64_t>(el.m_data.m_value.number_integer)); | |
| } | |
| /*! | |
| @brief look up the BJData ND-array dtype marker for an `_ArrayType_` name | |
| @return the one-character marker, or '\0' if @a name does not name a known dtype | |
| A C++11 `constexpr` function cannot contain a `switch`, so this is a plain | |
| comparison chain instead; it is only reached once per ND-array candidate | |
| object. Keep in sync with binary_reader's `bjd_type_name()`, which maps | |
| the other way. | |
| */ | |
| static CharType bjdata_ndarray_type_marker(const string_t& name) | |
| { | |
| if (name == "uint8") | |
| { | |
| return 'U'; | |
| } | |
| if (name == "int8") | |
| { | |
| return 'i'; | |
| } | |
| if (name == "uint16") | |
| { | |
| return 'u'; | |
| } | |
| if (name == "int16") | |
| { | |
| return 'I'; | |
| } | |
| if (name == "uint32") | |
| { | |
| return 'm'; | |
| } | |
| if (name == "int32") | |
| { | |
| return 'l'; | |
| } | |
| if (name == "uint64") | |
| { | |
| return 'M'; | |
| } | |
| if (name == "int64") | |
| { | |
| return 'L'; | |
| } | |
| if (name == "single") | |
| { | |
| return 'd'; | |
| } | |
| if (name == "double") | |
| { | |
| return 'D'; | |
| } | |
| if (name == "char") | |
| { | |
| return 'C'; | |
| } | |
| if (name == "byte") | |
| { | |
| return 'B'; | |
| } | |
| return '\0'; | |
| } | |
| /*! | |
| @brief validate (dry_run) or write one BJData ND-array element of integer dtype @a T | |
| @return whether @a el's value is in range of @a T; always true when @a dry_run is false | |
| */ | |
| template<typename T> | |
| bool write_bjdata_ndarray_element(const BasicJsonType& el, const bool dry_run) | |
| { | |
| if (dry_run) | |
| { | |
| return bjdata_ndarray_value_in_range<T>(el); | |
| } | |
| using storage_type = typename std::conditional<std::is_unsigned<T>::value, std::uint64_t, std::int64_t>::type; | |
| write_number(static_cast<T>(el.template get<storage_type>()), true); | |
| return true; | |
| } | |
| /*! | |
| @brief validate (dry_run) or write one BJData ND-array element of dtype 'd' (single precision) | |
| @return whether @a el's value survives narrowing to float and back without any change | |
| (so the ND-array round-trips exactly), or is infinite or NaN; always true when | |
| @a dry_run is false | |
| */ | |
| bool write_bjdata_ndarray_float_element(const BasicJsonType& el, const bool dry_run) | |
| { | |
| const auto dval = static_cast<double>(el.m_data.m_value.number_float); | |
| if (dry_run) | |
| { | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") | |
| #endif | |
| // a value that would be rounded (rather than exactly represented) by the | |
| // narrowing to float is treated like an out-of-range integer element; this | |
| // is the same criterion write_compact_float() uses for CBOR/MessagePack | |
| const bool in_range = std::isnan(dval) || | |
| (dval >= static_cast<double>(std::numeric_limits<float>::lowest()) && | |
| dval <= static_cast<double>((std::numeric_limits<float>::max)()) && | |
| static_cast<double>(static_cast<float>(dval)) == dval) || | |
| std::isinf(dval); | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| return in_range; | |
| } | |
| write_number(static_cast<float>(dval), true); | |
| return true; | |
| } | |
| /*! | |
| @brief write the elements of an ND-array as the number kind @a dtype names | |
| (see @ref write_bjdata_ndarray), after they have been found to be | |
| in range by a dry run of @ref write_bjdata_ndarray_elements | |
| The elements are encoded in blocks into space reserved from the sink. | |
| */ | |
| void write_bjdata_ndarray_values(const BasicJsonType& array_data, const CharType dtype) | |
| { | |
| switch (dtype) | |
| { | |
| case 'U': | |
| case 'C': | |
| case 'B': | |
| write_bjdata_ndarray_block<std::uint8_t>(array_data); | |
| break; | |
| case 'i': | |
| write_bjdata_ndarray_block<std::int8_t>(array_data); | |
| break; | |
| case 'u': | |
| write_bjdata_ndarray_block<std::uint16_t>(array_data); | |
| break; | |
| case 'I': | |
| write_bjdata_ndarray_block<std::int16_t>(array_data); | |
| break; | |
| case 'm': | |
| write_bjdata_ndarray_block<std::uint32_t>(array_data); | |
| break; | |
| case 'l': | |
| write_bjdata_ndarray_block<std::int32_t>(array_data); | |
| break; | |
| case 'M': | |
| write_bjdata_ndarray_block<std::uint64_t>(array_data); | |
| break; | |
| case 'L': | |
| write_bjdata_ndarray_block<std::int64_t>(array_data); | |
| break; | |
| case 'd': | |
| write_bjdata_ndarray_block<float>(array_data); | |
| break; | |
| case 'D': | |
| default: | |
| // 'D' (double) already spans the full range of number_float_t | |
| write_bjdata_ndarray_block<double>(array_data); | |
| break; | |
| } | |
| } | |
| /// the value of an ND-array element that is an integer, as the integer type that @a T is converted from | |
| template<typename T> | |
| static T bjdata_ndarray_integer(const BasicJsonType& el, std::true_type /*is_integral*/) noexcept | |
| { | |
| using storage_type = typename std::conditional<std::is_unsigned<T>::value, std::uint64_t, std::int64_t>::type; | |
| return static_cast<T>(el.is_number_unsigned() | |
| ? static_cast<storage_type>(el.m_data.m_value.number_unsigned) | |
| : static_cast<storage_type>(el.m_data.m_value.number_integer)); | |
| } | |
| /// the value of an ND-array element that is a float | |
| template<typename T> | |
| static T bjdata_ndarray_integer(const BasicJsonType& el, std::false_type /*is_integral*/) noexcept | |
| { | |
| return static_cast<T>(static_cast<double>(el.m_data.m_value.number_float)); | |
| } | |
| /// write the elements of an ND-array as @a T, little-endian, in blocks | |
| template<typename T> | |
| void write_bjdata_ndarray_block(const BasicJsonType& array_data) | |
| { | |
| constexpr std::size_t per_block = max_reserve_size / sizeof(T); | |
| auto it = array_data.m_data.m_value.array->begin(); | |
| const auto end = array_data.m_data.m_value.array->end(); | |
| while (it != end) | |
| { | |
| CharType* const start = oa.reserve(per_block * sizeof(T)); | |
| CharType* out = start; | |
| for (std::size_t n = 0; n < per_block && it != end; ++n, ++it) | |
| { | |
| out = store_number(out, bjdata_ndarray_integer<T>(*it, std::is_integral<T>()), true); | |
| } | |
| oa.commit(static_cast<std::size_t>(out - start)); | |
| } | |
| } | |
| /*! | |
| @brief validate or write every element of a BJData ND-array's `_ArrayData_` | |
| @param[in] array_data the `_ArrayData_` array | |
| @param[in] dtype the ND-array dtype marker, as returned by bjdata_ndarray_type_marker() | |
| @param[in] dry_run true to only range-check each element, false to write it | |
| @return whether every element is in range for @a dtype (always true when @a dry_run is false) | |
| */ | |
| bool write_bjdata_ndarray_elements(const BasicJsonType& array_data, const CharType dtype, const bool dry_run) | |
| { | |
| if (!dry_run) | |
| { | |
| write_bjdata_ndarray_values(array_data, dtype); | |
| return true; | |
| } | |
| for (const auto& el : array_data) | |
| { | |
| bool ok = true; | |
| switch (dtype) | |
| { | |
| case 'U': | |
| case 'C': | |
| case 'B': | |
| ok = write_bjdata_ndarray_element<std::uint8_t>(el, dry_run); | |
| break; | |
| case 'i': | |
| ok = write_bjdata_ndarray_element<std::int8_t>(el, dry_run); | |
| break; | |
| case 'u': | |
| ok = write_bjdata_ndarray_element<std::uint16_t>(el, dry_run); | |
| break; | |
| case 'I': | |
| ok = write_bjdata_ndarray_element<std::int16_t>(el, dry_run); | |
| break; | |
| case 'm': | |
| ok = write_bjdata_ndarray_element<std::uint32_t>(el, dry_run); | |
| break; | |
| case 'l': | |
| ok = write_bjdata_ndarray_element<std::int32_t>(el, dry_run); | |
| break; | |
| case 'M': | |
| ok = write_bjdata_ndarray_element<std::uint64_t>(el, dry_run); | |
| break; | |
| case 'L': | |
| ok = write_bjdata_ndarray_element<std::int64_t>(el, dry_run); | |
| break; | |
| case 'd': | |
| ok = write_bjdata_ndarray_float_element(el, dry_run); | |
| break; | |
| case 'D': | |
| default: | |
| // 'D' (double) already spans the full range of number_float_t | |
| if (!dry_run) | |
| { | |
| write_number(el.template get<double>(), true); | |
| } | |
| break; | |
| } | |
| if (!ok) | |
| { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| /*! | |
| @return false if the object is successfully converted to a bjdata ndarray, true if the type or size is invalid | |
| */ | |
| bool write_bjdata_ndarray(const typename BasicJsonType::object_t& value, const bool use_count, const bool use_type, const bjdata_version_t bjdata_version) | |
| { | |
| const auto& array_type = value.at("_ArrayType_"); | |
| // the type name is looked up as a string below; a non-string | |
| // annotation (e.g. a number, null, or an array) cannot name a known | |
| // dtype, so it is treated the same as an unrecognized type name and | |
| // falls back to a plain object encoding instead of throwing | |
| // type_error.302 out of get<string_t>() | |
| if (!array_type.is_string()) | |
| { | |
| return true; | |
| } | |
| // use get<string_t>() instead of static_cast<string_t> to avoid an | |
| // ambiguous conversion under explicit instantiation on C++17 (see #4825) | |
| const CharType dtype = bjdata_ndarray_type_marker(array_type.template get<string_t>()); | |
| if (dtype == '\0') | |
| { | |
| return true; | |
| } | |
| // the 'B' (byte) marker is only defined from BJData Draft 3 onward; | |
| // emitting it under an earlier draft would produce a stream that an | |
| // earlier-draft reader rejects, so such an object falls back to a | |
| // plain object encoding instead (see the "Binary values" section of | |
| // the BJData documentation) | |
| if (dtype == 'B' && bjdata_version < bjdata_version_t::draft3) | |
| { | |
| return true; | |
| } | |
| const auto& array_size = value.at("_ArraySize_"); | |
| // the dimensions are written verbatim as the header length below, so a | |
| // value that is not an array cannot produce a valid one: null emits 'Z' | |
| // and an object emits '{', neither of which a reader accepts after '#'. | |
| // Such an object is not a valid ndarray and falls back to a plain object. | |
| if (!array_size.is_array()) | |
| { | |
| return true; | |
| } | |
| // the reader only restores an annotated object from an ND-array header | |
| // with at least two dimensions: an empty dimension vector, a single | |
| // dimension, or a 1xN row vector is read back as a plain array, which | |
| // would silently drop the annotation, so such an object falls back to | |
| // a plain object encoding instead | |
| const auto& dims = array_size; | |
| if (dims.size() < 2 || (dims.size() == 2 && dims.at(0).is_number_integer() && dims.at(0).template get<std::int64_t>() == 1)) | |
| { | |
| return true; | |
| } | |
| std::size_t len = 1; | |
| for (const auto& el : dims) | |
| { | |
| // a dimension is read as an unsigned value below, so anything that | |
| // is not a non-negative integer in the range of std::uint64_t is | |
| // rejected: a non-integer entry would pun unrelated bytes as the | |
| // dimension, and a negative or wider one would wrap into a | |
| // nonsensical length | |
| if (!el.is_number_integer() || !bjdata_ndarray_value_in_range<std::uint64_t>(el)) | |
| { | |
| return true; | |
| } | |
| // a dimension that does not fit into std::size_t, or a product that | |
| // overflows it, would wrap around and could match the size of | |
| // _ArrayData_ by accident; the resulting header announces an | |
| // element count that no reader can honor (the binary reader rejects | |
| // it with out_of_range.408), so encode as a plain object instead | |
| const auto dim = el.template get<std::uint64_t>(); | |
| if (!value_in_range_of<std::size_t>(dim)) | |
| { | |
| return true; | |
| } | |
| const auto dim_size = static_cast<std::size_t>(dim); | |
| // the reader turns an ND-array with any zero dimension into an | |
| // empty plain array, dropping the annotation, so keep the object | |
| if (dim_size == 0) | |
| { | |
| return true; | |
| } | |
| if (len > (std::numeric_limits<std::size_t>::max)() / dim_size) | |
| { | |
| return true; | |
| } | |
| len *= dim_size; | |
| } | |
| // the elements are written from _ArrayData_ as a flat list, so it has | |
| // to be an array: size() is 0 for null and 1 for any other scalar, and | |
| // iterating an object visits its values, so any of these could match | |
| // the dimensions by accident and be encoded as an unrelated ND-array | |
| const auto& array_data = value.at("_ArrayData_"); | |
| if (!array_data.is_array() || array_data.size() != len) | |
| { | |
| return true; | |
| } | |
| // every element is written below as the number kind dtype names, so it | |
| // has to actually be a number of that category: an element of any other | |
| // type would reinterpret unrelated bytes, e.g. a string's heap pointer, | |
| // as that number. Such an object falls back to a plain object encoding. | |
| // dtype names the wire type, not the storage type: whether an integer | |
| // is held as number_integer or number_unsigned depends on how the value | |
| // was built (parsing stores non-negative integers as unsigned, the C++ | |
| // API stores int literals as signed), so both are accepted here and the | |
| // writes below go through get<>, which reads the member that is active. | |
| const bool ndarray_is_float = (dtype == 'd' || dtype == 'D'); | |
| for (const auto& el : array_data) | |
| { | |
| if (ndarray_is_float ? !el.is_number_float() : !el.is_number_integer()) | |
| { | |
| return true; | |
| } | |
| } | |
| // every element is cast to the (possibly narrower) C++ type matching | |
| // dtype below; a value that does not fit that type would silently | |
| // wrap (integers) or overflow to infinity (the "single" precision | |
| // float) instead of being reported, so such an object falls back to | |
| // a plain object encoding as well | |
| if (!write_bjdata_ndarray_elements(array_data, dtype, true)) | |
| { | |
| return true; | |
| } | |
| oa.write_character(to_char_type('[')); | |
| oa.write_character(to_char_type('$')); | |
| oa.write_character(dtype); | |
| oa.write_character(to_char_type('#')); | |
| write_ubjson(array_size, use_count, use_type, true, true, bjdata_version); | |
| write_bjdata_ndarray_elements(array_data, dtype, false); | |
| return false; | |
| } | |
| ////////// | |
| // BON8 // | |
| ////////// | |
| /*! | |
| @brief write a BON8 value | |
| A string is written without length or terminator: it ends at the first | |
| byte that cannot continue it, which is the first byte of any non-string | |
| value and of the end-of-container marker 0xFE. It only needs an explicit | |
| end-of-string marker (0xFF) when it is empty, when another string follows, | |
| or when it is the last thing in the message. | |
| @param[in] j JSON value to serialize | |
| @param[in,out] string_open whether the output ends with a non-empty | |
| string that has not been terminated with 0xFF | |
| @param[in] depth nesting level of @a j, counted from the | |
| top-level value passed to @ref basic_json::to_bon8 | |
| @throw type_error.316 if a string value or an object key is not valid | |
| UTF-8 | |
| @throw out_of_range.407 if an unsigned integer does not fit int64 | |
| @throw type_error.321 if @a j or a value nested in it is discarded | |
| Values nested deeper than @ref recursion_depth_limit are written by | |
| @ref write_bon8_iterative without the call stack. | |
| @sa @ref write_cbor | |
| @sa https://github.com/nlohmann/json/issues/5392 | |
| */ | |
| void write_bon8_value(const BasicJsonType& j, bool& string_open, const std::size_t depth = 0) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(depth >= recursion_depth_limit()) && (j.is_array() || j.is_object())) | |
| { | |
| write_bon8_iterative(j, string_open); | |
| return; | |
| } | |
| switch (j.type()) | |
| { | |
| case value_t::null: | |
| { | |
| write_bon8_marker(0xFA, string_open); | |
| break; | |
| } | |
| case value_t::boolean: | |
| { | |
| write_bon8_marker(j.m_data.m_value.boolean ? 0xF9 : 0xF8, string_open); | |
| break; | |
| } | |
| case value_t::number_unsigned: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!integer_fits_max<std::int64_t>(j.m_data.m_value.number_unsigned))) | |
| { | |
| throw_integer_out_of_range(j, input_format_t::bon8, "int64"); | |
| } | |
| write_bon8_integer(static_cast<std::int64_t>(j.m_data.m_value.number_unsigned)); | |
| string_open = false; | |
| break; | |
| } | |
| case value_t::number_integer: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!integer_fits<std::int64_t>(j.m_data.m_value.number_integer))) | |
| { | |
| throw_integer_out_of_range(j, input_format_t::bon8, "int64"); | |
| } | |
| write_bon8_integer(static_cast<std::int64_t>(j.m_data.m_value.number_integer)); | |
| string_open = false; | |
| break; | |
| } | |
| case value_t::number_float: | |
| { | |
| write_bon8_float(j.m_data.m_value.number_float); | |
| string_open = false; | |
| break; | |
| } | |
| case value_t::string: | |
| { | |
| write_bon8_string(*j.m_data.m_value.string, string_open, j); | |
| break; | |
| } | |
| case value_t::array: | |
| { | |
| const auto N = j.m_data.m_value.array->size(); | |
| // 0x80..0x84: array with 0..4 elements; 0x85: array ended by 0xFE | |
| write_bon8_marker(static_cast<std::uint8_t>(N <= 4 ? 0x80 + N : 0x85), string_open); | |
| if (N != 0 && j.m_data.m_value.array->front().is_number()) | |
| { | |
| write_bon8_array_elements(*j.m_data.m_value.array, string_open, depth); | |
| } | |
| else | |
| { | |
| for (const auto& el : *j.m_data.m_value.array) | |
| { | |
| write_bon8_value(el, string_open, depth + 1); | |
| } | |
| } | |
| if (N > 4) | |
| { | |
| write_bon8_marker(0xFE, string_open); | |
| } | |
| break; | |
| } | |
| case value_t::object: | |
| { | |
| const auto N = j.m_data.m_value.object->size(); | |
| // 0x86..0x8A: object with 0..4 members; 0x8B: object ended by 0xFE | |
| write_bon8_marker(static_cast<std::uint8_t>(N <= 4 ? 0x86 + N : 0x8B), string_open); | |
| write_bon8_members(j, string_open, depth); | |
| if (N > 4) | |
| { | |
| write_bon8_marker(0xFE, string_open); | |
| } | |
| break; | |
| } | |
| case value_t::binary: | |
| { | |
| write_bon8_binary(*j.m_data.m_value.binary, string_open); | |
| break; | |
| } | |
| case value_t::discarded: | |
| default: | |
| throw_on_discarded(j, input_format_t::bon8); | |
| } | |
| } | |
| /*! | |
| @brief write @a j with @ref write_bon8_value, or write its marker and push | |
| a frame for @ref write_bon8_iterative to continue with its elements | |
| A scalar, and an empty array or object, are written out in full and not | |
| pushed. | |
| @sa @ref write_container_value_or_push | |
| */ | |
| void write_bon8_value_or_push(const BasicJsonType& j, bool& string_open, std::vector<binary_container_frame>& stack) | |
| { | |
| if (j.is_array() || j.is_object()) | |
| { | |
| // arrays use the markers 0x80..0x85, objects 0x86..0x8B; the last | |
| // one stands for more than four elements, closed later with 0xFE | |
| const auto N = j.size(); | |
| const std::size_t base = j.is_array() ? 0x80 : 0x86; | |
| write_bon8_marker(static_cast<std::uint8_t>(base + (N <= 4 ? N : 5)), string_open); | |
| if (N != 0) | |
| { | |
| stack.emplace_back(&j); | |
| } | |
| return; | |
| } | |
| write_bon8_value(j, string_open); | |
| } | |
| /*! | |
| @brief write out @a root and everything below it without the call stack | |
| A container with more than four elements is closed with 0xFE once its | |
| last element is written, as in @ref write_bon8_value. | |
| @sa @ref write_cbor_iterative | |
| */ | |
| void write_bon8_iterative(const BasicJsonType& root, bool& string_open) | |
| { | |
| // only a container with elements is ever pushed; see write_bon8_value_or_push | |
| std::vector<binary_container_frame> stack; | |
| write_bon8_value_or_push(root, string_open, stack); | |
| while (!stack.empty()) | |
| { | |
| const binary_container_frame current = stack.back(); | |
| const bool is_array = current.value->is_array(); | |
| const bool at_end = is_array | |
| ? current.array_it == current.value->m_data.m_value.array->cend() | |
| : current.object_it == current.value->m_data.m_value.object->cend(); | |
| if (at_end) | |
| { | |
| if (current.value->size() > 4) | |
| { | |
| write_bon8_marker(0xFE, string_open); | |
| } | |
| stack.pop_back(); | |
| continue; | |
| } | |
| // read the child before pushing: entering it can move every frame | |
| const BasicJsonType* child = nullptr; | |
| if (is_array) | |
| { | |
| child = &(*current.array_it); | |
| ++stack.back().array_it; | |
| } | |
| else | |
| { | |
| write_bon8_string(current.object_it->first, string_open, *current.value); | |
| child = &(current.object_it->second); | |
| ++stack.back().object_it; | |
| } | |
| write_bon8_value_or_push(*child, string_open, stack); | |
| } | |
| } | |
| /*! | |
| @brief encode an integer as @ref write_bon8_integer writes it | |
| @param[in] out where the encoding goes; at most 9 characters are written | |
| @return the end of the encoding | |
| */ | |
| CharType* encode_bon8_integer(CharType* out, std::int64_t value) const noexcept | |
| { | |
| if (value < (std::numeric_limits<std::int32_t>::min)() || value > (std::numeric_limits<std::int32_t>::max)()) | |
| { | |
| *out++ = to_char_type(0x8D); | |
| return store_number(out, value, false); | |
| } | |
| if (value < -33818506 || value > 67637031) | |
| { | |
| *out++ = to_char_type(0x8C); | |
| return store_number(out, static_cast<std::int32_t>(value), false); | |
| } | |
| if (value <= -264075) | |
| { | |
| value = -(value + 264075); | |
| return put_bon8_bytes(out, 0xF0 + ((value >> 22) & 0x07), 0xC0 + ((value >> 16) & 0x3F), value >> 8, value); | |
| } | |
| if (value <= -1931) | |
| { | |
| value = -(value + 1931); | |
| return put_bon8_bytes(out, 0xE0 + ((value >> 14) & 0x0F), 0xC0 + ((value >> 8) & 0x3F), value); | |
| } | |
| if (value <= -11) | |
| { | |
| value = -(value + 11); | |
| return put_bon8_bytes(out, 0xC2 + ((value >> 6) & 0x1F), 0xC0 + (value & 0x3F)); | |
| } | |
| if (value <= -1) | |
| { | |
| return put_bon8_bytes(out, 0xB8 - (value + 1)); | |
| } | |
| if (value <= 39) | |
| { | |
| return put_bon8_bytes(out, 0x90 + value); | |
| } | |
| if (value <= 3879) | |
| { | |
| value -= 40; | |
| return put_bon8_bytes(out, 0xC2 + ((value >> 7) & 0x1F), value & 0x7F); | |
| } | |
| if (value <= 528167) | |
| { | |
| value -= 3880; | |
| return put_bon8_bytes(out, 0xE0 + ((value >> 15) & 0x0F), (value >> 8) & 0x7F, value); | |
| } | |
| value -= 528168; | |
| return put_bon8_bytes(out, 0xF0 + ((value >> 23) & 0x07), (value >> 16) & 0x7F, value >> 8, value); | |
| } | |
| /// store the low byte of each argument at @a out; return the end | |
| template<typename... Bytes> | |
| CharType* put_bon8_bytes(CharType* out, const Bytes... bytes) const noexcept | |
| { | |
| const std::array<CharType, sizeof...(Bytes)> buffer{{to_char_type(static_cast<std::uint8_t>(bytes & 0xFF))...}}; | |
| std::memcpy(out, buffer.data(), buffer.size()); | |
| return out + buffer.size(); | |
| } | |
| /*! | |
| @brief encode a float as @ref write_bon8_float writes it | |
| @param[in] out where the encoding goes; at most 9 characters are written | |
| @return the end of the encoding | |
| */ | |
| CharType* encode_bon8_float(CharType* out, const number_float_t n) const noexcept | |
| { | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") | |
| #endif | |
| if (n == static_cast<number_float_t>(-1)) | |
| { | |
| *out++ = to_char_type(0xFB); | |
| return out; | |
| } | |
| if (n == static_cast<number_float_t>(0) && !std::signbit(n)) | |
| { | |
| *out++ = to_char_type(0xFC); | |
| return out; | |
| } | |
| if (n == static_cast<number_float_t>(1)) | |
| { | |
| *out++ = to_char_type(0xFD); | |
| return out; | |
| } | |
| if (std::isnan(n)) | |
| { | |
| return put_bon8_bytes(out, 0x8E, 0x7F, 0x80, 0x00, 0x01); | |
| } | |
| return out + encode_compact_float(out, n, to_char_type(0x8E), to_char_type(0x8F)); | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| } | |
| /*! | |
| @brief write the elements of an array that starts with a number, with runs | |
| of numbers encoded without a call of @ref write_bon8_value for each | |
| Same output as calling write_bon8_value for each element. The numbers of a | |
| run are encoded into space reserved from the sink, as in | |
| @ref write_array_elements; an integer that BON8 cannot write (an unsigned | |
| one above the int64 range, or one of a number type wider than 64 bits) throws | |
| from write_bon8_value, like any other value that is not a number. Kept out | |
| of line, like @ref write_cbor_array. | |
| */ | |
| template<typename ArrayType> | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_bon8_array_elements(const ArrayType& array, bool& string_open, const std::size_t depth) | |
| { | |
| constexpr std::size_t max_run = max_reserve_size / 9; | |
| auto it = array.begin(); | |
| const auto end = array.end(); | |
| while (it != end) | |
| { | |
| if (!it->is_number()) | |
| { | |
| write_bon8_value(*it, string_open, depth + 1); | |
| ++it; | |
| continue; | |
| } | |
| CharType* const start = oa.reserve(max_run * 9); | |
| CharType* out = start; | |
| bool unencodable = false; | |
| for (std::size_t n = 0; n < max_run && it != end && it->is_number(); ++n) | |
| { | |
| if (it->is_number_float()) | |
| { | |
| out = encode_bon8_float(out, it->m_data.m_value.number_float); | |
| } | |
| else if (JSON_HEDLEY_UNLIKELY((it->m_data.m_type == value_t::number_unsigned | |
| && !integer_fits_max<std::int64_t>(it->m_data.m_value.number_unsigned)) | |
| || (it->m_data.m_type == value_t::number_integer | |
| && !integer_fits<std::int64_t>(it->m_data.m_value.number_integer)))) | |
| { | |
| unencodable = true; | |
| break; | |
| } | |
| else | |
| { | |
| out = encode_bon8_integer(out, it->m_data.m_type == value_t::number_integer | |
| ? static_cast<std::int64_t>(it->m_data.m_value.number_integer) | |
| : static_cast<std::int64_t>(it->m_data.m_value.number_unsigned)); | |
| } | |
| ++it; | |
| } | |
| oa.commit(static_cast<std::size_t>(out - start)); | |
| if (out != start) | |
| { | |
| // a number follows a string without terminating it | |
| string_open = false; | |
| } | |
| if (unencodable) | |
| { | |
| write_bon8_value(*it, string_open, depth + 1); | |
| ++it; | |
| } | |
| } | |
| } | |
| /*! | |
| @brief write the members of the object @a j as BON8 | |
| A member whose value is null, a boolean, a number, or a string is written | |
| without a call of @ref write_bon8_value. Kept out of line, like | |
| @ref write_cbor_object. | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_bon8_members(const BasicJsonType& j, bool& string_open, const std::size_t depth) | |
| { | |
| for (const auto& el : *j.m_data.m_value.object) | |
| { | |
| write_bon8_string(el.first, string_open, j); | |
| const BasicJsonType& value = el.second; | |
| switch (value.type()) | |
| { | |
| case value_t::null: | |
| write_bon8_marker(0xFA, string_open); | |
| break; | |
| case value_t::boolean: | |
| write_bon8_marker(value.m_data.m_value.boolean ? 0xF9 : 0xF8, string_open); | |
| break; | |
| case value_t::string: | |
| write_bon8_string(*value.m_data.m_value.string, string_open, value); | |
| break; | |
| case value_t::number_integer: | |
| if (JSON_HEDLEY_LIKELY(integer_fits<std::int64_t>(value.m_data.m_value.number_integer))) | |
| { | |
| write_bon8_integer(static_cast<std::int64_t>(value.m_data.m_value.number_integer)); | |
| string_open = false; | |
| break; | |
| } | |
| // beyond 64 bits (number types wider than that): throws | |
| write_bon8_value(value, string_open, depth + 1); | |
| break; | |
| case value_t::number_float: | |
| write_bon8_float(value.m_data.m_value.number_float); | |
| string_open = false; | |
| break; | |
| case value_t::number_unsigned: | |
| if (JSON_HEDLEY_LIKELY(integer_fits_max<std::int64_t>(value.m_data.m_value.number_unsigned))) | |
| { | |
| write_bon8_integer(static_cast<std::int64_t>(value.m_data.m_value.number_unsigned)); | |
| string_open = false; | |
| break; | |
| } | |
| // too large for BON8: throws | |
| write_bon8_value(value, string_open, depth + 1); | |
| break; | |
| case value_t::object: | |
| case value_t::array: | |
| case value_t::binary: | |
| case value_t::discarded: | |
| default: | |
| write_bon8_value(value, string_open, depth + 1); | |
| break; | |
| } | |
| } | |
| } | |
| /*! | |
| @brief write a binary value as BON8 | |
| BON8 has no binary type: the bytes are written as an array of integers, | |
| like UBJSON and BJData do. Kept out of line, so that write_bon8_value does | |
| not carry the registers of its loop. | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE | |
| void write_bon8_binary(const binary_t& binary, bool& string_open) | |
| { | |
| const auto N = binary.size(); | |
| write_bon8_marker(static_cast<std::uint8_t>(N <= 4 ? 0x80 + N : 0x85), string_open); | |
| // a byte is an integer of 0 to 255: one byte up to 39, two bytes above | |
| const auto* const data = binary.data(); | |
| for (std::size_t i = 0; i < N;) | |
| { | |
| const std::size_t block = (std::min)(N - i, max_reserve_size / 2); | |
| CharType* const start = oa.reserve(2 * block); | |
| CharType* out = start; | |
| for (std::size_t k = 0; k < block; ++k, ++i) | |
| { | |
| // the cast is needed for binary types whose value type | |
| // is not an integer (e.g., std::byte) | |
| const auto value = static_cast<unsigned>(static_cast<std::uint8_t>(data[i])); | |
| // both bytes are stored, the second only counts for a value above 39: | |
| // 0xC2 + ((value - 40) >> 7), (value - 40) & 0x7F | |
| const unsigned wide = value - 40u; | |
| const bool is_wide = value > 39u; | |
| out[0] = to_char_type(static_cast<std::uint8_t>(is_wide ? 0xC2u + (wide >> 7u) : 0x90u + value)); | |
| out[1] = to_char_type(static_cast<std::uint8_t>(wide & 0x7Fu)); | |
| out += is_wide ? 2 : 1; | |
| } | |
| oa.commit(static_cast<std::size_t>(out - start)); | |
| } | |
| if (N > 4) | |
| { | |
| write_bon8_marker(0xFE, string_open); | |
| } | |
| } | |
| /*! | |
| @brief write a single byte that is not part of a string | |
| @param[in] marker the byte to write | |
| @param[out] string_open set to false, because the output no longer ends | |
| with a string; see @ref write_bon8_value | |
| */ | |
| void write_bon8_marker(const std::uint8_t marker, bool& string_open) | |
| { | |
| oa.write_character(to_char_type(marker)); | |
| string_open = false; | |
| } | |
| /*! | |
| @brief write a string | |
| @param[in] s the string to write | |
| @param[in,out] string_open see @ref write_bon8_value | |
| @param[in] context the value the string belongs to (for diagnostics) | |
| @throw type_error.316 if @a s is not valid UTF-8, because the end of a | |
| string is determined from its encoding | |
| */ | |
| void write_bon8_string(const string_t& s, bool& string_open, const BasicJsonType& context) | |
| { | |
| check_utf8(s, context); | |
| // a string that follows another string terminates it | |
| if (string_open) | |
| { | |
| oa.write_character(to_char_type(0xFF)); | |
| } | |
| if (s.empty()) | |
| { | |
| // the empty string is just the end-of-string marker | |
| oa.write_character(to_char_type(0xFF)); | |
| string_open = false; | |
| } | |
| else | |
| { | |
| write_bytes(s.data(), s.size()); | |
| string_open = true; | |
| } | |
| } | |
| /*! | |
| @brief check that a string is valid UTF-8 (RFC 3629) | |
| @param[in] s the string to check | |
| @param[in] context the value the string belongs to (for diagnostics) | |
| @throw type_error.316 if @a s is not valid UTF-8; the message names the | |
| first byte of the first invalid or incomplete sequence | |
| */ | |
| static void check_utf8(const string_t& s, const BasicJsonType& context) | |
| { | |
| const auto* data = reinterpret_cast<const unsigned char*>(s.data()); | |
| const std::size_t valid = valid_utf8_prefix(data, s.size()); | |
| if (JSON_HEDLEY_UNLIKELY(valid != s.size())) | |
| { | |
| throw_invalid_utf8(data, valid, context); | |
| } | |
| } | |
| /// @brief throw type_error.316 for the invalid byte at @a index of @a data; | |
| /// out of line, so that the message does not burden check_utf8() | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_invalid_utf8(const unsigned char* data, const std::size_t index, const BasicJsonType& context) | |
| { | |
| static_cast<void>(data); // only used when exceptions are enabled | |
| static_cast<void>(index); | |
| static_cast<void>(context); | |
| JSON_THROW(type_error::create(exception_id::invalid_utf8, concat("invalid UTF-8 byte at index ", std::to_string(index), ": 0x", detail::hex_byte(data[index])), &context)); | |
| } | |
| /*! | |
| @brief return @a s as it should be written, honoring @ref error_handler | |
| Used by @ref write_cbor, @ref write_msgpack, @ref write_ubjson (and so | |
| @ref write_bjdata), and the BSON writing functions for string values and | |
| object keys; never by @ref write_bon8, which always validates, since UTF-8 | |
| lead bytes are structural there. | |
| - @ref error_handler_t::keep: @a s is returned unchanged, without even | |
| checking it (the behavior of release 3.12.0 and earlier). | |
| - @ref error_handler_t::strict: @ref check_utf8 is called, which throws | |
| type_error.316 if @a s is not valid UTF-8. | |
| - @ref error_handler_t::replace / @ref error_handler_t::ignore: @a s is | |
| sanitized into @a storage with exactly the rules @ref | |
| serializer::dump_escaped_impl uses, so that parsing what @ref | |
| basic_json::dump produces for the same string and the same handler | |
| yields the same result. | |
| Well-formed input is never copied: this returns a reference to @a s | |
| itself in every case but a sanitized `replace`/`ignore` one, so @a | |
| storage must outlive the returned reference only then. | |
| @a s must be an lvalue that outlives the returned reference. An object key | |
| whose `key_type` is not @ref string_t must therefore first be converted | |
| into a named string_t (see @ref object_key_string_t); the deleted overload | |
| below enforces this at compile time. | |
| @param[in] s the string (value or object key) to write | |
| @param[in] context the value @a s belongs to (for diagnostics) | |
| @param[out] storage backing storage for a sanitized copy | |
| @return a reference to @a s, or to @a storage once it holds a sanitized copy | |
| */ | |
| const string_t& sanitize_utf8_for_write(const string_t& s, const BasicJsonType& context, string_t& storage) const | |
| { | |
| switch (error_handler) | |
| { | |
| case error_handler_t::keep: | |
| return s; // NOLINT(bugprone-return-const-ref-from-parameter): callers pass lvalues that outlive the call | |
| case error_handler_t::strict: | |
| check_utf8(s, context); | |
| return s; // NOLINT(bugprone-return-const-ref-from-parameter): callers pass lvalues that outlive the call | |
| case error_handler_t::replace: | |
| case error_handler_t::ignore: | |
| default: | |
| if (is_valid_utf8(s)) | |
| { | |
| return s; // NOLINT(bugprone-return-const-ref-from-parameter): callers pass lvalues that outlive the call | |
| } | |
| storage = sanitize_utf8(s, error_handler); | |
| return storage; | |
| } | |
| } | |
| /*! | |
| @brief the write-pass counterpart of @ref sanitize_utf8_for_write for BSON | |
| The size pass (@ref calc_bson_entry_header_size, @ref | |
| calc_bson_string_size) has already validated @a s, and thrown for @ref | |
| error_handler_t::strict if it was ill-formed. Here, @ref | |
| error_handler_t::strict therefore behaves like @ref error_handler_t::keep, | |
| and @ref error_handler_t::replace / @ref error_handler_t::ignore produce | |
| exactly the bytes the size pass measured. Hence no context is needed. | |
| @param[in] s the string (value or object key) to write | |
| @param[out] storage backing storage for a sanitized copy | |
| @return a reference to @a s, or to @a storage once it holds a sanitized copy | |
| */ | |
| const string_t& sanitize_utf8_for_bson_write(const string_t& s, string_t& storage) const | |
| { | |
| if (error_handler == error_handler_t::keep || error_handler == error_handler_t::strict || is_valid_utf8(s)) | |
| { | |
| return s; // NOLINT(bugprone-return-const-ref-from-parameter): callers pass lvalues that outlive the call | |
| } | |
| storage = sanitize_utf8(s, error_handler); | |
| return storage; | |
| } | |
| /// deleted: anything but a string_t would bind a temporary that dies before the returned reference is used | |
| template < typename T, enable_if_t < !std::is_same<T, string_t>::value, int > = 0 > | |
| const string_t& sanitize_utf8_for_write(const T& /*s*/, const BasicJsonType& /*context*/, string_t& /*storage*/) const = delete; // NOLINT(hicpp-use-equals-delete,modernize-use-equals-delete): a private helper's guard, not part of the interface | |
| /*! | |
| @brief write an integer in the shortest encoding | |
| Integers from -10 to 39 take one byte. Up to -33818506 and 67637031, an | |
| integer takes 2 to 4 bytes that begin with a UTF-8 lead byte (0xC2..0xF7) | |
| followed by a byte that is not a continuation byte: 0x00..0x7F for | |
| positive and 0xC0..0xFF for negative integers. Each range starts where the | |
| shorter one ends. Larger integers are written as int32 (0x8C) or int64 | |
| (0x8D) in big-endian byte order. | |
| @param[in] value the integer to write | |
| */ | |
| void write_bon8_integer(std::int64_t value) | |
| { | |
| if (value < (std::numeric_limits<std::int32_t>::min)() || value > (std::numeric_limits<std::int32_t>::max)()) | |
| { | |
| oa.write_character(to_char_type(0x8D)); | |
| write_number(value); | |
| } | |
| else if (value < -33818506 || value > 67637031) | |
| { | |
| oa.write_character(to_char_type(0x8C)); | |
| write_number(static_cast<std::int32_t>(value)); | |
| } | |
| else if (value <= -264075) | |
| { | |
| value = -(value + 264075); | |
| write_bon8_bytes(0xF0 + ((value >> 22) & 0x07), 0xC0 + ((value >> 16) & 0x3F), value >> 8, value); | |
| } | |
| else if (value <= -1931) | |
| { | |
| value = -(value + 1931); | |
| write_bon8_bytes(0xE0 + ((value >> 14) & 0x0F), 0xC0 + ((value >> 8) & 0x3F), value); | |
| } | |
| else if (value <= -11) | |
| { | |
| value = -(value + 11); | |
| write_bon8_bytes(0xC2 + ((value >> 6) & 0x1F), 0xC0 + (value & 0x3F)); | |
| } | |
| else if (value <= -1) | |
| { | |
| write_bon8_bytes(0xB8 - (value + 1)); | |
| } | |
| else if (value <= 39) | |
| { | |
| write_bon8_bytes(0x90 + value); | |
| } | |
| else if (value <= 3879) | |
| { | |
| value -= 40; | |
| write_bon8_bytes(0xC2 + ((value >> 7) & 0x1F), value & 0x7F); | |
| } | |
| else if (value <= 528167) | |
| { | |
| value -= 3880; | |
| write_bon8_bytes(0xE0 + ((value >> 15) & 0x0F), (value >> 8) & 0x7F, value); | |
| } | |
| else | |
| { | |
| value -= 528168; | |
| write_bon8_bytes(0xF0 + ((value >> 23) & 0x07), (value >> 16) & 0x7F, value >> 8, value); | |
| } | |
| } | |
| /// write the low byte of each argument | |
| template<typename... Bytes> | |
| void write_bon8_bytes(const Bytes... bytes) | |
| { | |
| const std::array<CharType, sizeof...(Bytes)> buffer{{to_char_type(static_cast<std::uint8_t>(bytes & 0xFF))...}}; | |
| oa.write_characters(buffer.data(), buffer.size()); | |
| } | |
| /*! | |
| @brief write a floating-point number | |
| -1.0, +0.0, and 1.0 take one byte. Other numbers are written as binary32 | |
| (0x8E) if that loses no precision, and as binary64 (0x8F) otherwise; -0.0, | |
| infinities, and NaN are always written as binary32, NaN as 0x7F800001. | |
| @param[in] n the number to write | |
| */ | |
| void write_bon8_float(const number_float_t n) | |
| { | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") | |
| #endif | |
| if (n == static_cast<number_float_t>(-1)) | |
| { | |
| oa.write_character(to_char_type(0xFB)); | |
| } | |
| else if (n == static_cast<number_float_t>(0) && !std::signbit(n)) | |
| { | |
| oa.write_character(to_char_type(0xFC)); | |
| } | |
| else if (n == static_cast<number_float_t>(1)) | |
| { | |
| oa.write_character(to_char_type(0xFD)); | |
| } | |
| else if (std::isnan(n)) | |
| { | |
| write_bon8_bytes(0x8E, 0x7F, 0x80, 0x00, 0x01); | |
| } | |
| else | |
| { | |
| write_compact_float(n, to_char_type(0x8E), to_char_type(0x8F)); | |
| } | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| } | |
| /////////////////////// | |
| // Utility functions // | |
| /////////////////////// | |
| /*! | |
| @brief reverse the bytes of a buffer by byte-swapping it as UIntType | |
| Loading the buffer into an unsigned integer of the same width and swapping | |
| that is what lets the compiler emit a single bswap/rev/movbe; reversing the | |
| buffer element by element does not reliably get there (clang keeps a scalar | |
| shuffle). (The two memcpy calls, rather than bit_cast, keep GCC from | |
| inlining differently in C++20, which made writing slower.) | |
| */ | |
| template<typename UIntType, std::size_t N> | |
| static void byte_swap_buffer(std::array<CharType, N>& a) noexcept | |
| { | |
| static_assert(sizeof(UIntType) == N, "swap width must match the buffer size"); | |
| UIntType v{}; | |
| std::memcpy(&v, a.data(), sizeof(v)); | |
| v = byteswap(v); | |
| std::memcpy(a.data(), &v, sizeof(v)); | |
| } | |
| // reverse the bytes of a fixed-size buffer; a single byteswap() for the | |
| // common 2/4/8-byte number payloads, std::reverse for any other size | |
| static void reverse_bytes(std::array<CharType, 2>& a) noexcept | |
| { | |
| byte_swap_buffer<std::uint16_t>(a); | |
| } | |
| static void reverse_bytes(std::array<CharType, 4>& a) noexcept | |
| { | |
| byte_swap_buffer<std::uint32_t>(a); | |
| } | |
| static void reverse_bytes(std::array<CharType, 8>& a) noexcept | |
| { | |
| byte_swap_buffer<std::uint64_t>(a); | |
| } | |
| template<std::size_t N> | |
| static void reverse_bytes(std::array<CharType, N>& a) noexcept | |
| { | |
| std::reverse(a.begin(), a.end()); | |
| } | |
| /*! | |
| @brief write a number to the output | |
| @param[in] n number of type @a NumberType | |
| @param[in] OutputIsLittleEndian Set to true if output data is | |
| required to be little endian | |
| @tparam NumberType the type of the number | |
| @note This function needs to respect the system's endianness, because bytes | |
| in CBOR, MessagePack, UBJSON, and BON8 are stored in network order | |
| (big endian) and therefore need reordering on little endian systems. | |
| On the other hand, BSON and BJData use little endian and should | |
| reorder on big endian systems. | |
| */ | |
| template<typename NumberType> | |
| void write_number(const NumberType n, const bool OutputIsLittleEndian = false) | |
| { | |
| // step 1: write the number to an array of length NumberType | |
| std::array<CharType, sizeof(NumberType)> vec{}; | |
| std::memcpy(vec.data(), &n, sizeof(NumberType)); | |
| // step 2: write the array to output (with possible reordering) | |
| if (is_little_endian != OutputIsLittleEndian) | |
| { | |
| // reverse byte order prior to conversion if necessary | |
| reverse_bytes(vec); | |
| } | |
| oa.write_characters(vec.data(), sizeof(NumberType)); | |
| } | |
| /// whether @a n is written as a float32 by @ref write_compact_float | |
| static bool fits_float32(const number_float_t n) noexcept | |
| { | |
| static_assert(std::is_same<number_float_t, float>::value || std::is_same<number_float_t, double>::value, | |
| "number_float_t must be float or double for the CBOR/MessagePack/BON8 writer"); | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") | |
| #endif | |
| #if defined(__GNUC__) && !defined(__clang__) && (__GNUC__ >= 7) | |
| JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wduplicated-branches") | |
| #endif | |
| return !std::isfinite(n) || ((static_cast<double>(n) >= static_cast<double>(std::numeric_limits<float>::lowest()) && | |
| static_cast<double>(n) <= static_cast<double>((std::numeric_limits<float>::max)()) && | |
| static_cast<double>(static_cast<float>(n)) == static_cast<double>(n))); | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| } | |
| /*! | |
| @brief encode @a n to @a out as @ref write_compact_float writes it | |
| @return the number of characters, 5 or 9 | |
| */ | |
| std::size_t encode_compact_float(CharType* out, const number_float_t n, const CharType float32_marker, const CharType float64_marker) const noexcept | |
| { | |
| if (fits_float32(n)) | |
| { | |
| *out = float32_marker; | |
| store_number(out + 1, static_cast<float>(n), false); | |
| return 1 + sizeof(float); | |
| } | |
| *out = float64_marker; | |
| store_number(out + 1, n, false); | |
| return 1 + sizeof(number_float_t); | |
| } | |
| /*! | |
| @brief encode a float as @ref write_cbor writes it | |
| @return the number of characters, 3, 5 or 9 | |
| */ | |
| std::size_t encode_cbor_float(CharType* out, const number_float_t n) const noexcept | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!std::isfinite(n))) | |
| { | |
| // NaN is 0xf97e00, Infinity is 0xf97c00, -Infinity is 0xf9fc00 | |
| out[0] = to_char_type(0xF9); | |
| if (std::isnan(n)) | |
| { | |
| out[1] = to_char_type(0x7E); | |
| } | |
| else | |
| { | |
| out[1] = n > 0 ? to_char_type(0x7C) : to_char_type(0xFC); | |
| } | |
| out[2] = to_char_type(0x00); | |
| return 3; | |
| } | |
| return encode_compact_float(out, n, to_char_type(0xFA), to_char_type(0xFB)); | |
| } | |
| /// @brief write @a n using @a float32_marker if it round-trips through | |
| /// float, otherwise using @a float64_marker | |
| /// | |
| /// @a float32_marker and @a float64_marker are the format-specific type | |
| /// markers (CBOR: 0xFA/0xFB, MessagePack: 0xCA/0xCB, BON8: 0x8E/0x8F); | |
| /// each caller already knows them at compile time, so the format itself | |
| /// no longer needs to be passed in. | |
| void write_compact_float(const number_float_t n, const CharType float32_marker, const CharType float64_marker) | |
| { | |
| if (fits_float32(n)) | |
| { | |
| oa.write_character(float32_marker); | |
| write_number(static_cast<float>(n)); | |
| } | |
| else | |
| { | |
| oa.write_character(float64_marker); | |
| write_number(n); | |
| } | |
| } | |
| public: | |
| // The following to_char_type functions implement the conversion | |
| // between uint8_t and CharType. In case CharType is not unsigned, | |
| // such a conversion is required to allow values greater than 128. | |
| // See <https://github.com/nlohmann/json/issues/1286> for a discussion. | |
| template < typename C = CharType, | |
| enable_if_t < std::is_signed<C>::value && std::is_signed<char>::value > * = nullptr > | |
| static constexpr CharType to_char_type(std::uint8_t x) noexcept | |
| { | |
| return *reinterpret_cast<char*>(&x); | |
| } | |
| template < typename C = CharType, | |
| enable_if_t < std::is_signed<C>::value && std::is_unsigned<char>::value > * = nullptr > | |
| static CharType to_char_type(std::uint8_t x) noexcept | |
| { | |
| // The std::is_trivial trait is deprecated in C++26. The replacement is to use | |
| // std::is_trivially_copyable and std::is_trivially_default_constructible. | |
| // However, some older library implementations support std::is_trivial | |
| // but not all the std::is_trivially_* traits. | |
| // Since detecting full support across all libraries is difficult, | |
| // we use std::is_trivial unless we are using a standard where it has been deprecated. | |
| // For more details, see: https://github.com/nlohmann/json/pull/4775#issuecomment-2884361627 | |
| #ifdef JSON_HAS_CPP_26 | |
| static_assert(std::is_trivially_copyable<CharType>::value, "CharType must be trivially copyable"); | |
| static_assert(std::is_trivially_default_constructible<CharType>::value, "CharType must be trivially default constructible"); | |
| #else | |
| static_assert(std::is_trivial<CharType>::value, "CharType must be trivial"); | |
| #endif | |
| static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t"); | |
| return bit_cast<CharType>(x); | |
| } | |
| template<typename C = CharType, | |
| enable_if_t<std::is_unsigned<C>::value>* = nullptr> | |
| static constexpr CharType to_char_type(std::uint8_t x) noexcept | |
| { | |
| return x; | |
| } | |
| template < typename InputCharType, typename C = CharType, | |
| enable_if_t < | |
| std::is_signed<C>::value && | |
| std::is_signed<char>::value && | |
| std::is_same<char, typename std::remove_cv<InputCharType>::type>::value | |
| > * = nullptr > | |
| static constexpr CharType to_char_type(InputCharType x) noexcept | |
| { | |
| return x; | |
| } | |
| private: | |
| /// whether we can assume little endianness | |
| const bool is_little_endian = little_endianness(); | |
| /// the output | |
| OutputSinkType oa; | |
| /// how to treat a string value or object key that is not valid UTF-8 | |
| /// (CBOR, MessagePack, UBJSON, BJData, and BSON; not BON8) | |
| const error_handler_t error_handler = binary_writer_default_error_handler(); | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/output/output_adapters.hpp> | |
| // #include <nlohmann/detail/output/serializer.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <algorithm> // remove, fill, find, none_of, min | |
| #include <array> // array | |
| #include <clocale> // localeconv, lconv | |
| #include <cmath> // isfinite | |
| #include <cstddef> // size_t, ptrdiff_t | |
| #include <cstdint> // uint8_t | |
| #include <cstdio> // snprintf | |
| #include <cstring> // memcpy, memset | |
| #include <iterator> // next | |
| #include <limits> // numeric_limits | |
| #include <string> // string, char_traits | |
| #include <type_traits> // is_same | |
| #include <vector> // vector | |
| // #include <nlohmann/detail/conversions/to_chars.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2009 Florian Loitsch <https://florian.loitsch.com/> | |
| // SPDX-FileCopyrightText: 2025 Victor Zverovich <https://github.com/vitaut/zmij> | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <array> // array | |
| #include <cmath> // signbit, isfinite | |
| #include <cstddef> // size_t | |
| #include <cstdint> // intN_t, uintN_t | |
| #include <cstring> // memcpy, memmove | |
| #include <limits> // numeric_limits | |
| #include <type_traits> // conditional | |
| // SSE2 (every x86-64 CPU) and NEON (every 64-bit Arm CPU) convert the 16 | |
| // digits of a double at once (unless JSON_NO_SIMD selects the portable code) | |
| #if !defined(JSON_NO_SIMD) && (defined(__x86_64__) || (defined(_M_X64) && !defined(_M_ARM64EC))) | |
| #include <emmintrin.h> | |
| #define JSON_DTOA_SSE2 1 | |
| #define JSON_DTOA_NEON 0 | |
| #elif !defined(JSON_NO_SIMD) && (defined(__aarch64__) || defined(_M_ARM64)) && !defined(_M_ARM64EC) && !defined(__ARM_BIG_ENDIAN) | |
| #include <arm_neon.h> | |
| #define JSON_DTOA_SSE2 0 | |
| #define JSON_DTOA_NEON 1 | |
| #else | |
| #define JSON_DTOA_SSE2 0 | |
| #define JSON_DTOA_NEON 0 | |
| #endif | |
| // #include <nlohmann/detail/bit_ops.hpp> | |
| // #include <nlohmann/detail/conversions/zmij.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2025 Victor Zverovich <https://github.com/vitaut/zmij> | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <array> // array | |
| #include <cstddef> // size_t | |
| #include <cstdint> // uint32_t, uint64_t | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| // #include <nlohmann/detail/bit_ops.hpp> | |
| // #include <nlohmann/detail/input/pow5_table.hpp> | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /*! | |
| @brief the shortest decimal representation of a double | |
| A C++11 port of the conversion of Zmij by Victor Zverovich | |
| (https://github.com/vitaut/zmij, MIT license): the shortest decimal in the | |
| rounding interval of a double, the closest one if there are several. Zmij | |
| credits Xiang JunBo (producing the shorter candidate without a division) and | |
| Dougall Johnson (the compressed powers of ten). The powers of ten are taken | |
| from the table for number parsing (pow5_table.hpp) where it holds them, and | |
| computed from the compressed tables of Zmij beyond it. | |
| */ | |
| namespace zmij | |
| { | |
| /// the compressed powers of ten of Zmij | |
| inline const std::array<std::uint64_t, 28>& pow10_minor() noexcept | |
| { | |
| static const std::array<std::uint64_t, 28> table = | |
| { | |
| { | |
| 0x8000000000000000u, 0xa000000000000000u, 0xc800000000000000u, 0xfa00000000000000u, 0x9c40000000000000u, | |
| 0xc350000000000000u, 0xf424000000000000u, 0x9896800000000000u, 0xbebc200000000000u, 0xee6b280000000000u, | |
| 0x9502f90000000000u, 0xba43b74000000000u, 0xe8d4a51000000000u, 0x9184e72a00000000u, 0xb5e620f480000000u, | |
| 0xe35fa931a0000000u, 0x8e1bc9bf04000000u, 0xb1a2bc2ec5000000u, 0xde0b6b3a76400000u, 0x8ac7230489e80000u, | |
| 0xad78ebc5ac620000u, 0xd8d726b7177a8000u, 0x878678326eac9000u, 0xa968163f0a57b400u, 0xd3c21bcecceda100u, | |
| 0x84595161401484a0u, 0xa56fa5b99019a5c8u, 0xcecb8f27f4200f3au | |
| } | |
| }; | |
| return table; | |
| } | |
| /// (high, low) pairs | |
| inline const std::array<std::uint64_t, 50>& pow10_major() noexcept | |
| { | |
| static const std::array<std::uint64_t, 50> table = | |
| { | |
| { | |
| 0xaddcb9e83c6b1793u, 0xdf4abe242a1bbf3eu, 0xaf8e5410288e1b6fu, 0x07ecf0ae5ee44ddau, 0xb1442798f49ffb4au, 0x99cd11cfdf41779du, | |
| 0xb2fe3f0b8599ef07u, 0x861fa7e6dcb4aa15u, 0xb4bca50b065abe63u, 0x0fed077a756b53aau, 0xb67f6455292cbf08u, 0x1a3bc84c17b1d543u, | |
| 0xb84687c269ef3bfbu, 0x3d5d514f40eea742u, 0xba121a4650e4ddebu, 0x92f34d62616ce413u, 0xbbe226efb628afeau, 0x890489f70a55368cu, | |
| 0xbdb6b8e905cb600fu, 0x5400e987bbc1c921u, 0xbf8fdb78849a5f96u, 0xde98520472bdd034u, 0xc16d9a0095928a27u, 0x75b7053c0f178294u, | |
| 0xc350000000000000u, 0x0000000000000000u, 0xc5371912364ce305u, 0x6c28000000000000u, 0xc722f0ef9d80aad6u, 0x424d3ad2b7b97ef6u, | |
| 0xc913936dd571c84cu, 0x03bc3a19cd1e38eau, 0xcb090c8001ab551cu, 0x5cadf5bfd3072cc6u, 0xcd036837130890a1u, 0x36dba887c37a8c10u, | |
| 0xcf02b2c21207ef2eu, 0x94f967e45e03f4bcu, 0xd106f86e69d785c7u, 0xe13336d701beba52u, 0xd31045a8341ca07cu, 0x1ede48111209a051u, | |
| 0xd51ea6fa85785631u, 0x552a74227f3ea566u, 0xd732290fbacaf133u, 0xa97c177947ad4096u, 0xd94ad8b1c7380874u, 0x18375281ae7822bdu, | |
| 0xdb68c2ca82ed2a05u, 0xa67398db9f6820e1u | |
| } | |
| }; | |
| return table; | |
| } | |
| /// one bit per power: whether the computed value is one unit too large | |
| inline const std::array<std::uint32_t, 21>& pow10_fixups() noexcept | |
| { | |
| static const std::array<std::uint32_t, 21> table = | |
| { | |
| { | |
| 0x8d8fc810u, 0x06100293u, 0x19000000u, 0x00100000u, 0x00000908u, 0x00000000u, 0x04e00300u, 0x3807e0b2u, 0x3d83d793u, 0x0006f5ccu, | |
| 0x00000000u, 0xffff0000u, 0x8076337du, 0x4ff45ba0u, 0x09405033u, 0x034376d9u, 0x09000000u, 0x4e100501u, 0x076d14dcu, 0xf964f45eu, | |
| 0x0000003du | |
| } | |
| }; | |
| return table; | |
| } | |
| /// the 128-bit significand of 10^k, rounded down, for k in [-307, 341] | |
| /// (compute_pow10 of Zmij) | |
| inline uint128_parts compute_pow10(int k) noexcept | |
| { | |
| const auto i = static_cast<unsigned>(k + 307); | |
| const std::uint64_t m = pow10_minor()[(i + 24) % 28]; | |
| const std::size_t j = 2 * static_cast<std::size_t>((i + 24) / 28); | |
| const std::uint64_t h_hi = pow10_major()[j]; | |
| const std::uint64_t h_lo = pow10_major()[j + 1]; | |
| const std::uint64_t h1 = full_multiplication(h_lo, m).high; | |
| const std::uint64_t c0 = h_lo * m; | |
| const std::uint64_t c1 = h1 + (h_hi * m); | |
| const std::uint64_t c2 = (c1 < h1 ? 1u : 0u) + full_multiplication(h_hi, m).high; | |
| uint128_parts r{}; | |
| if ((c2 >> 63u) != 0) | |
| { | |
| r.high = c2; | |
| r.low = c1; | |
| } | |
| else | |
| { | |
| r.high = (c2 << 1u) | (c1 >> 63u); | |
| r.low = (c1 << 1u) | (c0 >> 63u); | |
| } | |
| r.low -= (pow10_fixups()[i >> 5u] >> (i & 31u)) & 1u; | |
| return r; | |
| } | |
| /// The 128-bit significand of 10^k, rounded down, for k in [-342, 341]. | |
| /// Up to 10^308, the table for number parsing holds the same significands | |
| /// (those of 5^k), except for k in [-27, -1], where it holds them one unit | |
| /// larger (as the Eisel-Lemire algorithm needs them). | |
| inline uint128_parts pow10(int k) noexcept | |
| { | |
| if (k > pow5_128_largest_power) | |
| { | |
| return compute_pow10(k); // (only for the smallest doubles) | |
| } | |
| const auto i = 2 * static_cast<std::size_t>(k - pow5_128_smallest_power); | |
| uint128_parts r{pow5_128()[i + 1], pow5_128()[i]}; | |
| const std::uint64_t adjust = static_cast<unsigned>(k + 27) < 27u ? 1u : 0u; | |
| r.high -= r.low < adjust ? 1u : 0u; | |
| r.low -= adjust; | |
| return r; | |
| } | |
| /// (x_hi * 2^64 + x_lo) * y >> 64, as 128 bits | |
| inline uint128_parts umul192_hi128(std::uint64_t x_hi, std::uint64_t x_lo, std::uint64_t y) noexcept | |
| { | |
| const uint128_parts p = full_multiplication(x_hi, y); | |
| uint128_parts r{}; | |
| r.low = p.low + full_multiplication(x_lo, y).high; | |
| r.high = p.high + (r.low < p.low ? 1u : 0u); | |
| return r; | |
| } | |
| /// (x * y + c) >> 64 | |
| inline std::uint64_t umul128_add_hi64(std::uint64_t x, std::uint64_t y, std::uint64_t c) noexcept | |
| { | |
| const uint128_parts p = full_multiplication(x, y); | |
| return p.high + (p.low + c < p.low ? 1u : 0u); | |
| } | |
| /// the result of Zmij: the shorter candidate and, if that is outside the | |
| /// rounding interval, the digit after it (16 bytes: returned in registers) | |
| struct shortest_decimal | |
| { | |
| std::uint64_t integral; ///< the shorter candidate (15 or 16 digits for normal doubles) | |
| int exponent; ///< the decimal exponent of the digit after it | |
| unsigned char digit; ///< the digit after it (if has_digit) | |
| bool has_digit; ///< whether the shortest decimal is integral * 10 + digit | |
| }; | |
| /// The shortest decimal in the rounding interval of a positive finite double | |
| /// given by its bits, the closest one if there are several (to_decimal of | |
| /// Zmij, which keeps the last digit apart: the 15 or 16 digits before it can be | |
| /// converted without a multiplication by 10 first). Always inlined: GCC | |
| /// otherwise calls it, and its result goes through memory. | |
| JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept | |
| { | |
| constexpr int extra_shift = 9; | |
| const auto raw_exp = static_cast<int>((bits >> 52u) & 0x7FFu); | |
| std::uint64_t bin_sig = bits & ((std::uint64_t{1} << 52u) - 1); | |
| // a power of two has a narrower interval below (except the smallest normal) | |
| const bool regular = bin_sig != 0 || raw_exp <= 1; | |
| const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - 1075; | |
| if (raw_exp != 0) | |
| { | |
| bin_sig |= std::uint64_t{1} << 52u; | |
| } | |
| // floor(log10(2^bin_exp)), or floor(log10(3/4 * 2^bin_exp)) for the irregular case | |
| const int dec_exp = ((bin_exp * 315653) - (regular ? 0 : 131072)) >> 20; | |
| // scaled by 10^(-dec_exp - 1): the integral part is the shorter candidate | |
| const int shift = bin_exp + ((-(dec_exp + 1) * 217707) >> 16) + 1 + extra_shift; | |
| const uint128_parts p10 = pow10(-dec_exp - 1); | |
| const uint128_parts p = umul192_hi128(p10.high, p10.low, bin_sig << static_cast<unsigned>(shift)); | |
| std::uint64_t integral = p.high >> static_cast<unsigned>(extra_shift); | |
| // (no casts in the shifts: MSVC 2015 warns C4554 on them despite the parentheses) | |
| constexpr auto fractional_low_shift = static_cast<unsigned>(extra_shift); | |
| constexpr unsigned fractional_high_shift = 64u - fractional_low_shift; | |
| const std::uint64_t fractional = (p.high << fractional_high_shift) | (p.low >> fractional_low_shift); | |
| std::uint64_t digit = 0; | |
| bool round_up = false; | |
| bool round_down = false; | |
| if (JSON_HEDLEY_LIKELY(regular)) | |
| { | |
| const std::uint64_t half_ulp = (p10.high >> static_cast<unsigned>(extra_shift + 1 - shift)) + (1 - (bin_sig & 1u)); | |
| round_up = fractional + half_ulp < fractional; | |
| round_down = half_ulp > fractional; | |
| // the last digit of the longer candidate, rounded to nearest | |
| digit = umul128_add_hi64(fractional, 10, (std::uint64_t{1} << 63u) + 6); | |
| if (fractional == (std::uint64_t{1} << 62u)) | |
| { | |
| digit = 2; // 2.5 rounds to 2 | |
| } | |
| } | |
| else | |
| { | |
| const std::uint64_t half_ulp = p10.high >> static_cast<unsigned>(extra_shift + 1 - shift); | |
| round_up = half_ulp > ~std::uint64_t{0} - fractional; | |
| round_down = (half_ulp >> 1u) > fractional; | |
| digit = umul128_add_hi64(fractional, 10, (std::uint64_t{1} << 63u) - 1); | |
| const std::uint64_t lowest = umul128_add_hi64(fractional - (half_ulp >> 1u), 10, ~std::uint64_t{0}); | |
| digit = digit < lowest ? lowest : digit; | |
| } | |
| integral += round_up ? 1u : 0u; | |
| // if the shorter candidate is outside the rounding interval: one digit more | |
| return shortest_decimal{integral, dec_exp, static_cast<unsigned char>(digit), !round_up && !round_down}; | |
| } | |
| } // namespace zmij | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /*! | |
| @brief implements the Grisu2 algorithm for binary to decimal floating-point | |
| conversion. | |
| This implementation is a slightly modified version of the reference | |
| implementation which may be obtained from | |
| http://florian.loitsch.com/publications (bench.tar.gz). | |
| The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. | |
| For a detailed description of the algorithm see: | |
| [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with | |
| Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming | |
| Language Design and Implementation, PLDI 2010 | |
| [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", | |
| Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language | |
| Design and Implementation, PLDI 1996 | |
| */ | |
| namespace dtoa_impl | |
| { | |
| struct diyfp // f * 2^e | |
| { | |
| static constexpr int kPrecision = 64; // = q | |
| std::uint64_t f = 0; | |
| int e = 0; | |
| constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {} | |
| /*! | |
| @brief returns x - y | |
| @pre x.e == y.e and x.f >= y.f | |
| */ | |
| static diyfp sub(const diyfp& x, const diyfp& y) noexcept | |
| { | |
| JSON_ASSERT(x.e == y.e); | |
| JSON_ASSERT(x.f >= y.f); | |
| return {x.f - y.f, x.e}; | |
| } | |
| /*! | |
| @brief returns x * y | |
| @note The result is rounded. (Only the upper q bits are returned.) | |
| */ | |
| static diyfp mul(const diyfp& x, const diyfp& y) noexcept | |
| { | |
| static_assert(kPrecision == 64, "internal error"); | |
| // Computes: | |
| // f = round((x.f * y.f) / 2^q) | |
| // e = x.e + y.e + q | |
| // Emulate the 64-bit * 64-bit multiplication: | |
| // | |
| // p = u * v | |
| // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) | |
| // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) | |
| // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) | |
| // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) | |
| // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) | |
| // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) | |
| // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) | |
| // | |
| // (Since Q might be larger than 2^32 - 1) | |
| // | |
| // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) | |
| // | |
| // (Q_hi + H does not overflow a 64-bit int) | |
| // | |
| // = p_lo + 2^64 p_hi | |
| const std::uint64_t u_lo = x.f & 0xFFFFFFFFu; | |
| const std::uint64_t u_hi = x.f >> 32u; | |
| const std::uint64_t v_lo = y.f & 0xFFFFFFFFu; | |
| const std::uint64_t v_hi = y.f >> 32u; | |
| const std::uint64_t p0 = u_lo * v_lo; | |
| const std::uint64_t p1 = u_lo * v_hi; | |
| const std::uint64_t p2 = u_hi * v_lo; | |
| const std::uint64_t p3 = u_hi * v_hi; | |
| const std::uint64_t p0_hi = p0 >> 32u; | |
| const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu; | |
| const std::uint64_t p1_hi = p1 >> 32u; | |
| const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu; | |
| const std::uint64_t p2_hi = p2 >> 32u; | |
| std::uint64_t Q = p0_hi + p1_lo + p2_lo; | |
| // The full product might now be computed as | |
| // | |
| // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) | |
| // p_lo = p0_lo + (Q << 32) | |
| // | |
| // But in this particular case here, the full p_lo is not required. | |
| // Effectively, we only need to add the highest bit in p_lo to p_hi (and | |
| // Q_hi + 1 does not overflow). | |
| Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up | |
| const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u); | |
| return {h, x.e + y.e + 64}; | |
| } | |
| /*! | |
| @brief normalize x such that the significand is >= 2^(q-1) | |
| @pre x.f != 0 | |
| */ | |
| static diyfp normalize(diyfp x) noexcept | |
| { | |
| JSON_ASSERT(x.f != 0); | |
| while ((x.f >> 63u) == 0) | |
| { | |
| x.f <<= 1u; | |
| x.e--; | |
| } | |
| return x; | |
| } | |
| /*! | |
| @brief normalize x such that the result has the exponent E | |
| @pre e >= x.e and the upper e - x.e bits of x.f must be zero. | |
| */ | |
| static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept | |
| { | |
| const int delta = x.e - target_exponent; | |
| JSON_ASSERT(delta >= 0); | |
| JSON_ASSERT(((x.f << delta) >> delta) == x.f); | |
| return {x.f << delta, target_exponent}; | |
| } | |
| }; | |
| struct boundaries | |
| { | |
| diyfp w; | |
| diyfp minus; | |
| diyfp plus; | |
| }; | |
| /*! | |
| Compute the (normalized) diyfp representing the input number 'value' and its | |
| boundaries. | |
| @pre value must be finite and positive | |
| */ | |
| template<typename FloatType> | |
| boundaries compute_boundaries(FloatType value) | |
| { | |
| JSON_ASSERT(std::isfinite(value)); | |
| JSON_ASSERT(value > 0); | |
| // Convert the IEEE representation into a diyfp. | |
| // | |
| // If v is denormal: | |
| // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) | |
| // If v is normalized: | |
| // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) | |
| static_assert(std::numeric_limits<FloatType>::is_iec559, | |
| "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); | |
| constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit) | |
| constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1); | |
| constexpr int kMinExp = 1 - kBias; | |
| constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) | |
| using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type; | |
| const auto bits = static_cast<std::uint64_t>(bit_cast<bits_type>(value)); | |
| const std::uint64_t E = bits >> (kPrecision - 1); | |
| const std::uint64_t F = bits & (kHiddenBit - 1); | |
| const bool is_denormal = E == 0; | |
| const diyfp v = is_denormal | |
| ? diyfp(F, kMinExp) | |
| : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias); | |
| // Compute the boundaries m- and m+ of the floating-point value | |
| // v = f * 2^e. | |
| // | |
| // Determine v- and v+, the floating-point predecessor and successor of v, | |
| // respectively. | |
| // | |
| // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) | |
| // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) | |
| // | |
| // v+ = v + 2^e | |
| // | |
| // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ | |
| // between m- and m+ round to v, regardless of how the input rounding | |
| // algorithm breaks ties. | |
| // | |
| // ---+-------------+-------------+-------------+-------------+--- (A) | |
| // v- m- v m+ v+ | |
| // | |
| // -----------------+------+------+-------------+-------------+--- (B) | |
| // v- m- v m+ v+ | |
| const bool lower_boundary_is_closer = F == 0 && E > 1; | |
| const diyfp m_plus = diyfp((2 * v.f) + 1, v.e - 1); | |
| const diyfp m_minus = lower_boundary_is_closer | |
| ? diyfp((4 * v.f) - 1, v.e - 2) // (B) | |
| : diyfp((2 * v.f) - 1, v.e - 1); // (A) | |
| // Determine the normalized w+ = m+. | |
| const diyfp w_plus = diyfp::normalize(m_plus); | |
| // Determine w- = m- such that e_(w-) = e_(w+). | |
| const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); | |
| return {diyfp::normalize(v), w_minus, w_plus}; | |
| } | |
| // Given normalized diyfp w, Grisu needs to find a (normalized) cached | |
| // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies | |
| // within a certain range [alpha, gamma] (Definition 3.2 from [1]) | |
| // | |
| // alpha <= e = e_c + e_w + q <= gamma | |
| // | |
| // or | |
| // | |
| // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q | |
| // <= f_c * f_w * 2^gamma | |
| // | |
| // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies | |
| // | |
| // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma | |
| // | |
| // or | |
| // | |
| // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) | |
| // | |
| // The choice of (alpha,gamma) determines the size of the table and the form of | |
| // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well | |
| // in practice: | |
| // | |
| // The idea is to cut the number c * w = f * 2^e into two parts, which can be | |
| // processed independently: An integral part p1, and a fractional part p2: | |
| // | |
| // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e | |
| // = (f div 2^-e) + (f mod 2^-e) * 2^e | |
| // = p1 + p2 * 2^e | |
| // | |
| // The conversion of p1 into decimal form requires a series of divisions and | |
| // modulos by (a power of) 10. These operations are faster for 32-bit than for | |
| // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be | |
| // achieved by choosing | |
| // | |
| // -e >= 32 or e <= -32 := gamma | |
| // | |
| // In order to convert the fractional part | |
| // | |
| // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... | |
| // | |
| // into decimal form, the fraction is repeatedly multiplied by 10 and the digits | |
| // d[-i] are extracted in order: | |
| // | |
| // (10 * p2) div 2^-e = d[-1] | |
| // (10 * p2) mod 2^-e = d[-2] / 10^1 + ... | |
| // | |
| // The multiplication by 10 must not overflow. It is sufficient to choose | |
| // | |
| // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. | |
| // | |
| // Since p2 = f mod 2^-e < 2^-e, | |
| // | |
| // -e <= 60 or e >= -60 := alpha | |
| JSON_INLINE_VARIABLE constexpr int kAlpha = -60; | |
| JSON_INLINE_VARIABLE constexpr int kGamma = -32; | |
| struct cached_power // c = f * 2^e ~= 10^k | |
| { | |
| std::uint64_t f; | |
| int e; | |
| int k; | |
| }; | |
| /*! | |
| For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached | |
| power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c | |
| satisfies (Definition 3.2 from [1]) | |
| alpha <= e_c + e + q <= gamma. | |
| */ | |
| inline cached_power get_cached_power_for_binary_exponent(int e) | |
| { | |
| // Now | |
| // | |
| // alpha <= e_c + e + q <= gamma (1) | |
| // ==> f_c * 2^alpha <= c * 2^e * 2^q | |
| // | |
| // and since the c's are normalized, 2^(q-1) <= f_c, | |
| // | |
| // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) | |
| // ==> 2^(alpha - e - 1) <= c | |
| // | |
| // If c were an exact power of ten, i.e. c = 10^k, one may determine k as | |
| // | |
| // k = ceil( log_10( 2^(alpha - e - 1) ) ) | |
| // = ceil( (alpha - e - 1) * log_10(2) ) | |
| // | |
| // From the paper: | |
| // "In theory the result of the procedure could be wrong since c is rounded, | |
| // and the computation itself is approximated [...]. In practice, however, | |
| // this simple function is sufficient." | |
| // | |
| // For IEEE double precision floating-point numbers converted into | |
| // normalized diyfp's w = f * 2^e, with q = 64, | |
| // | |
| // e >= -1022 (min IEEE exponent) | |
| // -52 (p - 1) | |
| // -52 (p - 1, possibly normalize denormal IEEE numbers) | |
| // -11 (normalize the diyfp) | |
| // = -1137 | |
| // | |
| // and | |
| // | |
| // e <= +1023 (max IEEE exponent) | |
| // -52 (p - 1) | |
| // -11 (normalize the diyfp) | |
| // = 960 | |
| // | |
| // This binary exponent range [-1137,960] results in a decimal exponent | |
| // range [-307,324]. One does not need to store a cached power for each | |
| // k in this range. For each such k it suffices to find a cached power | |
| // such that the exponent of the product lies in [alpha,gamma]. | |
| // This implies that the difference of the decimal exponents of adjacent | |
| // table entries must be less than or equal to | |
| // | |
| // floor( (gamma - alpha) * log_10(2) ) = 8. | |
| // | |
| // (A smaller distance gamma-alpha would require a larger table.) | |
| // NB: | |
| // Actually, this function returns c, such that -60 <= e_c + e + 64 <= -34. | |
| constexpr int kCachedPowersMinDecExp = -300; | |
| constexpr int kCachedPowersDecStep = 8; | |
| static constexpr std::array<cached_power, 79> kCachedPowers = | |
| { | |
| { | |
| { 0xAB70FE17C79AC6CA, -1060, -300 }, | |
| { 0xFF77B1FCBEBCDC4F, -1034, -292 }, | |
| { 0xBE5691EF416BD60C, -1007, -284 }, | |
| { 0x8DD01FAD907FFC3C, -980, -276 }, | |
| { 0xD3515C2831559A83, -954, -268 }, | |
| { 0x9D71AC8FADA6C9B5, -927, -260 }, | |
| { 0xEA9C227723EE8BCB, -901, -252 }, | |
| { 0xAECC49914078536D, -874, -244 }, | |
| { 0x823C12795DB6CE57, -847, -236 }, | |
| { 0xC21094364DFB5637, -821, -228 }, | |
| { 0x9096EA6F3848984F, -794, -220 }, | |
| { 0xD77485CB25823AC7, -768, -212 }, | |
| { 0xA086CFCD97BF97F4, -741, -204 }, | |
| { 0xEF340A98172AACE5, -715, -196 }, | |
| { 0xB23867FB2A35B28E, -688, -188 }, | |
| { 0x84C8D4DFD2C63F3B, -661, -180 }, | |
| { 0xC5DD44271AD3CDBA, -635, -172 }, | |
| { 0x936B9FCEBB25C996, -608, -164 }, | |
| { 0xDBAC6C247D62A584, -582, -156 }, | |
| { 0xA3AB66580D5FDAF6, -555, -148 }, | |
| { 0xF3E2F893DEC3F126, -529, -140 }, | |
| { 0xB5B5ADA8AAFF80B8, -502, -132 }, | |
| { 0x87625F056C7C4A8B, -475, -124 }, | |
| { 0xC9BCFF6034C13053, -449, -116 }, | |
| { 0x964E858C91BA2655, -422, -108 }, | |
| { 0xDFF9772470297EBD, -396, -100 }, | |
| { 0xA6DFBD9FB8E5B88F, -369, -92 }, | |
| { 0xF8A95FCF88747D94, -343, -84 }, | |
| { 0xB94470938FA89BCF, -316, -76 }, | |
| { 0x8A08F0F8BF0F156B, -289, -68 }, | |
| { 0xCDB02555653131B6, -263, -60 }, | |
| { 0x993FE2C6D07B7FAC, -236, -52 }, | |
| { 0xE45C10C42A2B3B06, -210, -44 }, | |
| { 0xAA242499697392D3, -183, -36 }, | |
| { 0xFD87B5F28300CA0E, -157, -28 }, | |
| { 0xBCE5086492111AEB, -130, -20 }, | |
| { 0x8CBCCC096F5088CC, -103, -12 }, | |
| { 0xD1B71758E219652C, -77, -4 }, | |
| { 0x9C40000000000000, -50, 4 }, | |
| { 0xE8D4A51000000000, -24, 12 }, | |
| { 0xAD78EBC5AC620000, 3, 20 }, | |
| { 0x813F3978F8940984, 30, 28 }, | |
| { 0xC097CE7BC90715B3, 56, 36 }, | |
| { 0x8F7E32CE7BEA5C70, 83, 44 }, | |
| { 0xD5D238A4ABE98068, 109, 52 }, | |
| { 0x9F4F2726179A2245, 136, 60 }, | |
| { 0xED63A231D4C4FB27, 162, 68 }, | |
| { 0xB0DE65388CC8ADA8, 189, 76 }, | |
| { 0x83C7088E1AAB65DB, 216, 84 }, | |
| { 0xC45D1DF942711D9A, 242, 92 }, | |
| { 0x924D692CA61BE758, 269, 100 }, | |
| { 0xDA01EE641A708DEA, 295, 108 }, | |
| { 0xA26DA3999AEF774A, 322, 116 }, | |
| { 0xF209787BB47D6B85, 348, 124 }, | |
| { 0xB454E4A179DD1877, 375, 132 }, | |
| { 0x865B86925B9BC5C2, 402, 140 }, | |
| { 0xC83553C5C8965D3D, 428, 148 }, | |
| { 0x952AB45CFA97A0B3, 455, 156 }, | |
| { 0xDE469FBD99A05FE3, 481, 164 }, | |
| { 0xA59BC234DB398C25, 508, 172 }, | |
| { 0xF6C69A72A3989F5C, 534, 180 }, | |
| { 0xB7DCBF5354E9BECE, 561, 188 }, | |
| { 0x88FCF317F22241E2, 588, 196 }, | |
| { 0xCC20CE9BD35C78A5, 614, 204 }, | |
| { 0x98165AF37B2153DF, 641, 212 }, | |
| { 0xE2A0B5DC971F303A, 667, 220 }, | |
| { 0xA8D9D1535CE3B396, 694, 228 }, | |
| { 0xFB9B7CD9A4A7443C, 720, 236 }, | |
| { 0xBB764C4CA7A44410, 747, 244 }, | |
| { 0x8BAB8EEFB6409C1A, 774, 252 }, | |
| { 0xD01FEF10A657842C, 800, 260 }, | |
| { 0x9B10A4E5E9913129, 827, 268 }, | |
| { 0xE7109BFBA19C0C9D, 853, 276 }, | |
| { 0xAC2820D9623BF429, 880, 284 }, | |
| { 0x80444B5E7AA7CF85, 907, 292 }, | |
| { 0xBF21E44003ACDD2D, 933, 300 }, | |
| { 0x8E679C2F5E44FF8F, 960, 308 }, | |
| { 0xD433179D9C8CB841, 986, 316 }, | |
| { 0x9E19DB92B4E31BA9, 1013, 324 }, | |
| } | |
| }; | |
| // This computation gives exactly the same results for k as | |
| // k = ceil((kAlpha - e - 1) * 0.30102999566398114) | |
| // for |e| <= 1500, but doesn't require floating-point operations. | |
| // NB: log_10(2) ~= 78913 / 2^18 | |
| JSON_ASSERT(e >= -1500); | |
| JSON_ASSERT(e <= 1500); | |
| const int f = kAlpha - e - 1; | |
| const int k = ((f * 78913) / (1 << 18)) + static_cast<int>(f > 0); | |
| const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; | |
| JSON_ASSERT(index >= 0); | |
| JSON_ASSERT(static_cast<std::size_t>(index) < kCachedPowers.size()); | |
| const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)]; | |
| JSON_ASSERT(kAlpha <= cached.e + e + 64); | |
| JSON_ASSERT(kGamma >= cached.e + e + 64); | |
| return cached; | |
| } | |
| /*! | |
| For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. | |
| For n == 0, returns 1 and sets pow10 := 1. | |
| */ | |
| inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) | |
| { | |
| // LCOV_EXCL_START | |
| if (n >= 1000000000) | |
| { | |
| pow10 = 1000000000; | |
| return 10; | |
| } | |
| // LCOV_EXCL_STOP | |
| if (n >= 100000000) | |
| { | |
| pow10 = 100000000; | |
| return 9; | |
| } | |
| if (n >= 10000000) | |
| { | |
| pow10 = 10000000; | |
| return 8; | |
| } | |
| if (n >= 1000000) | |
| { | |
| pow10 = 1000000; | |
| return 7; | |
| } | |
| if (n >= 100000) | |
| { | |
| pow10 = 100000; | |
| return 6; | |
| } | |
| if (n >= 10000) | |
| { | |
| pow10 = 10000; | |
| return 5; | |
| } | |
| if (n >= 1000) | |
| { | |
| pow10 = 1000; | |
| return 4; | |
| } | |
| if (n >= 100) | |
| { | |
| pow10 = 100; | |
| return 3; | |
| } | |
| if (n >= 10) | |
| { | |
| pow10 = 10; | |
| return 2; | |
| } | |
| pow10 = 1; | |
| return 1; | |
| } | |
| inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, | |
| std::uint64_t rest, std::uint64_t ten_k) | |
| { | |
| JSON_ASSERT(len >= 1); | |
| JSON_ASSERT(dist <= delta); | |
| JSON_ASSERT(rest <= delta); | |
| JSON_ASSERT(ten_k > 0); | |
| // <--------------------------- delta ----> | |
| // <---- dist ---------> | |
| // --------------[------------------+-------------------]-------------- | |
| // M- w M+ | |
| // | |
| // ten_k | |
| // <------> | |
| // <---- rest ----> | |
| // --------------[------------------+----+--------------]-------------- | |
| // w V | |
| // = buf * 10^k | |
| // | |
| // ten_k represents a unit-in-the-last-place in the decimal representation | |
| // stored in buf. | |
| // Decrement buf by ten_k while this takes buf closer to w. | |
| // The tests are written in this order to avoid overflow in unsigned | |
| // integer arithmetic. | |
| while (rest < dist | |
| && delta - rest >= ten_k | |
| && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) | |
| { | |
| JSON_ASSERT(buf[len - 1] != '0'); | |
| buf[len - 1]--; | |
| rest += ten_k; | |
| } | |
| } | |
| /*! | |
| Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. | |
| M- and M+ must be normalized and share the same exponent -60 <= e <= -32. | |
| */ | |
| inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, | |
| diyfp M_minus, diyfp w, diyfp M_plus) | |
| { | |
| static_assert(kAlpha >= -60, "internal error"); | |
| static_assert(kGamma <= -32, "internal error"); | |
| // Generates the digits (and the exponent) of a decimal floating-point | |
| // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's | |
| // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. | |
| // | |
| // <--------------------------- delta ----> | |
| // <---- dist ---------> | |
| // --------------[------------------+-------------------]-------------- | |
| // M- w M+ | |
| // | |
| // Grisu2 generates the digits of M+ from left to right and stops as soon as | |
| // V is in [M-,M+]. | |
| JSON_ASSERT(M_plus.e >= kAlpha); | |
| JSON_ASSERT(M_plus.e <= kGamma); | |
| std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) | |
| std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) | |
| // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): | |
| // | |
| // M+ = f * 2^e | |
| // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e | |
| // = ((p1 ) * 2^-e + (p2 )) * 2^e | |
| // = p1 + p2 * 2^e | |
| const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e); | |
| auto p1 = static_cast<std::uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) | |
| std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e | |
| // 1) | |
| // | |
| // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] | |
| JSON_ASSERT(p1 > 0); | |
| std::uint32_t pow10{}; | |
| const int k = find_largest_pow10(p1, pow10); | |
| // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) | |
| // | |
| // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) | |
| // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) | |
| // | |
| // M+ = p1 + p2 * 2^e | |
| // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e | |
| // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e | |
| // = d[k-1] * 10^(k-1) + ( rest) * 2^e | |
| // | |
| // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) | |
| // | |
| // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] | |
| // | |
| // but stop as soon as | |
| // | |
| // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e | |
| int n = k; | |
| while (n > 0) | |
| { | |
| // Invariants: | |
| // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) | |
| // pow10 = 10^(n-1) <= p1 < 10^n | |
| // | |
| const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) | |
| const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) | |
| // | |
| // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e | |
| // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) | |
| // | |
| JSON_ASSERT(d <= 9); | |
| buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d | |
| // | |
| // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) | |
| // | |
| p1 = r; | |
| n--; | |
| // | |
| // M+ = buffer * 10^n + (p1 + p2 * 2^e) | |
| // pow10 = 10^n | |
| // | |
| // Now check if enough digits have been generated. | |
| // Compute | |
| // | |
| // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e | |
| // | |
| // Note: | |
| // Since rest and delta share the same exponent e, it suffices to | |
| // compare the significands. | |
| const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2; | |
| if (rest <= delta) | |
| { | |
| // V = buffer * 10^n, with M- <= V <= M+. | |
| decimal_exponent += n; | |
| // We may now just stop. But instead, it looks as if the buffer | |
| // could be decremented to bring V closer to w. | |
| // | |
| // pow10 = 10^n is now 1 ulp in the decimal representation V. | |
| // The rounding procedure works with diyfp's with an implicit | |
| // exponent of e. | |
| // | |
| // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e | |
| // | |
| const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e; | |
| grisu2_round(buffer, length, dist, delta, rest, ten_n); | |
| return; | |
| } | |
| pow10 /= 10; | |
| // | |
| // pow10 = 10^(n-1) <= p1 < 10^n | |
| // Invariants restored. | |
| } | |
| // 2) | |
| // | |
| // The digits of the integral part have been generated: | |
| // | |
| // M+ = d[k-1]...d[1]d[0] + p2 * 2^e | |
| // = buffer + p2 * 2^e | |
| // | |
| // Now generate the digits of the fractional part p2 * 2^e. | |
| // | |
| // Note: | |
| // No decimal point is generated: the exponent is adjusted instead. | |
| // | |
| // p2 actually represents the fraction | |
| // | |
| // p2 * 2^e | |
| // = p2 / 2^-e | |
| // = d[-1] / 10^1 + d[-2] / 10^2 + ... | |
| // | |
| // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) | |
| // | |
| // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m | |
| // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) | |
| // | |
| // using | |
| // | |
| // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) | |
| // = ( d) * 2^-e + ( r) | |
| // | |
| // or | |
| // 10^m * p2 * 2^e = d + r * 2^e | |
| // | |
| // i.e. | |
| // | |
| // M+ = buffer + p2 * 2^e | |
| // = buffer + 10^-m * (d + r * 2^e) | |
| // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e | |
| // | |
| // and stop as soon as 10^-m * r * 2^e <= delta * 2^e | |
| JSON_ASSERT(p2 > delta); | |
| int m = 0; | |
| for (;;) | |
| { | |
| // Invariant: | |
| // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e | |
| // = buffer * 10^-m + 10^-m * (p2 ) * 2^e | |
| // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e | |
| // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e | |
| // | |
| JSON_ASSERT(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10); | |
| p2 *= 10; | |
| const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e | |
| const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e | |
| // | |
| // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e | |
| // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) | |
| // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e | |
| // | |
| JSON_ASSERT(d <= 9); | |
| buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d | |
| // | |
| // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e | |
| // | |
| p2 = r; | |
| m++; | |
| // | |
| // M+ = buffer * 10^-m + 10^-m * p2 * 2^e | |
| // Invariant restored. | |
| // Check if enough digits have been generated. | |
| // | |
| // 10^-m * p2 * 2^e <= delta * 2^e | |
| // p2 * 2^e <= 10^m * delta * 2^e | |
| // p2 <= 10^m * delta | |
| delta *= 10; | |
| dist *= 10; | |
| if (p2 <= delta) | |
| { | |
| break; | |
| } | |
| } | |
| // V = buffer * 10^-m, with M- <= V <= M+. | |
| decimal_exponent -= m; | |
| // 1 ulp in the decimal representation is now 10^-m. | |
| // Since delta and dist are now scaled by 10^m, we need to do the | |
| // same with ulp in order to keep the units in sync. | |
| // | |
| // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e | |
| // | |
| const std::uint64_t ten_m = one.f; | |
| grisu2_round(buffer, length, dist, delta, p2, ten_m); | |
| // By construction this algorithm generates the shortest possible decimal | |
| // number (Loitsch, Theorem 6.2) which rounds back to w. | |
| // For an input number of precision p, at least | |
| // | |
| // N = 1 + ceil(p * log_10(2)) | |
| // | |
| // decimal digits are sufficient to identify all binary floating-point | |
| // numbers (Matula, "In-and-Out conversions"). | |
| // This implies that the algorithm does not produce more than N decimal | |
| // digits. | |
| // | |
| // N = 17 for p = 53 (IEEE double precision) | |
| // N = 9 for p = 24 (IEEE single precision) | |
| } | |
| /*! | |
| v = buf * 10^decimal_exponent | |
| len is the length of the buffer (number of decimal digits) | |
| The buffer must be large enough, i.e. >= max_digits10. | |
| */ | |
| JSON_HEDLEY_NON_NULL(1) | |
| inline void grisu2(char* buf, int& len, int& decimal_exponent, | |
| diyfp m_minus, diyfp v, diyfp m_plus) | |
| { | |
| JSON_ASSERT(m_plus.e == m_minus.e); | |
| JSON_ASSERT(m_plus.e == v.e); | |
| // --------(-----------------------+-----------------------)-------- (A) | |
| // m- v m+ | |
| // | |
| // --------------------(-----------+-----------------------)-------- (B) | |
| // m- v m+ | |
| // | |
| // First scale v (and m- and m+) such that the exponent is in the range | |
| // [alpha, gamma]. | |
| const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); | |
| const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k | |
| // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] | |
| const diyfp w = diyfp::mul(v, c_minus_k); | |
| const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); | |
| const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); | |
| // ----(---+---)---------------(---+---)---------------(---+---)---- | |
| // w- w w+ | |
| // = c*m- = c*v = c*m+ | |
| // | |
| // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and | |
| // w+ are now off by a small amount. | |
| // In fact: | |
| // | |
| // w - v * 10^k < 1 ulp | |
| // | |
| // To account for this inaccuracy, add resp. subtract 1 ulp. | |
| // | |
| // --------+---[---------------(---+---)---------------]---+-------- | |
| // w- M- w M+ w+ | |
| // | |
| // Now any number in [M-, M+] (bounds included) will round to w when input, | |
| // regardless of how the input rounding algorithm breaks ties. | |
| // | |
| // And digit_gen generates the shortest possible such number in [M-, M+]. | |
| // Note that this does not mean that Grisu2 always generates the shortest | |
| // possible number in the interval (m-, m+). | |
| const diyfp M_minus(w_minus.f + 1, w_minus.e); | |
| const diyfp M_plus (w_plus.f - 1, w_plus.e ); | |
| decimal_exponent = -cached.k; // = -(-k) = k | |
| grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); | |
| } | |
| /*! | |
| v = buf * 10^decimal_exponent | |
| len is the length of the buffer (number of decimal digits) | |
| The buffer must be large enough, i.e. >= max_digits10. | |
| */ | |
| template<typename FloatType> | |
| JSON_HEDLEY_NON_NULL(1) | |
| void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) | |
| { | |
| static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3, | |
| "internal error: not enough precision"); | |
| JSON_ASSERT(std::isfinite(value)); | |
| JSON_ASSERT(value > 0); | |
| // If the neighbors (and boundaries) of 'value' are always computed for double-precision | |
| // numbers, all float's can be recovered using strtod (and strtof). However, the resulting | |
| // decimal representations are not exactly "short". | |
| // | |
| // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) | |
| // says "value is converted to a string as if by std::sprintf in the default ("C") locale" | |
| // and since sprintf promotes floats to doubles, I think this is exactly what 'std::to_chars' | |
| // does. | |
| // On the other hand, the documentation for 'std::to_chars' requires that "parsing the | |
| // representation using the corresponding std::from_chars function recovers value exactly". That | |
| // indicates that single precision floating-point numbers should be recovered using | |
| // 'std::strtof'. | |
| // | |
| // NB: If the neighbors are computed for single-precision numbers, there is a single float | |
| // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision | |
| // value is off by 1 ulp. | |
| #if 0 // NOLINT(readability-avoid-unconditional-preprocessor-if) | |
| const boundaries w = compute_boundaries(static_cast<double>(value)); | |
| #else | |
| const boundaries w = compute_boundaries(value); | |
| #endif | |
| grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); | |
| } | |
| /*! | |
| @brief appends a decimal representation of e to buf | |
| @return a pointer to the element following the exponent. | |
| @pre -1000 < e < 1000 | |
| */ | |
| JSON_HEDLEY_NON_NULL(1) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| inline char* append_exponent(char* buf, int e) | |
| { | |
| JSON_ASSERT(e > -1000); | |
| JSON_ASSERT(e < 1000); | |
| if (e < 0) | |
| { | |
| e = -e; | |
| *buf++ = '-'; | |
| } | |
| else | |
| { | |
| *buf++ = '+'; | |
| } | |
| auto k = static_cast<std::uint32_t>(e); | |
| if (k < 10) | |
| { | |
| // Always print at least two digits in the exponent. | |
| // This is for compatibility with printf("%g"). | |
| *buf++ = '0'; | |
| *buf++ = static_cast<char>('0' + k); | |
| } | |
| else if (k < 100) | |
| { | |
| *buf++ = static_cast<char>('0' + (k / 10)); | |
| k %= 10; | |
| *buf++ = static_cast<char>('0' + k); | |
| } | |
| else | |
| { | |
| *buf++ = static_cast<char>('0' + (k / 100)); | |
| k %= 100; | |
| *buf++ = static_cast<char>('0' + (k / 10)); | |
| k %= 10; | |
| *buf++ = static_cast<char>('0' + k); | |
| } | |
| return buf; | |
| } | |
| /*! | |
| @brief prettify v = buf * 10^decimal_exponent | |
| If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point | |
| notation. Otherwise it will be printed in exponential notation. | |
| @pre min_exp < 0 | |
| @pre max_exp > 0 | |
| */ | |
| JSON_HEDLEY_NON_NULL(1) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| inline char* format_buffer(char* buf, int len, int decimal_exponent, | |
| int min_exp, int max_exp) | |
| { | |
| JSON_ASSERT(min_exp < 0); | |
| JSON_ASSERT(max_exp > 0); | |
| const int k = len; | |
| const int n = len + decimal_exponent; | |
| // v = buf * 10^(n-k) | |
| // k is the length of the buffer (number of decimal digits) | |
| // n is the position of the decimal point relative to the start of the buffer. | |
| if (k <= n && n <= max_exp) | |
| { | |
| // digits[000] | |
| // len <= max_exp + 2 | |
| std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k)); | |
| // Make it look like a floating-point number (#362, #378) | |
| buf[n + 0] = '.'; | |
| buf[n + 1] = '0'; | |
| return buf + (static_cast<size_t>(n) + 2); | |
| } | |
| if (0 < n && n <= max_exp) | |
| { | |
| // dig.its | |
| // len <= max_digits10 + 1 | |
| JSON_ASSERT(k > n); | |
| std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n)); | |
| buf[n] = '.'; | |
| return buf + (static_cast<size_t>(k) + 1U); | |
| } | |
| if (min_exp < n && n <= 0) | |
| { | |
| // 0.[000]digits | |
| // len <= 2 + (-min_exp - 1) + max_digits10 | |
| std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k)); | |
| buf[0] = '0'; | |
| buf[1] = '.'; | |
| std::memset(buf + 2, '0', static_cast<size_t>(-n)); | |
| return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k)); | |
| } | |
| if (k == 1) | |
| { | |
| // dE+123 | |
| // len <= 1 + 5 | |
| buf += 1; | |
| } | |
| else | |
| { | |
| // d.igitsE+123 | |
| // len <= max_digits10 + 1 + 5 | |
| std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1); | |
| buf[1] = '.'; | |
| buf += 1 + static_cast<size_t>(k); | |
| } | |
| *buf++ = 'e'; | |
| return append_exponent(buf, n - 1); | |
| } | |
| /// eight decimal digits (a value below 10^8) as bytes 0..9, the first digit | |
| /// in the most significant byte: three steps that divide all lanes at once | |
| /// by a multiplication (the conversion of Xiang JunBo, as in Zmij) | |
| inline std::uint64_t eight_digit_bytes(std::uint64_t abcdefgh) noexcept | |
| { | |
| const std::uint64_t abcd_efgh = abcdefgh + (((std::uint64_t{1} << 32u) - 10000u) * ((abcdefgh * (((std::uint64_t{1} << 40u) / 10000u) + 1u)) >> 40u)); | |
| const std::uint64_t ab_cd_ef_gh = abcd_efgh + (((std::uint64_t{1} << 16u) - 100u) * (((abcd_efgh * (((std::uint64_t{1} << 19u) / 100u) + 1u)) >> 19u) & 0x7F0000007Fu)); | |
| return ab_cd_ef_gh + (((std::uint64_t{1} << 8u) - 10u) * (((ab_cd_ef_gh * (((std::uint64_t{1} << 10u) / 10u) + 1u)) >> 10u) & 0x000F000F000F000Fu)); | |
| } | |
| /// store the bytes of v, the most significant one first (one byte swap and | |
| /// one store where the byte order is known: compilers do not reliably merge | |
| /// the byte stores once this is inlined) | |
| inline void store_msb_first(char* p, std::uint64_t v) noexcept | |
| { | |
| #if JSON_LITTLE_ENDIAN_TARGET | |
| v = byteswap(v); | |
| std::memcpy(p, &v, sizeof(v)); | |
| #elif JSON_BIG_ENDIAN_TARGET | |
| std::memcpy(p, &v, sizeof(v)); | |
| #else | |
| for (unsigned i = 0; i < 8; ++i) | |
| { | |
| p[i] = static_cast<char>(v >> (56u - (8u * i))); | |
| } | |
| #endif | |
| } | |
| /*! | |
| @brief digits * 10^exp for a double, in the layout of format_buffer() | |
| The layout is that of format_buffer() with min_exp -4 and max_exp 15 (the | |
| digits10 of double). The digits are converted eight at a time and placed | |
| with fixed-size moves instead of per-digit loops and moves of the buffer. | |
| @param[in] digits the digits (not 0, at most 17 digits; trailing zeros allowed) | |
| @param[in] exp the decimal exponent of the last digit | |
| @return a pointer past the text; up to 41 bytes at @a first are written | |
| (some beyond the returned end) | |
| */ | |
| JSON_HEDLEY_NON_NULL(1) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| inline char* write_decimal(char* first, std::uint64_t digits, int exp) noexcept | |
| { | |
| JSON_ASSERT(digits != 0 && digits < 100000000000000000u); | |
| const std::uint64_t upper = digits / 100000000u; | |
| const std::uint64_t b0 = upper / 100000000u; // (one digit: it is its own byte) | |
| const std::uint64_t b1 = eight_digit_bytes(upper % 100000000u); | |
| const std::uint64_t b2 = eight_digit_bytes(digits % 100000000u); | |
| // leading and trailing zero digits: zero bytes, counted without division | |
| int leading = 16; | |
| int zeros = 16; | |
| if (b0 != 0) | |
| { | |
| leading = count_leading_zeros(b0) / 8; | |
| } | |
| else if (b1 != 0) | |
| { | |
| leading = 8 + (count_leading_zeros(b1) / 8); | |
| } | |
| else | |
| { | |
| leading += count_leading_zeros(b2) / 8; | |
| } | |
| if (b2 != 0) | |
| { | |
| zeros = count_trailing_zeros(b2) / 8; | |
| } | |
| else if (b1 != 0) | |
| { | |
| zeros = 8 + (count_trailing_zeros(b1) / 8); | |
| } | |
| // (else: 16, b0 is the one digit that is not 0) | |
| // the digits as text at text + leading, then '0's, so that fixed-size | |
| // moves need not check how many digits there are | |
| std::array<char, 64> text; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read | |
| store_msb_first(text.data(), b0 + 0x3030303030303030u); | |
| store_msb_first(text.data() + 8, b1 + 0x3030303030303030u); | |
| store_msb_first(text.data() + 16, b2 + 0x3030303030303030u); | |
| std::memset(text.data() + 24, '0', 40); | |
| const int k = 24 - leading - zeros; // significant digits | |
| const int n = k + exp + zeros; // position of the decimal point after the first digit | |
| const char* const s0 = text.data() + leading; | |
| if (-4 < n && n <= 15) | |
| { | |
| // "0.[000]digits" (n <= 0) is the digits after 1 - n leading '0's | |
| // with the point after the first; "digits[000].0" (n >= k) and | |
| // "dig.its" put the point after n characters | |
| const int pad = n <= 0 ? 1 - n : 0; | |
| const char* const s = s0 - pad; | |
| const int len = k + pad; | |
| const int point = n + pad; | |
| std::memcpy(first, s, 16); | |
| std::memcpy(first + point + 1, s + point, 24); | |
| first[point] = '.'; | |
| return first + (point >= len ? point + 2 : len + 1); | |
| } | |
| // d.igitse+XX, with at least two exponent digits (as append_exponent()) | |
| std::memcpy(first, s0, 16); | |
| std::memcpy(first + 2, s0 + 1, 16); | |
| first[1] = '.'; | |
| char* const end = first + (k == 1 ? 1 : k + 1); | |
| const int e = n - 1; | |
| const auto ea = e < 0 ? 0u - static_cast<unsigned>(e) : static_cast<unsigned>(e); // (unsigned: no signed overflow to assume) | |
| const bool three = ea >= 100; | |
| end[0] = 'e'; | |
| end[1] = e < 0 ? '-' : '+'; | |
| end[2] = static_cast<char>('0' + (three ? ea / 100 : (ea / 10) % 10)); | |
| end[3] = static_cast<char>('0' + (three ? (ea / 10) % 10 : ea % 10)); | |
| end[4] = static_cast<char>('0' + (ea % 10)); | |
| return end + (three ? 5 : 4); | |
| } | |
| /*! | |
| @brief the shortest decimal of a positive double (Zmij), as write_decimal() | |
| writes it | |
| For a normal double, the shorter candidate has 15 or 16 digits: they are | |
| converted at once (two halves of eight digits) and followed by the digit | |
| after them, if there is one, without the multiplication and division by 10 | |
| that counting the digits of one number would take. The fixed layouts move | |
| the digits after the point by one byte. | |
| @return a pointer past the text; up to 41 bytes at @a first are written | |
| (some beyond the returned end) | |
| */ | |
| JSON_HEDLEY_NON_NULL(1) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| inline char* write_shortest(char* first, const zmij::shortest_decimal d) noexcept | |
| { | |
| const std::uint64_t sig = d.integral; | |
| if (JSON_HEDLEY_UNLIKELY(sig < 100000000000000u || sig >= 10000000000000000u)) | |
| { | |
| // (subnormals) | |
| return d.has_digit ? write_decimal(first, (sig * 10) + d.digit, d.exponent) : write_decimal(first, sig, d.exponent + 1); | |
| } | |
| const bool sixteen = sig >= 1000000000000000u; // (else 15 digits) | |
| const int last = d.has_digit ? d.digit : 0; | |
| const std::uint64_t upper = sig / 100000000u; | |
| #if JSON_DTOA_SSE2 | |
| // NOLINTBEGIN(portability-simd-intrinsics) | |
| // the two halves in the 64-bit lanes, each as abcd * 2^32 + efgh, then as | |
| // bytes (as eight_digit_bytes(), one lane each) | |
| const __m128i x = _mm_set_epi64x(static_cast<long long>(sig - (upper * 100000000u)), static_cast<long long>(upper)); // NOLINT(runtime/int) | |
| const __m128i abcd = _mm_srli_epi64(_mm_mul_epu32(x, _mm_set1_epi64x(109951163)), 40); // 2^40 / 10000 + 1 | |
| const __m128i abcd_efgh = _mm_add_epi64(x, _mm_mul_epu32(abcd, _mm_set1_epi64x(4294957296))); // 2^32 - 10000 | |
| // 32-bit lanes in the order of the text: abcd, efgh of both halves | |
| const __m128i fours = _mm_shuffle_epi32(abcd_efgh, _MM_SHUFFLE(2, 3, 0, 1)); | |
| const __m128i ab = _mm_srli_epi16(_mm_mulhi_epu16(fours, _mm_set1_epi32(5243)), 3); | |
| const __m128i ab_cd = _mm_or_si128(_mm_slli_epi32(_mm_sub_epi16(fours, _mm_mullo_epi16(ab, _mm_set1_epi32(100))), 16), ab); | |
| // 16-bit lanes ab (< 100) -> bytes a, b: 256 * ab - 2559 * (ab / 10) | |
| const __m128i bytes = _mm_sub_epi16(_mm_slli_epi16(ab_cd, 8), _mm_mullo_epi16(_mm_set1_epi16(2559), _mm_mulhi_epu16(ab_cd, _mm_set1_epi16(6554)))); | |
| // the last digit that is not 0 (sig is not 0) | |
| const auto nonzero = static_cast<std::uint64_t>(_mm_movemask_epi8(_mm_cmpgt_epi8(bytes, _mm_setzero_si128()))); | |
| const int digits = 63 - count_leading_zeros(nonzero) + (sixteen ? 1 : 0); // without trailing zeros | |
| const __m128i chars = _mm_add_epi8(bytes, _mm_set1_epi8('0')); | |
| // the 16 characters from the first digit | |
| const __m128i s = sixteen ? chars : _mm_or_si128(_mm_srli_si128(chars, 1), _mm_slli_si128(_mm_cvtsi32_si128('0' + last), 15)); | |
| const char s16 = static_cast<char>(sixteen ? '0' + last : '0'); // the 17th | |
| const auto store_16 = [&s](char* p) noexcept | |
| { | |
| std::memcpy(p, &s, 16); | |
| }; | |
| const char first_digit = static_cast<char>(_mm_cvtsi128_si32(s)); | |
| // NOLINTEND(portability-simd-intrinsics) | |
| #elif JSON_DTOA_NEON | |
| // as with SSE2: the halves in 32-bit lanes, then abcd, efgh of both | |
| const uint32x2_t halves = vcreate_u32(upper | ((sig - (upper * 100000000u)) << 32u)); | |
| const uint32x2_t abcd = vmovn_u64(vshrq_n_u64(vmull_n_u32(halves, static_cast<std::uint32_t>(((std::uint64_t{1} << 40u) / 10000u) + 1u)), 40)); | |
| const uint32x2_t efgh = vmls_n_u32(halves, abcd, 10000u); | |
| const uint32x4_t fours = vcombine_u32(vzip1_u32(abcd, efgh), vzip2_u32(abcd, efgh)); | |
| const uint32x4_t ab = vshrq_n_u32(vmulq_n_u32(fours, 5243u), 19); | |
| const uint16x8_t ab_cd = vreinterpretq_u16_u32(vorrq_u32(ab, vshlq_n_u32(vmlsq_n_u32(fours, ab, 100u), 16))); | |
| const uint16x8_t tens = vshrq_n_u16(vmulq_n_u16(ab_cd, 103u), 10); | |
| const uint8x16_t bytes = vreinterpretq_u8_u16(vorrq_u16(tens, vshlq_n_u16(vmlsq_n_u16(ab_cd, tens, 10u), 8))); | |
| // the last digit that is not 0 (sig is not 0): a nibble per byte | |
| const std::uint64_t nonzero = vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(vreinterpretq_u16_u8(vtstq_u8(bytes, bytes)), 4)), 0); | |
| const int digits = ((63 - count_leading_zeros(nonzero)) / 4) + (sixteen ? 1 : 0); // without trailing zeros | |
| const uint8x16_t chars = vaddq_u8(bytes, vdupq_n_u8('0')); | |
| // the 16 characters from the first digit | |
| const uint8x16_t s = sixteen ? chars : vextq_u8(chars, vdupq_n_u8(static_cast<std::uint8_t>('0' + last)), 1); | |
| const char s16 = static_cast<char>(sixteen ? '0' + last : '0'); // the 17th | |
| const auto store_16 = [&s](char* p) noexcept | |
| { | |
| vst1q_u8(reinterpret_cast<std::uint8_t*>(p), s); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) | |
| }; | |
| const auto first_digit = static_cast<char>(vgetq_lane_u8(s, 0)); | |
| #else | |
| const std::uint64_t hi = eight_digit_bytes(upper); | |
| const std::uint64_t lo = eight_digit_bytes(sig - (upper * 100000000u)); | |
| // trailing zero digits: zero bytes (sig is not 0) | |
| const int zeros = lo != 0 ? count_trailing_zeros(lo) / 8 : 8 + (count_trailing_zeros(hi) / 8); | |
| const int digits = 15 - zeros + (sixteen ? 1 : 0); // without trailing zeros | |
| // the 16 characters from the first digit | |
| const std::uint64_t s_hi = (sixteen ? hi : (hi << 8u) | (lo >> 56u)) + 0x3030303030303030u; | |
| const std::uint64_t s_lo = (sixteen ? lo : (lo << 8u) | static_cast<std::uint64_t>(last)) + 0x3030303030303030u; | |
| const char s16 = static_cast<char>(sixteen ? '0' + last : '0'); // the 17th | |
| const auto store_16 = [s_hi, s_lo](char* p) noexcept | |
| { | |
| store_msb_first(p, s_hi); | |
| store_msb_first(p + 8, s_lo); | |
| }; | |
| const auto first_digit = static_cast<char>(s_hi >> 56u); | |
| #endif | |
| const int len = d.has_digit ? 16 + (sixteen ? 1 : 0) : digits; // significant digits | |
| const int n = 16 + (sixteen ? 1 : 0) + d.exponent; // digits before the point | |
| if (JSON_HEDLEY_LIKELY(n >= 1 && n <= 15)) | |
| { | |
| // "dig.its" and "digits[000].0": the digits after the point move by | |
| // one byte ('0's follow the digits) | |
| #if JSON_DTOA_SSE2 | |
| // NOLINTBEGIN(portability-simd-intrinsics) | |
| // (in the register: reading the digits back from memory right after | |
| // storing them waits until the stores are done) | |
| const __m128i at = _mm_set1_epi8(static_cast<char>(n)); | |
| const __m128i index = _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); | |
| const __m128i before = _mm_cmpgt_epi8(at, index); | |
| const __m128i after = _mm_cmpgt_epi8(index, at); | |
| const __m128i text = _mm_or_si128(_mm_or_si128(_mm_and_si128(s, before), _mm_and_si128(_mm_slli_si128(s, 1), after)), | |
| _mm_andnot_si128(_mm_or_si128(before, after), _mm_set1_epi8('.'))); | |
| std::memcpy(first, &text, 16); | |
| first[16] = static_cast<char>(_mm_extract_epi16(s, 7) >> 8); | |
| first[17] = s16; | |
| // NOLINTEND(portability-simd-intrinsics) | |
| #elif JSON_DTOA_NEON | |
| const uint8x16_t index = vcombine_u8(vcreate_u8(0x0706050403020100u), vcreate_u8(0x0F0E0D0C0B0A0908u)); | |
| const uint8x16_t at = vdupq_n_u8(static_cast<std::uint8_t>(n)); | |
| const uint8x16_t after_point = vbslq_u8(vcgtq_u8(index, at), vextq_u8(vdupq_n_u8(0), s, 15), vdupq_n_u8('.')); | |
| vst1q_u8(reinterpret_cast<std::uint8_t*>(first), vbslq_u8(vcltq_u8(index, at), s, after_point)); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) | |
| first[16] = static_cast<char>(vgetq_lane_u8(s, 15)); | |
| first[17] = s16; | |
| #else | |
| store_16(first); | |
| first[16] = s16; | |
| std::uint64_t after_point[2]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read | |
| std::memcpy(after_point, first + n, 16); | |
| std::memcpy(first + n + 1, after_point, 16); | |
| first[n] = '.'; | |
| #endif | |
| return first + (n >= len ? n + 2 : len + 1); | |
| } | |
| if (n <= 0 && n > -4) | |
| { | |
| // "0.[000]digits" | |
| std::memset(first, '0', 8); | |
| first[1] = '.'; | |
| store_16(first + 2 - n); | |
| first[18 - n] = s16; | |
| return first + 2 - n + len; | |
| } | |
| // d.igitse+XX, with at least two exponent digits (as append_exponent()) | |
| store_16(first + 1); | |
| first[17] = s16; | |
| first[0] = first_digit; | |
| first[1] = '.'; | |
| char* const end = first + (len == 1 ? 1 : len + 1); | |
| const int e = n - 1; | |
| const auto ea = e < 0 ? 0u - static_cast<unsigned>(e) : static_cast<unsigned>(e); // (unsigned: no signed overflow to assume) | |
| const bool three = ea >= 100; | |
| end[0] = 'e'; | |
| end[1] = e < 0 ? '-' : '+'; | |
| end[2] = static_cast<char>('0' + (three ? ea / 100 : (ea / 10) % 10)); | |
| end[3] = static_cast<char>('0' + (three ? (ea / 10) % 10 : ea % 10)); | |
| end[4] = static_cast<char>('0' + (ea % 10)); | |
| return end + (three ? 5 : 4); | |
| } | |
| /// the powers of ten up to 10^19 (all that fit in std::uint64_t) | |
| inline const std::array<std::uint64_t, 20>& powers_of_ten() noexcept | |
| { | |
| static const std::array<std::uint64_t, 20> powers = | |
| { | |
| { | |
| 1u, | |
| 10u, | |
| 100u, | |
| 1000u, | |
| 10000u, | |
| 100000u, | |
| 1000000u, | |
| 10000000u, | |
| 100000000u, | |
| 1000000000u, | |
| 10000000000u, | |
| 100000000000u, | |
| 1000000000000u, | |
| 10000000000000u, | |
| 100000000000000u, | |
| 1000000000000000u, | |
| 10000000000000000u, | |
| 100000000000000000u, | |
| 1000000000000000000u, | |
| 10000000000000000000u | |
| } | |
| }; | |
| return powers; | |
| } | |
| /*! | |
| @brief digits * 10^exp, as write_decimal() writes it, for the digits of a | |
| double that need no conversion (count digits, at most 15, the first not 0; | |
| trailing zeros allowed): extended to 16 digits and written by write_shortest() | |
| @return a pointer past the text; up to 41 bytes at @a first are written | |
| (some beyond the returned end) | |
| */ | |
| JSON_HEDLEY_NON_NULL(1) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| inline char* write_short_decimal(char* first, std::uint64_t digits, int count, int exp) noexcept | |
| { | |
| JSON_ASSERT(digits >= powers_of_ten()[static_cast<std::size_t>(count - 1)] && count <= 15); | |
| const int scale = 16 - count; | |
| return write_shortest(first, zmij::shortest_decimal{digits * powers_of_ten()[static_cast<std::size_t>(scale)], exp - scale - 1, 0, false}); | |
| } | |
| /// as write_short_decimal(), counting the digits (not 0, less than 10^15) | |
| JSON_HEDLEY_NON_NULL(1) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| inline char* write_short_decimal(char* first, std::uint64_t digits, int exp) noexcept | |
| { | |
| JSON_ASSERT(digits != 0 && digits < 1000000000000000u); | |
| // floor(log10(2^bits)) + 1 digits, or one less | |
| const int log2_bound = ((64 - count_leading_zeros(digits)) * 1233) >> 12; | |
| const int count = log2_bound + (digits >= powers_of_ten()[static_cast<std::size_t>(log2_bound)] ? 1 : 0); | |
| return write_short_decimal(first, digits, count, exp); | |
| } | |
| /*! | |
| @brief whether FloatType is an IEEE 754 binary64 type (a double, or a long double | |
| that has the same format, as with MSVC and on Apple's Arm CPUs) | |
| These are the types the conversion of Zmij (see zmij.hpp) is used for; all | |
| others (binary32, or a format the library does not know) use Grisu2. | |
| */ | |
| template<typename FloatType> | |
| constexpr bool has_binary64_format() noexcept | |
| { | |
| return std::numeric_limits<FloatType>::is_iec559 | |
| && std::numeric_limits<FloatType>::digits == 53 | |
| && std::numeric_limits<FloatType>::max_exponent == 1024 | |
| && sizeof(FloatType) == sizeof(std::uint64_t); | |
| } | |
| template<typename FloatType> | |
| struct is_binary64 : std::integral_constant<bool, has_binary64_format<FloatType>()> {}; | |
| /// a positive finite float (other than binary64): Grisu2 and format_buffer() | |
| template<typename FloatType> | |
| JSON_HEDLEY_NON_NULL(1, 2) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| char* write_positive_grisu2(char* first, const char* last, FloatType value) | |
| { | |
| JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10); | |
| static_cast<void>(last); // (only used in the assertion) | |
| // Compute v = buffer * 10^decimal_exponent. | |
| // The decimal digits are stored in the buffer, which needs to be interpreted | |
| // as an unsigned decimal integer. | |
| // len is the length of the buffer, i.e., the number of decimal digits. | |
| int len = 0; | |
| int decimal_exponent = 0; | |
| grisu2(first, len, decimal_exponent, value); | |
| JSON_ASSERT(len <= std::numeric_limits<FloatType>::max_digits10); | |
| // Format the buffer like printf("%.*g", prec, value) | |
| constexpr int kMinExp = -4; | |
| // Use digits10 here to increase compatibility with version 2. | |
| constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10; | |
| JSON_ASSERT(last - first >= kMaxExp + 2); | |
| JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10); | |
| JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6); | |
| return format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); | |
| } | |
| /// a positive finite binary64 number: the shortest digits (Zmij), laid out by | |
| /// write_shortest() (through a local buffer if [first, last) is shorter than | |
| /// the 41 bytes it may write) | |
| template<typename FloatType> | |
| JSON_HEDLEY_NON_NULL(1, 2) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| char* write_positive_zmij(char* first, const char* last, FloatType value) | |
| { | |
| static_assert(is_binary64<FloatType>::value, | |
| "internal error: the conversion of Zmij needs IEEE 754 binary64 numbers"); | |
| const auto bits = bit_cast<std::uint64_t>(value); | |
| const zmij::shortest_decimal d = zmij::to_shortest(bits); | |
| if (JSON_HEDLEY_LIKELY(last - first >= 41)) | |
| { | |
| return write_shortest(first, d); | |
| } | |
| std::array<char, 64> buf; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read | |
| const auto len = static_cast<std::size_t>(write_shortest(buf.data(), d) - buf.data()); | |
| JSON_ASSERT(last - first >= static_cast<std::ptrdiff_t>(len)); | |
| std::memcpy(first, buf.data(), len); | |
| return first + len; | |
| } | |
| /// a positive finite binary64 number: Zmij (as a long double has the format of | |
| /// a double here, its bits are those of the double of the same value) | |
| template<typename FloatType> | |
| JSON_HEDLEY_NON_NULL(1, 2) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| char* write_positive(char* first, const char* last, FloatType value, std::true_type /*is_binary64*/) | |
| { | |
| return write_positive_zmij(first, last, value); | |
| } | |
| /// a positive finite float of any other format: Grisu2 | |
| template<typename FloatType> | |
| JSON_HEDLEY_NON_NULL(1, 2) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| char* write_positive(char* first, const char* last, FloatType value, std::false_type /*is_binary64*/) | |
| { | |
| return write_positive_grisu2(first, last, value); | |
| } | |
| /// a positive finite float: Zmij for binary64 numbers, Grisu2 otherwise | |
| template<typename FloatType> | |
| JSON_HEDLEY_NON_NULL(1, 2) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| char* write_positive(char* first, const char* last, FloatType value) | |
| { | |
| return write_positive(first, last, value, is_binary64<FloatType> {}); | |
| } | |
| } // namespace dtoa_impl | |
| /*! | |
| @brief generates a decimal representation of the floating-point number value in [first, last). | |
| The format of the resulting decimal representation is similar to printf's %g | |
| format. Returns an iterator pointing past-the-end of the decimal representation. | |
| @note The input number must be finite, i.e. NaN's and Inf's are not supported. | |
| @note The buffer must be large enough. | |
| @note The result is NOT null-terminated. | |
| */ | |
| template<typename FloatType> | |
| JSON_HEDLEY_NON_NULL(1, 2) | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| char* to_chars(char* first, const char* last, FloatType value) | |
| { | |
| JSON_ASSERT(std::isfinite(value)); | |
| // Use signbit(value) instead of (value < 0) since signbit works for -0. | |
| if (std::signbit(value)) | |
| { | |
| value = -value; | |
| *first++ = '-'; | |
| } | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") | |
| #endif | |
| if (value == 0) // +-0 | |
| { | |
| *first++ = '0'; | |
| // Make it look like a floating-point number (#362, #378) | |
| *first++ = '.'; | |
| *first++ = '0'; | |
| return first; | |
| } | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| return dtoa_impl::write_positive(first, last, value); | |
| } | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/exceptions.hpp> | |
| // #include <nlohmann/detail/input/string_scan.hpp> | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/meta/cpp_future.hpp> | |
| // #include <nlohmann/detail/output/error_handler.hpp> | |
| // #include <nlohmann/detail/output/output_adapters.hpp> | |
| // #include <nlohmann/detail/recursion_depth_limit.hpp> | |
| // #include <nlohmann/detail/string_concat.hpp> | |
| // #include <nlohmann/detail/string_utils.hpp> | |
| // #include <nlohmann/detail/value_t.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| /////////////////// | |
| // serialization // | |
| /////////////////// | |
| template<typename BasicJsonType> | |
| class serializer | |
| { | |
| using string_t = typename BasicJsonType::string_t; | |
| using number_float_t = typename BasicJsonType::number_float_t; | |
| using number_integer_t = typename BasicJsonType::number_integer_t; | |
| using number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
| /// type of the absolute value of an integer: number_unsigned_t, or its | |
| /// unsigned counterpart if it is signed (it may be number_integer_t, #2573) | |
| using number_magnitude_t = typename std::conditional < | |
| std::is_integral<number_unsigned_t>::value && std::is_signed<number_unsigned_t>::value, | |
| std::make_unsigned<number_unsigned_t>, | |
| std::enable_if<true, number_unsigned_t >>::type::type; | |
| using binary_char_t = typename BasicJsonType::binary_t::value_type; | |
| public: | |
| /*! | |
| @param[in] s output adapter to serialize to; not owned by the serializer, | |
| so it must outlive it (it lives at the call site) | |
| @param[in] ichar indentation character to use | |
| @param[in] pretty_print_ whether the output shall be pretty-printed | |
| @param[in] ensure_ascii_ If @a ensure_ascii_ is true, all non-ASCII | |
| characters in the output are escaped with `\\uXXXX` sequences, and the | |
| result consists of ASCII characters only. | |
| @param[in] indent_step_ the indent level | |
| @param[in] error_handler_ how to react on decoding errors | |
| None of @a pretty_print_, @a ensure_ascii_ and @a indent_step_ change over | |
| the life of the serializer, so they are captured once here instead of | |
| being threaded through every call to @ref dump, @ref dump_container and | |
| @ref dump_iteratively. | |
| */ | |
| serializer(output_adapter_protocol<char>& s, const char ichar, | |
| const bool pretty_print_ = false, | |
| const bool ensure_ascii_ = false, | |
| const std::size_t indent_step_ = 0, | |
| error_handler_t error_handler_ = error_handler_t::strict) | |
| : o(&s) | |
| , number_buffer() // NOLINT(readability-redundant-member-init) | |
| , string_buffer() // NOLINT(readability-redundant-member-init) | |
| , indent_char(ichar) | |
| , pretty_print(pretty_print_) | |
| , ensure_ascii(ensure_ascii_) | |
| , indent_step(indent_step_) | |
| , error_handler(error_handler_) | |
| , write_buffer() // NOLINT(readability-redundant-member-init) | |
| {} | |
| // deleted because of pointer members | |
| serializer(const serializer&) = delete; | |
| serializer& operator=(const serializer&) = delete; | |
| serializer(serializer&&) = delete; | |
| serializer& operator=(serializer&&) = delete; | |
| ~serializer() = default; | |
| /*! | |
| @brief internal implementation of the serialization function | |
| This function is called by the public member function dump and organizes | |
| the serialization internally. The indentation level is propagated as | |
| additional parameter. Arrays and objects are serialized without recursion, | |
| however deeply they are nested. | |
| - strings and object keys are escaped using @ref dump_escaped | |
| - integer numbers are converted using a digit-pair lookup table (@ref dump_integer) | |
| - floating-point numbers are converted to a string using @ref dump_float, which | |
| uses `to_chars` for IEEE-754 types and `snprintf` otherwise | |
| - binary values are serialized as objects containing the subtype and the | |
| byte array | |
| @param[in] val value to serialize | |
| @param[in] current_indent the current indent level (only used internally) | |
| */ | |
| void dump(const BasicJsonType& val, | |
| const std::size_t current_indent = 0) | |
| { | |
| dump_element(val, current_indent, 0); | |
| flush(); | |
| } | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| /*! | |
| @brief serialize the object or array @a val | |
| Writes into the serializer's internal @ref write_buffer instead of issuing | |
| a virtual call per token; the public @ref dump flushes the buffer once the | |
| top-level value has been serialized. Scalars are written by @ref dump_scalar, | |
| which @ref dump_element calls without entering this function. | |
| Serializing a container descends into its elements, so a value nested deeply | |
| enough used to exhaust the call stack and terminate the process with no | |
| exception to catch. The descent is bounded here: once @ref recursion_depth_limit | |
| levels have been entered, @ref dump_iteratively writes out what is left | |
| without the call stack. A value nested less deeply than that - all but a | |
| vanishing minority - is written by exactly the code that always wrote it. | |
| @sa https://github.com/nlohmann/json/issues/5387 | |
| */ | |
| void dump_container(const BasicJsonType& val, | |
| const std::size_t current_indent, | |
| const std::size_t depth) | |
| { | |
| JSON_ASSERT(val.m_data.m_type == value_t::object || val.m_data.m_type == value_t::array); | |
| if (JSON_HEDLEY_UNLIKELY(depth >= recursion_depth_limit())) | |
| { | |
| dump_iteratively(val, current_indent); | |
| return; | |
| } | |
| if (val.m_data.m_type == value_t::object) | |
| { | |
| if (val.m_data.m_value.object->empty()) | |
| { | |
| put_literal("{}"); | |
| return; | |
| } | |
| if (pretty_print) | |
| { | |
| // variable to hold indentation for recursive calls | |
| const auto new_indent = next_indent(current_indent, indent_step); | |
| put_literal_indent("{\n", new_indent); | |
| // first n-1 elements | |
| auto i = val.m_data.m_value.object->cbegin(); | |
| for (std::size_t cnt = 0; cnt < val.m_data.m_value.object->size() - 1; ++cnt, ++i) | |
| { | |
| put_object_key(i->first, "\": "); | |
| dump_element(i->second, new_indent, depth + 1); | |
| put_literal_indent(",\n", new_indent); | |
| } | |
| // last element | |
| JSON_ASSERT(i != val.m_data.m_value.object->cend()); | |
| JSON_ASSERT(std::next(i) == val.m_data.m_value.object->cend()); | |
| put_object_key(i->first, "\": "); | |
| dump_element(i->second, new_indent, depth + 1); | |
| put_literal_indent("\n", current_indent); | |
| put_char('}'); | |
| } | |
| else | |
| { | |
| put_char('{'); | |
| // first n-1 elements | |
| auto i = val.m_data.m_value.object->cbegin(); | |
| for (std::size_t cnt = 0; cnt < val.m_data.m_value.object->size() - 1; ++cnt, ++i) | |
| { | |
| put_object_key(i->first, "\":"); | |
| dump_element(i->second, 0, depth + 1); | |
| put_char(','); | |
| } | |
| // last element | |
| JSON_ASSERT(i != val.m_data.m_value.object->cend()); | |
| JSON_ASSERT(std::next(i) == val.m_data.m_value.object->cend()); | |
| put_object_key(i->first, "\":"); | |
| dump_element(i->second, 0, depth + 1); | |
| put_char('}'); | |
| } | |
| return; | |
| } | |
| if (val.m_data.m_value.array->empty()) | |
| { | |
| put_literal("[]"); | |
| return; | |
| } | |
| if (pretty_print) | |
| { | |
| // variable to hold indentation for recursive calls | |
| const auto new_indent = next_indent(current_indent, indent_step); | |
| put_literal_indent("[\n", new_indent); | |
| // first n-1 elements | |
| for (auto i = val.m_data.m_value.array->cbegin(); | |
| i != val.m_data.m_value.array->cend() - 1; ++i) | |
| { | |
| dump_element(*i, new_indent, depth + 1); | |
| put_literal_indent(",\n", new_indent); | |
| } | |
| // last element | |
| JSON_ASSERT(!val.m_data.m_value.array->empty()); | |
| dump_element(val.m_data.m_value.array->back(), new_indent, depth + 1); | |
| put_literal_indent("\n", current_indent); | |
| put_char(']'); | |
| } | |
| else | |
| { | |
| put_char('['); | |
| // first n-1 elements | |
| for (auto i = val.m_data.m_value.array->cbegin(); | |
| i != val.m_data.m_value.array->cend() - 1; ++i) | |
| { | |
| dump_element(*i, 0, depth + 1); | |
| put_char(','); | |
| } | |
| // last element | |
| JSON_ASSERT(!val.m_data.m_value.array->empty()); | |
| dump_element(val.m_data.m_value.array->back(), 0, depth + 1); | |
| put_char(']'); | |
| } | |
| } | |
| private: | |
| /*! | |
| @brief serialize an element of a container | |
| Most elements are scalars, which need none of the state dump_container() keeps | |
| for a container; writing them from here spares each the entry and exit of | |
| that function. | |
| */ | |
| JSON_HEDLEY_ALWAYS_INLINE void dump_element(const BasicJsonType& val, | |
| const std::size_t current_indent, | |
| const std::size_t depth) | |
| { | |
| if (val.m_data.m_type == value_t::object || val.m_data.m_type == value_t::array) | |
| { | |
| dump_container(val, current_indent, depth); | |
| } | |
| else | |
| { | |
| dump_scalar(val, current_indent); | |
| } | |
| } | |
| /*! | |
| @brief write out @a val and everything below it without the call stack | |
| Emits the same bytes as @ref dump_container, keeping the containers it has | |
| entered on an explicit stack instead of descending into them. Only reached | |
| for values nested deeper than @ref recursion_depth_limit, which is why it is not | |
| written for speed: walking every value this way measured up to 20% slower on | |
| object-heavy documents than letting the compiler drive the descent. | |
| */ | |
| void dump_iteratively(const BasicJsonType& val, | |
| const std::size_t current_indent = 0) | |
| { | |
| // Scalars, empty containers and binary values are written by dump_value | |
| // alone, so nothing is allocated for them: only a container with | |
| // elements is ever pushed. | |
| std::vector<dump_frame> stack; | |
| dump_value(val, current_indent, stack); | |
| while (!stack.empty()) | |
| { | |
| dump_frame& frame = stack.back(); | |
| if (frame.value->m_data.m_type == value_t::object) | |
| { | |
| const auto* object = frame.value->m_data.m_value.object; | |
| if (frame.object_it == object->cend()) | |
| { | |
| if (pretty_print) | |
| { | |
| put_literal_indent("\n", frame.current_indent); | |
| } | |
| put_char('}'); | |
| stack.pop_back(); | |
| continue; | |
| } | |
| // the separator goes in front of every element but the first, | |
| // which puts exactly one between each pair and none at the end | |
| if (frame.object_it != object->cbegin()) | |
| { | |
| if (pretty_print) | |
| { | |
| put_literal(",\n"); | |
| } | |
| else | |
| { | |
| put_char(','); | |
| } | |
| } | |
| if (pretty_print) | |
| { | |
| put_indent(frame.child_indent); | |
| } | |
| if (pretty_print) | |
| { | |
| put_object_key(frame.object_it->first, "\": "); | |
| } | |
| else | |
| { | |
| put_object_key(frame.object_it->first, "\":"); | |
| } | |
| const BasicJsonType& element = frame.object_it->second; | |
| ++frame.object_it; | |
| // read everything needed from the frame before this: entering a | |
| // container pushes another one and can move them all | |
| const std::size_t element_indent = frame.child_indent; | |
| dump_value(element, element_indent, stack); | |
| } | |
| else | |
| { | |
| const auto* array = frame.value->m_data.m_value.array; | |
| if (frame.array_it == array->cend()) | |
| { | |
| if (pretty_print) | |
| { | |
| put_literal_indent("\n", frame.current_indent); | |
| } | |
| put_char(']'); | |
| stack.pop_back(); | |
| continue; | |
| } | |
| if (frame.array_it != array->cbegin()) | |
| { | |
| if (pretty_print) | |
| { | |
| put_literal(",\n"); | |
| } | |
| else | |
| { | |
| put_char(','); | |
| } | |
| } | |
| if (pretty_print) | |
| { | |
| put_indent(frame.child_indent); | |
| } | |
| const BasicJsonType& element = *frame.array_it; | |
| ++frame.array_it; | |
| // see above | |
| const std::size_t element_indent = frame.child_indent; | |
| dump_value(element, element_indent, stack); | |
| } | |
| } | |
| } | |
| private: | |
| /// @brief a container that has been opened but not closed yet | |
| struct dump_frame | |
| { | |
| dump_frame(const BasicJsonType* value_, const std::size_t current_indent_, | |
| const std::size_t child_indent_) noexcept | |
| : value(value_) | |
| , current_indent(current_indent_) | |
| , child_indent(child_indent_) | |
| {} | |
| /// the object or array being serialized | |
| const BasicJsonType* value; | |
| /// the element to serialize next; which of the two is live follows from | |
| /// the type of @a value. They are kept side by side rather than in a | |
| /// union, which would need its special members written out by hand, see | |
| /// detail/iterators/internal_iterator.hpp | |
| typename BasicJsonType::object_t::const_iterator object_it{}; | |
| typename BasicJsonType::array_t::const_iterator array_it{}; | |
| /// the indentation of the container itself, used by its closing bracket | |
| std::size_t current_indent; | |
| /// the indentation of the container's elements | |
| std::size_t child_indent; | |
| }; | |
| /*! | |
| @brief serialize the value @a val, but not the elements of a container | |
| An object or array with elements is opened and pushed onto @a stack for | |
| @ref dump_iteratively to walk; everything else - including a binary value, | |
| which looks like an object but has no elements to descend into - is written | |
| out in full by @ref dump_scalar. | |
| */ | |
| void dump_value(const BasicJsonType& val, | |
| const std::size_t current_indent, | |
| std::vector<dump_frame>& stack) | |
| { | |
| switch (val.m_data.m_type) | |
| { | |
| case value_t::object: | |
| { | |
| if (val.m_data.m_value.object->empty()) | |
| { | |
| put_literal("{}"); | |
| return; | |
| } | |
| std::size_t child_indent = current_indent; | |
| if (pretty_print) | |
| { | |
| put_literal("{\n"); | |
| child_indent = next_indent(current_indent, indent_step); | |
| } | |
| else | |
| { | |
| put_char('{'); | |
| } | |
| stack.emplace_back(&val, current_indent, child_indent); | |
| stack.back().object_it = val.m_data.m_value.object->cbegin(); | |
| return; | |
| } | |
| case value_t::array: | |
| { | |
| if (val.m_data.m_value.array->empty()) | |
| { | |
| put_literal("[]"); | |
| return; | |
| } | |
| std::size_t child_indent = current_indent; | |
| if (pretty_print) | |
| { | |
| put_literal("[\n"); | |
| child_indent = next_indent(current_indent, indent_step); | |
| } | |
| else | |
| { | |
| put_char('['); | |
| } | |
| stack.emplace_back(&val, current_indent, child_indent); | |
| stack.back().array_it = val.m_data.m_value.array->cbegin(); | |
| return; | |
| } | |
| case value_t::string: | |
| case value_t::binary: | |
| case value_t::boolean: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| case value_t::discarded: | |
| case value_t::null: | |
| default: | |
| dump_scalar(val, current_indent); | |
| return; | |
| } | |
| } | |
| /*! | |
| @brief serialize the value @a val, which is neither an object nor an array | |
| Shared by @ref dump_element and @ref dump_value, so that a value is written | |
| the same way however deeply it is nested. A binary value is written out here | |
| in full: it looks like an object, but has no elements to descend into. | |
| @param[in] val value to serialize; not an object or array | |
| @param[in] current_indent the indentation of @a val, used for a | |
| pretty-printed binary value | |
| */ | |
| void dump_scalar(const BasicJsonType& val, const std::size_t current_indent) | |
| { | |
| switch (val.m_data.m_type) | |
| { | |
| case value_t::string: | |
| { | |
| dump_string_value(*val.m_data.m_value.string); | |
| return; | |
| } | |
| case value_t::binary: | |
| { | |
| dump_binary_value(current_indent, *val.m_data.m_value.binary); | |
| 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_signed_value(val.m_data.m_value.number_integer); | |
| return; | |
| } | |
| case value_t::number_unsigned: | |
| { | |
| dump_unsigned_value(val.m_data.m_value.number_unsigned); | |
| return; | |
| } | |
| case value_t::number_float: | |
| { | |
| dump_float_value(val.m_data.m_value.number_float); | |
| return; | |
| } | |
| case value_t::discarded: | |
| { | |
| put_literal("<discarded>"); | |
| return; | |
| } | |
| case value_t::null: | |
| { | |
| put_literal("null"); | |
| return; | |
| } | |
| case value_t::object: // LCOV_EXCL_LINE | |
| case value_t::array: // LCOV_EXCL_LINE | |
| default: // LCOV_EXCL_LINE | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE | |
| } | |
| } | |
| /// @brief write the string @a s in quotes; kept out of line, so that the | |
| /// other scalars do not pay for its register needs (and the other way round) | |
| JSON_HEDLEY_NEVER_INLINE void dump_string_value(const string_t& s) | |
| { | |
| #if JSON_LITTLE_ENDIAN_TARGET | |
| if (s.size() <= short_string_max && put_short_quoted(s, "\"")) | |
| { | |
| return; | |
| } | |
| #endif | |
| put_char('"'); | |
| dump_escaped(s); | |
| put_char('"'); | |
| } | |
| // The numbers, and the rest of what dump_scalar() writes, are left to | |
| // functions of their own as well: a single function holding all of them | |
| // saves and restores every register any of them needs, on every call. Now | |
| // dump_scalar() only dispatches, and each writer pays for what it uses. | |
| JSON_HEDLEY_NEVER_INLINE void dump_signed_value(const number_integer_t x) | |
| { | |
| dump_integer(x); | |
| } | |
| JSON_HEDLEY_NEVER_INLINE void dump_unsigned_value(const number_unsigned_t x) | |
| { | |
| dump_integer(x); | |
| } | |
| JSON_HEDLEY_NEVER_INLINE void dump_float_value(const number_float_t x) | |
| { | |
| dump_float(x); | |
| } | |
| JSON_HEDLEY_NEVER_INLINE void dump_binary_value(const std::size_t current_indent, const typename BasicJsonType::binary_t& binary) | |
| { | |
| if (pretty_print) | |
| { | |
| // variable to hold indentation for the bytes | |
| const auto new_indent = next_indent(current_indent, indent_step); | |
| put_literal_indent("{\n", new_indent); | |
| put_literal("\"bytes\": ["); | |
| if (!binary.empty()) | |
| { | |
| for (auto i = binary.cbegin(); i != binary.cend() - 1; ++i) | |
| { | |
| dump_byte(*i); | |
| put_literal(", "); | |
| } | |
| dump_byte(binary.back()); | |
| } | |
| put_literal_indent("],\n", new_indent); | |
| put_literal("\"subtype\": "); | |
| if (binary.has_subtype()) | |
| { | |
| dump_integer(binary.subtype()); | |
| } | |
| else | |
| { | |
| put_literal("null"); | |
| } | |
| put_literal_indent("\n", current_indent); | |
| put_char('}'); | |
| } | |
| else | |
| { | |
| put_literal("{\"bytes\":["); | |
| if (!binary.empty()) | |
| { | |
| for (auto i = binary.cbegin(); i != binary.cend() - 1; ++i) | |
| { | |
| dump_byte(*i); | |
| put_char(','); | |
| } | |
| dump_byte(binary.back()); | |
| } | |
| put_literal("],\"subtype\":"); | |
| if (binary.has_subtype()) | |
| { | |
| dump_integer(binary.subtype()); | |
| put_char('}'); | |
| } | |
| else | |
| { | |
| put_literal("null}"); | |
| } | |
| } | |
| } | |
| /*! | |
| @brief the indentation level to use for the children of the current value | |
| A very large @a indent_step can wrap the unsigned accumulation on deep | |
| nesting, which would silently truncate the indentation. Far harder to reach | |
| now that the accumulator is a std::size_t, but still reachable where that is | |
| 32 bits wide. | |
| */ | |
| static std::size_t next_indent(const std::size_t current_indent, const std::size_t indent_step) | |
| { | |
| const std::size_t new_indent = current_indent + indent_step; | |
| JSON_ASSERT(new_indent >= current_indent); | |
| return new_indent; | |
| } | |
| private: | |
| /*! | |
| @brief append the object key @a s in quotes, followed by @a tail | |
| @a tail is the closing quote and the colon, followed by a space when | |
| pretty-printing. The callers pass it because each of them already sits on | |
| the pretty-printing or the compact path; choosing it here would test | |
| @ref pretty_print once more for every key. Most keys are short and plain | |
| and are written in one go by put_short_quoted(); everything else takes the | |
| general path. | |
| */ | |
| template<std::size_t N> | |
| void put_object_key(const string_t& s, const char (&tail)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| { | |
| #if JSON_LITTLE_ENDIAN_TARGET | |
| if (put_short_quoted(s, tail)) | |
| { | |
| return; | |
| } | |
| #endif | |
| put_char('"'); | |
| dump_escaped(s); | |
| put_literal(tail); | |
| } | |
| // put_short_quoted() assembles words from little-endian loads | |
| #if JSON_LITTLE_ENDIAN_TARGET | |
| /// the longest string put_short_quoted() takes | |
| static constexpr std::size_t short_string_max = JSON_SCAN_VECTOR ? 32 : 16; | |
| /// the high bit of every byte of @a v that is not printable ASCII or is a | |
| /// quote, a backslash, or DEL (zero if the bytes can be copied as they are) | |
| static std::uint64_t swar_not_plain(const std::uint64_t v) noexcept | |
| { | |
| constexpr std::uint64_t ones = 0x0101010101010101ull; | |
| const std::uint64_t q = v ^ 0x2222222222222222ull; // '"' | |
| const std::uint64_t b = v ^ 0x5C5C5C5C5C5C5C5Cull; // '\\' | |
| return (((q - ones) & ~q) | ((b - ones) & ~b) // == '"', == '\\' | |
| | ((v - 0x2020202020202020ull) & ~v) // < 0x20 | |
| | v | (v + ones)) // >= 0x7F | |
| & 0x8080808080808080ull; | |
| } | |
| template<typename WordType> | |
| static WordType load_word(const char* p) noexcept | |
| { | |
| WordType w; | |
| std::memcpy(&w, p, sizeof(w)); | |
| return w; | |
| } | |
| template<typename WordType> | |
| static void store_word(char* p, const WordType w) noexcept | |
| { | |
| std::memcpy(p, &w, sizeof(w)); | |
| } | |
| /*! | |
| @brief write `"`, @a s and @a tail if @a s is short and needs no escaping | |
| A string of up to 16 (32 with vector instructions) printable ASCII | |
| characters (no quote, backslash, or DEL) is read with two overlapping loads | |
| and written with two overlapping stores, instead of scanning it and calling | |
| memcpy with a length that is only known at run time. Returns false, having | |
| changed nothing, if @a s does not qualify or the write buffer lacks the | |
| room. | |
| */ | |
| template<std::size_t N> | |
| bool put_short_quoted(const string_t& s, const char (&tail)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| { | |
| const std::size_t n = s.size(); | |
| if (n > short_string_max || write_buffer_pos + n + N > write_buffer.size()) | |
| { | |
| return false; | |
| } | |
| char* d = write_buffer.data() + write_buffer_pos + 1; | |
| const char* const p = s.data(); | |
| if (n >= 8) | |
| { | |
| #if JSON_SCAN_VECTOR | |
| if (!(n >= 16 ? copy_plain_vectors(d, p, n) : copy_plain_halves(d, p, n))) | |
| { | |
| return false; | |
| } | |
| #else | |
| const auto a = load_word<std::uint64_t>(p); | |
| const auto b = load_word<std::uint64_t>(p + n - 8); | |
| if ((swar_not_plain(a) | swar_not_plain(b)) != 0) | |
| { | |
| return false; | |
| } | |
| store_word(d, a); | |
| store_word(d + n - 8, b); | |
| #endif | |
| } | |
| else if (n >= 4) | |
| { | |
| const auto a = load_word<std::uint32_t>(p); | |
| const auto b = load_word<std::uint32_t>(p + n - 4); | |
| // the bytes above the string are filled with a plain character | |
| const std::uint64_t w = a | (static_cast<std::uint64_t>(b) << (8 * (n - 4))) | |
| | (0x4141414141414141ull << (8 * n)); | |
| if (swar_not_plain(w) != 0) | |
| { | |
| return false; | |
| } | |
| store_word(d, a); | |
| store_word(d + n - 4, b); | |
| } | |
| else if (n >= 2) | |
| { | |
| const auto a = load_word<std::uint16_t>(p); | |
| const auto b = load_word<std::uint16_t>(p + n - 2); | |
| const std::uint64_t w = a | (static_cast<std::uint64_t>(b) << (8 * (n - 2))) | |
| | (0x4141414141414141ull << (8 * n)); | |
| if (swar_not_plain(w) != 0) | |
| { | |
| return false; | |
| } | |
| store_word(d, a); | |
| store_word(d + n - 2, b); | |
| } | |
| else if (n == 1) | |
| { | |
| const std::uint64_t w = static_cast<std::uint64_t>(static_cast<unsigned char>(p[0])) | (0x4141414141414141ull << 8u); | |
| if (swar_not_plain(w) != 0) | |
| { | |
| return false; | |
| } | |
| *d = p[0]; | |
| } | |
| d[-1] = '"'; | |
| std::memcpy(d + n, tail, N - 1); | |
| write_buffer_pos += n + N; | |
| return true; | |
| } | |
| #if JSON_SCAN_VECTOR | |
| /// copy the 8 to 15 bytes [@a p, @a p + @a n) to @a d with two overlapping | |
| /// words, tested together as one vector, see copy_plain_vectors() | |
| static bool copy_plain_halves(char* d, const char* p, const std::size_t n) noexcept | |
| { | |
| #if JSON_SCAN_NEON | |
| const uint8x8_t lo = vld1_u8(reinterpret_cast<const std::uint8_t*>(p)); | |
| const uint8x8_t hi = vld1_u8(reinterpret_cast<const std::uint8_t*>(p + n - 8)); | |
| const uint8x16_t in = vcombine_u8(lo, hi); | |
| const uint8x16_t special = vorrq_u8(vorrq_u8(vceqq_u8(in, vdupq_n_u8('"')), vceqq_u8(in, vdupq_n_u8('\\'))), | |
| vorrq_u8(vcltq_s8(vreinterpretq_s8_u8(in), vdupq_n_s8(0x20)), vceqq_u8(in, vdupq_n_u8(0x7F)))); | |
| if (vmaxvq_u8(special) != 0) | |
| { | |
| return false; | |
| } | |
| vst1_u8(reinterpret_cast<std::uint8_t*>(d), lo); | |
| vst1_u8(reinterpret_cast<std::uint8_t*>(d + n - 8), hi); | |
| #else | |
| const __m128i lo = _mm_loadl_epi64(static_cast<const __m128i*>(static_cast<const void*>(p))); // NOLINT(bugprone-casting-through-void) | |
| const __m128i hi = _mm_loadl_epi64(static_cast<const __m128i*>(static_cast<const void*>(p + n - 8))); // NOLINT(bugprone-casting-through-void) | |
| const __m128i in = _mm_unpacklo_epi64(lo, hi); | |
| const __m128i special = _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(in, _mm_set1_epi8('"')), _mm_cmpeq_epi8(in, _mm_set1_epi8('\\'))), | |
| _mm_or_si128(_mm_cmplt_epi8(in, _mm_set1_epi8(0x20)), _mm_cmpeq_epi8(in, _mm_set1_epi8(0x7F)))); | |
| if (_mm_movemask_epi8(special) != 0) | |
| { | |
| return false; | |
| } | |
| _mm_storel_epi64(static_cast<__m128i*>(static_cast<void*>(d)), lo); // NOLINT(bugprone-casting-through-void) | |
| _mm_storel_epi64(static_cast<__m128i*>(static_cast<void*>(d + n - 8)), hi); // NOLINT(bugprone-casting-through-void) | |
| #endif | |
| return true; | |
| } | |
| /// copy the 16 to 32 bytes [@a p, @a p + @a n) to @a d with two overlapping | |
| /// vectors, unless one of them is a quote, a backslash, a control | |
| /// character, DEL or not ASCII | |
| static bool copy_plain_vectors(char* d, const char* p, const std::size_t n) noexcept | |
| { | |
| #if JSON_SCAN_NEON | |
| const uint8x16_t a = vld1q_u8(reinterpret_cast<const std::uint8_t*>(p)); | |
| const uint8x16_t b = vld1q_u8(reinterpret_cast<const std::uint8_t*>(p + n - 16)); | |
| const uint8x16_t special = vorrq_u8(vorrq_u8(vorrq_u8(vceqq_u8(a, vdupq_n_u8('"')), vceqq_u8(a, vdupq_n_u8('\\'))), | |
| vorrq_u8(vceqq_u8(b, vdupq_n_u8('"')), vceqq_u8(b, vdupq_n_u8('\\')))), | |
| vorrq_u8(vorrq_u8(vcltq_s8(vreinterpretq_s8_u8(a), vdupq_n_s8(0x20)), vcltq_s8(vreinterpretq_s8_u8(b), vdupq_n_s8(0x20))), | |
| vorrq_u8(vceqq_u8(a, vdupq_n_u8(0x7F)), vceqq_u8(b, vdupq_n_u8(0x7F))))); | |
| if (vmaxvq_u8(special) != 0) | |
| { | |
| return false; | |
| } | |
| vst1q_u8(reinterpret_cast<std::uint8_t*>(d), a); | |
| vst1q_u8(reinterpret_cast<std::uint8_t*>(d + n - 16), b); | |
| #else | |
| const __m128i a = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(p))); // NOLINT(bugprone-casting-through-void) | |
| const __m128i b = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(p + n - 16))); // NOLINT(bugprone-casting-through-void) | |
| const __m128i quote = _mm_set1_epi8('"'); | |
| const __m128i backslash = _mm_set1_epi8('\\'); | |
| const __m128i space = _mm_set1_epi8(0x20); | |
| const __m128i del = _mm_set1_epi8(0x7F); | |
| const __m128i special = _mm_or_si128(_mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(a, quote), _mm_cmpeq_epi8(a, backslash)), | |
| _mm_or_si128(_mm_cmpeq_epi8(b, quote), _mm_cmpeq_epi8(b, backslash))), | |
| _mm_or_si128(_mm_or_si128(_mm_cmplt_epi8(a, space), _mm_cmplt_epi8(b, space)), | |
| _mm_or_si128(_mm_cmpeq_epi8(a, del), _mm_cmpeq_epi8(b, del)))); | |
| if (_mm_movemask_epi8(special) != 0) | |
| { | |
| return false; | |
| } | |
| _mm_storeu_si128(static_cast<__m128i*>(static_cast<void*>(d)), a); // NOLINT(bugprone-casting-through-void) | |
| _mm_storeu_si128(static_cast<__m128i*>(static_cast<void*>(d + n - 16)), b); // NOLINT(bugprone-casting-through-void) | |
| #endif | |
| return true; | |
| } | |
| #endif | |
| #endif | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| /*! | |
| @brief dump escaped string | |
| Escape a string by replacing certain special characters by a sequence of an | |
| escape character (backslash) and another character and other control | |
| characters by a sequence of "\u" followed by a four-digit hex | |
| representation. The escaped string is appended to @ref write_buffer. | |
| @param[in] s the string to escape | |
| Complexity: Linear in the length of string @a s. | |
| @note kept out of line: with the short-string attempts in front of it gone | |
| from here, compilers would otherwise inline it into @ref put_object_key | |
| and then no longer into the loops that call that | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE void dump_escaped(const string_t& s) | |
| { | |
| // Short strings of printable ASCII - most object keys and many values - | |
| // are checked byte by byte against a table and then copied in one go. | |
| // For them, this is cheaper than starting the vector scanner below, | |
| // whose setup costs more than such a string takes to scan. The same | |
| // check serves both values of ensure_ascii. | |
| // | |
| // Where put_short_quoted() exists and takes strings of up to 32 bytes, | |
| // the callers have tried it already, and repeating the attempt only | |
| // costs time for strings that need escaping or are not ASCII. | |
| #if !JSON_LITTLE_ENDIAN_TARGET || !JSON_SCAN_VECTOR | |
| if (s.size() <= 32) | |
| { | |
| const auto& copyable = ascii_copyable(); | |
| const auto* const data = reinterpret_cast<const unsigned char*>(s.data()); | |
| const std::size_t n = s.size(); | |
| std::size_t k = 0; | |
| while (k + 4 <= n && copyable[data[k]] != 0 && copyable[data[k + 1]] != 0 | |
| && copyable[data[k + 2]] != 0 && copyable[data[k + 3]] != 0) | |
| { | |
| k += 4; | |
| } | |
| while (k < n && copyable[data[k]] != 0) | |
| { | |
| ++k; | |
| } | |
| if (k == n) | |
| { | |
| put_string(s, 0, n); | |
| return; | |
| } | |
| } | |
| #endif | |
| // dispatch once here rather than test the flag inside the loop: it does | |
| // not change while a string is written, and folding it lets each of the | |
| // two scanners be inlined into a loop of its own | |
| if (ensure_ascii) | |
| { | |
| dump_escaped_impl<true>(s); | |
| } | |
| else | |
| { | |
| dump_escaped_impl<false>(s); | |
| } | |
| } | |
| /// write out the bytes pending in @ref string_buffer and reset @a bytes | |
| JSON_HEDLEY_ALWAYS_INLINE void emit_pending(std::size_t& bytes) | |
| { | |
| if (bytes != 0) | |
| { | |
| put_buffer(string_buffer, bytes); | |
| bytes = 0; | |
| } | |
| } | |
| /// write buffer and reset index if fewer than 13 bytes are left, as this | |
| /// is the maximal number of bytes to be written ("\uxxxx\uxxxx\0") for one | |
| /// code point | |
| JSON_HEDLEY_ALWAYS_INLINE void reserve_string_buffer(std::size_t& bytes) | |
| { | |
| if (string_buffer.size() - bytes < 13) | |
| { | |
| put_buffer(string_buffer, bytes); | |
| bytes = 0; | |
| } | |
| } | |
| /*! | |
| @brief worker for @ref dump_escaped | |
| @a ensure_ascii is a template parameter here so that the branch on it is | |
| resolved once, outside the loop; see @ref dump_escaped. | |
| */ | |
| #ifdef JSON_HEDLEY_MSVC_VERSION | |
| #pragma warning(push) | |
| // EnsureAscii is a template parameter; C++11 has no if constexpr | |
| #pragma warning(disable : 4127) // conditional expression is constant | |
| #endif | |
| template<bool EnsureAscii> | |
| void dump_escaped_impl(const string_t& s) | |
| { | |
| std::uint32_t codepoint{}; | |
| std::uint8_t state = UTF8_ACCEPT; | |
| std::size_t bytes = 0; // number of bytes written to string_buffer | |
| // number of bytes written at the point of the last valid byte | |
| std::size_t bytes_after_last_accept = 0; | |
| std::size_t undumped_chars = 0; | |
| for (std::size_t i = 0; i < s.size(); ++i) | |
| { | |
| // Fast path: at a character boundary (state == UTF8_ACCEPT), | |
| // bulk-copy the longest run of bytes that need no escaping using a | |
| // SWAR scanner shared with the lexer's contiguous path. The scanner | |
| // stops exactly at the first byte dump_escaped would handle | |
| // individually, so that byte is left to the byte-at-a-time path | |
| // below, keeping escaping output and error diagnostics unchanged. | |
| // | |
| // - EnsureAscii == false: string_bulk_run() copies ordinary bytes | |
| // and complete well-formed UTF-8, stopping at a quote, backslash, | |
| // control character (< 0x20), or ill-formed/truncated sequence. | |
| // - EnsureAscii == true: only printable ASCII may be copied | |
| // verbatim; find_ascii_copyable_run() additionally stops at 0x7F | |
| // and every non-ASCII byte (>= 0x80), which must be \u-escaped. | |
| if (state == UTF8_ACCEPT) | |
| { | |
| const auto* const data = reinterpret_cast<const unsigned char*>(s.data()); | |
| // A run can only be non-empty when the very first byte is one | |
| // the scanner may copy, so test that single byte before paying | |
| // for the scan. Without it, text whose characters all have to be | |
| // escaped - CJK under ensure_ascii, where every byte is >= 0x80 - | |
| // runs the scanner once per character only to be told zero. | |
| std::size_t run = 0; | |
| if (!EnsureAscii) | |
| { | |
| run = string_bulk_run(data + i, s.size() - i); | |
| } | |
| else if (is_ascii_copyable(data[i])) | |
| { | |
| run = find_ascii_copyable_run(data + i, s.size() - i); | |
| } | |
| if (run != 0) | |
| { | |
| // emit any bytes still pending in string_buffer first to | |
| // preserve output order, then write the run directly | |
| emit_pending(bytes); | |
| put_run(s, i, run); | |
| bytes_after_last_accept = 0; | |
| undumped_chars = 0; | |
| i += run; | |
| if (i >= s.size()) | |
| { | |
| break; | |
| } | |
| } | |
| // A byte below 0x60 is a complete code point and needs no | |
| // UTF-8 decoding. The scanner stops only at a control | |
| // character, a quote, or a backslash in that range, so look up | |
| // its escape sequence and write all 8 bytes of the table entry | |
| // straight into the write buffer; only the length stored in the | |
| // last byte of the entry is kept. | |
| if (data[i] < 0x60) | |
| { | |
| // emit any bytes still pending in string_buffer first to | |
| // preserve output order | |
| emit_pending(bytes); | |
| // deliberately not put_buffer(): a fixed 8-byte memcpy | |
| // has no asserts and no write-through branch, which | |
| // matters on the hot path | |
| const auto& escape = ascii_escapes()[data[i]]; | |
| if (JSON_HEDLEY_UNLIKELY(write_buffer.size() - write_buffer_pos < escape.size())) | |
| { | |
| flush(); | |
| } | |
| std::memcpy(write_buffer.data() + write_buffer_pos, escape.data(), escape.size()); | |
| write_buffer_pos += static_cast<std::size_t>(escape[7]); | |
| bytes_after_last_accept = 0; | |
| undumped_chars = 0; | |
| continue; | |
| } | |
| } | |
| const auto byte = static_cast<std::uint8_t>(s[i]); | |
| if (EnsureAscii && state == UTF8_ACCEPT && byte >= 0x80) | |
| { | |
| // a run of well-formed multi-byte characters is escaped | |
| // straight into the write buffer; an ill-formed sequence | |
| // ends the run and is left to the byte-at-a-time path | |
| if (bytes != 0) | |
| { | |
| put_buffer(string_buffer, bytes); | |
| bytes = 0; | |
| bytes_after_last_accept = 0; | |
| } | |
| const std::size_t escaped = write_u_escapes(reinterpret_cast<const unsigned char*>(s.data()) + i, s.size() - i); | |
| if (escaped != 0) | |
| { | |
| bytes_after_last_accept = 0; | |
| undumped_chars = 0; | |
| i += escaped - 1; | |
| continue; | |
| } | |
| } | |
| switch (decode(state, codepoint, byte)) | |
| { | |
| case UTF8_ACCEPT: // decode found a new code point | |
| { | |
| // the code point is at least 0x60 (smaller ones are handled | |
| // above) and is not printable ASCII (which the scanner | |
| // copies): it is DEL (0x7F) under EnsureAscii or a non-ASCII | |
| // character | |
| if (EnsureAscii) | |
| { | |
| JSON_ASSERT(codepoint >= 0x7F); | |
| if (error_handler == error_handler_t::keep) | |
| { | |
| // this character was buffered as raw bytes below | |
| // in case it turned out to be part of an | |
| // ill-formed sequence (which is kept as is); now | |
| // that it decoded to a well-formed code point, | |
| // undo that and \u-escape it like any other | |
| // character instead | |
| bytes = bytes_after_last_accept; | |
| } | |
| if (codepoint <= 0xFFFF) | |
| { | |
| write_u_escape(bytes, static_cast<std::uint16_t>(codepoint)); | |
| } | |
| else | |
| { | |
| write_u_escape(bytes, static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u))); | |
| write_u_escape(bytes, static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu))); | |
| } | |
| } | |
| else | |
| { | |
| // copy byte to buffer (all previous bytes of the | |
| // sequence have been copied in the default case below) | |
| string_buffer[bytes++] = s[i]; | |
| } | |
| reserve_string_buffer(bytes); | |
| // remember the byte position of this accept | |
| bytes_after_last_accept = bytes; | |
| undumped_chars = 0; | |
| break; | |
| } | |
| case UTF8_REJECT: // decode found invalid UTF-8 byte | |
| { | |
| switch (error_handler) | |
| { | |
| case error_handler_t::strict: | |
| { | |
| JSON_THROW(type_error::create(exception_id::invalid_utf8, concat("invalid UTF-8 byte at index ", std::to_string(i), ": 0x", detail::hex_byte(byte)), nullptr)); | |
| } | |
| case error_handler_t::ignore: | |
| case error_handler_t::replace: | |
| { | |
| // in case we saw this character the first time, we | |
| // would like to read it again, because the byte | |
| // may be OK for itself, but just not OK for the | |
| // previous sequence | |
| if (undumped_chars > 0) | |
| { | |
| --i; | |
| } | |
| // reset length buffer to the last accepted index; | |
| // thus removing/ignoring the invalid characters | |
| bytes = bytes_after_last_accept; | |
| if (error_handler == error_handler_t::replace) | |
| { | |
| // add a replacement character | |
| if (EnsureAscii) | |
| { | |
| string_buffer[bytes++] = '\\'; | |
| string_buffer[bytes++] = 'u'; | |
| string_buffer[bytes++] = 'f'; | |
| string_buffer[bytes++] = 'f'; | |
| string_buffer[bytes++] = 'f'; | |
| string_buffer[bytes++] = 'd'; | |
| } | |
| else | |
| { | |
| string_buffer[bytes++] = '\xEF'; | |
| string_buffer[bytes++] = '\xBF'; | |
| string_buffer[bytes++] = '\xBD'; | |
| } | |
| reserve_string_buffer(bytes); | |
| bytes_after_last_accept = bytes; | |
| } | |
| undumped_chars = 0; | |
| // continue processing the string | |
| state = UTF8_ACCEPT; | |
| break; | |
| } | |
| case error_handler_t::keep: | |
| { | |
| // the bytes of this (now abandoned) ill-formed | |
| // sequence seen so far are already buffered below | |
| // and are kept unchanged in the output | |
| if (undumped_chars > 0) | |
| { | |
| // the byte that ended the sequence may be OK | |
| // for itself (e.g., a quote that must still be | |
| // escaped, or the lead byte of a well-formed | |
| // code point), so read it again | |
| --i; | |
| } | |
| else | |
| { | |
| // a byte that cannot start a sequence (e.g., | |
| // 0xFF or a stray continuation byte) is kept | |
| // as well | |
| string_buffer[bytes++] = s[i]; | |
| } | |
| reserve_string_buffer(bytes); | |
| bytes_after_last_accept = bytes; | |
| undumped_chars = 0; | |
| // continue processing the string | |
| state = UTF8_ACCEPT; | |
| break; | |
| } | |
| default: // LCOV_EXCL_LINE | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE | |
| } | |
| break; | |
| } | |
| default: // decode found yet incomplete multibyte code point | |
| { | |
| if (!EnsureAscii || error_handler == error_handler_t::keep) | |
| { | |
| // code point will not be escaped (or will be kept as | |
| // is if it turns out to be ill-formed) - copy byte to | |
| // buffer; dropped again above if it decodes to a | |
| // well-formed code point that needs \u-escaping | |
| string_buffer[bytes++] = s[i]; | |
| } | |
| ++undumped_chars; | |
| break; | |
| } | |
| } | |
| } | |
| // we finished processing the string | |
| if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT)) | |
| { | |
| // write buffer | |
| if (bytes > 0) | |
| { | |
| put_buffer(string_buffer, bytes); | |
| } | |
| } | |
| else | |
| { | |
| // we finish reading, but do not accept: string was incomplete | |
| switch (error_handler) | |
| { | |
| case error_handler_t::strict: | |
| { | |
| JSON_THROW(type_error::create(exception_id::invalid_utf8, concat("incomplete UTF-8 string; last byte: 0x", detail::hex_byte(static_cast<std::uint8_t>(s[s.size() - 1]))), nullptr)); | |
| } | |
| case error_handler_t::ignore: | |
| { | |
| // write all accepted bytes | |
| put_buffer(string_buffer, bytes_after_last_accept); | |
| break; | |
| } | |
| case error_handler_t::replace: | |
| { | |
| // write all accepted bytes | |
| put_buffer(string_buffer, bytes_after_last_accept); | |
| // add a replacement character | |
| if (EnsureAscii) | |
| { | |
| put_literal("\\ufffd"); | |
| } | |
| else | |
| { | |
| put_literal("\xEF\xBF\xBD"); | |
| } | |
| break; | |
| } | |
| case error_handler_t::keep: | |
| { | |
| // write the ill-formed trailing bytes as is; they were | |
| // buffered above regardless of EnsureAscii | |
| put_buffer(string_buffer, bytes); | |
| break; | |
| } | |
| default: // LCOV_EXCL_LINE | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE | |
| } | |
| } | |
| } | |
| #ifdef JSON_HEDLEY_MSVC_VERSION | |
| #pragma warning(pop) | |
| #endif | |
| private: | |
| /*! | |
| @brief append a single character to the write buffer | |
| Structural characters ('{', '"', ',', ...) previously went straight to the | |
| output adapter, one virtual call each. Buffering them and flushing in bulk | |
| turns those many indirect calls into a single memcpy plus an occasional | |
| flush, which dominates the cost of serializing object/array-heavy values. | |
| */ | |
| void put_char(char c) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(write_buffer_pos == write_buffer.size())) | |
| { | |
| flush(); | |
| } | |
| write_buffer[write_buffer_pos++] = c; | |
| } | |
| /*! | |
| @brief append @a indent indentation characters to the write buffer | |
| Writes the indentation straight into the buffer instead of copying it out of | |
| a pre-grown indentation string, so no auxiliary string has to be sized, | |
| resized, or kept in sync with the deepest nesting level reached. | |
| An indentation wider than the buffer is emitted by filling the buffer with | |
| the indentation character once and flushing that same content repeatedly: | |
| flushing does not disturb what the buffer holds, so re-filling it between | |
| flushes would be redundant work. | |
| @note inlined on purpose, as is @ref put_literal: GCC otherwise stops | |
| inlining both into the pretty-printing loops once @ref dump_escaped | |
| has grown, which made indented output up to 13% slower | |
| */ | |
| JSON_HEDLEY_ALWAYS_INLINE void put_indent(std::size_t indent) | |
| { | |
| // closing braces at the outermost level ask for no indentation at all | |
| if (indent == 0) | |
| { | |
| return; | |
| } | |
| // the usual indentation, without a call of memset | |
| if (JSON_HEDLEY_LIKELY(put_short_literal_indent("", indent))) | |
| { | |
| return; | |
| } | |
| const std::size_t capacity = write_buffer.size(); | |
| // fill whatever room is left in the buffer; this is the whole job | |
| // whenever the indentation is narrower than the buffer, which is the | |
| // case for every sane indent_step | |
| const std::size_t head = (std::min)(indent, capacity - write_buffer_pos); | |
| std::memset(write_buffer.data() + write_buffer_pos, indent_char, head); | |
| write_buffer_pos += head; | |
| indent -= head; | |
| if (JSON_HEDLEY_LIKELY(indent == 0)) | |
| { | |
| return; | |
| } | |
| // the buffer is full and the remainder spans whole buffer-fulls: flush | |
| // what is pending, then fill the buffer with the indentation character | |
| // exactly once and hand the same bytes to the adapter as often as needed | |
| flush(); | |
| std::memset(write_buffer.data(), indent_char, capacity); | |
| while (indent >= capacity) | |
| { | |
| write_buffer_pos = capacity; | |
| flush(); | |
| indent -= capacity; | |
| } | |
| // the buffer still holds indentation characters throughout, so the tail | |
| // only has to be claimed, not written again | |
| write_buffer_pos = indent; | |
| } | |
| /*! | |
| @brief append a string literal and then @a indent indentation characters | |
| The usual line break and indentation go into the buffer with one check of | |
| its room and four stores of the indentation, see @ref put_short_literal_indent. | |
| */ | |
| template<std::size_t N> | |
| JSON_HEDLEY_ALWAYS_INLINE void put_literal_indent(const char (&s)[N], const std::size_t indent) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| { | |
| if (JSON_HEDLEY_LIKELY(put_short_literal_indent(s, indent))) | |
| { | |
| return; | |
| } | |
| put_literal(s); | |
| put_indent(indent); | |
| } | |
| /*! | |
| @brief append a string literal and up to 32 indentation characters in one go | |
| Four words of the indentation character are stored unconditionally and only | |
| the part wanted is claimed, which spares the call of memset. Shared by | |
| @ref put_indent (with an empty literal, whose copy compiles to nothing) and | |
| @ref put_literal_indent. Returns false, having written nothing, if | |
| @a indent is wider or the write buffer lacks the room. | |
| */ | |
| template<std::size_t N> | |
| JSON_HEDLEY_ALWAYS_INLINE bool put_short_literal_indent(const char (&s)[N], const std::size_t indent) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| { | |
| constexpr std::size_t length = N - 1; | |
| if (indent > 32 || write_buffer_pos + length + 32 > write_buffer.size()) | |
| { | |
| return false; | |
| } | |
| const std::uint64_t word = 0x0101010101010101ull * static_cast<unsigned char>(indent_char); | |
| char* const d = write_buffer.data() + write_buffer_pos; | |
| std::memcpy(d, s, length); | |
| std::memcpy(d + length, &word, sizeof(word)); | |
| std::memcpy(d + length + 8, &word, sizeof(word)); | |
| std::memcpy(d + length + 16, &word, sizeof(word)); | |
| std::memcpy(d + length + 24, &word, sizeof(word)); | |
| write_buffer_pos += length + indent; | |
| return true; | |
| } | |
| /*! | |
| @brief append a string literal to the write buffer | |
| The length comes from the array bound rather than a hand-written count, so | |
| it cannot drift out of sync with the literal. A literal always fits into the | |
| buffer (checked at compile time), so unlike @ref put_string this needs no | |
| write-through path for oversized runs. | |
| */ | |
| template<std::size_t N> | |
| JSON_HEDLEY_ALWAYS_INLINE void put_literal(const char (&s)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| { | |
| static_assert(N >= 2, "put_literal expects a non-empty string literal"); | |
| // the array bound counts the terminating NUL, which is not written | |
| constexpr std::size_t length = N - 1; | |
| static_assert(length < write_buffer_size, "string literal must fit into the write buffer"); | |
| if (JSON_HEDLEY_UNLIKELY(write_buffer_pos + length > write_buffer.size())) | |
| { | |
| flush(); | |
| } | |
| std::memcpy(write_buffer.data() + write_buffer_pos, s, length); | |
| write_buffer_pos += length; | |
| } | |
| /*! | |
| @brief append the characters of @a str in [@a start, @a start + @a length) | |
| A run of up to 16 characters with 16 or more in the string from @a start on | |
| and in the write buffer from its end on is copied as a whole block of 16, | |
| which spares the call of memcpy with a length known only at run time; the | |
| surplus characters in the buffer are overwritten by what follows. | |
| */ | |
| template<typename StringType> | |
| void put_run(const StringType& str, const std::size_t start, const std::size_t length) | |
| { | |
| // a short run is the exception in text without escapes (CJK, accented | |
| // Latin), for which this keeps the long path the fast one | |
| if (JSON_HEDLEY_UNLIKELY(length <= 16 && start + 16 <= str.size() && write_buffer_pos + 16 <= write_buffer.size())) | |
| { | |
| std::memcpy(write_buffer.data() + write_buffer_pos, str.data() + start, 16); | |
| write_buffer_pos += length; | |
| return; | |
| } | |
| put_string(str, start, start + length); | |
| } | |
| /*! | |
| @brief append the characters of @a str in [@a start, @a end) | |
| The only way to append a run of characters: @a str carries its own bound, | |
| so the range can be checked against it, which a bare pointer plus a count | |
| could not do. Runs that do not fit the buffer are written straight through | |
| the output adapter (after flushing what is pending), so large string and | |
| number payloads are not copied an extra time. | |
| */ | |
| template<typename StringType> | |
| void put_string(const StringType& str, std::size_t start, std::size_t end) | |
| { | |
| JSON_ASSERT(start <= end); | |
| JSON_ASSERT(end <= str.size()); | |
| const char* const s = str.data() + start; | |
| const std::size_t length = end - start; | |
| if (JSON_HEDLEY_UNLIKELY(length >= write_buffer.size())) | |
| { | |
| flush(); | |
| o->write_characters(s, length); | |
| return; | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(write_buffer_pos + length > write_buffer.size())) | |
| { | |
| flush(); | |
| } | |
| std::memcpy(write_buffer.data() + write_buffer_pos, s, length); | |
| write_buffer_pos += length; | |
| } | |
| /*! | |
| @brief append the first @a length characters of a fixed-size buffer | |
| */ | |
| template<std::size_t N> | |
| void put_buffer(const std::array<char, N>& buffer, std::size_t length) | |
| { | |
| put_string(buffer, 0, length); | |
| } | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| /*! | |
| @brief flush the write buffer to the output adapter | |
| Writing zero characters is a well-defined no-op for every output adapter, so | |
| the buffered length is passed through unconditionally (no empty-guard branch | |
| to leave uncovered). | |
| @note dump_escaped() and dump_integer()/dump_float() write into the internal | |
| write buffer; callers that invoke them directly (rather than through the | |
| public dump()) must call flush() before inspecting the output. | |
| */ | |
| void flush() | |
| { | |
| o->write_characters(write_buffer.data(), write_buffer_pos); | |
| write_buffer_pos = 0; | |
| } | |
| private: | |
| /*! | |
| @brief count digits | |
| Count the number of decimal (base 10) digits for an input unsigned integer. | |
| @param[in] x unsigned integer number to count its digits | |
| @return number of decimal digits | |
| */ | |
| unsigned int count_digits(number_magnitude_t x) noexcept | |
| { | |
| unsigned int n_digits = 1; | |
| for (;;) | |
| { | |
| if (x < 10) | |
| { | |
| return n_digits; | |
| } | |
| if (x < 100) | |
| { | |
| return n_digits + 1; | |
| } | |
| if (x < 1000) | |
| { | |
| return n_digits + 2; | |
| } | |
| if (x < 10000) | |
| { | |
| return n_digits + 3; | |
| } | |
| x = x / 10000u; | |
| n_digits += 4; | |
| } | |
| } | |
| /*! | |
| @brief whether each byte can be written verbatim under either value of ensure_ascii | |
| Entry c is 1 for printable ASCII other than '"' and '\\' (see | |
| is_ascii_copyable()) and 0 otherwise. A table lookup per byte is the | |
| cheapest test for the short strings handled first in dump_escaped(). | |
| */ | |
| static const std::array<std::uint8_t, 256>& ascii_copyable() noexcept | |
| { | |
| // constant-initialized from the predicate: no runtime loop, no guard | |
| static constexpr std::array<std::uint8_t, 256> copyable = make_ascii_copyable(make_index_sequence<256> {}); | |
| return copyable; | |
| } | |
| template<std::size_t... Is> | |
| static constexpr std::array<std::uint8_t, 256> make_ascii_copyable(index_sequence<Is...> /*unused*/) noexcept | |
| { | |
| return {{ static_cast<std::uint8_t>(is_ascii_copyable(static_cast<unsigned char>(Is)) ? 1 : 0)... }}; | |
| } | |
| /*! | |
| @brief the JSON form of each character below 0x60 | |
| Entry c holds the escape sequence of character c - the short form for | |
| \\b, \\t, \\n, \\f, \\r, \\" and \\\\, \\u00xx for the other control characters - | |
| or c itself if it needs no escaping, padded with zeros to 7 bytes. The last | |
| byte is the length of the sequence. The 8 bytes of an entry are copied at | |
| once, so writing an escape needs neither a branch nor a byte-wise loop. | |
| */ | |
| static const std::array<std::array<char, 8>, 0x60>& ascii_escapes() noexcept | |
| { | |
| static const std::array<std::array<char, 8>, 0x60> escapes = | |
| { | |
| { | |
| {{'\\', 'u', '0', '0', '0', '0', 0, 6}}, // 0x00 | |
| {{'\\', 'u', '0', '0', '0', '1', 0, 6}}, // 0x01 | |
| {{'\\', 'u', '0', '0', '0', '2', 0, 6}}, // 0x02 | |
| {{'\\', 'u', '0', '0', '0', '3', 0, 6}}, // 0x03 | |
| {{'\\', 'u', '0', '0', '0', '4', 0, 6}}, // 0x04 | |
| {{'\\', 'u', '0', '0', '0', '5', 0, 6}}, // 0x05 | |
| {{'\\', 'u', '0', '0', '0', '6', 0, 6}}, // 0x06 | |
| {{'\\', 'u', '0', '0', '0', '7', 0, 6}}, // 0x07 | |
| {{'\\', 'b', 0, 0, 0, 0, 0, 2}}, // 0x08 | |
| {{'\\', 't', 0, 0, 0, 0, 0, 2}}, // 0x09 | |
| {{'\\', 'n', 0, 0, 0, 0, 0, 2}}, // 0x0A | |
| {{'\\', 'u', '0', '0', '0', 'b', 0, 6}}, // 0x0B | |
| {{'\\', 'f', 0, 0, 0, 0, 0, 2}}, // 0x0C | |
| {{'\\', 'r', 0, 0, 0, 0, 0, 2}}, // 0x0D | |
| {{'\\', 'u', '0', '0', '0', 'e', 0, 6}}, // 0x0E | |
| {{'\\', 'u', '0', '0', '0', 'f', 0, 6}}, // 0x0F | |
| {{'\\', 'u', '0', '0', '1', '0', 0, 6}}, // 0x10 | |
| {{'\\', 'u', '0', '0', '1', '1', 0, 6}}, // 0x11 | |
| {{'\\', 'u', '0', '0', '1', '2', 0, 6}}, // 0x12 | |
| {{'\\', 'u', '0', '0', '1', '3', 0, 6}}, // 0x13 | |
| {{'\\', 'u', '0', '0', '1', '4', 0, 6}}, // 0x14 | |
| {{'\\', 'u', '0', '0', '1', '5', 0, 6}}, // 0x15 | |
| {{'\\', 'u', '0', '0', '1', '6', 0, 6}}, // 0x16 | |
| {{'\\', 'u', '0', '0', '1', '7', 0, 6}}, // 0x17 | |
| {{'\\', 'u', '0', '0', '1', '8', 0, 6}}, // 0x18 | |
| {{'\\', 'u', '0', '0', '1', '9', 0, 6}}, // 0x19 | |
| {{'\\', 'u', '0', '0', '1', 'a', 0, 6}}, // 0x1A | |
| {{'\\', 'u', '0', '0', '1', 'b', 0, 6}}, // 0x1B | |
| {{'\\', 'u', '0', '0', '1', 'c', 0, 6}}, // 0x1C | |
| {{'\\', 'u', '0', '0', '1', 'd', 0, 6}}, // 0x1D | |
| {{'\\', 'u', '0', '0', '1', 'e', 0, 6}}, // 0x1E | |
| {{'\\', 'u', '0', '0', '1', 'f', 0, 6}}, // 0x1F | |
| {{' ', 0, 0, 0, 0, 0, 0, 1}}, // 0x20 | |
| {{'!', 0, 0, 0, 0, 0, 0, 1}}, // 0x21 | |
| {{'\\', '"', 0, 0, 0, 0, 0, 2}}, // 0x22 | |
| {{'#', 0, 0, 0, 0, 0, 0, 1}}, // 0x23 | |
| {{'$', 0, 0, 0, 0, 0, 0, 1}}, // 0x24 | |
| {{'%', 0, 0, 0, 0, 0, 0, 1}}, // 0x25 | |
| {{'&', 0, 0, 0, 0, 0, 0, 1}}, // 0x26 | |
| {{'\'', 0, 0, 0, 0, 0, 0, 1}}, // 0x27 | |
| {{'(', 0, 0, 0, 0, 0, 0, 1}}, // 0x28 | |
| {{')', 0, 0, 0, 0, 0, 0, 1}}, // 0x29 | |
| {{'*', 0, 0, 0, 0, 0, 0, 1}}, // 0x2A | |
| {{'+', 0, 0, 0, 0, 0, 0, 1}}, // 0x2B | |
| {{',', 0, 0, 0, 0, 0, 0, 1}}, // 0x2C | |
| {{'-', 0, 0, 0, 0, 0, 0, 1}}, // 0x2D | |
| {{'.', 0, 0, 0, 0, 0, 0, 1}}, // 0x2E | |
| {{'/', 0, 0, 0, 0, 0, 0, 1}}, // 0x2F | |
| {{'0', 0, 0, 0, 0, 0, 0, 1}}, // 0x30 | |
| {{'1', 0, 0, 0, 0, 0, 0, 1}}, // 0x31 | |
| {{'2', 0, 0, 0, 0, 0, 0, 1}}, // 0x32 | |
| {{'3', 0, 0, 0, 0, 0, 0, 1}}, // 0x33 | |
| {{'4', 0, 0, 0, 0, 0, 0, 1}}, // 0x34 | |
| {{'5', 0, 0, 0, 0, 0, 0, 1}}, // 0x35 | |
| {{'6', 0, 0, 0, 0, 0, 0, 1}}, // 0x36 | |
| {{'7', 0, 0, 0, 0, 0, 0, 1}}, // 0x37 | |
| {{'8', 0, 0, 0, 0, 0, 0, 1}}, // 0x38 | |
| {{'9', 0, 0, 0, 0, 0, 0, 1}}, // 0x39 | |
| {{':', 0, 0, 0, 0, 0, 0, 1}}, // 0x3A | |
| {{';', 0, 0, 0, 0, 0, 0, 1}}, // 0x3B | |
| {{'<', 0, 0, 0, 0, 0, 0, 1}}, // 0x3C | |
| {{'=', 0, 0, 0, 0, 0, 0, 1}}, // 0x3D | |
| {{'>', 0, 0, 0, 0, 0, 0, 1}}, // 0x3E | |
| {{'?', 0, 0, 0, 0, 0, 0, 1}}, // 0x3F | |
| {{'@', 0, 0, 0, 0, 0, 0, 1}}, // 0x40 | |
| {{'A', 0, 0, 0, 0, 0, 0, 1}}, // 0x41 | |
| {{'B', 0, 0, 0, 0, 0, 0, 1}}, // 0x42 | |
| {{'C', 0, 0, 0, 0, 0, 0, 1}}, // 0x43 | |
| {{'D', 0, 0, 0, 0, 0, 0, 1}}, // 0x44 | |
| {{'E', 0, 0, 0, 0, 0, 0, 1}}, // 0x45 | |
| {{'F', 0, 0, 0, 0, 0, 0, 1}}, // 0x46 | |
| {{'G', 0, 0, 0, 0, 0, 0, 1}}, // 0x47 | |
| {{'H', 0, 0, 0, 0, 0, 0, 1}}, // 0x48 | |
| {{'I', 0, 0, 0, 0, 0, 0, 1}}, // 0x49 | |
| {{'J', 0, 0, 0, 0, 0, 0, 1}}, // 0x4A | |
| {{'K', 0, 0, 0, 0, 0, 0, 1}}, // 0x4B | |
| {{'L', 0, 0, 0, 0, 0, 0, 1}}, // 0x4C | |
| {{'M', 0, 0, 0, 0, 0, 0, 1}}, // 0x4D | |
| {{'N', 0, 0, 0, 0, 0, 0, 1}}, // 0x4E | |
| {{'O', 0, 0, 0, 0, 0, 0, 1}}, // 0x4F | |
| {{'P', 0, 0, 0, 0, 0, 0, 1}}, // 0x50 | |
| {{'Q', 0, 0, 0, 0, 0, 0, 1}}, // 0x51 | |
| {{'R', 0, 0, 0, 0, 0, 0, 1}}, // 0x52 | |
| {{'S', 0, 0, 0, 0, 0, 0, 1}}, // 0x53 | |
| {{'T', 0, 0, 0, 0, 0, 0, 1}}, // 0x54 | |
| {{'U', 0, 0, 0, 0, 0, 0, 1}}, // 0x55 | |
| {{'V', 0, 0, 0, 0, 0, 0, 1}}, // 0x56 | |
| {{'W', 0, 0, 0, 0, 0, 0, 1}}, // 0x57 | |
| {{'X', 0, 0, 0, 0, 0, 0, 1}}, // 0x58 | |
| {{'Y', 0, 0, 0, 0, 0, 0, 1}}, // 0x59 | |
| {{'Z', 0, 0, 0, 0, 0, 0, 1}}, // 0x5A | |
| {{'[', 0, 0, 0, 0, 0, 0, 1}}, // 0x5B | |
| {{'\\', '\\', 0, 0, 0, 0, 0, 2}}, // 0x5C | |
| {{']', 0, 0, 0, 0, 0, 0, 1}}, // 0x5D | |
| {{'^', 0, 0, 0, 0, 0, 0, 1}}, // 0x5E | |
| {{'_', 0, 0, 0, 0, 0, 0, 1}}, // 0x5F | |
| } | |
| }; | |
| return escapes; | |
| } | |
| /*! | |
| @brief escape the well-formed multi-byte characters at the start of @a data | |
| Writes the "\\uXXXX" escape of each character (two of them for a character | |
| above U+FFFF) straight into the write buffer, which is why the caller must | |
| have written out what is pending in @ref string_buffer. Stops at the first | |
| byte that is below 0x80 or starts an ill-formed or truncated sequence, which | |
| the caller handles. | |
| @return the number of bytes of @a data that have been escaped | |
| */ | |
| JSON_HEDLEY_NEVER_INLINE std::size_t write_u_escapes(const unsigned char* data, std::size_t n) | |
| { | |
| std::size_t i = 0; | |
| while (i < n && data[i] >= 0x80) | |
| { | |
| const std::size_t length = validate_one_utf8(data + i, n - i); | |
| if (length == 0) | |
| { | |
| break; | |
| } | |
| // a lead byte of 0x80 or above starts a sequence of 2 to 4 bytes | |
| JSON_ASSERT(length >= 2 && length <= 4); | |
| const auto b0 = static_cast<std::uint32_t>(data[i]); | |
| const auto b1 = static_cast<std::uint32_t>(data[i + 1]); | |
| std::uint32_t codepoint = 0; | |
| switch (length) | |
| { | |
| case 2: | |
| codepoint = ((b0 & 0x1Fu) << 6u) | (b1 & 0x3Fu); | |
| break; | |
| case 3: | |
| codepoint = ((b0 & 0x0Fu) << 12u) | ((b1 & 0x3Fu) << 6u) | (static_cast<std::uint32_t>(data[i + 2]) & 0x3Fu); | |
| break; | |
| default: // 4 | |
| codepoint = ((b0 & 0x07u) << 18u) | ((b1 & 0x3Fu) << 12u) | ((static_cast<std::uint32_t>(data[i + 2]) & 0x3Fu) << 6u) | (static_cast<std::uint32_t>(data[i + 3]) & 0x3Fu); | |
| break; | |
| } | |
| // at most two escapes of six bytes each | |
| if (JSON_HEDLEY_UNLIKELY(write_buffer.size() - write_buffer_pos < 12)) | |
| { | |
| flush(); | |
| } | |
| char* d = write_buffer.data() + write_buffer_pos; | |
| if (codepoint > 0xFFFFu) | |
| { | |
| d = put_u_escape(d, static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u))); | |
| codepoint = 0xDC00u + (codepoint & 0x3FFu); | |
| } | |
| d = put_u_escape(d, static_cast<std::uint16_t>(codepoint)); | |
| write_buffer_pos = static_cast<std::size_t>(d - write_buffer.data()); | |
| i += length; | |
| } | |
| return i; | |
| } | |
| static char* put_u_escape(char* d, const std::uint16_t codeunit) noexcept | |
| { | |
| d[0] = '\\'; | |
| d[1] = 'u'; | |
| return hex4_lower(codeunit, d + 2); | |
| } | |
| /*! | |
| * @brief write a lowercase "\\uXXXX" escape sequence into @a string_buffer | |
| * | |
| * Branch-free replacement for `snprintf(buf, 7, "\\u%04x", codeunit)` in the | |
| * string escaping hot path. It writes exactly six characters ('\\', 'u' and | |
| * four hex digits) at position @a pos of @a string_buffer via a nibble | |
| * lookup table (@ref hex4_lower), avoiding the format-string parsing and locale machinery of | |
| * `snprintf`. Advances @a pos by the number of bytes written (6). | |
| * | |
| * @param[in] pos position in @a string_buffer to write at; there must | |
| * be at least 6 bytes of headroom | |
| * @param[in] codeunit 16-bit value to encode | |
| */ | |
| void write_u_escape(std::size_t& pos, std::uint16_t codeunit) noexcept | |
| { | |
| JSON_ASSERT(string_buffer.size() - pos >= 6); | |
| string_buffer[pos + 0] = '\\'; | |
| string_buffer[pos + 1] = 'u'; | |
| hex4_lower(codeunit, &string_buffer[pos + 2]); | |
| pos += 6; | |
| } | |
| /*! | |
| @brief convert a single element of a binary value to its byte value | |
| The elements of a binary value are dumped as the numbers 0..255, regardless | |
| of the value type of the configured BinaryType: that type may be signed | |
| (`char`), unsigned (`std::uint8_t`), or not an integer at all | |
| (`std::byte`), none of which @ref dump_integer can handle uniformly. | |
| */ | |
| static std::uint8_t to_byte_value(binary_char_t x) noexcept | |
| { | |
| return static_cast<std::uint8_t>(x); | |
| } | |
| // templates to avoid warnings about useless casts | |
| template <typename NumberType, enable_if_t<std::is_signed<NumberType>::value, int> = 0> | |
| bool is_negative_number(NumberType x) | |
| { | |
| return x < 0; | |
| } | |
| template < typename NumberType, enable_if_t <std::is_unsigned<NumberType>::value, int > = 0 > | |
| bool is_negative_number(NumberType /*unused*/) | |
| { | |
| return false; | |
| } | |
| /*! | |
| @brief write the decimal representation of the byte @a value | |
| A binary value's bytes are always in [0, 255], so writing one needs neither | |
| the digit counting nor the 64-bit arithmetic that @ref dump_integer does for | |
| an arbitrary number, and the three digits it takes at most are written | |
| straight into the write buffer. | |
| Any byte type that is not a plain unsigned byte is converted to its | |
| @ref to_byte_value "byte value" and left to @ref dump_integer, so a signed | |
| or non-integral BinaryType::value_type (`char`, `std::byte`, ...) still | |
| dumps as 0..255. | |
| */ | |
| template<typename ByteType> | |
| void dump_byte(const ByteType value) | |
| { | |
| dump_byte(value, std::integral_constant < bool, | |
| std::is_unsigned<ByteType>::value && sizeof(ByteType) == 1 | |
| && !std::is_same<ByteType, bool>::value > {}); | |
| } | |
| template<typename ByteType> | |
| void dump_byte(const ByteType value, std::false_type /*is_plain_byte*/) | |
| { | |
| dump_integer(to_byte_value(value)); | |
| } | |
| template<typename ByteType> | |
| void dump_byte(const ByteType value, std::true_type /*is_plain_byte*/) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(write_buffer_pos + 3 > write_buffer.size())) | |
| { | |
| flush(); | |
| } | |
| const auto byte = static_cast<unsigned>(value); | |
| // Accumulate the offset in a local and store it back once. Writing | |
| // through write_buffer[] is a char write, which may alias any object, | |
| // so with the member updated in place the compiler has to reload and | |
| // store it around every digit - measured 2.4x slower on a dump of a | |
| // multi-megabyte binary value. | |
| std::size_t pos = write_buffer_pos; | |
| if (byte >= 100) | |
| { | |
| write_buffer[pos++] = static_cast<char>('0' + (byte / 100)); | |
| write_buffer[pos++] = static_cast<char>('0' + ((byte / 10) % 10)); | |
| } | |
| else if (byte >= 10) | |
| { | |
| write_buffer[pos++] = static_cast<char>('0' + (byte / 10)); | |
| } | |
| write_buffer[pos++] = static_cast<char>('0' + (byte % 10)); | |
| write_buffer_pos = pos; | |
| } | |
| /*! | |
| @brief dump an integer | |
| Dump a given integer, appending it to @ref write_buffer (directly: copying | |
| the digits from another buffer right after writing them waits until the | |
| stores are done). | |
| @param[in] x integer number (signed or unsigned) to dump | |
| @tparam NumberType either @a number_integer_t or @a number_unsigned_t | |
| */ | |
| template < typename NumberType, detail::enable_if_t < | |
| std::is_integral<NumberType>::value || | |
| std::is_same<NumberType, number_unsigned_t>::value || | |
| std::is_same<NumberType, number_integer_t>::value, | |
| int > = 0 > | |
| void dump_integer(NumberType x) | |
| { | |
| static constexpr std::array<std::array<char, 2>, 100> digits_to_99 | |
| { | |
| { | |
| {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}}, | |
| {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}}, | |
| {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}}, | |
| {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}}, | |
| {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}}, | |
| {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}}, | |
| {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}}, | |
| {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}}, | |
| {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}}, | |
| {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}}, | |
| } | |
| }; | |
| // special case for "0" | |
| if (x == 0) | |
| { | |
| put_char('0'); | |
| return; | |
| } | |
| // use a pointer to fill the buffer (room for as much as number_buffer holds) | |
| if (JSON_HEDLEY_UNLIKELY(write_buffer_pos + number_buffer.size() > write_buffer.size())) | |
| { | |
| flush(); | |
| } | |
| auto* buffer_ptr = write_buffer.data() + write_buffer_pos; | |
| number_magnitude_t abs_value; | |
| // one byte for the minus sign | |
| unsigned int n_chars = 0; | |
| if (is_negative_number(x)) | |
| { | |
| *buffer_ptr = '-'; | |
| abs_value = remove_sign(static_cast<number_integer_t>(x)); | |
| n_chars = 1; | |
| } | |
| else | |
| { | |
| abs_value = static_cast<number_magnitude_t>(x); | |
| } | |
| // up to 16 digits: eight at a time (as the digits of floats), written | |
| // without leading zeros | |
| if (abs_value < 10000000000000000u) | |
| { | |
| const auto value = static_cast<std::uint64_t>(abs_value); // fits: abs_value < 10^16 | |
| const std::uint64_t upper = value / 100000000u; | |
| const std::uint64_t first = dtoa_impl::eight_digit_bytes(upper != 0 ? upper : value); | |
| const auto leading = static_cast<unsigned>(count_leading_zeros(first) / 8); // (first is not 0) | |
| char* const p = buffer_ptr + n_chars; | |
| dtoa_impl::store_msb_first(p, (first << (8 * leading)) + 0x3030303030303030u); | |
| n_chars += 8 - leading; | |
| if (upper != 0) | |
| { | |
| dtoa_impl::store_msb_first(p + 8 - leading, dtoa_impl::eight_digit_bytes(value - (upper * 100000000u)) + 0x3030303030303030u); | |
| n_chars += 8; | |
| } | |
| write_buffer_pos += n_chars; | |
| return; | |
| } | |
| n_chars += count_digits(abs_value); | |
| // spare 1 byte for '\0' | |
| JSON_ASSERT(n_chars < number_buffer.size() - 1); | |
| // jump to the end to generate the string from backward, | |
| // so we later avoid reversing the result | |
| buffer_ptr += n_chars; | |
| // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu | |
| // See: https://www.youtube.com/watch?v=o4-CwDo2zpg | |
| while (abs_value >= 100) | |
| { | |
| const auto digits_index = static_cast<unsigned>((abs_value % 100)); | |
| abs_value /= 100; | |
| *(--buffer_ptr) = digits_to_99[digits_index][1]; | |
| *(--buffer_ptr) = digits_to_99[digits_index][0]; | |
| } | |
| if (abs_value >= 10) | |
| { | |
| const auto digits_index = static_cast<unsigned>(abs_value); | |
| *(--buffer_ptr) = digits_to_99[digits_index][1]; | |
| *(--buffer_ptr) = digits_to_99[digits_index][0]; | |
| } | |
| else | |
| { | |
| *(--buffer_ptr) = static_cast<char>('0' + abs_value); | |
| } | |
| write_buffer_pos += n_chars; | |
| } | |
| /*! | |
| @brief dump a floating-point number | |
| Dump a given floating-point number, appending it to @ref write_buffer. | |
| @param[in] x floating-point number to dump | |
| */ | |
| void dump_float(number_float_t x) | |
| { | |
| // NaN / inf | |
| if (!std::isfinite(x)) | |
| { | |
| put_literal("null"); | |
| return; | |
| } | |
| // If number_float_t is an IEEE-754 single or double precision number, | |
| // use the Grisu2 algorithm to produce short numbers which are | |
| // guaranteed to round-trip, using strtof and strtod, resp. | |
| // | |
| // NB: The test below works if <long double> == <double>. | |
| static constexpr bool is_ieee_single_or_double | |
| = (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 24 && std::numeric_limits<number_float_t>::max_exponent == 128) || | |
| (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 53 && std::numeric_limits<number_float_t>::max_exponent == 1024); | |
| dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>()); | |
| } | |
| void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) | |
| { | |
| // directly into the write buffer: copying the text from number_buffer | |
| // right after to_chars() wrote it waits until its stores are done | |
| if (JSON_HEDLEY_UNLIKELY(write_buffer_pos + number_buffer.size() > write_buffer.size())) | |
| { | |
| flush(); | |
| } | |
| auto* begin = write_buffer.data() + write_buffer_pos; | |
| auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); | |
| write_buffer_pos += static_cast<std::size_t>(end - begin); | |
| } | |
| JSON_HEDLEY_NON_NULL(1) | |
| static int snprintf_float(char* buf, std::size_t size, int d, double x) | |
| { | |
| // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) | |
| return (std::snprintf)(buf, size, "%.*g", d, x); | |
| } | |
| JSON_HEDLEY_NON_NULL(1) | |
| static int snprintf_float(char* buf, std::size_t size, int d, long double x) | |
| { | |
| // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) | |
| return (std::snprintf)(buf, size, "%.*Lg", d, x); | |
| } | |
| void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) | |
| { | |
| // get the number of digits for a float -> text -> float round-trip | |
| static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10; | |
| // the actual conversion | |
| std::ptrdiff_t len = snprintf_float(number_buffer.data(), number_buffer.size(), d, x); | |
| // negative value indicates an error | |
| JSON_ASSERT(len > 0); | |
| // check if the buffer was large enough | |
| JSON_ASSERT(static_cast<std::size_t>(len) < number_buffer.size()); | |
| // look up the locale's thousands separator and decimal point now, | |
| // matching what snprintf_float() just used (see lexer::get_decimal_point()) | |
| const auto* loc = std::localeconv(); | |
| JSON_ASSERT(loc != nullptr); | |
| const char thousands_sep = (loc->thousands_sep == nullptr) ? '\0' : *loc->thousands_sep; | |
| const char decimal_point = (loc->decimal_point == nullptr) ? '\0' : *loc->decimal_point; | |
| // erase thousands separators | |
| if (thousands_sep != '\0') | |
| { | |
| // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081 | |
| const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep); | |
| std::fill(end, number_buffer.end(), '\0'); | |
| JSON_ASSERT((end - number_buffer.begin()) <= len); | |
| len = (end - number_buffer.begin()); | |
| } | |
| // convert decimal point to '.' | |
| if (decimal_point != '\0' && decimal_point != '.') | |
| { | |
| // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see https://github.com/nlohmann/json/issues/3081 | |
| const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); | |
| if (dec_pos != number_buffer.end()) | |
| { | |
| *dec_pos = '.'; | |
| } | |
| } | |
| put_buffer(number_buffer, static_cast<std::size_t>(len)); | |
| // determine if we need to append ".0" | |
| const bool value_is_int_like = | |
| std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, | |
| [](char c) | |
| { | |
| return c == '.' || c == 'e'; | |
| }); | |
| if (value_is_int_like) | |
| { | |
| put_literal(".0"); | |
| } | |
| } | |
| /* | |
| * Helper function for dump_integer | |
| * | |
| * This function takes a negative signed integer and returns its absolute | |
| * value as an unsigned integer. The plus/minus shuffling is necessary as we | |
| * cannot directly remove the sign of an arbitrary signed integer as the | |
| * absolute values of INT_MIN and INT_MAX are usually not the same. See | |
| * #1708 for details. | |
| */ | |
| number_magnitude_t remove_sign(number_integer_t x) noexcept | |
| { | |
| JSON_ASSERT(x < 0); | |
| return static_cast<number_magnitude_t>(-(x + 1)) + 1; | |
| } | |
| private: | |
| /// the output of the serializer (non-owning; the adapter lives at the call site) | |
| output_adapter_protocol<char>* o = nullptr; | |
| /// a character buffer left uninitialized: the buffers below are written | |
| /// before they are read (only the part written is ever read), and zeroing | |
| /// 1.6 KiB took more than half of what dumping a small value costs (the | |
| /// user-provided constructor keeps the member initialization, which | |
| /// -Weffc++ asks for, from zeroing them) | |
| template<std::size_t N> | |
| struct uninitialized_buffer : std::array<char, N> | |
| { | |
| uninitialized_buffer() noexcept {} // NOLINT(modernize-use-equals-default,hicpp-use-equals-default,cppcoreguidelines-pro-type-member-init,hicpp-member-init): see above | |
| }; | |
| /// a (hopefully) large enough character buffer | |
| uninitialized_buffer<64> number_buffer; | |
| /// string buffer | |
| uninitialized_buffer<512> string_buffer; | |
| /// the indentation character | |
| const char indent_char; | |
| /// whether to pretty-print the output | |
| const bool pretty_print; | |
| /// whether to escape non-ASCII characters with \\uXXXX sequences | |
| const bool ensure_ascii; | |
| /// the indent level | |
| const std::size_t indent_step; | |
| /// error_handler how to react on decoding errors | |
| const error_handler_t error_handler; | |
| /// buffer collecting output before it is flushed to the output adapter, so | |
| /// that the many small structural writes become few bulk writes | |
| static constexpr std::size_t write_buffer_size = 1024; | |
| uninitialized_buffer<write_buffer_size> write_buffer; | |
| /// number of valid bytes currently held in @ref write_buffer | |
| std::size_t write_buffer_pos = 0; | |
| }; | |
| } // namespace detail | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // #include <nlohmann/detail/recursion_depth_limit.hpp> | |
| // #include <nlohmann/detail/value_t.hpp> | |
| // #include <nlohmann/json_fwd.hpp> | |
| // IWYU pragma: export | |
| // #include <nlohmann/ordered_map.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #include <algorithm> // max, min | |
| #include <functional> // equal_to, less | |
| #include <initializer_list> // initializer_list | |
| #include <iterator> // input_iterator_tag, iterator_traits | |
| #include <memory> // allocator // IWYU pragma: keep | |
| #include <new> // for operator new (placement new) | |
| #include <stdexcept> // for out_of_range | |
| #include <tuple> // forward_as_tuple | |
| #include <type_traits> // enable_if, integral_constant, is_convertible, is_nothrow_move_constructible | |
| #include <utility> // forward, move, pair, piecewise_construct | |
| #include <vector> // vector | |
| // #include <nlohmann/detail/abi_macros.hpp> | |
| // #include <nlohmann/detail/macro_scope.hpp> | |
| // #include <nlohmann/detail/meta/type_traits.hpp> | |
| // #include <nlohmann/thirdparty/hedley/hedley.hpp> | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| /// ordered_map: a minimal map-like container that preserves insertion order | |
| /// for use within nlohmann::basic_json<ordered_map> | |
| template <class Key, class T, class IgnoredLess = std::less<Key>, | |
| class Allocator = std::allocator<std::pair<const Key, T>>> | |
| struct ordered_map : std::vector<std::pair<const Key, T>, Allocator> | |
| { | |
| using key_type = Key; | |
| using mapped_type = T; | |
| using Container = std::vector<std::pair<const Key, T>, Allocator>; | |
| using iterator = typename Container::iterator; | |
| using const_iterator = typename Container::const_iterator; | |
| using size_type = typename Container::size_type; | |
| using value_type = typename Container::value_type; | |
| #ifdef JSON_HAS_CPP_14 | |
| using key_compare = std::equal_to<>; | |
| #else | |
| using key_compare = std::equal_to<Key>; | |
| #endif | |
| // Explicit constructors instead of `using Container::Container` | |
| // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4) | |
| ordered_map() noexcept(noexcept(Container())) : Container{} {} | |
| explicit ordered_map(const Allocator& alloc) noexcept(noexcept(Container(alloc))) : Container{alloc} {} | |
| template <class It> | |
| ordered_map(It first, It last, const Allocator& alloc = Allocator()) | |
| : Container{first, last, alloc} {} | |
| ordered_map(std::initializer_list<value_type> init, const Allocator& alloc = Allocator() ) | |
| : Container{init, alloc} {} | |
| ordered_map(const ordered_map&) = default; | |
| ordered_map(ordered_map&&) noexcept(std::is_nothrow_move_constructible<Container>::value) = default; | |
| ~ordered_map() = default; | |
| ordered_map& operator=(const ordered_map& other) | |
| { | |
| if (this != &other) | |
| { | |
| ordered_map tmp(other); | |
| Container::operator=(std::move(static_cast<Container&>(tmp))); | |
| } | |
| return *this; | |
| } | |
| ordered_map& operator=(ordered_map&& other) noexcept(std::is_nothrow_move_assignable<Container>::value) | |
| { | |
| Container::operator=(std::move(static_cast<Container&>(other))); | |
| return *this; | |
| } | |
| private: | |
| /// @brief find the entry for @a key, for either constness of @a self | |
| /// @note the single place that performs the linear key search | |
| template<typename Self, typename KeyType> | |
| static auto find_impl(Self& self, const KeyType& key) -> decltype(self.begin()) | |
| { | |
| for (auto it = self.begin(); it != self.end(); ++it) | |
| { | |
| if (self.m_compare(it->first, key)) | |
| { | |
| return it; | |
| } | |
| } | |
| return self.end(); | |
| } | |
| /// @brief throw the exception of a failed at() lookup | |
| /// @note kept out of line so that at_impl() stays small enough to inline | |
| /// @throw std::out_of_range always | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_key_not_found() | |
| { | |
| JSON_THROW(std::out_of_range("key not found")); | |
| } | |
| /// @brief shared implementation of the const and non-const at() overloads | |
| /// @throw std::out_of_range if @a key is not found | |
| template<typename Self, typename KeyType> | |
| static auto at_impl(Self& self, const KeyType& key) -> decltype((self.begin()->second)) | |
| { | |
| const auto it = find_impl(self, key); | |
| if (it == self.end()) | |
| { | |
| throw_key_not_found(); | |
| } | |
| return it->second; | |
| } | |
| /// @brief remove the entry @a it points to, preserving order | |
| /// @note keys are not movable, so the tail is destroyed and re-constructed in place | |
| void erase_at(iterator it) | |
| { | |
| for (auto next = it; ++next != this->end(); ++it) | |
| { | |
| it->~value_type(); // Destroy but keep allocation | |
| new (&*it) value_type{std::move(*next)}; | |
| } | |
| Container::pop_back(); | |
| } | |
| /// @brief remove the entry with the given key; returns the number of removed entries | |
| template<class K> | |
| size_type erase_impl(const K& key) | |
| { | |
| const auto it = find_impl(*this, key); | |
| if (it != this->end()) | |
| { | |
| erase_at(it); | |
| return 1; | |
| } | |
| return 0; | |
| } | |
| public: | |
| template<class V, detail::enable_if_t< | |
| detail::is_constructible<T, V>::value, int> = 0> | |
| std::pair<iterator, bool> emplace(const key_type& key, V && t) | |
| { | |
| const auto it = find_impl(*this, key); | |
| if (it != this->end()) | |
| { | |
| return {it, false}; | |
| } | |
| append(key, std::forward<V>(t)); | |
| return {std::prev(this->end()), true}; | |
| } | |
| template<class KeyType, class V, detail::enable_if_t< | |
| detail::conjunction<detail::is_usable_as_key_type<key_compare, key_type, KeyType>, | |
| detail::is_constructible<T, V>>::value, int> = 0> | |
| std::pair<iterator, bool> emplace(KeyType && key, V && t) | |
| { | |
| const auto it = find_impl(*this, key); | |
| if (it != this->end()) | |
| { | |
| return {it, false}; | |
| } | |
| append(std::forward<KeyType>(key), std::forward<V>(t)); | |
| return {std::prev(this->end()), true}; | |
| } | |
| /// @brief add an element at the end without checking whether the key exists | |
| /// @note The caller must guarantee that @a key is not yet contained, otherwise | |
| /// the container holds duplicate keys. This avoids the linear search of | |
| /// emplace() and operator[] when many keys known to be new are added. | |
| template<class V, detail::enable_if_t< | |
| detail::is_constructible<T, V>::value, int> = 0> | |
| void emplace_new_key(const key_type& key, V && t) | |
| { | |
| append(key, std::forward<V>(t)); | |
| } | |
| T& operator[](const key_type& key) | |
| { | |
| return emplace(key, T{}).first->second; | |
| } | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0> | |
| T & operator[](KeyType && key) | |
| { | |
| return emplace(std::forward<KeyType>(key), T{}).first->second; | |
| } | |
| const T& operator[](const key_type& key) const | |
| { | |
| return at(key); | |
| } | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0> | |
| const T & operator[](KeyType && key) const | |
| { | |
| return at(std::forward<KeyType>(key)); | |
| } | |
| T& at(const key_type& key) | |
| { | |
| return at_impl(*this, key); | |
| } | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0> | |
| T & at(KeyType && key) // NOLINT(cppcoreguidelines-missing-std-forward) | |
| { | |
| return at_impl(*this, key); | |
| } | |
| const T& at(const key_type& key) const | |
| { | |
| return at_impl(*this, key); | |
| } | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0> | |
| const T & at(KeyType && key) const // NOLINT(cppcoreguidelines-missing-std-forward) | |
| { | |
| return at_impl(*this, key); | |
| } | |
| size_type erase(const key_type& key) | |
| { | |
| return erase_impl(key); | |
| } | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0> | |
| size_type erase(KeyType && key) // NOLINT(cppcoreguidelines-missing-std-forward) | |
| { | |
| return erase_impl(key); | |
| } | |
| iterator erase(iterator pos) | |
| { | |
| return erase(pos, std::next(pos)); | |
| } | |
| iterator erase(iterator first, iterator last) | |
| { | |
| if (first == last) | |
| { | |
| return first; | |
| } | |
| const auto elements_affected = std::distance(first, last); | |
| const auto offset = std::distance(Container::begin(), first); | |
| // This is the start situation. We need to delete elements_affected | |
| // elements (3 in this example: e, f, g), and need to return an | |
| // iterator past the last deleted element (h in this example). | |
| // Note that offset is the distance from the start of the vector | |
| // to first. We will need this later. | |
| // [ a, b, c, d, e, f, g, h, i, j ] | |
| // ^ ^ | |
| // first last | |
| // Note on conformance: before C++20, [basic.life]/8 did not allow an | |
| // object of a type with a const member (like value_type's const Key) | |
| // to transparently replace the destroyed one, so strictly, accessing | |
| // it through the vector's existing pointers would have required | |
| // std::launder (which does not exist before C++17). C++20 dropped that | |
| // condition (P1971R0, NB comment US 041). Compilers have always treated | |
| // this pattern as intended, so it is kept deliberately. | |
| // Since we cannot move const Keys, we re-construct them in place. | |
| // We start at first and re-construct (viz. copy) the elements from | |
| // the back of the vector. Example for the first iteration: | |
| // ,--------. | |
| // v | destroy e and re-construct with h | |
| // [ a, b, c, d, e, f, g, h, i, j ] | |
| // ^ ^ | |
| // it it + elements_affected | |
| for (auto it = first; std::next(it, elements_affected) != Container::end(); ++it) | |
| { | |
| // false positive: Infer's model of std::string keeps the buffer of a | |
| // moved-from string, so it assumes a buffer is destroyed twice | |
| // @infer-ignore USE_AFTER_DELETE | |
| it->~value_type(); // destroy but keep allocation | |
| new (&*it) value_type{std::move(*std::next(it, elements_affected))}; // "move" next element to it | |
| } | |
| // [ a, b, c, d, h, i, j, h, i, j ] | |
| // ^ ^ | |
| // first last | |
| // remove the unneeded elements at the end of the vector | |
| Container::resize(this->size() - static_cast<size_type>(elements_affected)); | |
| // [ a, b, c, d, h, i, j ] | |
| // ^ ^ | |
| // first last | |
| // first is now pointing past the last deleted element, but we cannot | |
| // use this iterator, because it may have been invalidated by the | |
| // resize call. Instead, we can return begin() + offset. | |
| return Container::begin() + offset; | |
| } | |
| size_type count(const key_type& key) const | |
| { | |
| return find_impl(*this, key) != this->end() ? 1 : 0; | |
| } | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0> | |
| size_type count(KeyType && key) const // NOLINT(cppcoreguidelines-missing-std-forward) | |
| { | |
| return find_impl(*this, key) != this->end() ? 1 : 0; | |
| } | |
| iterator find(const key_type& key) | |
| { | |
| return find_impl(*this, key); | |
| } | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0> | |
| iterator find(KeyType && key) // NOLINT(cppcoreguidelines-missing-std-forward) | |
| { | |
| return find_impl(*this, key); | |
| } | |
| const_iterator find(const key_type& key) const | |
| { | |
| return find_impl(*this, key); | |
| } | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_key_type<key_compare, key_type, KeyType>::value, int> = 0> | |
| const_iterator find(KeyType && key) const // NOLINT(cppcoreguidelines-missing-std-forward) | |
| { | |
| return find_impl(*this, key); | |
| } | |
| std::pair<iterator, bool> insert( value_type&& value ) | |
| { | |
| return emplace(value.first, std::move(value.second)); | |
| } | |
| std::pair<iterator, bool> insert( const value_type& value ) | |
| { | |
| const auto it = find_impl(*this, value.first); | |
| if (it != this->end()) | |
| { | |
| return {it, false}; | |
| } | |
| append(value); | |
| return {--this->end(), true}; | |
| } | |
| template<typename InputIt> | |
| using require_input_iter = typename std::enable_if<std::is_convertible<typename std::iterator_traits<InputIt>::iterator_category, | |
| std::input_iterator_tag>::value>::type; | |
| template<typename InputIt, typename = require_input_iter<InputIt>> | |
| void insert(InputIt first, InputIt last) | |
| { | |
| for (auto it = first; it != last; ++it) | |
| { | |
| insert(*it); | |
| } | |
| } | |
| private: | |
| /*! | |
| @brief add an element whose key is not yet contained at the end | |
| A std::vector copies all elements when it grows, because their const keys | |
| make them not nothrow move constructible. For ordered_json, this is a deep | |
| copy of every value. Where the strong exception guarantee can be kept, grow | |
| the storage here instead, copying only the keys and moving the values. | |
| */ | |
| template<typename... Args> | |
| void append(Args&& ... args) | |
| { | |
| // evaluated here rather than at class scope, because T is still | |
| // incomplete when basic_json instantiates its object_t | |
| using move_values = std::integral_constant<bool, detail::conjunction< | |
| detail::negation<std::is_nothrow_move_constructible<value_type>>, | |
| std::is_copy_constructible<key_type>, | |
| detail::is_default_constructible<mapped_type>, | |
| std::is_nothrow_move_assignable<mapped_type>>::value>; | |
| append_impl(move_values{}, std::forward<Args>(args)...); | |
| } | |
| template<typename... Args> | |
| void append_impl(std::true_type /*unused*/, Args&& ... args) | |
| { | |
| if (this->size() < this->capacity()) | |
| { | |
| Container::emplace_back(std::forward<Args>(args)...); | |
| return; | |
| } | |
| // 1. May throw, but only changes tmp: copy the keys, value-initialize | |
| // the values, and add the new element. The arguments may refer to | |
| // elements of this container, so they are used before any value is | |
| // moved out of it. | |
| Container tmp(this->get_allocator()); // equal allocators, so swap() is valid | |
| tmp.reserve((std::min)(this->max_size(), (std::max)(size_type{1}, 2 * this->size()))); | |
| for (const auto& element : *this) | |
| { | |
| tmp.emplace_back(std::piecewise_construct, std::forward_as_tuple(element.first), std::forward_as_tuple()); | |
| } | |
| tmp.emplace_back(std::forward<Args>(args)...); | |
| // 2. Cannot throw: move the values over and adopt the new storage. | |
| auto it = tmp.begin(); | |
| for (auto& element : *this) | |
| { | |
| it->second = std::move(element.second); | |
| ++it; | |
| } | |
| Container::swap(tmp); | |
| } | |
| template<typename... Args> | |
| void append_impl(std::false_type /*unused*/, Args&& ... args) | |
| { | |
| Container::emplace_back(std::forward<Args>(args)...); | |
| } | |
| JSON_NO_UNIQUE_ADDRESS key_compare m_compare = key_compare(); | |
| }; | |
| NLOHMANN_JSON_NAMESPACE_END | |
| // IWYU pragma: keep | |
| // #include <nlohmann/thirdparty/hedley/hedley.hpp> | |
| #if defined(JSON_HAS_CPP_17) | |
| #if JSON_HAS_STATIC_RTTI | |
| #include <any> | |
| #endif | |
| #include <string_view> | |
| #endif | |
| #if JSON_HAS_STD_FORMAT | |
| #include <format> // format_parse_context, format_context, formatter, format_error | |
| #endif | |
| /*! | |
| @brief namespace for Niels Lohmann | |
| @see https://github.com/nlohmann | |
| @since version 1.0.0 | |
| */ | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| namespace detail | |
| { | |
| // Trait to detect std::optional<T> specializations. It is defined here rather | |
| // than in type_traits.hpp so that adding the <optional> include does not change | |
| // the include order of the C++20 module's global module fragment (the include | |
| // is already pulled in by the conversion headers above); see src/modules/json.cppm. | |
| template<typename> | |
| struct is_std_optional : std::false_type {}; | |
| #ifdef JSON_HAS_CPP_17 | |
| template<typename T> | |
| struct is_std_optional<std::optional<T>> : std::true_type {}; | |
| #endif | |
| } // namespace detail | |
| /*! | |
| @brief a class to store JSON values | |
| @internal | |
| @invariant The member variables @a m_data.m_value and @a m_data.m_type have | |
| the following relationship: | |
| - If `m_data.m_type == value_t::object`, then `m_data.m_value.object != nullptr`. | |
| - If `m_data.m_type == value_t::array`, then `m_data.m_value.array != nullptr`. | |
| - If `m_data.m_type == value_t::string`, then `m_data.m_value.string != nullptr`. | |
| - If `m_data.m_type == value_t::binary`, then `m_data.m_value.binary != nullptr`. | |
| The invariants are checked by member function assert_invariant(). | |
| @note ObjectType trick from https://stackoverflow.com/a/9860911 | |
| @endinternal | |
| @since version 1.0.0 | |
| @nosubgrouping | |
| */ | |
| NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
| class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) | |
| : public ::nlohmann::detail::json_base_class<CustomBaseClass> | |
| { | |
| private: | |
| template<detail::value_t> friend struct detail::external_constructor; | |
| template<typename> | |
| friend class ::nlohmann::json_pointer; | |
| // can be restored when json_pointer backwards compatibility is removed | |
| // friend ::nlohmann::json_pointer<StringType>; | |
| template<typename BasicJsonType, typename InputType> | |
| friend class ::nlohmann::detail::parser; | |
| friend ::nlohmann::detail::serializer<basic_json>; | |
| template<typename BasicJsonType> | |
| friend class ::nlohmann::detail::iter_impl; | |
| template<typename BasicJsonType, typename CharType, typename OutputSinkType> | |
| friend class ::nlohmann::detail::binary_writer; | |
| template<typename BasicJsonType, typename InputType, typename SAX> | |
| friend class ::nlohmann::detail::binary_reader; | |
| template<typename BasicJsonType, typename InputAdapterType, bool Collect> | |
| friend class ::nlohmann::detail::json_sax_dom_parser; | |
| template<typename BasicJsonType, typename InputAdapterType> | |
| friend class ::nlohmann::detail::json_sax_dom_binary_parser; | |
| template<typename BasicJsonType, typename InputAdapterType> | |
| friend class ::nlohmann::detail::json_sax_dom_callback_parser; | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| friend struct ::nlohmann::detail::diagnostic_positions; | |
| #endif | |
| friend class ::nlohmann::detail::exception; | |
| /// workaround type for MSVC | |
| using basic_json_t = NLOHMANN_BASIC_JSON_TPL; | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| // convenience aliases for types residing in namespace detail; | |
| using lexer = ::nlohmann::detail::lexer_base<basic_json>; | |
| template<typename InputAdapterType> | |
| static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser( | |
| InputAdapterType adapter, | |
| detail::parser_callback_t<basic_json>cb = nullptr, | |
| const bool allow_exceptions = true, | |
| const bool ignore_comments = false, | |
| const bool ignore_trailing_commas = false, | |
| const bool discard_number_values = false | |
| ) | |
| { | |
| return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter), | |
| std::move(cb), allow_exceptions, ignore_comments, ignore_trailing_commas, discard_number_values); | |
| } | |
| private: | |
| template<typename BasicJsonType> | |
| using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>; | |
| template<typename Iterator> | |
| using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>; | |
| template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>; | |
| template<typename InputType> | |
| using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>; | |
| template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>; | |
| // binary_writer over a concrete (non-virtual) sink appending into a std::vector, | |
| // used by the vector-returning to_* overloads | |
| template<typename CharType> using vector_binary_writer = | |
| ::nlohmann::detail::binary_writer<basic_json, CharType, ::nlohmann::detail::output_vector_sink<CharType>>; | |
| template<typename CharType> static vector_binary_writer<CharType> vector_writer( | |
| std::vector<CharType>& v, const ::nlohmann::detail::error_handler_t error_handler = ::nlohmann::detail::binary_writer_default_error_handler()) | |
| { | |
| return vector_binary_writer<CharType>(::nlohmann::detail::output_vector_sink<CharType>(v), error_handler); | |
| } | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| using serializer = ::nlohmann::detail::serializer<basic_json>; | |
| public: | |
| using value_t = detail::value_t; | |
| /// JSON Pointer, see @ref nlohmann::json_pointer | |
| using json_pointer = ::nlohmann::json_pointer<StringType>; | |
| template<typename T, typename SFINAE> | |
| using json_serializer = JSONSerializer<T, SFINAE>; | |
| /// how to treat decoding errors | |
| using error_handler_t = detail::error_handler_t; | |
| /// how to treat CBOR tags | |
| using cbor_tag_handler_t = detail::cbor_tag_handler_t; | |
| /// how to encode BJData | |
| using bjdata_version_t = detail::bjdata_version_t; | |
| /// base class used to inject custom functionality into each instance of basic_json | |
| /// @sa https://json.nlohmann.me/api/basic_json/json_base_class_t/ | |
| using json_base_class_t = ::nlohmann::detail::json_base_class<CustomBaseClass>; | |
| /// helper type for initializer lists of basic_json values | |
| using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>; | |
| using input_format_t = detail::input_format_t; | |
| /// SAX interface type, see @ref nlohmann::json_sax | |
| using json_sax_t = json_sax<basic_json>; | |
| //////////////////////////////////////////////////////////////////////////////// | |
| // utility templates to create a json type with different template parameters // | |
| //////////////////////////////////////////////////////////////////////////////// | |
| /// Json type using a different type for storing objects | |
| /// @sa https://json.nlohmann.me/api/basic_json/with_t/ | |
| template<template<typename, typename, typename...> class ObjectType2> | |
| using with_object_t = basic_json<ObjectType2, ArrayType, StringType, BooleanType, | |
| NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType, CustomBaseClass>; | |
| /// Json type using a different type for storing arrays | |
| /// @sa https://json.nlohmann.me/api/basic_json/with_t/ | |
| template<template<typename, typename...> class ArrayType2> | |
| using with_array_t = basic_json<ObjectType, ArrayType2, StringType, BooleanType, | |
| NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType, CustomBaseClass>; | |
| /// Json type using a different type for storing strings | |
| /// @sa https://json.nlohmann.me/api/basic_json/with_t/ | |
| template<class StringType2> | |
| using with_string_t = basic_json<ObjectType, ArrayType, StringType2, BooleanType, | |
| NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType, CustomBaseClass>; | |
| /// Json type using a different type for storing booleans | |
| /// @sa https://json.nlohmann.me/api/basic_json/with_t/ | |
| template<class BooleanType2> | |
| using with_boolean_t = basic_json<ObjectType, ArrayType, StringType, BooleanType2, | |
| NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType, CustomBaseClass>; | |
| /// Json type using different types for storing signed and unsigned integers | |
| /// @sa https://json.nlohmann.me/api/basic_json/with_t/ | |
| template<class NumberIntegerType2, class NumberUnsignedType2> | |
| using with_integers_t = basic_json<ObjectType, ArrayType, StringType, BooleanType, | |
| NumberIntegerType2, NumberUnsignedType2, NumberFloatType, AllocatorType, JSONSerializer, BinaryType, CustomBaseClass>; | |
| /// Json type using a different type for storing floating point numbers | |
| /// @sa https://json.nlohmann.me/api/basic_json/with_t/ | |
| template<class NumberFloatType2> | |
| using with_float_t = basic_json<ObjectType, ArrayType, StringType, BooleanType, | |
| NumberIntegerType, NumberUnsignedType, NumberFloatType2, AllocatorType, JSONSerializer, BinaryType, CustomBaseClass>; | |
| /// Json type using a different type as base allocator | |
| /// @sa https://json.nlohmann.me/api/basic_json/with_t/ | |
| template<template<typename> class AllocatorType2> | |
| using with_allocator_t = basic_json<ObjectType, ArrayType, StringType, BooleanType, | |
| NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType2, JSONSerializer, BinaryType, CustomBaseClass>; | |
| /// Json type using a different type as json serializer | |
| /// @sa https://json.nlohmann.me/api/basic_json/with_t/ | |
| template<template<typename, typename = void> class JSONSerializer2> | |
| using with_json_serializer_t = basic_json<ObjectType, ArrayType, StringType, BooleanType, | |
| NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer2, BinaryType, CustomBaseClass>; | |
| /// Json type using a different type for storing binary data | |
| /// @sa https://json.nlohmann.me/api/basic_json/with_t/ | |
| template<class BinaryType2> | |
| using with_binary_t = basic_json<ObjectType, ArrayType, StringType, BooleanType, | |
| NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType2, CustomBaseClass>; | |
| /// Json type using a different type as base class | |
| /// @sa https://json.nlohmann.me/api/basic_json/with_t/ | |
| template<class CustomBaseClass2> | |
| using with_base_class_t = basic_json<ObjectType, ArrayType, StringType, BooleanType, | |
| NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType, CustomBaseClass2>; | |
| //////////////// | |
| // exceptions // | |
| //////////////// | |
| /// @name exceptions | |
| /// Classes to implement user-defined exceptions. | |
| /// @{ | |
| using exception = detail::exception; | |
| using parse_error = detail::parse_error; | |
| using invalid_iterator = detail::invalid_iterator; | |
| using type_error = detail::type_error; | |
| using out_of_range = detail::out_of_range; | |
| using other_error = detail::other_error; | |
| /// @} | |
| ///////////////////// | |
| // container types // | |
| ///////////////////// | |
| /// @name container types | |
| /// The canonic container types to use @ref basic_json like any other STL | |
| /// container. | |
| /// @{ | |
| /// the type of elements in a basic_json container | |
| using value_type = basic_json; | |
| /// the type of an element reference | |
| using reference = value_type&; | |
| /// the type of an element const reference | |
| using const_reference = const value_type&; | |
| /// a type to represent differences between iterators | |
| using difference_type = std::ptrdiff_t; | |
| /// a type to represent container sizes | |
| using size_type = std::size_t; | |
| /// the allocator type | |
| using allocator_type = AllocatorType<basic_json>; | |
| /// the type of an element pointer | |
| using pointer = typename std::allocator_traits<allocator_type>::pointer; | |
| /// the type of an element const pointer | |
| using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer; | |
| /// an iterator for a basic_json container | |
| using iterator = iter_impl<basic_json>; | |
| /// a const iterator for a basic_json container | |
| using const_iterator = iter_impl<const basic_json>; | |
| /// a reverse iterator for a basic_json container | |
| using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>; | |
| /// a const reverse iterator for a basic_json container | |
| using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>; | |
| /// @} | |
| /// @brief returns the allocator associated with the container | |
| /// @sa https://json.nlohmann.me/api/basic_json/get_allocator/ | |
| static allocator_type get_allocator() | |
| { | |
| return allocator_type(); | |
| } | |
| /// @brief returns version information on the library | |
| /// @sa https://json.nlohmann.me/api/basic_json/meta/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json meta() | |
| { | |
| basic_json result; | |
| result["copyright"] = "(C) 2013-2026 Niels Lohmann"; | |
| result["name"] = "JSON for Modern C++"; | |
| result["url"] = "https://github.com/nlohmann/json"; | |
| result["version"]["string"] = | |
| detail::concat<string_t>(detail::to_string<string_t>(static_cast<std::size_t>(NLOHMANN_JSON_VERSION_MAJOR)), '.', | |
| detail::to_string<string_t>(static_cast<std::size_t>(NLOHMANN_JSON_VERSION_MINOR)), '.', | |
| detail::to_string<string_t>(static_cast<std::size_t>(NLOHMANN_JSON_VERSION_PATCH))); | |
| result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; | |
| result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; | |
| result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; | |
| #ifdef _WIN32 | |
| result["platform"] = "win32"; | |
| #elif defined __linux__ | |
| result["platform"] = "linux"; | |
| #elif defined __APPLE__ | |
| result["platform"] = "apple"; | |
| #elif defined __unix__ | |
| result["platform"] = "unix"; | |
| #else | |
| result["platform"] = "unknown"; | |
| #endif | |
| #if defined(__ICC) || defined(__INTEL_COMPILER) | |
| result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; | |
| #elif defined(__clang__) | |
| result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; | |
| #elif defined(__GNUC__) || defined(__GNUG__) | |
| result["compiler"] = {{"family", "gcc"}, {"version", detail::concat<string_t>( | |
| detail::to_string<string_t>(static_cast<std::size_t>(__GNUC__)), '.', | |
| detail::to_string<string_t>(static_cast<std::size_t>(__GNUC_MINOR__)), '.', | |
| detail::to_string<string_t>(static_cast<std::size_t>(__GNUC_PATCHLEVEL__))) | |
| } | |
| }; | |
| #elif defined(__HP_aCC) | |
| result["compiler"] = {{"family", "hp"}, {"version", __HP_aCC}}; | |
| #elif defined(__IBMCPP__) | |
| result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; | |
| #elif defined(_MSC_VER) | |
| result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; | |
| #elif defined(__PGI) | |
| result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; | |
| #elif defined(__SUNPRO_CC) | |
| result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; | |
| #else | |
| result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; | |
| #endif | |
| #if defined(_MSVC_LANG) | |
| result["compiler"]["c++"] = detail::to_string<string_t>(static_cast<std::size_t>(_MSVC_LANG)); | |
| #elif defined(__cplusplus) | |
| result["compiler"]["c++"] = detail::to_string<string_t>(static_cast<std::size_t>(__cplusplus)); | |
| #else | |
| result["compiler"]["c++"] = "unknown"; | |
| #endif | |
| return result; | |
| } | |
| /////////////////////////// | |
| // JSON value data types // | |
| /////////////////////////// | |
| /// @name JSON value data types | |
| /// The data types to store a JSON value. These types are derived from | |
| /// the template arguments passed to class @ref basic_json. | |
| /// @{ | |
| /// @brief default object key comparator type | |
| /// The actual object key comparator type (@ref object_comparator_t) may be | |
| /// different. | |
| /// @sa https://json.nlohmann.me/api/basic_json/default_object_comparator_t/ | |
| #if defined(JSON_HAS_CPP_14) | |
| // use of transparent comparator avoids unnecessary repeated construction of temporaries | |
| // in functions involving lookup by key with types other than object_t::key_type (aka. StringType) | |
| using default_object_comparator_t = std::less<>; | |
| #else | |
| using default_object_comparator_t = std::less<StringType>; | |
| #endif | |
| /// @brief a type for an object | |
| /// @sa https://json.nlohmann.me/api/basic_json/object_t/ | |
| using object_t = ObjectType<StringType, | |
| basic_json, | |
| default_object_comparator_t, | |
| AllocatorType<std::pair<const StringType, | |
| basic_json>>>; | |
| /// @brief a type for an array | |
| /// @sa https://json.nlohmann.me/api/basic_json/array_t/ | |
| using array_t = ArrayType<basic_json, AllocatorType<basic_json>>; | |
| /// @brief a type for a string | |
| /// @sa https://json.nlohmann.me/api/basic_json/string_t/ | |
| using string_t = StringType; | |
| /// @brief a type for a boolean | |
| /// @sa https://json.nlohmann.me/api/basic_json/boolean_t/ | |
| using boolean_t = BooleanType; | |
| /// @brief a type for a number (integer) | |
| /// @sa https://json.nlohmann.me/api/basic_json/number_integer_t/ | |
| using number_integer_t = NumberIntegerType; | |
| /// @brief a type for a number (unsigned) | |
| /// @sa https://json.nlohmann.me/api/basic_json/number_unsigned_t/ | |
| using number_unsigned_t = NumberUnsignedType; | |
| /// @brief a type for a number (floating-point) | |
| /// @sa https://json.nlohmann.me/api/basic_json/number_float_t/ | |
| using number_float_t = NumberFloatType; | |
| /// @brief a type for a packed binary type | |
| /// @sa https://json.nlohmann.me/api/basic_json/binary_t/ | |
| using binary_t = nlohmann::byte_container_with_subtype<BinaryType>; | |
| /// @brief object key comparator type | |
| /// @sa https://json.nlohmann.me/api/basic_json/object_comparator_t/ | |
| using object_comparator_t = detail::actual_object_comparator_t<basic_json>; | |
| /// @} | |
| // Two template parameter requirements that would otherwise be silently | |
| // violated: neither produces a diagnostic of its own, and both corrupt | |
| // values rather than failing. | |
| static_assert(sizeof(typename BinaryType::value_type) == 1, | |
| "BinaryType::value_type must be exactly one byte wide, " | |
| "because the binary readers and writers reinterpret the container's storage as raw bytes"); | |
| static_assert(sizeof(NumberUnsignedType) >= sizeof(NumberIntegerType), | |
| "NumberUnsignedType must be at least as wide as NumberIntegerType, " | |
| "because it has to hold the absolute value of every NumberIntegerType value"); | |
| // NumberUnsignedType may be the same type as NumberIntegerType (#2573), but | |
| // a repeated NumberFloatType would give overloads that collide, so it gets | |
| // a readable diagnostic instead. | |
| static_assert(!std::is_same<NumberFloatType, NumberIntegerType>::value && !std::is_same<NumberFloatType, NumberUnsignedType>::value, | |
| "NumberFloatType must be a different type than NumberIntegerType and NumberUnsignedType"); | |
| private: | |
| /// the kind a value of kind @a t is stored as: if number_unsigned_t is the | |
| /// same type as number_integer_t, every integer is stored as number_integer | |
| /// (#2573); every other kind is stored as itself | |
| static constexpr value_t stored_kind(const value_t t) noexcept | |
| { | |
| return (std::is_same<number_integer_t, number_unsigned_t>::value && t == value_t::number_unsigned) ? value_t::number_integer : t; | |
| } | |
| /// helper for exception-safe object creation | |
| template<typename T, typename... Args> | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| static T* create(Args&& ... args) | |
| { | |
| AllocatorType<T> alloc; | |
| using AllocatorTraits = std::allocator_traits<AllocatorType<T>>; | |
| auto deleter = [&](T * obj) | |
| { | |
| AllocatorTraits::deallocate(alloc, obj, 1); | |
| }; | |
| std::unique_ptr<T, decltype(deleter)> obj(AllocatorTraits::allocate(alloc, 1), deleter); | |
| AllocatorTraits::construct(alloc, obj.get(), std::forward<Args>(args)...); | |
| JSON_ASSERT(obj); | |
| return obj.release(); | |
| } | |
| //////////////////////// | |
| // JSON value storage // | |
| //////////////////////// | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| /*! | |
| @brief a JSON value | |
| The actual storage for a JSON value of the @ref basic_json class. This | |
| union combines the different storage types for the JSON value types | |
| defined in @ref value_t. | |
| JSON type | value_t type | used type | |
| --------- | --------------- | ------------------------ | |
| object | object | pointer to @ref object_t | |
| array | array | pointer to @ref array_t | |
| string | string | pointer to @ref string_t | |
| boolean | boolean | @ref boolean_t | |
| number | number_integer | @ref number_integer_t | |
| number | number_unsigned | @ref number_unsigned_t | |
| number | number_float | @ref number_float_t | |
| binary | binary | pointer to @ref binary_t | |
| null | null | *no value is stored* | |
| @note Variable-length types (objects, arrays, strings, and binary | |
| values) are stored as pointers. The size of the union should not exceed | |
| 64 bits if the default value types are used. | |
| @since version 1.0.0 | |
| */ | |
| union json_value | |
| { | |
| /// object (stored with pointer to save storage) | |
| object_t* object; | |
| /// array (stored with pointer to save storage) | |
| array_t* array; | |
| /// string (stored with pointer to save storage) | |
| string_t* string; | |
| /// binary (stored with pointer to save storage) | |
| binary_t* binary; | |
| /// boolean | |
| boolean_t boolean; | |
| /// number (integer) | |
| number_integer_t number_integer; | |
| /// number (unsigned integer) | |
| number_unsigned_t number_unsigned; | |
| /// number (floating-point) | |
| number_float_t number_float; | |
| /// default constructor (for null values) | |
| json_value() = default; | |
| /// constructor for booleans | |
| json_value(boolean_t v) noexcept : boolean(v) {} | |
| /// constructor for numbers (integer) | |
| json_value(number_integer_t v) noexcept : number_integer(v) {} | |
| /// constructor for numbers (unsigned); takes a placeholder if number_unsigned_t is number_integer_t | |
| json_value(detail::number_unsigned_overload_type<NumberIntegerType, NumberUnsignedType> v) noexcept : number_unsigned(v) {} | |
| /// constructor for numbers (floating-point) | |
| json_value(number_float_t v) noexcept : number_float(v) {} | |
| /// constructor for empty values of a given type | |
| json_value(value_t t) | |
| { | |
| switch (t) | |
| { | |
| case value_t::object: | |
| case value_t::array: | |
| case value_t::string: | |
| case value_t::binary: | |
| { | |
| // allocating: kept out of line, so the scalar cases below inline | |
| init_owned(t); | |
| break; | |
| } | |
| case value_t::boolean: | |
| { | |
| boolean = static_cast<boolean_t>(false); | |
| break; | |
| } | |
| case value_t::number_integer: | |
| { | |
| number_integer = static_cast<number_integer_t>(0); | |
| break; | |
| } | |
| case value_t::number_unsigned: | |
| { | |
| number_unsigned = static_cast<number_unsigned_t>(0); | |
| break; | |
| } | |
| case value_t::number_float: | |
| { | |
| number_float = static_cast<number_float_t>(0.0); | |
| break; | |
| } | |
| case value_t::null: | |
| { | |
| object = nullptr; // silence warning, see #821 | |
| break; | |
| } | |
| case value_t::discarded: | |
| default: | |
| { | |
| object = nullptr; // silence warning, see #821 | |
| if (JSON_HEDLEY_UNLIKELY(t == value_t::null)) | |
| { | |
| detail::throw_literal<other_error>(detail::exception_id::internal_error, "961c151d2e87f2686a955a9be24d316f1362bf21 3.12.0", nullptr); // LCOV_EXCL_LINE | |
| } | |
| break; | |
| } | |
| } | |
| } | |
| JSON_HEDLEY_NEVER_INLINE | |
| void init_owned(value_t t) | |
| { | |
| switch (t) | |
| { | |
| case value_t::object: | |
| object = create<object_t>(); | |
| break; | |
| case value_t::array: | |
| array = create<array_t>(); | |
| break; | |
| case value_t::string: | |
| string = create<string_t>(""); | |
| break; | |
| case value_t::binary: | |
| binary = create<binary_t>(); | |
| break; | |
| case value_t::null: | |
| case value_t::boolean: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| case value_t::discarded: | |
| default: | |
| break; | |
| } | |
| } | |
| /// constructor for strings | |
| json_value(const string_t& value) : string(create<string_t>(value)) {} | |
| /// constructor for rvalue strings | |
| json_value(string_t&& value) : string(create<string_t>(std::move(value))) {} | |
| /// constructor for objects | |
| json_value(const object_t& value) : object(create<object_t>(value)) {} | |
| /// constructor for rvalue objects | |
| json_value(object_t&& value) : object(create<object_t>(std::move(value))) {} | |
| /// constructor for arrays | |
| json_value(const array_t& value) : array(create<array_t>(value)) {} | |
| /// constructor for rvalue arrays | |
| json_value(array_t&& value) : array(create<array_t>(std::move(value))) {} | |
| /// constructor for binary arrays | |
| json_value(const typename binary_t::container_type& value) : binary(create<binary_t>(value)) {} | |
| /// constructor for rvalue binary arrays | |
| json_value(typename binary_t::container_type&& value) : binary(create<binary_t>(std::move(value))) {} | |
| /// constructor for binary arrays (internal type) | |
| json_value(const binary_t& value) : binary(create<binary_t>(value)) {} | |
| /// constructor for rvalue binary arrays (internal type) | |
| json_value(binary_t&& value) : binary(create<binary_t>(std::move(value))) {} | |
| /// constructors taking ownership of an already created value | |
| explicit json_value(string_t* value) noexcept : string(value) {} | |
| explicit json_value(object_t* value) noexcept : object(value) {} | |
| explicit json_value(array_t* value) noexcept : array(value) {} | |
| private: | |
| // raw, allocation-free transfer of m_data from src to dst: no | |
| // set_parents()/assert_invariant() (the former is O(#children) per | |
| // call under JSON_DIAGNOSTICS, which would make the walk below | |
| // quadratic); dst takes ownership, src is left as value_t::null. | |
| static void take(basic_json& dst, basic_json& src) noexcept | |
| { | |
| dst.m_data.m_type = src.m_data.m_type; | |
| dst.m_data.m_value = src.m_data.m_value; | |
| src.m_data.m_type = value_t::null; | |
| } | |
| // true if v is not an array/object, or is an already-empty one | |
| static bool has_no_children(const basic_json& v) noexcept | |
| { | |
| if (v.m_data.m_type == value_t::array) | |
| { | |
| return v.m_data.m_value.array->empty(); | |
| } | |
| if (v.m_data.m_type == value_t::object) | |
| { | |
| return v.m_data.m_value.object->empty(); | |
| } | |
| return true; | |
| } | |
| // true if no child of the non-empty array/object v has children of | |
| // its own, i.e. v can be freed in one go (its destructor then | |
| // destroys scalars and empty containers only, so it recurses at most | |
| // one level deep); stops at the first structured child it meets | |
| static bool all_children_leaves(const basic_json& v) noexcept | |
| { | |
| // array_t only needs forward iterators (see custom_array_type) | |
| if (v.m_data.m_type == value_t::array) | |
| { | |
| const auto& a = *v.m_data.m_value.array; | |
| return std::all_of(a.begin(), a.end(), [](const basic_json & el) | |
| { | |
| return has_no_children(el); | |
| }); | |
| } | |
| const auto& o = *v.m_data.m_value.object; | |
| return std::all_of(o.begin(), o.end(), [](const typename object_t::value_type & el) | |
| { | |
| return has_no_children(el.second); | |
| }); | |
| } | |
| // The walk in destroy_container() may take the children of a | |
| // container in any order, as long as it picks the same child again | |
| // while that container is not modified in between. Arrays and | |
| // objects with bidirectional iterators (std::map, ordered_map, ...) | |
| // use their last child, which a vector-based container can remove | |
| // in O(1). ObjectType only needs forward iterators, though (e.g. | |
| // std::unordered_map), so other objects use their first child. | |
| template<typename ObjectType_> | |
| static typename ObjectType_::iterator walk_child_it(ObjectType_& o, std::bidirectional_iterator_tag /*unused*/) | |
| { | |
| return std::prev(o.end()); | |
| } | |
| template<typename ObjectType_> | |
| static typename ObjectType_::iterator walk_child_it(ObjectType_& o, std::forward_iterator_tag /*unused*/) | |
| { | |
| return o.begin(); | |
| } | |
| template<typename ObjectType_> | |
| static typename ObjectType_::iterator walk_child_it(ObjectType_& o) | |
| { | |
| JSON_ASSERT(!o.empty()); | |
| return walk_child_it(o, typename std::iterator_traits<typename ObjectType_::iterator>::iterator_category()); | |
| } | |
| // the child of a non-empty array/object v that the walk in | |
| // destroy_container() continues with (see walk_child_it() above) | |
| static basic_json& walk_child(basic_json& v) | |
| { | |
| if (v.m_data.m_type == value_t::array) | |
| { | |
| return v.m_data.m_value.array->back(); | |
| } | |
| JSON_ASSERT(v.m_data.m_type == value_t::object); | |
| return walk_child_it(*v.m_data.m_value.object)->second; | |
| } | |
| // removes walk_child(v) from a non-empty array/object v; this never | |
| // allocates, and since it is only ever called when that child is a | |
| // scalar or an already-empty array/object, destroying it never | |
| // recurses more than one level deep (see destroy() below) | |
| static void pop_walk_child(basic_json& v) | |
| { | |
| if (v.m_data.m_type == value_t::array) | |
| { | |
| v.m_data.m_value.array->pop_back(); | |
| } | |
| else | |
| { | |
| JSON_ASSERT(v.m_data.m_type == value_t::object); | |
| v.m_data.m_value.object->erase(walk_child_it(*v.m_data.m_value.object)); | |
| } | |
| } | |
| // deallocates the array/object held by v, which is either empty or | |
| // holds only scalars and empty containers (so its destructor | |
| // recurses at most one level deep); this is the same allocator-based | |
| // free the old recursive implementation used, just factored out so | |
| // every level of the walk in destroy() can share it | |
| static void free_container(basic_json& v) noexcept | |
| { | |
| JSON_ASSERT(has_no_children(v) || all_children_leaves(v)); | |
| if (v.m_data.m_type == value_t::array) | |
| { | |
| AllocatorType<array_t> alloc; | |
| std::allocator_traits<decltype(alloc)>::destroy(alloc, v.m_data.m_value.array); | |
| std::allocator_traits<decltype(alloc)>::deallocate(alloc, v.m_data.m_value.array, 1); | |
| } | |
| else | |
| { | |
| JSON_ASSERT(v.m_data.m_type == value_t::object); | |
| AllocatorType<object_t> alloc; | |
| std::allocator_traits<decltype(alloc)>::destroy(alloc, v.m_data.m_value.object); | |
| std::allocator_traits<decltype(alloc)>::deallocate(alloc, v.m_data.m_value.object, 1); | |
| } | |
| v.m_data.m_type = value_t::null; // avoid a double free if v is later destructed | |
| } | |
| public: | |
| template<typename T> | |
| static void destroy_pointer(T*& ptr) noexcept | |
| { | |
| if (ptr == nullptr) | |
| { | |
| // not initialized (e.g., due to exception in the ctor) | |
| return; | |
| } | |
| AllocatorType<T> alloc; | |
| std::allocator_traits<decltype(alloc)>::destroy(alloc, ptr); | |
| std::allocator_traits<decltype(alloc)>::deallocate(alloc, ptr, 1); | |
| } | |
| // t must be value_t::array or value_t::object | |
| void destroy_container(value_t t) noexcept | |
| { | |
| if ( | |
| (t == value_t::object && object == nullptr) || | |
| (t == value_t::array && array == nullptr) | |
| ) | |
| { | |
| // not initialized (e.g., due to exception in the ctor) | |
| return; | |
| } | |
| // This json_value is not itself a basic_json, so the top-level | |
| // container is first moved into a local stand-in ("cur"); a | |
| // default-constructed basic_json has a null pointer in its | |
| // m_value (see data::m_value's initializer), so swapping it | |
| // with *this leaves this union's own pointer null, and it is | |
| // never looked at or freed a second time. | |
| basic_json cur; | |
| cur.m_data.m_type = t; | |
| using std::swap; | |
| swap(cur.m_data.m_value, *this); | |
| destroy_bounded(cur, 0); | |
| } | |
| // Destroy the array/object v, whose children are destroyed first. | |
| // The first recursion_depth_limit() levels are destroyed by plain | |
| // recursion, which is the fastest way and cannot throw; anything | |
| // nested deeper is handed to destroy_walk(), which uses no call stack. | |
| static void destroy_bounded(basic_json& v, std::size_t depth) noexcept | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(depth >= detail::recursion_depth_limit())) | |
| { | |
| destroy_walk(v); | |
| return; | |
| } | |
| if (v.m_data.m_type == value_t::array) | |
| { | |
| for (auto& child : *v.m_data.m_value.array) | |
| { | |
| if (child.m_data.m_type == value_t::array || child.m_data.m_type == value_t::object) | |
| { | |
| destroy_bounded(child, depth + 1); | |
| } | |
| } | |
| } | |
| else | |
| { | |
| for (auto& child : *v.m_data.m_value.object) | |
| { | |
| if (child.second.m_data.m_type == value_t::array || child.second.m_data.m_type == value_t::object) | |
| { | |
| destroy_bounded(child.second, depth + 1); | |
| } | |
| } | |
| } | |
| // only leaves and already destroyed (null) children remain | |
| free_container(v); | |
| } | |
| // Destroy the tree below top without recursing per nesting level and | |
| // without any heap allocation: a heap-allocated flattening | |
| // stack (the previous implementation) can itself throw | |
| // bad_alloc, which would escape this noexcept destructor and | |
| // terminate the program (#5135). | |
| // | |
| // Instead, walk down a chain of children (always the one | |
| // walk_child() picks), reversing links as we go: cur is the | |
| // container currently being emptied, and prev is its parent | |
| // (value_t::null when there is none). Each parent's | |
| // walk_child() slot doubles as storage for that parent's own | |
| // parent link while we are below it, so no extra memory is | |
| // needed; the parent is not modified meanwhile, so | |
| // walk_child() finds that same slot again on the way up. We | |
| // only ever remove a child once it is a scalar or an empty | |
| // array/object, which neither allocates nor recurses more | |
| // than one level deep. | |
| // | |
| // This json_value is not itself a basic_json, so the | |
| // top-level container is first moved into a local stand-in | |
| // ("cur"); a default-constructed basic_json has a null | |
| // pointer in its m_value (see data::m_value's initializer), | |
| // so swapping it with *this leaves this union's own pointer | |
| // null, and it is never looked at or freed a second time. | |
| static void destroy_walk(basic_json& top) noexcept | |
| { | |
| basic_json cur; | |
| take(cur, top); | |
| basic_json prev; // value_t::null: no parent | |
| // true right after cur was entered: its children have not been | |
| // looked at yet. If none of them has children of its own, cur is | |
| // freed in one go instead of child by child; this is tried once | |
| // per container, so the walk stays linear. | |
| bool fresh = true; | |
| while (true) | |
| { | |
| const bool fresh_now = fresh; | |
| fresh = false; | |
| if (has_no_children(cur) || (fresh_now && all_children_leaves(cur))) | |
| { | |
| if (prev.m_data.m_type == value_t::null) | |
| { | |
| free_container(cur); | |
| return; // back at the top with nothing left to do | |
| } | |
| // ascend: detach the grandparent link from prev's | |
| // walk_child() slot, drop that (now null) slot, free cur | |
| // (it is empty), then move up one level | |
| basic_json gp; | |
| take(gp, walk_child(prev)); | |
| pop_walk_child(prev); | |
| free_container(cur); | |
| take(cur, prev); | |
| take(prev, gp); | |
| continue; | |
| } | |
| basic_json& cur_child_ref = walk_child(cur); | |
| if (has_no_children(cur_child_ref)) | |
| { | |
| // scalar, or already-empty array/object | |
| pop_walk_child(cur); | |
| continue; | |
| } | |
| // descend into the non-empty child, reversing the | |
| // link: its slot takes over prev, and the child becomes | |
| // the new cur | |
| basic_json tmp; | |
| take(tmp, cur_child_ref); | |
| take(cur_child_ref, prev); | |
| take(prev, cur); | |
| take(cur, tmp); | |
| fresh = true; | |
| } | |
| } | |
| // keep the check whether t owns memory inline so destroying a scalar | |
| // is a compare and a branch, and leave the actual work to an | |
| // out-of-line function | |
| void destroy(value_t t) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(detail::owns_memory(t))) | |
| { | |
| destroy_owned(t); | |
| } | |
| } | |
| JSON_HEDLEY_NEVER_INLINE void destroy_owned(value_t t) | |
| { | |
| switch (t) | |
| { | |
| case value_t::string: | |
| destroy_pointer(string); | |
| break; | |
| case value_t::binary: | |
| destroy_pointer(binary); | |
| break; | |
| case value_t::object: | |
| case value_t::array: | |
| destroy_container(t); | |
| break; | |
| case value_t::null: | |
| case value_t::boolean: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| case value_t::discarded: | |
| default: | |
| break; | |
| } | |
| } | |
| }; | |
| private: | |
| /*! | |
| @brief checks the class invariants | |
| This function asserts the class invariants. It needs to be called at the | |
| end of every constructor to make sure that created objects respect the | |
| invariant. Furthermore, it has to be called each time the type of a JSON | |
| value is changed, because the invariant expresses a relationship between | |
| @a m_data.m_type and @a m_data.m_value. | |
| Furthermore, the parent relation is checked for arrays and objects: If | |
| @a check_parents true and the value is an array or object, then the | |
| container's elements must have the current value as parent. | |
| @param[in] check_parents whether the parent relation should be checked. | |
| The value is true by default and should only be set to false | |
| during destruction of objects when the invariant does not | |
| need to hold. | |
| */ | |
| void assert_invariant(bool check_parents = true) const noexcept | |
| { | |
| JSON_ASSERT(m_data.m_type != value_t::object || m_data.m_value.object != nullptr); | |
| JSON_ASSERT(m_data.m_type != value_t::array || m_data.m_value.array != nullptr); | |
| JSON_ASSERT(m_data.m_type != value_t::string || m_data.m_value.string != nullptr); | |
| JSON_ASSERT(m_data.m_type != value_t::binary || m_data.m_value.binary != nullptr); | |
| #if JSON_DIAGNOSTICS | |
| JSON_TRY | |
| { | |
| JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j) | |
| { | |
| return j.m_parent == this; | |
| })); | |
| } | |
| JSON_CATCH(...) {} // LCOV_EXCL_LINE | |
| #endif | |
| static_cast<void>(check_parents); | |
| } | |
| void set_parents() | |
| { | |
| #if JSON_DIAGNOSTICS | |
| if (m_data.m_type == value_t::array) | |
| { | |
| for (auto& element : *m_data.m_value.array) | |
| { | |
| element.m_parent = this; | |
| } | |
| } | |
| else if (m_data.m_type == value_t::object) | |
| { | |
| for (auto& element : *m_data.m_value.object) | |
| { | |
| element.second.m_parent = this; | |
| } | |
| } | |
| #endif | |
| } | |
| /// @brief replace the stored value with an already created one | |
| /// The new value must be created before calling this function: if its | |
| /// creation throws, the current value is left untouched. | |
| void replace_value(value_t t, const json_value& v) noexcept | |
| { | |
| m_data.m_value.destroy(m_data.m_type); | |
| m_data.m_value = v; | |
| m_data.m_type = t; | |
| set_parents(); | |
| assert_invariant(); | |
| } | |
| iterator set_parents(iterator it, std::ptrdiff_t count_set_parents) | |
| { | |
| #if JSON_DIAGNOSTICS | |
| for (std::ptrdiff_t i = 0; i < count_set_parents; ++i) | |
| { | |
| (it + i)->m_parent = this; | |
| } | |
| #else | |
| static_cast<void>(count_set_parents); | |
| #endif | |
| return it; | |
| } | |
| /// @brief the key to look up an object member with: the key itself, or its | |
| /// std::string_view if the object can only be searched with that | |
| template < typename KeyType, detail::enable_if_t < | |
| !detail::is_string_view_convertible_key_type<basic_json_t, KeyType>::value, int > = 0 > | |
| static KeyType && lookup_key(KeyType && key) noexcept | |
| { | |
| return std::forward<KeyType>(key); | |
| } | |
| #ifdef JSON_HAS_CPP_17 | |
| template < typename KeyType, detail::enable_if_t < | |
| detail::is_string_view_convertible_key_type<basic_json_t, KeyType>::value, int > = 0 > | |
| static std::string_view lookup_key(KeyType && key) | |
| { | |
| return std::forward<KeyType>(key); | |
| } | |
| #endif | |
| /// @brief erase an element from the object and return the following one | |
| /// Not every map returns an iterator from erase(iterator): some containers | |
| /// (e.g., Abseil's hash maps) return void to avoid computing a successor | |
| /// the caller may not need. Compute it before erasing for those. | |
| template < typename It, detail::enable_if_t < | |
| !detail::erase_returns_void<object_t, It>::value, int > = 0 > | |
| typename object_t::iterator erase_from_object(It pos) | |
| { | |
| return m_data.m_value.object->erase(pos); | |
| } | |
| template < typename It, detail::enable_if_t < | |
| detail::erase_returns_void<object_t, It>::value, int > = 0 > | |
| typename object_t::iterator erase_from_object(It pos) | |
| { | |
| auto next = std::next(pos); | |
| m_data.m_value.object->erase(pos); | |
| return next; | |
| } | |
| /// @brief the capacity of the stored array or object, or unknown_size() | |
| /// Only JSON_DIAGNOSTICS uses the value, to detect an insertion that may | |
| /// have moved the other elements and so invalidated their parent pointers. | |
| /// unknown_size() means "the elements may have moved". Arrays only grow at | |
| /// the end, so their capacity tells whether they reallocated; arrays | |
| /// without a capacity() member report unknown_size(). For objects, only | |
| /// types known to keep their elements in place (std::map and the other | |
| /// node-based standard containers) report a fixed 0, and only | |
| /// nlohmann::ordered_map, which appends members, reports its capacity; any | |
| /// other object type (a sorted flat map, say) reports unknown_size(). | |
| #if JSON_DIAGNOSTICS | |
| template < typename A = array_t, detail::enable_if_t < detail::has_capacity<A>::value, int > = 0 > | |
| std::size_t array_capacity() const noexcept | |
| { | |
| return m_data.m_value.array->capacity(); | |
| } | |
| template < typename A = array_t, detail::enable_if_t < !detail::has_capacity<A>::value, int > = 0 > | |
| std::size_t array_capacity() const noexcept | |
| { | |
| return detail::unknown_size(); | |
| } | |
| template < typename O = object_t, detail::enable_if_t < detail::has_stable_elements<O>::value, int > = 0 > | |
| std::size_t object_capacity() const noexcept | |
| { | |
| return 0; | |
| } | |
| template < typename O = object_t, detail::enable_if_t < !detail::has_stable_elements<O>::value && detail::is_nlohmann_ordered_map<O>::value, int > = 0 > | |
| std::size_t object_capacity() const noexcept | |
| { | |
| return m_data.m_value.object->capacity(); | |
| } | |
| template < typename O = object_t, detail::enable_if_t < !detail::has_stable_elements<O>::value && !detail::is_nlohmann_ordered_map<O>::value, int > = 0 > | |
| std::size_t object_capacity() const noexcept | |
| { | |
| return detail::unknown_size(); | |
| } | |
| std::size_t container_capacity() const noexcept | |
| { | |
| return is_array() ? array_capacity() : object_capacity(); | |
| } | |
| #else | |
| static constexpr std::size_t container_capacity() noexcept | |
| { | |
| return detail::unknown_size(); | |
| } | |
| #endif | |
| /// @brief set the parent of a value that has just been added to an array or object | |
| /// @param j the added (or looked-up) value | |
| /// @param old_capacity the value @ref container_capacity() returned before the | |
| /// insertion | |
| reference set_parent_after_insert(reference j, std::size_t old_capacity) | |
| { | |
| #if JSON_DIAGNOSTICS | |
| // see https://github.com/nlohmann/json/issues/2838 | |
| if (JSON_HEDLEY_UNLIKELY(old_capacity == detail::unknown_size() | |
| || container_capacity() != old_capacity)) | |
| { | |
| // the capacity has changed, or the container type does not let us | |
| // tell: the elements may have moved, so update all parents | |
| set_parents(); | |
| return j; | |
| } | |
| #else | |
| static_cast<void>(old_capacity); | |
| #endif | |
| return set_parent_at(j); | |
| } | |
| /// @brief set the parent of an element accessed via at(); never moves elements | |
| reference set_parent_at(reference j) noexcept | |
| { | |
| #if JSON_DIAGNOSTICS | |
| j.m_parent = this; | |
| #endif | |
| return j; | |
| } | |
| #ifndef JSON_NO_THREAD_LOCAL | |
| // nesting_depth() is a byte and may exceed the limit by one level | |
| static_assert(detail::recursion_depth_limit() < 255, "the nesting depth count must fit in a byte"); | |
| /*! | |
| @brief how many levels the operation going on in this thread has descended into | |
| Copying a value, converting one from another specialization, and comparing | |
| two values share this count. The library never nests one of them inside | |
| another - none of them does either of the other two on the way - and where | |
| user code nests them anyway, sharing the count only ends a descent sooner | |
| than it had to, which costs a little speed and is never wrong. | |
| A byte is enough: the count never exceeds the limit by more than the single | |
| level that notices the limit has been reached. | |
| */ | |
| static std::uint8_t& nesting_depth() noexcept | |
| { | |
| static thread_local std::uint8_t depth = 0; // NOLINT(misc-use-internal-linkage) | |
| return depth; | |
| } | |
| #endif | |
| /*! | |
| @brief whether a descent must stop here and finish without the call stack | |
| @a may_descend says whether the operator descends at all; it is a constant | |
| at every call site, and is passed rather than tested by the caller so that | |
| the test does not become a constant condition there, which MSVC reports as | |
| C4127. | |
| The comparison operators use this rather than @ref nesting_depth_guard::okay, | |
| because they are written as a macro and a macro cannot use the preprocessor | |
| the way the guard's constructor does; @ref copy_structured, which can, asks | |
| the guard instead and never calls this. | |
| */ | |
| static bool nesting_depth_exhausted(bool may_descend = true) noexcept | |
| { | |
| #ifdef JSON_NO_THREAD_LOCAL | |
| // without a count of its own per thread, a descent cannot be bounded | |
| // without racing another one, so none is made | |
| static_cast<void>(may_descend); | |
| return true; | |
| #else | |
| return !may_descend || nesting_depth() >= detail::recursion_depth_limit(); | |
| #endif | |
| } | |
| /*! | |
| @brief counts one level of a bounded descent for as long as it runs, and | |
| reports whether the descent was still within the limit when it began | |
| Looks the count up and tests it against the limit itself, rather than | |
| leaving that to the caller: either way it is reached exactly once, so | |
| there is nothing to be gained by making the caller do it. | |
| Does nothing and is never @ref okay without thread-local storage, where no | |
| descent can be bounded at all: a caller that only descends while this says | |
| it may always ends up finishing without the call stack, exactly as if every | |
| value were nested past the limit. | |
| */ | |
| class nesting_depth_guard | |
| { | |
| public: | |
| nesting_depth_guard() noexcept | |
| #ifdef JSON_NO_THREAD_LOCAL | |
| : m_okay(false) | |
| #else | |
| : m_okay(nesting_depth() < detail::recursion_depth_limit()) | |
| #endif | |
| { | |
| #ifndef JSON_NO_THREAD_LOCAL | |
| ++nesting_depth(); | |
| #endif | |
| } | |
| ~nesting_depth_guard() | |
| { | |
| #ifndef JSON_NO_THREAD_LOCAL | |
| --nesting_depth(); | |
| #endif | |
| } | |
| nesting_depth_guard(const nesting_depth_guard&) = delete; | |
| nesting_depth_guard& operator=(const nesting_depth_guard&) = delete; | |
| nesting_depth_guard(nesting_depth_guard&&) = delete; | |
| nesting_depth_guard& operator=(nesting_depth_guard&&) = delete; | |
| bool okay() const noexcept | |
| { | |
| return m_okay; | |
| } | |
| private: | |
| bool m_okay; | |
| }; | |
| /// an entry of the iterative deep copy's worklist: a structured value and | |
| /// the value that is to become its copy | |
| using copy_worklist_t = std::vector<std::pair<const basic_json*, basic_json*>>; | |
| /// scratch space to build the key skeleton of an object copy in one go | |
| using copy_scratch_value_t = std::pair<typename object_t::key_type, basic_json>; | |
| using copy_scratch_t = std::vector<copy_scratch_value_t, AllocatorType<copy_scratch_value_t>>; | |
| /// @brief tag selecting the constructor below; used only to build the | |
| /// elements of a deep copy (@ref copy_array_level, @ref copy_object_level) | |
| struct copy_construct_tag {}; | |
| public: | |
| /*! | |
| @brief construct a null value whose base class - and, with @ref | |
| JSON_DIAGNOSTIC_POSITIONS, positions - are copied from @a src | |
| Copy-constructing @ref json_base_class_t here, rather than default- | |
| constructing the element and assigning its base class afterwards, means | |
| that copying a @ref basic_json only ever requires a copy-constructible | |
| base class, and never a move-assignable one as well. | |
| @note this constructor has to be public: @ref copy_array_level and | |
| @ref copy_object_level reach it through @ref array_t's or @ref | |
| object_t's own emplace_back(), which constructs the element from | |
| outside @ref basic_json and so cannot call a private constructor. | |
| @ref copy_construct_tag is private, though, and nothing in the | |
| public interface hands out a value of it, so outside code can still | |
| never name it to call this constructor itself. | |
| */ | |
| basic_json(copy_construct_tag /*unused*/, const basic_json& src) | |
| noexcept(std::is_nothrow_copy_constructible<json_base_class_t>::value) | |
| : json_base_class_t(src) | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| , start_position(src.start_position) | |
| , end_position(src.end_position) | |
| #endif | |
| { | |
| } | |
| private: | |
| /*! | |
| @brief copy the value of @a src into @a dst, which must not be structured | |
| Objects and arrays are left alone: creating those is the one thing the copy | |
| constructor and @ref copy_shallow do differently from one another, and it is | |
| the reason copying a value can descend at all. | |
| */ | |
| /// @note inlined on purpose: both callers have already told an object or an | |
| /// array apart from the rest, and letting the compiler fold that test | |
| /// into this switch is worth a few percent when copying a value made | |
| /// mostly of numbers | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| static void copy_leaf_value(const basic_json& src, basic_json& dst) | |
| { | |
| switch (src.m_data.m_type) | |
| { | |
| case value_t::string: | |
| { | |
| dst.m_data.m_value = *src.m_data.m_value.string; | |
| break; | |
| } | |
| case value_t::binary: | |
| { | |
| dst.m_data.m_value = *src.m_data.m_value.binary; | |
| break; | |
| } | |
| case value_t::boolean: | |
| { | |
| dst.m_data.m_value = src.m_data.m_value.boolean; | |
| break; | |
| } | |
| case value_t::number_integer: | |
| { | |
| dst.m_data.m_value = src.m_data.m_value.number_integer; | |
| break; | |
| } | |
| case value_t::number_unsigned: | |
| { | |
| dst.m_data.m_value = src.m_data.m_value.number_unsigned; | |
| break; | |
| } | |
| case value_t::number_float: | |
| { | |
| dst.m_data.m_value = src.m_data.m_value.number_float; | |
| break; | |
| } | |
| case value_t::object: | |
| case value_t::array: | |
| case value_t::null: | |
| case value_t::discarded: | |
| default: | |
| break; | |
| } | |
| } | |
| /*! | |
| @brief finish the copy @a dst of @a src that a @ref copy_construct_tag | |
| constructor started, other than the children of an object or array | |
| @a dst already has @a src's base class and, with @ref | |
| JSON_DIAGNOSTIC_POSITIONS, positions; only its value is still missing. | |
| Objects and arrays are not copied here; they are appended to @a worklist to | |
| be created later by @ref copy_iteratively. Until that happens, @a dst remains | |
| a null value, so that a partially built copy can be destroyed at any point | |
| without ever violating the class invariants. | |
| */ | |
| static void copy_shallow(const basic_json& src, basic_json& dst, copy_worklist_t& worklist) | |
| { | |
| if (src.m_data.m_type == value_t::object || src.m_data.m_type == value_t::array) | |
| { | |
| // defer: dst stays a null value until its container exists | |
| worklist.emplace_back(&src, &dst); | |
| return; | |
| } | |
| copy_leaf_value(src, dst); | |
| // only now that the value exists may the type be set: had the creation | |
| // of the value thrown, dst would have been left as a valid null value | |
| dst.m_data.m_type = src.m_data.m_type; | |
| } | |
| /// @brief create the copy of the array @a src in @a dst | |
| /// @note structured elements are appended to @a worklist instead | |
| static void copy_array_level(const basic_json& src, basic_json& dst, copy_worklist_t& worklist) | |
| { | |
| const array_t& src_array = *src.m_data.m_value.array; | |
| dst.m_data.m_value.array = create<array_t>(); | |
| // only now that the array exists may dst stop being a null value | |
| dst.m_data.m_type = value_t::array; | |
| // create every element - its base class already copy-constructed from | |
| // its counterpart in src, via the copy_construct_tag constructor - | |
| // before any of their addresses are handed to worklist below: growing | |
| // the array while that is going on could reallocate it and invalidate | |
| // addresses taken from an earlier iteration | |
| for (const auto& src_element : src_array) | |
| { | |
| dst.m_data.m_value.array->emplace_back(copy_construct_tag{}, src_element); | |
| } | |
| auto dst_it = dst.m_data.m_value.array->begin(); | |
| for (auto src_it = src_array.cbegin(); src_it != src_array.cend(); ++src_it, ++dst_it) | |
| { | |
| copy_shallow(*src_it, *dst_it, worklist); | |
| } | |
| } | |
| /// @brief create the object type from a range, preserving @a src_object's | |
| /// comparator when the object type supports it | |
| /// Enabled for object types that provide a key_comp() and a matching | |
| /// range-plus-comparator constructor, such as std::map. Other object | |
| /// types, such as nlohmann::ordered_map, fall back to the plain range | |
| /// constructor and default-construct their comparator, just as they | |
| /// always have (@ref detail::is_comparator_constructible_object_type). | |
| template<typename Iterator, detail::enable_if_t< | |
| detail::is_comparator_constructible_object_type<object_t, Iterator>::value, int> = 0> | |
| static object_t* create_object_with_comparator(const object_t& src_object, Iterator first, Iterator last) | |
| { | |
| return create<object_t>(first, last, src_object.key_comp()); | |
| } | |
| template<typename Iterator, detail::enable_if_t< | |
| detail::negation<detail::is_comparator_constructible_object_type<object_t, Iterator>>::value, int> = 0> | |
| static object_t* create_object_with_comparator(const object_t& /*src_object*/, Iterator first, Iterator last) | |
| { | |
| return create<object_t>(first, last); | |
| } | |
| /// @brief compare two object keys for equality, if the key type supports it | |
| /// @note object_t only needs operator< for its keys (std::map), so operator== | |
| /// may not exist; the keys are then reported as different, which makes | |
| /// copy_object_level pair the values via object_t::find() | |
| template<typename K = typename object_t::key_type, | |
| detail::enable_if_t<detail::is_detected<detail::detect_equal_comparable, K>::value, int> = 0> | |
| static bool copy_keys_equal(const K& a, const K& b) | |
| { | |
| return a == b; | |
| } | |
| template < typename K = typename object_t::key_type, | |
| detail::enable_if_t < !detail::is_detected<detail::detect_equal_comparable, K>::value, int > = 0 > | |
| static bool copy_keys_equal(const K& /*a*/, const K& /*b*/) | |
| { | |
| return false; | |
| } | |
| /// @brief create the copy of the object @a src in @a dst | |
| /// @note structured values are appended to @a worklist instead | |
| static void copy_object_level(const basic_json& src, basic_json& dst, | |
| copy_worklist_t& worklist, copy_scratch_t& scratch) | |
| { | |
| const object_t& src_object = *src.m_data.m_value.object; | |
| // build the complete key skeleton and hand it to the object's range | |
| // constructor: adding the keys one by one would be quadratic for object | |
| // types that are backed by a vector, such as nlohmann::ordered_map; each | |
| // value's base class is already copy-constructed from its counterpart | |
| // in src, via the copy_construct_tag constructor | |
| scratch.clear(); | |
| scratch.reserve(src_object.size()); | |
| for (const auto& element : src_object) | |
| { | |
| scratch.emplace_back(element.first, basic_json(copy_construct_tag{}, element.second)); | |
| } | |
| dst.m_data.m_value.object = create_object_with_comparator(src_object, | |
| std::make_move_iterator(scratch.begin()), | |
| std::make_move_iterator(scratch.end())); | |
| // only now that the object exists may dst stop being a null value | |
| dst.m_data.m_type = value_t::object; | |
| scratch.clear(); | |
| // pair every value of the copy with its counterpart in the original; | |
| // both are enumerated in the same order for every object type with a | |
| // deterministic order, so the lookup is only needed for exotic ones | |
| auto src_it = src_object.cbegin(); | |
| for (auto& element : *dst.m_data.m_value.object) | |
| { | |
| if (JSON_HEDLEY_LIKELY(src_it != src_object.cend() && copy_keys_equal(src_it->first, element.first))) | |
| { | |
| copy_shallow(src_it->second, element.second, worklist); | |
| ++src_it; | |
| } | |
| else | |
| { | |
| const auto found = src_object.find(element.first); | |
| JSON_ASSERT(found != src_object.cend()); | |
| copy_shallow(found->second, element.second, worklist); | |
| } | |
| } | |
| } | |
| /*! | |
| @brief deep-copy the object or array @a src into this value without recursing | |
| The values whose copy has not been created yet are kept on an explicit | |
| worklist rather than on the call stack. This is only reached for values | |
| nested deeper than @ref detail::recursion_depth_limit levels, which is why it copies | |
| every container by hand instead of letting the container do it: the fast | |
| ways of doing so would descend into the elements and defeat the purpose. | |
| */ | |
| void copy_iteratively(const basic_json& src) | |
| { | |
| copy_worklist_t worklist; | |
| copy_scratch_t scratch; | |
| const basic_json* src_value = &src; | |
| basic_json* dst_value = this; | |
| for (;;) | |
| { | |
| if (src_value->m_data.m_type == value_t::array) | |
| { | |
| copy_array_level(*src_value, *dst_value, worklist); | |
| } | |
| else | |
| { | |
| copy_object_level(*src_value, *dst_value, worklist, scratch); | |
| } | |
| // the container is complete and will not be modified again | |
| dst_value->set_parents(); | |
| if (worklist.empty()) | |
| { | |
| break; | |
| } | |
| const auto& next = worklist.back(); | |
| src_value = next.first; | |
| dst_value = next.second; | |
| worklist.pop_back(); | |
| } | |
| } | |
| /*! | |
| @brief copy one level of the object or array @a src into this value | |
| The container copies its own elements, which is the fastest way to fill it. | |
| Every element that is structured itself comes back to @ref copy_structured. | |
| */ | |
| void copy_level(const basic_json& src) | |
| { | |
| if (m_data.m_type == value_t::object) | |
| { | |
| m_data.m_value = *src.m_data.m_value.object; | |
| } | |
| else | |
| { | |
| m_data.m_value = *src.m_data.m_value.array; | |
| } | |
| set_parents(); | |
| } | |
| /*! | |
| @brief deep-copy the object or array @a src into this value | |
| Copying a container copies its elements, so a value nested deeply enough | |
| used to exhaust the call stack. The descent is bounded here: the first | |
| @ref detail::recursion_depth_limit levels are copied by the containers themselves, just | |
| as they always were, and anything below that is copied without the call | |
| stack by @ref copy_iteratively. Copying a value can therefore no longer | |
| exhaust the stack, however deeply it is nested, just like destroying one | |
| cannot since #1436. | |
| Nothing has to be scanned or built by hand to reach that: a value that is | |
| not nested deeper than the limit - all but a vanishing minority - is copied | |
| exactly as it was before, and this whole detour costs it one counter. | |
| @sa https://github.com/nlohmann/json/issues/5387 | |
| */ | |
| void copy_structured(const basic_json& src) | |
| { | |
| const nesting_depth_guard guard; | |
| if (JSON_HEDLEY_LIKELY(guard.okay())) | |
| { | |
| copy_level(src); | |
| return; | |
| } | |
| // Finish this value without descending any further. It is completed | |
| // before this returns, so a copy made by a custom base class - or by | |
| // anything else that runs while a copy is going on - is unaffected by | |
| // the copy it is nested in. | |
| copy_iteratively(src); | |
| } | |
| /*! | |
| @brief convert the value @a val of another specialization into this null | |
| value; @a val must be neither an object nor an array | |
| Converting such a value never descends, so both ways of converting an | |
| object or an array (@ref convert_structured) leave their elements of this | |
| kind to the converting constructor, which leaves them to this. | |
| */ | |
| template<typename BasicJsonType> | |
| void convert_leaf(const BasicJsonType& val) | |
| { | |
| using other_boolean_t = typename BasicJsonType::boolean_t; | |
| using other_number_float_t = typename BasicJsonType::number_float_t; | |
| using other_number_integer_t = typename BasicJsonType::number_integer_t; | |
| using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; | |
| using other_string_t = typename BasicJsonType::string_t; | |
| using other_binary_t = typename BasicJsonType::binary_t; | |
| switch (val.type()) | |
| { | |
| case value_t::boolean: | |
| JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>()); | |
| break; | |
| case value_t::number_float: | |
| JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>()); | |
| break; | |
| case value_t::number_integer: | |
| JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>()); | |
| break; | |
| case value_t::number_unsigned: | |
| JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>()); | |
| break; | |
| case value_t::string: | |
| JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>()); | |
| break; | |
| case value_t::binary: | |
| JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>()); | |
| break; | |
| case value_t::null: | |
| // m_data.m_type is already value_t::null | |
| break; | |
| case value_t::discarded: | |
| m_data.m_type = value_t::discarded; | |
| break; | |
| case value_t::object: // LCOV_EXCL_LINE | |
| case value_t::array: // LCOV_EXCL_LINE | |
| default: // LCOV_EXCL_LINE | |
| JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE | |
| } | |
| } | |
| /// scratch space for the converted elements of the arrays that | |
| /// @ref convert_iteratively has yet to create | |
| using convert_scratch_t = std::vector<basic_json, AllocatorType<basic_json>>; | |
| /*! | |
| @brief create the object or array @a val converted into this null value | |
| Its converted elements are the last `val.size()` entries of @a elements (an | |
| array) or of @a members (an object); they are moved into the container in | |
| one go and then removed. | |
| */ | |
| template<typename BasicJsonType> | |
| void convert_level(const BasicJsonType& val, convert_scratch_t& elements, copy_scratch_t& members) | |
| { | |
| if (val.is_object()) | |
| { | |
| const auto first = members.end() - static_cast<typename copy_scratch_t::difference_type>(val.size()); | |
| m_data.m_value.object = create<object_t>(std::make_move_iterator(first), | |
| std::make_move_iterator(members.end())); | |
| // only now that the object exists may this stop being a null value | |
| m_data.m_type = value_t::object; | |
| members.erase(first, members.end()); | |
| } | |
| else | |
| { | |
| const auto first = elements.end() - static_cast<typename convert_scratch_t::difference_type>(val.size()); | |
| m_data.m_value.array = create<array_t>(std::make_move_iterator(first), | |
| std::make_move_iterator(elements.end())); | |
| // only now that the array exists may this stop being a null value | |
| m_data.m_type = value_t::array; | |
| elements.erase(first, elements.end()); | |
| } | |
| set_parents(); | |
| } | |
| /*! | |
| @brief convert the object or array @a val of another specialization into | |
| this null value without recursing | |
| The containers whose conversion has begun are kept on an explicit stack | |
| rather than on the call stack. Unlike @ref copy_iteratively, this builds | |
| every container from the bottom up: all its elements are converted first, | |
| and the container is then created from them in one go, the way the range | |
| constructor that converts the levels above the bound does. The two object | |
| types need not enumerate their members in the same order, so the members | |
| could not be paired up by position anyway, and building from a range keeps | |
| what the range constructor does with keys that become equal on conversion. | |
| Every value is complete before it is handed on, and a container gets its | |
| type only once it exists, so whatever throws, every value left behind can | |
| be destroyed. | |
| */ | |
| template<typename BasicJsonType> | |
| void convert_iteratively(const BasicJsonType& val, std::true_type /*unused*/) | |
| { | |
| using other_const_iterator = typename BasicJsonType::const_iterator; | |
| // the containers whose conversion has begun, innermost last, each with | |
| // its element to convert next | |
| std::vector<std::pair<const BasicJsonType*, other_const_iterator>> pending; | |
| // the converted elements of the pending arrays and the converted | |
| // members of the pending objects, those of the innermost one last | |
| convert_scratch_t elements; | |
| copy_scratch_t members; | |
| pending.emplace_back(&val, val.cbegin()); | |
| for (;;) | |
| { | |
| const BasicJsonType& container = *pending.back().first; | |
| // a copy, as descending below can reallocate pending; the | |
| // iterator kept in pending is only advanced through pending.back() | |
| const other_const_iterator next = pending.back().second; | |
| if (next != container.cend()) | |
| { | |
| if (next->is_structured()) | |
| { | |
| // convert its elements first; next stays where it is until | |
| // the converted container is handed back to this one | |
| pending.emplace_back(&*next, next->cbegin()); | |
| continue; | |
| } | |
| // the converting constructor does not descend into this value | |
| if (container.is_object()) | |
| { | |
| members.emplace_back(next.key(), *next); | |
| } | |
| else | |
| { | |
| elements.emplace_back(*next); | |
| } | |
| ++pending.back().second; | |
| continue; | |
| } | |
| // all elements of the container are converted: create it | |
| pending.pop_back(); | |
| if (pending.empty()) | |
| { | |
| convert_level(container, elements, members); | |
| return; | |
| } | |
| basic_json converted; | |
| converted.convert_level(container, elements, members); | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| converted.start_position = container.start_pos(); | |
| converted.end_position = container.end_pos(); | |
| #endif | |
| // hand it to the container it is an element of | |
| if (pending.back().first->is_object()) | |
| { | |
| members.emplace_back(pending.back().second.key(), std::move(converted)); | |
| } | |
| else | |
| { | |
| elements.push_back(std::move(converted)); | |
| } | |
| ++pending.back().second; | |
| } | |
| } | |
| /*! | |
| @brief convert the object or array @a val of another specialization into | |
| this null value | |
| Converting a container converts its elements, so a value nested deeply | |
| enough used to exhaust the call stack. The descent is bounded here as in | |
| @ref copy_structured: the first `detail::recursion_depth_limit()` levels | |
| are converted by the containers' range constructors, just as they always were, | |
| and anything below that is converted without the call stack by | |
| @ref convert_iteratively. | |
| @sa https://github.com/nlohmann/json/issues/5650 | |
| */ | |
| template<typename BasicJsonType> | |
| void convert_structured(const BasicJsonType& val) | |
| { | |
| const nesting_depth_guard guard; | |
| if (JSON_HEDLEY_LIKELY(guard.okay())) | |
| { | |
| convert_by_serializers(val); | |
| return; | |
| } | |
| // the iterative conversion needs to construct this object type's keys | |
| // from those of @a val; if it cannot, neither can the range constructor, | |
| // and the serializers convert @a val some other way (see #3425) | |
| convert_iteratively(val, std::is_constructible<typename object_t::key_type, const typename BasicJsonType::string_t&> {}); | |
| } | |
| /// @brief convert the object or array @a val with the serializers; every | |
| /// element comes back to the converting constructor | |
| template<typename BasicJsonType> | |
| void convert_by_serializers(const BasicJsonType& val) | |
| { | |
| if (val.is_object()) | |
| { | |
| using other_object_t = typename BasicJsonType::object_t; | |
| JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>()); | |
| } | |
| else | |
| { | |
| using other_array_t = typename BasicJsonType::array_t; | |
| JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>()); | |
| } | |
| } | |
| /// @brief convert @a val whose keys cannot be converted, see @ref convert_structured | |
| template<typename BasicJsonType> | |
| void convert_iteratively(const BasicJsonType& val, std::false_type /*unused*/) | |
| { | |
| convert_by_serializers(val); | |
| } | |
| /// the result of comparing two values, including values that cannot be | |
| /// ordered at all, such as a discarded value or a NaN | |
| enum class compare_result { less, equal, greater, unordered }; | |
| #if JSON_HAS_THREE_WAY_COMPARISON | |
| /// @brief the ordering that @a result stands for | |
| static std::partial_ordering to_partial_ordering(compare_result result) noexcept // *NOPAD* | |
| { | |
| switch (result) | |
| { | |
| case compare_result::less: | |
| return std::partial_ordering::less; | |
| case compare_result::greater: | |
| return std::partial_ordering::greater; | |
| case compare_result::equal: | |
| return std::partial_ordering::equivalent; | |
| case compare_result::unordered: | |
| default: | |
| return std::partial_ordering::unordered; | |
| } | |
| } | |
| #endif | |
| /*! | |
| @brief compare two values that are not both an array or both an object | |
| Such a pair is compared by the operators themselves, which cannot descend | |
| into it and therefore cannot recurse. | |
| That holds for a pair whose types differ as much as for a pair of leaves: an | |
| array and an object are told apart by their types alone, because an operator | |
| only ever descends into two values of the same type. So `==` reports them as | |
| unequal without looking inside either, and an ordering falls back to the | |
| order of the types - an object sorts before an array - exactly as it does | |
| for a value that is not nested deeply enough to get here. | |
| */ | |
| template<bool Ordered> | |
| static compare_result compare_leaves(const_reference lhs, const_reference rhs) noexcept | |
| { | |
| return compare_leaves(lhs, rhs, std::integral_constant<bool, Ordered> {}); | |
| } | |
| /// @brief compare two leaves that are only being checked for equality | |
| static compare_result compare_leaves(const_reference lhs, const_reference rhs, std::false_type /*ordered*/) noexcept | |
| { | |
| if (lhs == rhs) | |
| { | |
| return compare_result::equal; | |
| } | |
| return order_leaves(lhs, rhs, std::false_type {}); | |
| } | |
| #if JSON_HAS_THREE_WAY_COMPARISON | |
| /*! | |
| @brief compare two leaves that are being ordered, for operator<=> | |
| Reached only from operator<=>, so the leaves must be classified exactly | |
| as operator<=> classifies them - which is not the same as asking | |
| == and then order_leaves(), the way the other overload does it. The two | |
| disagree on a binary value: == also compares the subtype, but <=> compares | |
| only the bytes, through std::vector<std::uint8_t>::operator<=>. Using <=> | |
| itself here keeps a leaf pair classified the same way regardless of how | |
| deep it is nested - == first would again call operator<=> a level down | |
| through order_leaves(), but call it after a mismatching == already ended | |
| the comparison for a pair that <=> alone would still call equivalent. | |
| */ | |
| static compare_result compare_leaves(const_reference lhs, const_reference rhs, std::true_type /*ordered*/) noexcept | |
| { | |
| const std::partial_ordering order = lhs <=> rhs; // *NOPAD* | |
| if (std::is_eq(order)) | |
| { | |
| return compare_result::equal; | |
| } | |
| if (std::is_lt(order)) | |
| { | |
| return compare_result::less; | |
| } | |
| if (std::is_gt(order)) | |
| { | |
| return compare_result::greater; | |
| } | |
| return compare_result::unordered; | |
| } | |
| #else | |
| /// @brief compare two leaves that are being ordered, for operator< | |
| static compare_result compare_leaves(const_reference lhs, const_reference rhs, std::true_type /*ordered*/) noexcept | |
| { | |
| if (lhs == rhs) | |
| { | |
| return compare_result::equal; | |
| } | |
| return order_leaves(lhs, rhs, std::true_type {}); | |
| } | |
| #endif | |
| /*! | |
| @brief compare two object keys | |
| An object compares its entries as pairs of a key and a value, so its keys | |
| are compared exactly as std::pair compares them: with < where the objects | |
| are being ordered, and with == where they are only checked for equality. | |
| Note that this is not the object's own comparator, which for a vector-backed | |
| object type such as nlohmann::ordered_map tells equality rather than order. | |
| */ | |
| static compare_result compare_keys(const typename object_t::key_type& lhs, | |
| const typename object_t::key_type& rhs, | |
| std::true_type /*ordered*/) | |
| { | |
| if (lhs < rhs) | |
| { | |
| return compare_result::less; | |
| } | |
| if (rhs < lhs) | |
| { | |
| return compare_result::greater; | |
| } | |
| return compare_result::equal; | |
| } | |
| /// @brief check two object keys for equality | |
| static compare_result compare_keys(const typename object_t::key_type& lhs, | |
| const typename object_t::key_type& rhs, | |
| std::false_type /*ordered*/) | |
| { | |
| return lhs == rhs ? compare_result::equal : compare_result::unordered; | |
| } | |
| /// @brief tell apart two values that are not equal | |
| /// @note only instantiated where the values are being ordered, as a key or | |
| /// string type is not required to be ordered to be compared for equality | |
| static compare_result order_leaves(const_reference lhs, const_reference rhs, std::true_type /*ordered*/) noexcept | |
| { | |
| if (lhs < rhs) | |
| { | |
| return compare_result::less; | |
| } | |
| if (rhs < lhs) | |
| { | |
| return compare_result::greater; | |
| } | |
| return compare_result::unordered; | |
| } | |
| /// @brief report two values as not equal without ordering them | |
| static compare_result order_leaves(const_reference /*lhs*/, const_reference /*rhs*/, std::false_type /*ordered*/) noexcept | |
| { | |
| return compare_result::unordered; | |
| } | |
| /*! | |
| @brief compare @a lhs and @a rhs without descending into them | |
| Reached once a comparison has descended @ref detail::recursion_depth_limit levels, so | |
| that comparing values cannot exhaust the call stack however deeply they are | |
| nested. The two values are walked in lockstep on an explicit stack and | |
| compared lexicographically, element by element in the order the containers | |
| enumerate them - which is how the container types this library ships compare | |
| themselves: a std::map enumerates its entries in key order, and | |
| nlohmann::ordered_map in insertion order. An object type that enumerates its | |
| entries in an unspecified order, such as std::unordered_map, compares them | |
| pairwise instead; the difference could only ever show below the bound. | |
| Note that the stack this walks with is allocated, while the comparison | |
| operators are noexcept and the container comparison this replaces allocated | |
| nothing. Failing that allocation therefore ends the process rather than | |
| throwing. It only arises for values nested past the bound, and only when | |
| memory has run out - where the same comparison used to exhaust the call | |
| stack instead - but it is a way to fail that the operators did not have. | |
| */ | |
| template<bool Ordered> | |
| static compare_result compare_iteratively(const_reference lhs, const_reference rhs, | |
| const bool unordered_compares_equal) noexcept | |
| { | |
| /// a pair of containers being compared in lockstep | |
| struct frame | |
| { | |
| const basic_json* lhs_value{nullptr}; | |
| const basic_json* rhs_value{nullptr}; | |
| typename array_t::const_iterator lhs_array_it{}; | |
| typename array_t::const_iterator rhs_array_it{}; | |
| typename object_t::const_iterator lhs_object_it{}; | |
| typename object_t::const_iterator rhs_object_it{}; | |
| }; | |
| std::vector<frame> stack; | |
| const basic_json* left = &lhs; | |
| const basic_json* right = &rhs; | |
| for (;;) | |
| { | |
| const auto type = left->m_data.m_type; | |
| if (type == right->m_data.m_type && (type == value_t::array || type == value_t::object)) | |
| { | |
| // descend: the elements decide, and are compared further down | |
| stack.emplace_back(); | |
| frame& pushed = stack.back(); | |
| pushed.lhs_value = left; | |
| pushed.rhs_value = right; | |
| if (type == value_t::array) | |
| { | |
| pushed.lhs_array_it = left->m_data.m_value.array->cbegin(); | |
| pushed.rhs_array_it = right->m_data.m_value.array->cbegin(); | |
| } | |
| else | |
| { | |
| pushed.lhs_object_it = left->m_data.m_value.object->cbegin(); | |
| pushed.rhs_object_it = right->m_data.m_value.object->cbegin(); | |
| } | |
| } | |
| else | |
| { | |
| const compare_result result = compare_leaves<Ordered>(*left, *right); | |
| // Values that cannot be ordered - a NaN, say - end an ordered | |
| // comparison for std::lexicographical_compare_three_way, but | |
| // std::lexicographical_compare treats them as equivalent and | |
| // carries on with the next element. Both are reproduced here, | |
| // so that a value nested too deeply to descend into compares | |
| // exactly as one that is not. | |
| if (result != compare_result::equal && | |
| !(unordered_compares_equal && result == compare_result::unordered)) | |
| { | |
| return result; | |
| } | |
| } | |
| // walk back up past the containers that are exhausted, then take the | |
| // next pair of elements from the innermost one that is not | |
| for (;;) | |
| { | |
| if (stack.empty()) | |
| { | |
| return compare_result::equal; | |
| } | |
| frame& current = stack.back(); | |
| const bool is_object = current.lhs_value->m_data.m_type == value_t::object; | |
| const bool lhs_done = is_object | |
| ? current.lhs_object_it == current.lhs_value->m_data.m_value.object->cend() | |
| : current.lhs_array_it == current.lhs_value->m_data.m_value.array->cend(); | |
| const bool rhs_done = is_object | |
| ? current.rhs_object_it == current.rhs_value->m_data.m_value.object->cend() | |
| : current.rhs_array_it == current.rhs_value->m_data.m_value.array->cend(); | |
| if (lhs_done || rhs_done) | |
| { | |
| // whichever ran out first holds the smaller container; if | |
| // both did, they are equal and the container above decides | |
| if (lhs_done != rhs_done) | |
| { | |
| return lhs_done ? compare_result::less : compare_result::greater; | |
| } | |
| stack.pop_back(); | |
| continue; | |
| } | |
| if (is_object) | |
| { | |
| // an entry is a key and a value, and the key decides first | |
| const compare_result key_result = | |
| compare_keys(current.lhs_object_it->first, current.rhs_object_it->first, | |
| std::integral_constant<bool, Ordered> {}); | |
| left = &(current.lhs_object_it->second); | |
| right = &(current.rhs_object_it->second); | |
| if (key_result != compare_result::equal) | |
| { | |
| // An object type without a fixed order of its entries - | |
| // std::unordered_map, say - may enumerate two equal | |
| // objects differently, and its operator== does not care. | |
| // Equality then finds the entry by its key; an ordering, | |
| // or an object type that compares its entries in | |
| // sequence (ordered_map), is decided by the key itself. | |
| const auto* rhs_object = current.rhs_value->m_data.m_value.object; | |
| const auto found = (!Ordered && !detail::is_ordered_map<object_t>::value) | |
| ? rhs_object->find(current.lhs_object_it->first) | |
| : rhs_object->cend(); | |
| // the object's comparator may find an entry whose | |
| // key is only equivalent, not equal, to this one | |
| if (found == rhs_object->cend() || !(found->first == current.lhs_object_it->first)) | |
| { | |
| return key_result; | |
| } | |
| right = &(found->second); | |
| } | |
| ++current.lhs_object_it; | |
| ++current.rhs_object_it; | |
| } | |
| else | |
| { | |
| left = &(*current.lhs_array_it); | |
| right = &(*current.rhs_array_it); | |
| ++current.lhs_array_it; | |
| ++current.rhs_array_it; | |
| } | |
| break; | |
| } | |
| } | |
| } | |
| /// @brief restore the parent pointers after erasing from an object | |
| /// Unless the object type is known to keep its elements in place (see | |
| /// detail::has_stable_elements), erasing a member may move the members | |
| /// after it; ordered_json, for instance, keeps its members in a vector | |
| /// and re-constructs every member after the erased one in place, which | |
| /// resets their parent pointers | |
| void set_parents_after_object_erase() | |
| { | |
| #if JSON_DIAGNOSTICS | |
| #ifdef JSON_HEDLEY_MSVC_VERSION | |
| #pragma warning(push ) | |
| #pragma warning(disable : 4127) // ignore warning to replace if with if constexpr | |
| #endif | |
| if (!detail::has_stable_elements<object_t>::value) | |
| { | |
| set_parents(); | |
| } | |
| #ifdef JSON_HEDLEY_MSVC_VERSION | |
| #pragma warning( pop ) | |
| #endif | |
| #endif | |
| } | |
| public: | |
| ////////////////////////// | |
| // JSON parser callback // | |
| ////////////////////////// | |
| /// @brief parser event types | |
| /// @sa https://json.nlohmann.me/api/basic_json/parse_event_t/ | |
| using parse_event_t = detail::parse_event_t; | |
| /// @brief per-element parser callback type | |
| /// @sa https://json.nlohmann.me/api/basic_json/parser_callback_t/ | |
| using parser_callback_t = detail::parser_callback_t<basic_json>; | |
| ////////////////// | |
| // constructors // | |
| ////////////////// | |
| /// @name constructors and destructors | |
| /// Constructors of class @ref basic_json, copy/move constructor, copy | |
| /// assignment, static functions creating objects, and the destructor. | |
| /// @{ | |
| /// @brief create an empty value with a given type | |
| /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ | |
| basic_json(const value_t v) | |
| : m_data(stored_kind(v)) | |
| { | |
| assert_invariant(); | |
| } | |
| /// @brief create a null object | |
| /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ | |
| basic_json(std::nullptr_t = nullptr) noexcept | |
| { | |
| assert_invariant(); | |
| } | |
| /// @brief create a JSON value from compatible types | |
| /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ | |
| template < typename CompatibleType, | |
| typename U = detail::uncvref_t<CompatibleType>, | |
| detail::enable_if_t < | |
| !detail::is_basic_json<U>::value && detail::is_compatible_type<basic_json_t, U>::value | |
| #if JSON_DISABLE_TUPLE_REFERENCE_CONVERSION | |
| // see https://github.com/nlohmann/json/issues/2226 | |
| && !detail::is_basic_json_reference_tuple<basic_json_t, U>::value | |
| #endif | |
| , int > = 0 > | |
| basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape) | |
| JSONSerializer<U>::to_json(std::declval<basic_json_t&>(), | |
| std::forward<CompatibleType>(val)))) | |
| { | |
| JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val)); | |
| set_parents(); | |
| assert_invariant(); | |
| } | |
| private: | |
| /// whether a basic_json specialization can be converted implicitly into this one; | |
| /// with JSON_USE_IMPLICIT_CONVERSIONS set to 0, this is only the case if both share | |
| /// the same string type (see https://github.com/nlohmann/json/issues/2649) | |
| template<typename BasicJsonType> | |
| using is_implicitly_convertible_basic_json = std::integral_constant < bool, | |
| (JSON_USE_IMPLICIT_CONVERSIONS != 0) | |
| || std::is_same<typename BasicJsonType::string_t, string_t>::value >; | |
| /// tag to select the constructor that performs the conversion from another basic_json specialization | |
| struct convert_basic_json_tag {}; | |
| public: | |
| /// @brief create a JSON value from an existing one | |
| /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ | |
| template < typename BasicJsonType, | |
| detail::enable_if_t < | |
| detail::is_basic_json<BasicJsonType>::value&& !std::is_same<basic_json, BasicJsonType>::value | |
| && is_implicitly_convertible_basic_json<BasicJsonType>::value, int > = 0 > | |
| basic_json(const BasicJsonType& val) | |
| : basic_json(val, convert_basic_json_tag{}) | |
| {} | |
| /// @brief create a JSON value from an existing one | |
| /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ | |
| template < typename BasicJsonType, | |
| detail::enable_if_t < | |
| detail::is_basic_json<BasicJsonType>::value&& !std::is_same<basic_json, BasicJsonType>::value | |
| && !is_implicitly_convertible_basic_json<BasicJsonType>::value, int > = 0 > | |
| explicit basic_json(const BasicJsonType& val) | |
| : basic_json(val, convert_basic_json_tag{}) | |
| {} | |
| private: | |
| template<typename BasicJsonType> | |
| basic_json(const BasicJsonType& val, convert_basic_json_tag /*unused*/) | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| : start_position(val.start_pos()), | |
| end_position(val.end_pos()) | |
| #endif | |
| { | |
| if (val.is_structured()) | |
| { | |
| convert_structured(val); | |
| } | |
| else | |
| { | |
| convert_leaf(val); | |
| } | |
| JSON_ASSERT(m_data.m_type == stored_kind(val.type())); | |
| set_parents(); | |
| assert_invariant(); | |
| } | |
| public: | |
| /// @brief create a container (array or object) from an initializer list | |
| /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ | |
| basic_json(initializer_list_t init, | |
| bool type_deduction = true, | |
| value_t manual_type = value_t::array) | |
| { | |
| #if JSON_BRACE_INIT_COPY_SEMANTICS | |
| // a single element that is a value rather than a braced list is | |
| // copied or moved as is, whatever its content looks like | |
| if (type_deduction && init.size() == 1 && !init.begin()->is_braced_list()) | |
| { | |
| *this = init.begin()->moved_or_copied(); | |
| set_parents(); | |
| assert_invariant(); | |
| return; | |
| } | |
| #endif | |
| // check if each element is an array with two elements whose first | |
| // element is a string | |
| bool is_an_object = std::all_of(init.begin(), init.end(), | |
| [](const detail::json_ref<basic_json>& element_ref) | |
| { | |
| // The cast is to ensure op[size_type] is called, bearing in mind size_type may not be int; | |
| // (many string types can be constructed from 0 via its null-pointer guise, so we get a | |
| // broken call to op[key_type], the wrong semantics, and a 4804 warning on Windows) | |
| return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[static_cast<size_type>(0)].is_string(); | |
| }); | |
| // adjust type if type deduction is not wanted | |
| if (!type_deduction) | |
| { | |
| // if an array is wanted, do not create an object though possible | |
| if (manual_type == value_t::array) | |
| { | |
| is_an_object = false; | |
| } | |
| // if an object is wanted but impossible, throw an exception | |
| if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object)) | |
| { | |
| detail::throw_literal<type_error>(detail::exception_id::object_from_non_pairs, "cannot create object from initializer list", nullptr); | |
| } | |
| } | |
| if (is_an_object) | |
| { | |
| // the initializer list is a list of pairs -> create an object | |
| m_data.m_value = value_t::object; | |
| m_data.m_type = value_t::object; | |
| for (auto& element_ref : init) | |
| { | |
| auto element = element_ref.moved_or_copied(); | |
| m_data.m_value.object->emplace( | |
| std::move(*((*element.m_data.m_value.array)[0].m_data.m_value.string)), | |
| std::move((*element.m_data.m_value.array)[1])); | |
| } | |
| } | |
| else | |
| { | |
| #if JSON_BRACE_INIT_COPY_SEMANTICS | |
| if (type_deduction && init.size() == 1) | |
| { | |
| *this = init.begin()->moved_or_copied(); | |
| set_parents(); | |
| assert_invariant(); | |
| return; | |
| } | |
| #endif | |
| // the initializer list describes an array -> create an array | |
| m_data.m_value.array = create<array_t>(init.begin(), init.end()); | |
| m_data.m_type = value_t::array; | |
| } | |
| set_parents(); | |
| assert_invariant(); | |
| } | |
| /// @brief explicitly create a binary array (without subtype) | |
| /// @sa https://json.nlohmann.me/api/basic_json/binary/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json binary(const typename binary_t::container_type& init) | |
| { | |
| auto res = basic_json(); | |
| res.m_data.m_value = init; | |
| res.m_data.m_type = value_t::binary; | |
| return res; | |
| } | |
| /// @brief explicitly create a binary array (with subtype) | |
| /// @sa https://json.nlohmann.me/api/basic_json/binary/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype) | |
| { | |
| auto res = basic_json(); | |
| res.m_data.m_value = binary_t(init, subtype); | |
| res.m_data.m_type = value_t::binary; | |
| return res; | |
| } | |
| /// @brief explicitly create a binary array | |
| /// @sa https://json.nlohmann.me/api/basic_json/binary/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json binary(typename binary_t::container_type&& init) | |
| { | |
| auto res = basic_json(); | |
| res.m_data.m_value = std::move(init); | |
| res.m_data.m_type = value_t::binary; | |
| return res; | |
| } | |
| /// @brief explicitly create a binary array (with subtype) | |
| /// @sa https://json.nlohmann.me/api/basic_json/binary/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype) | |
| { | |
| auto res = basic_json(); | |
| res.m_data.m_value = binary_t(std::move(init), subtype); | |
| res.m_data.m_type = value_t::binary; | |
| return res; | |
| } | |
| /// @brief explicitly create an array from an initializer list | |
| /// @sa https://json.nlohmann.me/api/basic_json/array/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json array(initializer_list_t init = {}) | |
| { | |
| return basic_json(init, false, value_t::array); | |
| } | |
| /// @brief explicitly create an object from an initializer list | |
| /// @sa https://json.nlohmann.me/api/basic_json/object/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json object(initializer_list_t init = {}) | |
| { | |
| return basic_json(init, false, value_t::object); | |
| } | |
| /// @brief construct an array with count copies of given value | |
| /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ | |
| basic_json(size_type cnt, const basic_json& val): | |
| m_data{cnt, val} | |
| { | |
| set_parents(); | |
| assert_invariant(); | |
| } | |
| /// @brief construct a JSON container given an iterator range | |
| /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ | |
| template < class InputIT, typename std::enable_if < | |
| std::is_same<InputIT, typename basic_json_t::iterator>::value || | |
| std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int >::type = 0 > | |
| basic_json(InputIT first, InputIT last) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| JSON_ASSERT(first.m_object != nullptr); | |
| JSON_ASSERT(last.m_object != nullptr); | |
| // make sure the iterator fits the current value | |
| if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) | |
| { | |
| detail::throw_literal<invalid_iterator>(detail::exception_id::iterators_incompatible, "iterators are not compatible", nullptr); | |
| } | |
| // copy type from the first iterator | |
| m_data.m_type = first.m_object->m_data.m_type; | |
| // check if the iterator range is complete for primitive values | |
| switch (m_data.m_type) | |
| { | |
| case value_t::boolean: | |
| case value_t::number_float: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::string: | |
| case value_t::binary: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!primitive_range_is_complete(first, last))) | |
| { | |
| detail::throw_literal<invalid_iterator>(detail::exception_id::iterator_range_out_of_range, "iterators out of range", first.m_object); | |
| } | |
| break; | |
| } | |
| case value_t::null: | |
| case value_t::object: | |
| case value_t::array: | |
| case value_t::discarded: | |
| default: | |
| break; | |
| } | |
| switch (m_data.m_type) | |
| { | |
| case value_t::number_integer: | |
| { | |
| m_data.m_value.number_integer = first.m_object->m_data.m_value.number_integer; | |
| break; | |
| } | |
| case value_t::number_unsigned: | |
| { | |
| m_data.m_value.number_unsigned = first.m_object->m_data.m_value.number_unsigned; | |
| break; | |
| } | |
| case value_t::number_float: | |
| { | |
| m_data.m_value.number_float = first.m_object->m_data.m_value.number_float; | |
| break; | |
| } | |
| case value_t::boolean: | |
| { | |
| m_data.m_value.boolean = first.m_object->m_data.m_value.boolean; | |
| break; | |
| } | |
| case value_t::string: | |
| { | |
| m_data.m_value = *first.m_object->m_data.m_value.string; | |
| break; | |
| } | |
| case value_t::object: | |
| { | |
| m_data.m_value.object = create<object_t>(first.m_it.object_iterator, | |
| last.m_it.object_iterator); | |
| break; | |
| } | |
| case value_t::array: | |
| { | |
| m_data.m_value.array = create<array_t>(first.m_it.array_iterator, | |
| last.m_it.array_iterator); | |
| break; | |
| } | |
| case value_t::binary: | |
| { | |
| m_data.m_value = *first.m_object->m_data.m_value.binary; | |
| break; | |
| } | |
| case value_t::null: | |
| case value_t::discarded: | |
| default: | |
| throw_iterator_range_of_null(first.m_object); | |
| } | |
| set_parents(); | |
| assert_invariant(); | |
| } | |
| /////////////////////////////////////// | |
| // other constructors and destructor // | |
| /////////////////////////////////////// | |
| template<typename JsonRef, | |
| detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>, | |
| std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 > | |
| basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {} | |
| /// @brief copy constructor | |
| /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ | |
| basic_json(const basic_json& other) | |
| : json_base_class_t(other) | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| , start_position(other.start_position) | |
| , end_position(other.end_position) | |
| #endif | |
| { | |
| m_data.m_type = other.m_data.m_type; | |
| // check of passed value is valid | |
| other.assert_invariant(); | |
| if (JSON_HEDLEY_LIKELY(!detail::owns_memory(m_data.m_type))) | |
| { | |
| // null, boolean, numbers, discarded: plain copy of the union | |
| m_data.m_value = other.m_data.m_value; | |
| } | |
| else | |
| { | |
| copy_owning(other); | |
| } | |
| assert_invariant(); | |
| } | |
| /// @brief move constructor | |
| /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ | |
| basic_json(basic_json&& other) noexcept | |
| : json_base_class_t(std::move(static_cast<json_base_class_t&>(other))), | |
| m_data(std::move(other.m_data)) | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| , start_position(other.start_position) | |
| , end_position(other.end_position) | |
| #endif | |
| { | |
| // check that the passed value is valid | |
| other.assert_invariant(false); | |
| // invalidate payload | |
| other.m_data.m_type = value_t::null; | |
| other.m_data.m_value = {}; | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| other.start_position = std::string::npos; | |
| other.end_position = std::string::npos; | |
| #endif | |
| set_parents(); | |
| assert_invariant(); | |
| } | |
| /// @brief copy assignment | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator=/ | |
| basic_json& operator=(basic_json other) noexcept ( // NOLINT(cppcoreguidelines-c-copy-assignment-signature,misc-unconventional-assign-operator) | |
| std::is_nothrow_move_constructible<value_t>::value&& | |
| std::is_nothrow_move_assignable<value_t>::value&& | |
| std::is_nothrow_move_constructible<json_value>::value&& | |
| std::is_nothrow_move_assignable<json_value>::value&& | |
| std::is_nothrow_move_assignable<json_base_class_t>::value | |
| ) | |
| { | |
| // check that the passed value is valid | |
| other.assert_invariant(); | |
| using std::swap; | |
| swap(m_data.m_type, other.m_data.m_type); | |
| swap(m_data.m_value, other.m_data.m_value); | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| swap(start_position, other.start_position); | |
| swap(end_position, other.end_position); | |
| #endif | |
| json_base_class_t::operator=(std::move(other)); | |
| set_parents(); | |
| assert_invariant(); | |
| return *this; | |
| } | |
| /// @brief destructor | |
| /// @sa https://json.nlohmann.me/api/basic_json/~basic_json/ | |
| ~basic_json() noexcept | |
| { | |
| assert_invariant(false); | |
| } | |
| /// @} | |
| public: | |
| /////////////////////// | |
| // object inspection // | |
| /////////////////////// | |
| /// @name object inspection | |
| /// Functions to inspect the type of a JSON value. | |
| /// @{ | |
| /// @brief serialization | |
| /// @sa https://json.nlohmann.me/api/basic_json/dump/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| string_t dump(const int indent = -1, | |
| const char indent_char = ' ', | |
| const bool ensure_ascii = false, | |
| const error_handler_t error_handler = error_handler_t::strict) const | |
| { | |
| string_t result; | |
| detail::output_string_adapter<char, string_t> string_adapter(result); | |
| if (indent >= 0) | |
| { | |
| serializer s(string_adapter, indent_char, | |
| true, ensure_ascii, static_cast<std::size_t>(indent), error_handler); | |
| s.dump(*this); | |
| } | |
| else | |
| { | |
| serializer s(string_adapter, indent_char, | |
| false, ensure_ascii, 0, error_handler); | |
| s.dump(*this); | |
| } | |
| return result; | |
| } | |
| /// @brief return the type of the JSON value (explicit) | |
| /// @sa https://json.nlohmann.me/api/basic_json/type/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr value_t type() const noexcept | |
| { | |
| return m_data.m_type; | |
| } | |
| /// @brief return whether type is primitive | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_primitive/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_primitive() const noexcept | |
| { | |
| return is_null() || is_string() || is_boolean() || is_number() || is_binary(); | |
| } | |
| /// @brief return whether type is structured | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_structured/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_structured() const noexcept | |
| { | |
| return is_array() || is_object(); | |
| } | |
| /// @brief return whether value is null | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_null/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_null() const noexcept | |
| { | |
| return m_data.m_type == value_t::null; | |
| } | |
| /// @brief return whether value is a boolean | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_boolean/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_boolean() const noexcept | |
| { | |
| return m_data.m_type == value_t::boolean; | |
| } | |
| /// @brief return whether value is a number | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_number/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_number() const noexcept | |
| { | |
| return is_number_integer() || is_number_float(); | |
| } | |
| /// @brief return whether value is an integer number | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_number_integer/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_number_integer() const noexcept | |
| { | |
| return m_data.m_type == value_t::number_integer || m_data.m_type == value_t::number_unsigned; | |
| } | |
| /// @brief return whether value is an unsigned integer number | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_number_unsigned/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_number_unsigned() const noexcept | |
| { | |
| return m_data.m_type == value_t::number_unsigned; | |
| } | |
| /// @brief return whether value is a floating-point number | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_number_float/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_number_float() const noexcept | |
| { | |
| return m_data.m_type == value_t::number_float; | |
| } | |
| /// @brief return whether value is an object | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_object/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_object() const noexcept | |
| { | |
| return m_data.m_type == value_t::object; | |
| } | |
| /// @brief return whether value is an array | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_array/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_array() const noexcept | |
| { | |
| return m_data.m_type == value_t::array; | |
| } | |
| /// @brief return whether value is a string | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_string/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_string() const noexcept | |
| { | |
| return m_data.m_type == value_t::string; | |
| } | |
| /// @brief return whether value is a binary array | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_binary/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_binary() const noexcept | |
| { | |
| return m_data.m_type == value_t::binary; | |
| } | |
| /// @brief return whether value is discarded | |
| /// @sa https://json.nlohmann.me/api/basic_json/is_discarded/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| constexpr bool is_discarded() const noexcept | |
| { | |
| return m_data.m_type == value_t::discarded; | |
| } | |
| /// @brief return the type of the JSON value (implicit) | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_value_t/ | |
| constexpr operator value_t() const noexcept | |
| { | |
| return m_data.m_type; | |
| } | |
| /// @} | |
| private: | |
| ////////////////// | |
| // value access // | |
| ////////////////// | |
| /// out-of-line part of the copy constructor for owning types | |
| JSON_HEDLEY_NEVER_INLINE | |
| void copy_owning(const basic_json& other) | |
| { | |
| if (m_data.m_type == value_t::object || m_data.m_type == value_t::array) | |
| { | |
| // copying the container directly would call this constructor again | |
| // for every element, once per nesting level | |
| copy_structured(other); | |
| } | |
| else | |
| { | |
| copy_leaf_value(other, *this); | |
| } | |
| } | |
| /// get a pointer to the value (object) | |
| object_t* get_impl_ptr(object_t* /*unused*/) noexcept | |
| { | |
| return is_object() ? m_data.m_value.object : nullptr; | |
| } | |
| /// get a pointer to the value (object) | |
| constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept | |
| { | |
| return is_object() ? m_data.m_value.object : nullptr; | |
| } | |
| /// get a pointer to the value (array) | |
| array_t* get_impl_ptr(array_t* /*unused*/) noexcept | |
| { | |
| return is_array() ? m_data.m_value.array : nullptr; | |
| } | |
| /// get a pointer to the value (array) | |
| constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept | |
| { | |
| return is_array() ? m_data.m_value.array : nullptr; | |
| } | |
| /// get a pointer to the value (string) | |
| string_t* get_impl_ptr(string_t* /*unused*/) noexcept | |
| { | |
| return is_string() ? m_data.m_value.string : nullptr; | |
| } | |
| /// get a pointer to the value (string) | |
| constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept | |
| { | |
| return is_string() ? m_data.m_value.string : nullptr; | |
| } | |
| /// get a pointer to the value (boolean) | |
| boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept | |
| { | |
| return is_boolean() ? &m_data.m_value.boolean : nullptr; | |
| } | |
| /// get a pointer to the value (boolean) | |
| constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept | |
| { | |
| return is_boolean() ? &m_data.m_value.boolean : nullptr; | |
| } | |
| /// get a pointer to the value (integer number) | |
| number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept | |
| { | |
| return m_data.m_type == value_t::number_integer ? &m_data.m_value.number_integer : nullptr; | |
| } | |
| /// get a pointer to the value (integer number) | |
| constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept | |
| { | |
| return m_data.m_type == value_t::number_integer ? &m_data.m_value.number_integer : nullptr; | |
| } | |
| /// get a pointer to the value (unsigned number); takes a placeholder if | |
| /// number_unsigned_t is number_integer_t (the integer overload handles it then) | |
| number_unsigned_t* get_impl_ptr(detail::number_unsigned_overload_type<NumberIntegerType, NumberUnsignedType>* /*unused*/) noexcept | |
| { | |
| return is_number_unsigned() ? &m_data.m_value.number_unsigned : nullptr; | |
| } | |
| /// get a pointer to the value (unsigned number); takes a placeholder if | |
| /// number_unsigned_t is number_integer_t (the integer overload handles it then) | |
| constexpr const number_unsigned_t* get_impl_ptr(const detail::number_unsigned_overload_type<NumberIntegerType, NumberUnsignedType>* /*unused*/) const noexcept | |
| { | |
| return is_number_unsigned() ? &m_data.m_value.number_unsigned : nullptr; | |
| } | |
| /// get a pointer to the value (floating-point number) | |
| number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept | |
| { | |
| return is_number_float() ? &m_data.m_value.number_float : nullptr; | |
| } | |
| /// get a pointer to the value (floating-point number) | |
| constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept | |
| { | |
| return is_number_float() ? &m_data.m_value.number_float : nullptr; | |
| } | |
| /// get a pointer to the value (binary) | |
| binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept | |
| { | |
| return is_binary() ? m_data.m_value.binary : nullptr; | |
| } | |
| /// get a pointer to the value (binary) | |
| constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept | |
| { | |
| return is_binary() ? m_data.m_value.binary : nullptr; | |
| } | |
| /// out-of-line throw helpers (message construction kept out of the hot paths) | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_iterator_range_of_null(const basic_json* obj) | |
| { | |
| static_cast<void>(obj); // unused when JSON_NOEXCEPTION is defined | |
| JSON_THROW(invalid_iterator::create(detail::exception_id::iterator_range_of_null, detail::concat("cannot construct with iterators from ", obj->type_name()), obj)); | |
| } | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_incompatible_reference_type(const basic_json& obj) | |
| { | |
| static_cast<void>(obj); // unused when JSON_NOEXCEPTION is defined | |
| JSON_THROW(type_error::create(detail::exception_id::incompatible_reference_type, detail::concat("incompatible ReferenceType for get_ref, actual type is ", obj.type_name()), &obj)); | |
| } | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_array_index_exceeds_size_type(size_type idx) | |
| { | |
| static_cast<void>(idx); // unused when JSON_NOEXCEPTION is defined | |
| JSON_THROW(std::length_error(detail::concat("array index ", std::to_string(idx), " exceeds size_type"))); | |
| } | |
| /// @throw type_error.309 always, as insert() is not defined for the type of @a j | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_insert_wrong_type(const basic_json& j) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::insert_wrong_type, "insert()", j); | |
| } | |
| /// @throw invalid_iterator.202 always, as an iterator belongs to another value than @a obj | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_iterator_from_other_value(const basic_json* obj) | |
| { | |
| detail::throw_literal<invalid_iterator>(detail::exception_id::iterator_from_other_value, "iterator does not fit current value", obj); | |
| } | |
| /// @throw type_error.310 always, as swap() with the given operand is not defined for the type of @a j | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_swap_wrong_type(const char* operation, const basic_json& j) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::swap_wrong_type, operation, j); | |
| } | |
| /// exchange the stored @a Stored value (if the value has that type) with @a other | |
| template<typename Stored, typename Other> | |
| void swap_impl(Other& other, const char* operation) | |
| { | |
| Stored* const stored = get_impl_ptr(static_cast<Stored*>(nullptr)); | |
| if (JSON_HEDLEY_UNLIKELY(stored == nullptr)) | |
| { | |
| throw_swap_wrong_type(operation, *this); | |
| } | |
| using std::swap; | |
| swap(*stored, other); | |
| } | |
| /// whether [first, last) spans the whole of a primitive value | |
| template<typename IteratorType> | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| static bool primitive_range_is_complete(const IteratorType& first, const IteratorType& last) noexcept | |
| { | |
| return first.m_it.primitive_iterator.is_begin() && last.m_it.primitive_iterator.is_end(); | |
| } | |
| /// destroy the current (primitive) value and become null | |
| void reset_to_null_impl() | |
| { | |
| m_data.m_value.destroy(m_data.m_type); | |
| m_data.m_value = {}; | |
| m_data.m_type = value_t::null; | |
| assert_invariant(); | |
| } | |
| /// append @a val (moved or copied) to the array; a null value becomes an array | |
| template<typename ValueType> | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| void push_back_array_impl(ValueType&& val) | |
| { | |
| // push_back only works for null objects or arrays | |
| if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::push_back_wrong_type, "push_back()", *this); | |
| } | |
| // transform a null object into an array | |
| if (is_null()) | |
| { | |
| convert_null_to<array_t>(); | |
| } | |
| // add the element to the array | |
| const auto old_capacity = container_capacity(); | |
| m_data.m_value.array->push_back(std::forward<ValueType>(val)); | |
| set_parent_after_insert(m_data.m_value.array->back(), old_capacity); | |
| } | |
| /// parse the input behind an already created adapter | |
| template<typename InputAdapterType> | |
| static basic_json parse_impl(InputAdapterType&& adapter, | |
| parser_callback_t cb, | |
| const bool allow_exceptions, | |
| const bool ignore_comments, | |
| const bool ignore_trailing_commas) | |
| { | |
| basic_json result; | |
| parser(std::forward<InputAdapterType>(adapter), std::move(cb), allow_exceptions, ignore_comments, ignore_trailing_commas).parse(true, result); | |
| return result; | |
| } | |
| /// check the input behind an already created adapter | |
| template<typename InputAdapterType> | |
| static bool accept_impl(InputAdapterType&& adapter, | |
| const bool ignore_comments, | |
| const bool ignore_trailing_commas) | |
| { | |
| return parser(std::forward<InputAdapterType>(adapter), nullptr, false, ignore_comments, ignore_trailing_commas, true).accept(true); | |
| } | |
| /// generate SAX events from the input behind an already created adapter | |
| template<typename InputAdapterType, typename SAX> | |
| static bool sax_parse_impl(InputAdapterType ia, SAX* sax, | |
| const input_format_t format, | |
| const bool strict, | |
| const bool ignore_comments, | |
| const bool ignore_trailing_commas, | |
| const cbor_tag_handler_t tag_handler) | |
| { | |
| if (format == input_format_t::json) | |
| { | |
| return parser(std::move(ia), nullptr, true, ignore_comments, ignore_trailing_commas).sax_parse(sax, strict); | |
| } | |
| return detail::binary_reader<basic_json, InputAdapterType, SAX>(std::move(ia), format).sax_parse(sax, strict, tag_handler); | |
| } | |
| /// serialize @a j into a new vector; @a write receives the vector-backed writer | |
| template<typename WriteFunction> | |
| static std::vector<std::uint8_t> to_binary_vector(const basic_json& j, const error_handler_t error_handler, WriteFunction write) | |
| { | |
| std::vector<std::uint8_t> result; | |
| result.reserve(detail::binary_initial_capacity(j)); | |
| { | |
| // the sink sets the size of result when it is destroyed, which | |
| // must happen before result is returned (without NRVO, it is moved) | |
| auto writer = vector_writer(result, error_handler); | |
| write(writer); | |
| } | |
| return result; | |
| } | |
| /// @throw out_of_range.401 always, as @a idx is out of range of @a j | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_array_index_out_of_range(size_type idx, const basic_json& j) | |
| { | |
| static_cast<void>(idx); // unused when JSON_NOEXCEPTION is defined | |
| static_cast<void>(j); | |
| JSON_THROW(out_of_range::create(detail::exception_id::array_index_out_of_range, detail::concat("array index ", std::to_string(idx), " is out of range"), &j)); | |
| } | |
| /// @throw out_of_range.403 always, as @a key is not found in @a j | |
| template<typename KeyType> | |
| JSON_HEDLEY_NO_RETURN JSON_HEDLEY_NEVER_INLINE | |
| static void throw_key_not_found(const KeyType& key, const basic_json& j) | |
| { | |
| static_cast<void>(key); // unused when JSON_NOEXCEPTION is defined | |
| static_cast<void>(j); | |
| JSON_THROW(out_of_range::create(detail::exception_id::key_not_found, detail::concat("key '", key, "' not found"), &j)); | |
| } | |
| /*! | |
| @brief helper function to implement get_ref() | |
| This function helps to implement get_ref() without code duplication for | |
| const and non-const overloads | |
| @tparam ThisType will be deduced as `basic_json` or `const basic_json` | |
| @throw type_error.303 if ReferenceType does not match underlying value | |
| type of the current JSON | |
| */ | |
| template<typename ReferenceType, typename ThisType> | |
| static ReferenceType get_ref_impl(ThisType& obj) | |
| { | |
| // delegate the call to get_ptr<>() | |
| auto* ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>(); | |
| if (JSON_HEDLEY_LIKELY(ptr != nullptr)) | |
| { | |
| return *ptr; | |
| } | |
| throw_incompatible_reference_type(obj); | |
| } | |
| public: | |
| /// @name value access | |
| /// Direct access to the stored value of a JSON value. | |
| /// @{ | |
| /// @brief get a pointer value (implicit) | |
| /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/ | |
| template<typename PointerType, typename std::enable_if< | |
| std::is_pointer<PointerType>::value, int>::type = 0> | |
| auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>())) | |
| { | |
| // delegate the call to get_impl_ptr<>() | |
| return get_impl_ptr(static_cast<PointerType>(nullptr)); | |
| } | |
| /// @brief get a pointer value (implicit) | |
| /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/ | |
| template < typename PointerType, typename std::enable_if < | |
| std::is_pointer<PointerType>::value&& | |
| std::is_const<typename std::remove_pointer<PointerType>::type>::value, int >::type = 0 > | |
| constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>())) | |
| { | |
| // delegate the call to get_impl_ptr<>() const | |
| return get_impl_ptr(static_cast<PointerType>(nullptr)); | |
| } | |
| private: | |
| /*! | |
| @brief get a value (explicit) | |
| Explicit type conversion between the JSON value and a compatible value | |
| which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) | |
| and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). | |
| The value is converted by calling the @ref json_serializer<ValueType> | |
| `from_json()` method. | |
| The function is equivalent to executing | |
| @code {.cpp} | |
| ValueType ret; | |
| JSONSerializer<ValueType>::from_json(*this, ret); | |
| return ret; | |
| @endcode | |
| This overloads is chosen if: | |
| - @a ValueType is not @ref basic_json, | |
| - @ref json_serializer<ValueType> has a `from_json()` method of the form | |
| `void from_json(const basic_json&, ValueType&)`, and | |
| - @ref json_serializer<ValueType> does not have a `from_json()` method of | |
| the form `ValueType from_json(const basic_json&)` | |
| @tparam ValueType the returned value type | |
| @return copy of the JSON value, converted to @a ValueType | |
| @throw what @ref json_serializer<ValueType> `from_json()` method throws | |
| The example below shows several conversions from JSON values | |
| to other types. There a few things to note: (1) Floating-point numbers can | |
| be converted to integers, (2) A JSON array can be converted to a standard | |
| `std::vector<short>`, (3) A JSON object can be converted to C++ | |
| associative containers such as `std::unordered_map<std::string, | |
| json>`. | |
| @since version 2.1.0 | |
| */ | |
| template < typename ValueType, | |
| detail::enable_if_t < | |
| detail::is_default_constructible<ValueType>::value&& | |
| detail::has_from_json<basic_json_t, ValueType>::value, | |
| int > = 0 > | |
| ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept( | |
| JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>()))) | |
| { | |
| auto ret = ValueType(); | |
| JSONSerializer<ValueType>::from_json(*this, ret); | |
| // false positive: ret is returned by value, not its address | |
| // @infer-ignore STACK_VARIABLE_ADDRESS_ESCAPE | |
| return ret; | |
| } | |
| /*! | |
| @brief get a value (explicit); special case | |
| Explicit type conversion between the JSON value and a compatible value | |
| which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) | |
| and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). | |
| The value is converted by calling the @ref json_serializer<ValueType> | |
| `from_json()` method. | |
| The function is equivalent to executing | |
| @code {.cpp} | |
| return JSONSerializer<ValueType>::from_json(*this); | |
| @endcode | |
| This overloads is chosen if: | |
| - @a ValueType is not @ref basic_json and | |
| - @ref json_serializer<ValueType> has a `from_json()` method of the form | |
| `ValueType from_json(const basic_json&)` | |
| @note If @ref json_serializer<ValueType> has both overloads of | |
| `from_json()`, this one is chosen. | |
| @tparam ValueType the returned value type | |
| @return copy of the JSON value, converted to @a ValueType | |
| @throw what @ref json_serializer<ValueType> `from_json()` method throws | |
| @since version 2.1.0 | |
| */ | |
| template < typename ValueType, | |
| detail::enable_if_t < | |
| detail::has_non_default_from_json<basic_json_t, ValueType>::value, | |
| int > = 0 > | |
| ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept( | |
| JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>()))) | |
| { | |
| return JSONSerializer<ValueType>::from_json(*this); | |
| } | |
| /*! | |
| @brief get special-case overload | |
| This overloads converts the current @ref basic_json in a different | |
| @ref basic_json type | |
| @tparam BasicJsonType == @ref basic_json | |
| @return a copy of *this, converted into @a BasicJsonType | |
| Complexity: Depending on the implementation of the called `from_json()` | |
| method. | |
| @since version 3.2.0 | |
| */ | |
| template < typename BasicJsonType, | |
| detail::enable_if_t < | |
| detail::is_basic_json<BasicJsonType>::value, | |
| int > = 0 > | |
| BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const | |
| { | |
| return BasicJsonType(*this); | |
| } | |
| /*! | |
| @brief get special-case overload | |
| This overloads avoids a lot of template boilerplate, it can be seen as the | |
| identity method | |
| @tparam BasicJsonType == @ref basic_json | |
| @return a copy of *this | |
| Complexity: Constant. | |
| @since version 2.1.0 | |
| */ | |
| template<typename BasicJsonType, | |
| detail::enable_if_t< | |
| std::is_same<BasicJsonType, basic_json_t>::value, | |
| int> = 0> | |
| basic_json get_impl(detail::priority_tag<3> /*unused*/) const | |
| { | |
| return *this; | |
| } | |
| /*! | |
| @brief get a pointer value (explicit) | |
| @copydoc get() | |
| */ | |
| template<typename PointerType, | |
| detail::enable_if_t< | |
| std::is_pointer<PointerType>::value, | |
| int> = 0> | |
| constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept | |
| -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>()) | |
| { | |
| // delegate the call to get_ptr | |
| return get_ptr<PointerType>(); | |
| } | |
| public: | |
| /*! | |
| @brief get a (pointer) value (explicit) | |
| Performs explicit type conversion between the JSON value and a compatible value if required. | |
| - If the requested type is a pointer to the internally stored JSON value that pointer is returned. | |
| No copies are made. | |
| - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible | |
| from the current @ref basic_json. | |
| - Otherwise the value is converted by calling the @ref json_serializer<ValueType> `from_json()` | |
| method. | |
| @tparam ValueTypeCV the provided value type | |
| @tparam ValueType the returned value type | |
| @return copy of the JSON value, converted to @a ValueType if necessary | |
| @throw what @ref json_serializer<ValueType> `from_json()` method throws if conversion is required | |
| @since version 2.1.0 | |
| */ | |
| template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>> | |
| #if defined(JSON_HAS_CPP_14) | |
| constexpr | |
| #endif | |
| auto get() const noexcept( | |
| noexcept(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {}))) | |
| -> decltype(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {})) | |
| { | |
| // we cannot static_assert on ValueTypeCV being non-const, because | |
| // there is support for get<const basic_json_t>(), which is why we | |
| // still need the uncvref | |
| static_assert(!std::is_reference<ValueTypeCV>::value, | |
| "get() cannot be used with reference types, you might want to use get_ref()"); | |
| return get_impl<ValueType>(detail::priority_tag<4> {}); | |
| } | |
| /*! | |
| @brief get a pointer value (explicit) | |
| Explicit pointer access to the internally stored JSON value. No copies are | |
| made. | |
| @warning The pointer becomes invalid if the underlying JSON object | |
| changes. | |
| @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref | |
| object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, | |
| @ref number_unsigned_t, @ref number_float_t, or @ref binary_t. | |
| @return pointer to the internally stored JSON value if the requested | |
| pointer type @a PointerType fits to the JSON value; `nullptr` otherwise | |
| Complexity: Constant. | |
| The example below shows how pointers to internal values of a | |
| JSON value can be requested. Note that no type conversions are made and a | |
| `nullptr` is returned if the value and the requested pointer type does not | |
| match. | |
| @sa see @ref get_ptr() for explicit pointer-member access | |
| @since version 1.0.0 | |
| */ | |
| template<typename PointerType, typename std::enable_if< | |
| std::is_pointer<PointerType>::value, int>::type = 0> | |
| auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>()) | |
| { | |
| // delegate the call to get_ptr | |
| return get_ptr<PointerType>(); | |
| } | |
| /// @brief get a value (explicit) | |
| /// @sa https://json.nlohmann.me/api/basic_json/get_to/ | |
| template < typename ValueType, | |
| detail::enable_if_t < | |
| !detail::is_basic_json<ValueType>::value&& | |
| detail::has_from_json<basic_json_t, ValueType>::value, | |
| int > = 0 > | |
| ValueType & get_to(ValueType& v) const noexcept(noexcept( | |
| JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v))) | |
| { | |
| static_assert(!std::is_const<ValueType>::value, "get_to() cannot deserialize into a const value"); | |
| JSONSerializer<ValueType>::from_json(*this, v); | |
| return v; | |
| } | |
| // specialization to allow calling get_to with a basic_json value | |
| // see https://github.com/nlohmann/json/issues/2175 | |
| template<typename ValueType, | |
| detail::enable_if_t < | |
| detail::is_basic_json<ValueType>::value, | |
| int> = 0> | |
| ValueType & get_to(ValueType& v) const | |
| { | |
| v = ValueType(*this); | |
| return v; | |
| } | |
| template < | |
| typename T, std::size_t N, | |
| typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| detail::enable_if_t < | |
| detail::has_from_json<basic_json_t, Array>::value, int > = 0 > | |
| Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) | |
| noexcept(noexcept(JSONSerializer<Array>::from_json( | |
| std::declval<const basic_json_t&>(), v))) | |
| { | |
| static_assert(!std::is_const<T>::value, "get_to() cannot deserialize into a const value"); | |
| JSONSerializer<Array>::from_json(*this, v); | |
| return v; | |
| } | |
| /// @brief get a reference value (implicit) | |
| /// @sa https://json.nlohmann.me/api/basic_json/get_ref/ | |
| template<typename ReferenceType, typename std::enable_if< | |
| std::is_reference<ReferenceType>::value, int>::type = 0> | |
| ReferenceType get_ref() | |
| { | |
| // delegate call to get_ref_impl | |
| return get_ref_impl<ReferenceType>(*this); | |
| } | |
| /// @brief get a reference value (implicit) | |
| /// @sa https://json.nlohmann.me/api/basic_json/get_ref/ | |
| template < typename ReferenceType, typename std::enable_if < | |
| std::is_reference<ReferenceType>::value&& | |
| std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int >::type = 0 > | |
| ReferenceType get_ref() const | |
| { | |
| // delegate call to get_ref_impl | |
| return get_ref_impl<ReferenceType>(*this); | |
| } | |
| /*! | |
| @brief get a value (implicit) | |
| Implicit type conversion between the JSON value and a compatible value. | |
| The call is realized by calling @ref get() const. | |
| @tparam ValueType non-pointer type compatible to the JSON value, for | |
| instance `int` for JSON integer numbers, `bool` for JSON booleans, or | |
| `std::vector` types for JSON arrays. The character type of @ref string_t | |
| as well as an initializer list of this type is excluded to avoid | |
| ambiguities as these types implicitly convert to `std::string`. | |
| @return copy of the JSON value, converted to type @a ValueType | |
| @throw type_error.302 in case passed type @a ValueType is incompatible | |
| to the JSON value type (e.g., the JSON value is of type boolean, but a | |
| string is requested); see example below | |
| Complexity: Linear in the size of the JSON value. | |
| The example below shows several conversions from JSON values | |
| to other types. There a few things to note: (1) Floating-point numbers can | |
| be converted to integers, (2) A JSON array can be converted to a standard | |
| `std::vector<short>`, (3) A JSON object can be converted to C++ | |
| associative containers such as `std::unordered_map<std::string, | |
| json>`. | |
| @since version 1.0.0 | |
| */ | |
| template < typename ValueType, typename std::enable_if < | |
| detail::conjunction < | |
| detail::negation<std::is_pointer<ValueType>>, | |
| detail::negation<std::is_same<ValueType, std::nullptr_t>>, | |
| detail::negation<std::is_same<ValueType, detail::json_ref<basic_json>>>, | |
| detail::negation<std::is_same<ValueType, typename string_t::value_type>>, | |
| detail::negation<detail::is_basic_json<ValueType>>, | |
| detail::negation<std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>>, | |
| #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914)) | |
| detail::negation<std::is_same<ValueType, std::string_view>>, | |
| #endif | |
| #if defined(JSON_HAS_CPP_17) && JSON_HAS_STATIC_RTTI | |
| detail::negation<std::is_same<ValueType, std::any>>, | |
| #endif | |
| #if defined(JSON_HAS_CPP_17) | |
| // std::optional<T> can construct itself from basic_json; excluding it | |
| // here avoids an ambiguity with that constructor (e.g., under C++26) | |
| detail::negation<detail::is_std_optional<ValueType>>, | |
| #endif | |
| detail::is_detected_lazy<detail::get_template_function, const basic_json_t&, ValueType> | |
| >::value, int >::type = 0 > | |
| JSON_EXPLICIT operator ValueType() const | |
| { | |
| // delegate the call to get<>() const | |
| return get<ValueType>(); | |
| } | |
| /// @brief get a binary value | |
| /// @sa https://json.nlohmann.me/api/basic_json/get_binary/ | |
| binary_t& get_binary() | |
| { | |
| if (!is_binary()) | |
| { | |
| detail::throw_type_must_be("binary", *this); | |
| } | |
| return *get_ptr<binary_t*>(); | |
| } | |
| /// @brief get a binary value | |
| /// @sa https://json.nlohmann.me/api/basic_json/get_binary/ | |
| const binary_t& get_binary() const | |
| { | |
| if (!is_binary()) | |
| { | |
| detail::throw_type_must_be("binary", *this); | |
| } | |
| return *get_ptr<const binary_t*>(); | |
| } | |
| /// @brief access the custom base class | |
| /// @sa https://json.nlohmann.me/api/basic_json/as_base_class/ | |
| json_base_class_t& as_base_class() noexcept | |
| { | |
| return static_cast<json_base_class_t&>(*this); | |
| } | |
| /// @brief access the custom base class | |
| /// @sa https://json.nlohmann.me/api/basic_json/as_base_class/ | |
| const json_base_class_t& as_base_class() const noexcept | |
| { | |
| return static_cast<const json_base_class_t&>(*this); | |
| } | |
| /// @} | |
| private: | |
| /// @brief look up @a key in the object held by @a j, for either constness of @a j | |
| /// @note the single place that performs a (possibly transparent) object key lookup | |
| template<typename Self, typename KeyType> | |
| static auto object_lookup(Self& j, KeyType&& key) | |
| -> decltype(j.m_data.m_value.object->find(lookup_key(std::forward<KeyType>(key)))) | |
| { | |
| return j.m_data.m_value.object->find(lookup_key(std::forward<KeyType>(key))); | |
| } | |
| /// @brief checked object element access used by the at() overloads taking a key | |
| /// @throw type_error.304 if @a j is not an object | |
| /// @throw out_of_range.403 if @a key is not found | |
| template<typename Self, typename KeyType> | |
| static auto object_at(Self& j, KeyType&& key) | |
| -> decltype((object_lookup(j, std::forward<KeyType>(key))->second)) | |
| { | |
| // at only works for objects | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_object())) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::at_wrong_type, "at()", j); | |
| } | |
| auto it = object_lookup(j, std::forward<KeyType>(key)); | |
| if (it == j.m_data.m_value.object->end()) | |
| { | |
| // key is only forwarded into the lookup above: object_t::find() (a plain | |
| // std::map or ordered_map) never moves from its argument, so key is still | |
| // valid here regardless of whether KeyType was deduced as an rvalue reference | |
| // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved) | |
| throw_key_not_found(key_for_message(key), j); | |
| } | |
| return it->second; | |
| } | |
| /// @brief key as it is passed to detail::concat for an error message | |
| /// @note keys with data() and size() (such as string_t itself or a string | |
| /// view) are passed through unchanged, so a miss does not copy them; | |
| /// other keys (such as string literals or key types that only convert | |
| /// to string_t) are converted to string_t | |
| template < typename KeyType, detail::enable_if_t < detail::detect_string_can_append_data<string_t, KeyType>::value, int > = 0 > | |
| static const KeyType & key_for_message(const KeyType& key) | |
| { | |
| return key; // NOLINT(bugprone-return-const-ref-from-parameter): the result is only passed to concat() within the full-expression that holds key | |
| } | |
| template < typename KeyType, detail::enable_if_t < !detail::detect_string_can_append_data<string_t, KeyType>::value, int > = 0 > | |
| static string_t key_for_message(const KeyType& key) | |
| { | |
| return string_t(key); | |
| } | |
| /// @brief checked array element access used by the at() overloads taking an index | |
| /// @throw type_error.304 if @a j is not an array | |
| /// @throw out_of_range.401 if @a idx is out of range | |
| template<typename Self> | |
| static auto array_at(Self& j, size_type idx) | |
| -> decltype((*j.m_data.m_value.array)[idx]) | |
| { | |
| // at only works for arrays | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_array())) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::at_wrong_type, "at()", j); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(idx >= j.m_data.m_value.array->size())) | |
| { | |
| throw_array_index_out_of_range(idx, j); | |
| } | |
| return (*j.m_data.m_value.array)[idx]; | |
| } | |
| /// @brief convert a null value to an empty container of type @a Container | |
| /// @tparam Container array_t or object_t; any other type does not compile | |
| template<typename Container> | |
| void convert_null_to() | |
| { | |
| JSON_ASSERT(is_null()); | |
| // create the container before touching the type, so a throwing | |
| // allocation leaves this value as a valid null rather than a type | |
| // tag with a dangling/null pointer behind it | |
| set_container(create<Container>()); | |
| assert_invariant(); | |
| } | |
| /// @brief store a freshly created array and set the matching type | |
| void set_container(array_t* array) noexcept | |
| { | |
| m_data.m_value.array = array; | |
| m_data.m_type = value_t::array; | |
| } | |
| /// @brief store a freshly created object and set the matching type | |
| void set_container(object_t* object) noexcept | |
| { | |
| m_data.m_value.object = object; | |
| m_data.m_type = value_t::object; | |
| } | |
| /// @brief throws because operator[] is not supported for the type of this value | |
| /// @param[in] argument the kind of the operator's argument, "numeric" or "string" | |
| /// @throw type_error.305 always | |
| JSON_HEDLEY_NO_RETURN void throw_subscript_wrong_type(const char* argument) const | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::subscript_wrong_type, | |
| detail::concat("operator[] with a ", argument, " argument").c_str(), *this); | |
| } | |
| public: | |
| //////////////////// | |
| // element access // | |
| //////////////////// | |
| /// @name element access | |
| /// Access to the JSON value. | |
| /// @{ | |
| /// @brief access specified array element with bounds checking | |
| /// @sa https://json.nlohmann.me/api/basic_json/at/ | |
| reference at(size_type idx) | |
| { | |
| return set_parent_at(array_at(*this, idx)); | |
| } | |
| /// @brief access specified array element with bounds checking | |
| /// @sa https://json.nlohmann.me/api/basic_json/at/ | |
| const_reference at(size_type idx) const | |
| { | |
| return array_at(*this, idx); | |
| } | |
| /// @brief access specified object element with bounds checking | |
| /// @sa https://json.nlohmann.me/api/basic_json/at/ | |
| reference at(const typename object_t::key_type& key) | |
| { | |
| return set_parent_at(object_at(*this, key)); | |
| } | |
| /// @brief access specified object element with bounds checking | |
| /// @sa https://json.nlohmann.me/api/basic_json/at/ | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0> | |
| reference at(KeyType && key) | |
| { | |
| return set_parent_at(object_at(*this, std::forward<KeyType>(key))); | |
| } | |
| /// @brief access specified object element with bounds checking | |
| /// @sa https://json.nlohmann.me/api/basic_json/at/ | |
| const_reference at(const typename object_t::key_type& key) const | |
| { | |
| return object_at(*this, key); | |
| } | |
| /// @brief access specified object element with bounds checking | |
| /// @sa https://json.nlohmann.me/api/basic_json/at/ | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0> | |
| const_reference at(KeyType && key) const | |
| { | |
| return object_at(*this, std::forward<KeyType>(key)); | |
| } | |
| /// @brief access specified array element | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ | |
| reference operator[](size_type idx) | |
| { | |
| // implicitly convert a null value to an empty array | |
| if (is_null()) | |
| { | |
| convert_null_to<array_t>(); | |
| } | |
| // operator[] only works for arrays | |
| if (JSON_HEDLEY_LIKELY(is_array())) | |
| { | |
| // fill up the array with null values if given idx is outside the range | |
| if (idx >= m_data.m_value.array->size()) | |
| { | |
| // idx + 1 would overflow size_type and wrap to 0, which would empty | |
| // the array instead of growing it; reject such an idx the same way | |
| // resize() rejects other indices that are too large to represent | |
| if (JSON_HEDLEY_UNLIKELY(idx == (std::numeric_limits<size_type>::max)())) | |
| { | |
| throw_array_index_exceeds_size_type(idx); | |
| } | |
| #if JSON_DIAGNOSTICS | |
| // remember array size & capacity before resizing | |
| const auto old_size = m_data.m_value.array->size(); | |
| const auto old_capacity = container_capacity(); | |
| #endif | |
| m_data.m_value.array->resize(idx + 1); | |
| #if JSON_DIAGNOSTICS | |
| if (JSON_HEDLEY_UNLIKELY(old_capacity == detail::unknown_size() | |
| || container_capacity() != old_capacity)) | |
| { | |
| // capacity has changed: update all parents | |
| set_parents(); | |
| } | |
| else | |
| { | |
| // set parent for values added above | |
| set_parents(begin() + static_cast<typename iterator::difference_type>(old_size), static_cast<typename iterator::difference_type>(idx + 1 - old_size)); | |
| } | |
| #endif | |
| assert_invariant(); | |
| } | |
| return m_data.m_value.array->operator[](idx); | |
| } | |
| throw_subscript_wrong_type("numeric"); | |
| } | |
| /// @brief access specified array element | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ | |
| const_reference operator[](size_type idx) const | |
| { | |
| // const operator[] only works for arrays | |
| if (JSON_HEDLEY_LIKELY(is_array())) | |
| { | |
| JSON_ASSERT(idx < m_data.m_value.array->size()); | |
| return m_data.m_value.array->operator[](idx); | |
| } | |
| throw_subscript_wrong_type("numeric"); | |
| } | |
| /// @brief access specified object element | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ | |
| reference operator[](typename object_t::key_type key) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| // implicitly convert a null value to an empty object | |
| if (is_null()) | |
| { | |
| convert_null_to<object_t>(); | |
| } | |
| // operator[] only works for objects | |
| if (JSON_HEDLEY_LIKELY(is_object())) | |
| { | |
| const auto old_capacity = container_capacity(); | |
| auto result = m_data.m_value.object->emplace(std::move(key), nullptr); | |
| return set_parent_after_insert(result.first->second, old_capacity); | |
| } | |
| throw_subscript_wrong_type("string"); | |
| } | |
| /// @brief access specified object element | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ | |
| const_reference operator[](const typename object_t::key_type& key) const | |
| { | |
| // const operator[] only works for objects | |
| if (JSON_HEDLEY_LIKELY(is_object())) | |
| { | |
| auto it = object_lookup(*this, key); | |
| JSON_ASSERT(it != m_data.m_value.object->end()); | |
| return it->second; | |
| } | |
| throw_subscript_wrong_type("string"); | |
| } | |
| // these two functions resolve a (const) char * ambiguity affecting Clang and MSVC | |
| // (they seemingly cannot be constrained to resolve the ambiguity) | |
| template<typename T> | |
| reference operator[](T* key) | |
| { | |
| return operator[](typename object_t::key_type(key)); | |
| } | |
| template<typename T> | |
| const_reference operator[](T* key) const | |
| { | |
| return operator[](typename object_t::key_type(key)); | |
| } | |
| /// @brief access specified object element | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int > = 0 > | |
| reference operator[](KeyType && key) | |
| { | |
| // implicitly convert a null value to an empty object | |
| if (is_null()) | |
| { | |
| convert_null_to<object_t>(); | |
| } | |
| // operator[] only works for objects | |
| if (JSON_HEDLEY_LIKELY(is_object())) | |
| { | |
| const auto old_capacity = container_capacity(); | |
| auto result = m_data.m_value.object->emplace(lookup_key(std::forward<KeyType>(key)), nullptr); | |
| return set_parent_after_insert(result.first->second, old_capacity); | |
| } | |
| throw_subscript_wrong_type("string"); | |
| } | |
| /// @brief access specified object element | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int > = 0 > | |
| const_reference operator[](KeyType && key) const | |
| { | |
| // const operator[] only works for objects | |
| if (JSON_HEDLEY_LIKELY(is_object())) | |
| { | |
| auto it = object_lookup(*this, std::forward<KeyType>(key)); | |
| JSON_ASSERT(it != m_data.m_value.object->end()); | |
| return it->second; | |
| } | |
| throw_subscript_wrong_type("string"); | |
| } | |
| private: | |
| template<typename KeyType> | |
| using is_comparable_with_object_key = std::integral_constant < bool, | |
| detail::is_comparable < | |
| object_comparator_t, const typename object_t::key_type&, KeyType >::value | |
| || detail::is_string_view_convertible_key_type<basic_json_t, KeyType>::value >; | |
| template<typename ValueType> | |
| using value_return_type = std::conditional < | |
| detail::is_c_string_uncvref<ValueType>::value, | |
| string_t, typename std::decay<ValueType>::type >; | |
| /// @brief look up @a key for value(), the single place shared by all key-based overloads | |
| /// @throw type_error.306 if this is not an object | |
| /// @return a pointer to the found value, or `nullptr` if @a key was not found | |
| template<typename KeyType> | |
| const basic_json* value_member(KeyType&& key) const | |
| { | |
| // value only works for objects | |
| if (JSON_HEDLEY_UNLIKELY(!is_object())) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::value_wrong_type, "value()", *this); | |
| } | |
| const auto it = find(std::forward<KeyType>(key)); | |
| return it != end() ? &*it : nullptr; | |
| } | |
| /// @brief resolve @a ptr for value(), the single place shared by both json_pointer overloads | |
| /// @throw type_error.306 if this is not an array or object | |
| /// @return a pointer to the resolved value, or `nullptr` if @a ptr does not resolve | |
| const basic_json* value_pointee(const json_pointer& ptr) const | |
| { | |
| // value only works for arrays and objects | |
| if (JSON_HEDLEY_UNLIKELY(!is_structured())) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::value_wrong_type, "value()", *this); | |
| } | |
| return ptr.get_checked_or_null(this); | |
| } | |
| public: | |
| // an integer literal 0 would otherwise convert to a null const char* and from there to key_type | |
| template<typename T, typename ValueType, detail::enable_if_t<std::is_integral<T>::value, int> = 0> | |
| ValueType value(T, ValueType&&) const = delete; | |
| /// @brief access specified object element with default value | |
| /// @sa https://json.nlohmann.me/api/basic_json/value/ | |
| template < class ValueType, detail::enable_if_t < | |
| !detail::is_transparent<object_comparator_t>::value | |
| && detail::is_getable<basic_json_t, ValueType>::value | |
| && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 > | |
| ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const | |
| { | |
| // If 'key' is found, return its value. Otherwise, return `default_value'. | |
| const auto* found = value_member(key); | |
| return found != nullptr ? found->template get<ValueType>() : default_value; | |
| } | |
| /// @brief access specified object element with default value | |
| /// @sa https://json.nlohmann.me/api/basic_json/value/ | |
| template < class ValueType, class ReturnType = typename value_return_type<ValueType>::type, | |
| detail::enable_if_t < | |
| !detail::is_transparent<object_comparator_t>::value | |
| && detail::is_getable<basic_json_t, ReturnType>::value | |
| && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 > | |
| ReturnType value(const typename object_t::key_type& key, ValueType && default_value) const | |
| { | |
| // If 'key' is found, return its value. Otherwise, return `default_value'. | |
| const auto* found = value_member(key); | |
| return found != nullptr ? found->template get<ReturnType>() : std::forward<ValueType>(default_value); | |
| } | |
| /// @brief access specified object element with default value | |
| /// @sa https://json.nlohmann.me/api/basic_json/value/ | |
| template < class ValueType, class KeyType, detail::enable_if_t < | |
| detail::is_transparent<object_comparator_t>::value | |
| && !detail::is_json_pointer<KeyType>::value | |
| && is_comparable_with_object_key<KeyType>::value | |
| && detail::is_getable<basic_json_t, ValueType>::value | |
| && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 > | |
| ValueType value(KeyType && key, const ValueType& default_value) const | |
| { | |
| // If 'key' is found, return its value. Otherwise, return `default_value'. | |
| const auto* found = value_member(std::forward<KeyType>(key)); | |
| return found != nullptr ? found->template get<ValueType>() : default_value; | |
| } | |
| /// @brief access specified object element with default value | |
| /// @sa https://json.nlohmann.me/api/basic_json/value/ | |
| template < class ValueType, class KeyType, class ReturnType = typename value_return_type<ValueType>::type, | |
| detail::enable_if_t < | |
| detail::is_transparent<object_comparator_t>::value | |
| && !detail::is_json_pointer<KeyType>::value | |
| && is_comparable_with_object_key<KeyType>::value | |
| && detail::is_getable<basic_json_t, ReturnType>::value | |
| && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 > | |
| ReturnType value(KeyType && key, ValueType && default_value) const | |
| { | |
| // If 'key' is found, return its value. Otherwise, return `default_value'. | |
| const auto* found = value_member(std::forward<KeyType>(key)); | |
| return found != nullptr ? found->template get<ReturnType>() : std::forward<ValueType>(default_value); | |
| } | |
| /// @brief access specified object element via JSON Pointer with default value | |
| /// @sa https://json.nlohmann.me/api/basic_json/value/ | |
| template < class ValueType, detail::enable_if_t < | |
| detail::is_getable<basic_json_t, ValueType>::value | |
| && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 > | |
| ValueType value(const json_pointer& ptr, const ValueType& default_value) const | |
| { | |
| // If the pointer resolves to a value, return it. Otherwise, return | |
| // 'default_value'. | |
| const auto* found = value_pointee(ptr); | |
| return found != nullptr ? found->template get<ValueType>() : default_value; | |
| } | |
| /// @brief access specified object element via JSON Pointer with default value | |
| /// @sa https://json.nlohmann.me/api/basic_json/value/ | |
| template < class ValueType, class ReturnType = typename value_return_type<ValueType>::type, | |
| detail::enable_if_t < | |
| detail::is_getable<basic_json_t, ReturnType>::value | |
| && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 > | |
| ReturnType value(const json_pointer& ptr, ValueType && default_value) const | |
| { | |
| // If the pointer resolves to a value, return it. Otherwise, return | |
| // 'default_value'. | |
| const auto* found = value_pointee(ptr); | |
| return found != nullptr ? found->template get<ReturnType>() : std::forward<ValueType>(default_value); | |
| } | |
| template < class ValueType, class BasicJsonType, detail::enable_if_t < | |
| detail::is_basic_json<BasicJsonType>::value | |
| && detail::is_getable<basic_json_t, ValueType>::value | |
| && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 > | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens) | |
| ValueType value(const ::nlohmann::json_pointer<BasicJsonType>& ptr, const ValueType& default_value) const | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return value(ptr.convert(), default_value); | |
| } | |
| #endif | |
| template < class ValueType, class BasicJsonType, class ReturnType = typename value_return_type<ValueType>::type, | |
| detail::enable_if_t < | |
| detail::is_basic_json<BasicJsonType>::value | |
| && detail::is_getable<basic_json_t, ReturnType>::value | |
| && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 > | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens) | |
| ReturnType value(const ::nlohmann::json_pointer<BasicJsonType>& ptr, ValueType && default_value) const | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return value(ptr.convert(), std::forward<ValueType>(default_value)); | |
| } | |
| #endif | |
| /// @brief access the first element | |
| /// @sa https://json.nlohmann.me/api/basic_json/front/ | |
| reference front() | |
| { | |
| return *begin(); | |
| } | |
| /// @brief access the first element | |
| /// @sa https://json.nlohmann.me/api/basic_json/front/ | |
| const_reference front() const | |
| { | |
| return *cbegin(); | |
| } | |
| /// @brief access the last element | |
| /// @sa https://json.nlohmann.me/api/basic_json/back/ | |
| reference back() | |
| { | |
| auto tmp = end(); | |
| --tmp; | |
| return *tmp; | |
| } | |
| /// @brief access the last element | |
| /// @sa https://json.nlohmann.me/api/basic_json/back/ | |
| const_reference back() const | |
| { | |
| auto tmp = cend(); | |
| --tmp; | |
| return *tmp; | |
| } | |
| /// @brief remove element given an iterator | |
| /// @sa https://json.nlohmann.me/api/basic_json/erase/ | |
| template < class IteratorType, detail::enable_if_t < | |
| std::is_same<IteratorType, typename basic_json_t::iterator>::value || | |
| std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int > = 0 > | |
| IteratorType erase(IteratorType pos) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| // make sure the iterator fits the current value | |
| if (JSON_HEDLEY_UNLIKELY(this != pos.m_object)) | |
| { | |
| throw_iterator_from_other_value(this); | |
| } | |
| IteratorType result = end(); | |
| switch (m_data.m_type) | |
| { | |
| case value_t::boolean: | |
| case value_t::number_float: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::string: | |
| case value_t::binary: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin())) | |
| { | |
| detail::throw_literal<invalid_iterator>(detail::exception_id::iterator_out_of_range, "iterator out of range", this); | |
| } | |
| reset_to_null_impl(); | |
| break; | |
| } | |
| case value_t::object: | |
| { | |
| result.m_it.object_iterator = erase_from_object(pos.m_it.object_iterator); | |
| set_parents_after_object_erase(); | |
| break; | |
| } | |
| case value_t::array: | |
| { | |
| result.m_it.array_iterator = m_data.m_value.array->erase(pos.m_it.array_iterator); | |
| break; | |
| } | |
| case value_t::null: | |
| case value_t::discarded: | |
| default: | |
| detail::throw_cannot_use_with(detail::exception_id::erase_wrong_type, "erase()", *this); | |
| } | |
| return result; | |
| } | |
| /// @brief remove elements given an iterator range | |
| /// @sa https://json.nlohmann.me/api/basic_json/erase/ | |
| template < class IteratorType, detail::enable_if_t < | |
| std::is_same<IteratorType, typename basic_json_t::iterator>::value || | |
| std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int > = 0 > | |
| IteratorType erase(IteratorType first, IteratorType last) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| // make sure the iterator fits the current value | |
| if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object)) | |
| { | |
| detail::throw_literal<invalid_iterator>(detail::exception_id::iterator_range_from_other_value, "iterators do not fit current value", this); | |
| } | |
| IteratorType result = end(); | |
| switch (m_data.m_type) | |
| { | |
| case value_t::boolean: | |
| case value_t::number_float: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::string: | |
| case value_t::binary: | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(!primitive_range_is_complete(first, last))) | |
| { | |
| detail::throw_literal<invalid_iterator>(detail::exception_id::iterator_range_out_of_range, "iterators out of range", this); | |
| } | |
| reset_to_null_impl(); | |
| break; | |
| } | |
| case value_t::object: | |
| { | |
| result.m_it.object_iterator = m_data.m_value.object->erase(first.m_it.object_iterator, | |
| last.m_it.object_iterator); | |
| set_parents_after_object_erase(); | |
| break; | |
| } | |
| case value_t::array: | |
| { | |
| result.m_it.array_iterator = m_data.m_value.array->erase(first.m_it.array_iterator, | |
| last.m_it.array_iterator); | |
| break; | |
| } | |
| case value_t::null: | |
| case value_t::discarded: | |
| default: | |
| detail::throw_cannot_use_with(detail::exception_id::erase_wrong_type, "erase()", *this); | |
| } | |
| return result; | |
| } | |
| private: | |
| template < typename KeyType, detail::enable_if_t < | |
| detail::has_erase_with_key_type<basic_json_t, KeyType>::value, int > = 0 > | |
| size_type erase_internal(KeyType && key) | |
| { | |
| // this erase only works for objects | |
| if (JSON_HEDLEY_UNLIKELY(!is_object())) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::erase_wrong_type, "erase()", *this); | |
| } | |
| const auto erased = m_data.m_value.object->erase(std::forward<KeyType>(key)); | |
| set_parents_after_object_erase(); | |
| return erased; | |
| } | |
| template < typename KeyType, detail::enable_if_t < | |
| !detail::has_erase_with_key_type<basic_json_t, KeyType>::value, int > = 0 > | |
| size_type erase_internal(KeyType && key) | |
| { | |
| // this erase only works for objects | |
| if (JSON_HEDLEY_UNLIKELY(!is_object())) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::erase_wrong_type, "erase()", *this); | |
| } | |
| const auto it = object_lookup(*this, std::forward<KeyType>(key)); | |
| if (it != m_data.m_value.object->end()) | |
| { | |
| m_data.m_value.object->erase(it); | |
| set_parents_after_object_erase(); | |
| return 1; | |
| } | |
| return 0; | |
| } | |
| public: | |
| /// @brief remove element from a JSON object given a key | |
| /// @sa https://json.nlohmann.me/api/basic_json/erase/ | |
| size_type erase(const typename object_t::key_type& key) | |
| { | |
| // the indirection via erase_internal() is added to avoid making this | |
| // function a template and thus de-rank it during overload resolution | |
| return erase_internal(key); | |
| } | |
| /// @brief remove element from a JSON object given a key | |
| /// @sa https://json.nlohmann.me/api/basic_json/erase/ | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0> | |
| size_type erase(KeyType && key) | |
| { | |
| return erase_internal(lookup_key(std::forward<KeyType>(key))); | |
| } | |
| /// @brief remove element from a JSON array given an index | |
| /// @sa https://json.nlohmann.me/api/basic_json/erase/ | |
| void erase(const size_type idx) | |
| { | |
| // this erase only works for arrays | |
| if (JSON_HEDLEY_LIKELY(is_array())) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(idx >= size())) | |
| { | |
| throw_array_index_out_of_range(idx, *this); | |
| } | |
| m_data.m_value.array->erase(m_data.m_value.array->begin() + static_cast<difference_type>(idx)); | |
| } | |
| else | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::erase_wrong_type, "erase()", *this); | |
| } | |
| } | |
| /// @} | |
| //////////// | |
| // lookup // | |
| //////////// | |
| /// @name lookup | |
| /// @{ | |
| // an integer literal 0 would otherwise convert to a null const char* and from there to key_type | |
| template<typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0> | |
| iterator find(T) = delete; | |
| template<typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0> | |
| const_iterator find(T) const = delete; | |
| template<typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0> | |
| size_type count(T) const = delete; | |
| template<typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0> | |
| bool contains(T) const = delete; | |
| /// @brief find an element in a JSON object | |
| /// @sa https://json.nlohmann.me/api/basic_json/find/ | |
| iterator find(const typename object_t::key_type& key) | |
| { | |
| auto result = end(); | |
| if (is_object()) | |
| { | |
| result.m_it.object_iterator = object_lookup(*this, key); | |
| } | |
| return result; | |
| } | |
| /// @brief find an element in a JSON object | |
| /// @sa https://json.nlohmann.me/api/basic_json/find/ | |
| const_iterator find(const typename object_t::key_type& key) const | |
| { | |
| auto result = cend(); | |
| if (is_object()) | |
| { | |
| result.m_it.object_iterator = object_lookup(*this, key); | |
| } | |
| return result; | |
| } | |
| /// @brief find an element in a JSON object | |
| /// @sa https://json.nlohmann.me/api/basic_json/find/ | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0> | |
| iterator find(KeyType && key) | |
| { | |
| auto result = end(); | |
| if (is_object()) | |
| { | |
| result.m_it.object_iterator = object_lookup(*this, std::forward<KeyType>(key)); | |
| } | |
| return result; | |
| } | |
| /// @brief find an element in a JSON object | |
| /// @sa https://json.nlohmann.me/api/basic_json/find/ | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0> | |
| const_iterator find(KeyType && key) const | |
| { | |
| auto result = cend(); | |
| if (is_object()) | |
| { | |
| result.m_it.object_iterator = object_lookup(*this, std::forward<KeyType>(key)); | |
| } | |
| return result; | |
| } | |
| /// @brief returns the number of occurrences of a key in a JSON object | |
| /// @sa https://json.nlohmann.me/api/basic_json/count/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| size_type count(const typename object_t::key_type& key) const | |
| { | |
| // return 0 for all nonobject types | |
| return is_object() ? m_data.m_value.object->count(key) : 0; | |
| } | |
| /// @brief returns the number of occurrences of a key in a JSON object | |
| /// @sa https://json.nlohmann.me/api/basic_json/count/ | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| size_type count(KeyType && key) const | |
| { | |
| // return 0 for all nonobject types | |
| return is_object() ? m_data.m_value.object->count(lookup_key(std::forward<KeyType>(key))) : 0; | |
| } | |
| /// @brief check the existence of an element in a JSON object | |
| /// @sa https://json.nlohmann.me/api/basic_json/contains/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| bool contains(const typename object_t::key_type& key) const | |
| { | |
| return is_object() && object_lookup(*this, key) != m_data.m_value.object->end(); | |
| } | |
| /// @brief check the existence of an element in a JSON object | |
| /// @sa https://json.nlohmann.me/api/basic_json/contains/ | |
| template<class KeyType, detail::enable_if_t< | |
| detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| bool contains(KeyType && key) const | |
| { | |
| return is_object() && object_lookup(*this, std::forward<KeyType>(key)) != m_data.m_value.object->end(); | |
| } | |
| /// @brief check the existence of an element in a JSON object given a JSON pointer | |
| /// @sa https://json.nlohmann.me/api/basic_json/contains/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| bool contains(const json_pointer& ptr) const | |
| { | |
| return ptr.contains(this); | |
| } | |
| template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens) | |
| bool contains(const typename ::nlohmann::json_pointer<BasicJsonType>& ptr) const | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return ptr.contains(this); | |
| } | |
| #endif | |
| /// @} | |
| /////////////// | |
| // iterators // | |
| /////////////// | |
| /// @name iterators | |
| /// @{ | |
| /// @brief returns an iterator to the first element | |
| /// @sa https://json.nlohmann.me/api/basic_json/begin/ | |
| iterator begin() noexcept | |
| { | |
| iterator result(this); | |
| result.set_begin(); | |
| return result; | |
| } | |
| /// @brief returns an iterator to the first element | |
| /// @sa https://json.nlohmann.me/api/basic_json/begin/ | |
| const_iterator begin() const noexcept | |
| { | |
| return cbegin(); | |
| } | |
| /// @brief returns a const iterator to the first element | |
| /// @sa https://json.nlohmann.me/api/basic_json/cbegin/ | |
| const_iterator cbegin() const noexcept | |
| { | |
| const_iterator result(this); | |
| result.set_begin(); | |
| return result; | |
| } | |
| /// @brief returns an iterator to one past the last element | |
| /// @sa https://json.nlohmann.me/api/basic_json/end/ | |
| iterator end() noexcept | |
| { | |
| iterator result(this); | |
| result.set_end(); | |
| return result; | |
| } | |
| /// @brief returns an iterator to one past the last element | |
| /// @sa https://json.nlohmann.me/api/basic_json/end/ | |
| const_iterator end() const noexcept | |
| { | |
| return cend(); | |
| } | |
| /// @brief returns an iterator to one past the last element | |
| /// @sa https://json.nlohmann.me/api/basic_json/cend/ | |
| const_iterator cend() const noexcept | |
| { | |
| const_iterator result(this); | |
| result.set_end(); | |
| return result; | |
| } | |
| /// @brief returns an iterator to the reverse-beginning | |
| /// @sa https://json.nlohmann.me/api/basic_json/rbegin/ | |
| reverse_iterator rbegin() noexcept | |
| { | |
| return reverse_iterator(end()); | |
| } | |
| /// @brief returns an iterator to the reverse-beginning | |
| /// @sa https://json.nlohmann.me/api/basic_json/rbegin/ | |
| const_reverse_iterator rbegin() const noexcept | |
| { | |
| return crbegin(); | |
| } | |
| /// @brief returns an iterator to the reverse-end | |
| /// @sa https://json.nlohmann.me/api/basic_json/rend/ | |
| reverse_iterator rend() noexcept | |
| { | |
| return reverse_iterator(begin()); | |
| } | |
| /// @brief returns an iterator to the reverse-end | |
| /// @sa https://json.nlohmann.me/api/basic_json/rend/ | |
| const_reverse_iterator rend() const noexcept | |
| { | |
| return crend(); | |
| } | |
| /// @brief returns a const reverse iterator to the last element | |
| /// @sa https://json.nlohmann.me/api/basic_json/crbegin/ | |
| const_reverse_iterator crbegin() const noexcept | |
| { | |
| return const_reverse_iterator(cend()); | |
| } | |
| /// @brief returns a const reverse iterator to one before the first | |
| /// @sa https://json.nlohmann.me/api/basic_json/crend/ | |
| const_reverse_iterator crend() const noexcept | |
| { | |
| return const_reverse_iterator(cbegin()); | |
| } | |
| public: | |
| /// @brief wrapper to access iterator member functions in range-based for | |
| /// @sa https://json.nlohmann.me/api/basic_json/items/ | |
| /// @deprecated This function is deprecated since 3.1.0 and will be removed in | |
| /// version 4.0.0 of the library. Please use @ref items() instead; | |
| /// that is, replace `json::iterator_wrapper(j)` with `j.items()`. | |
| JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) | |
| static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return ref.items(); | |
| } | |
| #endif | |
| /// @brief wrapper to access iterator member functions in range-based for | |
| /// @sa https://json.nlohmann.me/api/basic_json/items/ | |
| /// @deprecated This function is deprecated since 3.1.0 and will be removed in | |
| /// version 4.0.0 of the library. Please use @ref items() instead; | |
| /// that is, replace `json::iterator_wrapper(j)` with `j.items()`. | |
| JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) | |
| static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return ref.items(); | |
| } | |
| #endif | |
| /// @brief helper to access iterator member functions in range-based for | |
| /// @sa https://json.nlohmann.me/api/basic_json/items/ | |
| iteration_proxy<iterator> items() noexcept | |
| { | |
| return iteration_proxy<iterator>(*this); | |
| } | |
| /// @brief helper to access iterator member functions in range-based for | |
| /// @sa https://json.nlohmann.me/api/basic_json/items/ | |
| iteration_proxy<const_iterator> items() const noexcept | |
| { | |
| return iteration_proxy<const_iterator>(*this); | |
| } | |
| /// @} | |
| ////////////// | |
| // capacity // | |
| ////////////// | |
| /// @name capacity | |
| /// @{ | |
| /// @brief checks whether the container is empty. | |
| /// @sa https://json.nlohmann.me/api/basic_json/empty/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| bool empty() const noexcept | |
| { | |
| switch (m_data.m_type) | |
| { | |
| case value_t::null: | |
| { | |
| // null values are empty | |
| return true; | |
| } | |
| case value_t::array: | |
| { | |
| // delegate call to array_t::empty() | |
| return m_data.m_value.array->empty(); | |
| } | |
| case value_t::object: | |
| { | |
| // delegate call to object_t::empty() | |
| return m_data.m_value.object->empty(); | |
| } | |
| case value_t::string: | |
| case value_t::boolean: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| case value_t::binary: | |
| case value_t::discarded: | |
| default: | |
| { | |
| // all other types are nonempty | |
| return false; | |
| } | |
| } | |
| } | |
| /// @brief returns the number of elements | |
| /// @sa https://json.nlohmann.me/api/basic_json/size/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| size_type size() const noexcept | |
| { | |
| switch (m_data.m_type) | |
| { | |
| case value_t::null: | |
| { | |
| // null values are empty | |
| return 0; | |
| } | |
| case value_t::array: | |
| { | |
| // delegate call to array_t::size() | |
| return m_data.m_value.array->size(); | |
| } | |
| case value_t::object: | |
| { | |
| // delegate call to object_t::size() | |
| return m_data.m_value.object->size(); | |
| } | |
| case value_t::string: | |
| case value_t::boolean: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| case value_t::binary: | |
| case value_t::discarded: | |
| default: | |
| { | |
| // all other types have size 1 | |
| return 1; | |
| } | |
| } | |
| } | |
| /// @brief returns the maximum possible number of elements | |
| /// @sa https://json.nlohmann.me/api/basic_json/max_size/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| size_type max_size() const noexcept | |
| { | |
| if (m_data.m_type == value_t::array) | |
| { | |
| // delegate call to array_t::max_size() | |
| return m_data.m_value.array->max_size(); | |
| } | |
| if (m_data.m_type == value_t::object) | |
| { | |
| // delegate call to object_t::max_size() | |
| return m_data.m_value.object->max_size(); | |
| } | |
| // all other types have max_size() == size() | |
| return size(); | |
| } | |
| /// @} | |
| /////////////// | |
| // modifiers // | |
| /////////////// | |
| /// @name modifiers | |
| /// @{ | |
| /// @brief clears the contents | |
| /// @sa https://json.nlohmann.me/api/basic_json/clear/ | |
| void clear() noexcept | |
| { | |
| switch (m_data.m_type) | |
| { | |
| case value_t::number_integer: | |
| { | |
| m_data.m_value.number_integer = 0; | |
| break; | |
| } | |
| case value_t::number_unsigned: | |
| { | |
| m_data.m_value.number_unsigned = 0; | |
| break; | |
| } | |
| case value_t::number_float: | |
| { | |
| m_data.m_value.number_float = 0.0; | |
| break; | |
| } | |
| case value_t::boolean: | |
| { | |
| m_data.m_value.boolean = false; | |
| break; | |
| } | |
| case value_t::string: | |
| { | |
| m_data.m_value.string->clear(); | |
| break; | |
| } | |
| case value_t::binary: | |
| { | |
| m_data.m_value.binary->clear(); | |
| m_data.m_value.binary->clear_subtype(); | |
| break; | |
| } | |
| case value_t::array: | |
| { | |
| m_data.m_value.array->clear(); | |
| break; | |
| } | |
| case value_t::object: | |
| { | |
| m_data.m_value.object->clear(); | |
| break; | |
| } | |
| case value_t::null: | |
| case value_t::discarded: | |
| default: | |
| break; | |
| } | |
| } | |
| /// @brief add an object to an array | |
| /// @sa https://json.nlohmann.me/api/basic_json/push_back/ | |
| void push_back(basic_json&& val) | |
| { | |
| push_back_array_impl(std::move(val)); | |
| // if val is moved from, basic_json move constructor marks it null, so we do not call the destructor | |
| } | |
| /// @brief add an object to an array | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ | |
| reference operator+=(basic_json&& val) | |
| { | |
| push_back(std::move(val)); | |
| return *this; | |
| } | |
| /// @brief add an object to an array | |
| /// @sa https://json.nlohmann.me/api/basic_json/push_back/ | |
| void push_back(const basic_json& val) | |
| { | |
| push_back_array_impl(val); | |
| } | |
| /// @brief add an object to an array | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ | |
| reference operator+=(const basic_json& val) | |
| { | |
| push_back(val); | |
| return *this; | |
| } | |
| /// @brief add an object to an object | |
| /// @sa https://json.nlohmann.me/api/basic_json/push_back/ | |
| void push_back(const typename object_t::value_type& val) | |
| { | |
| // push_back only works for null objects or objects | |
| if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::push_back_wrong_type, "push_back()", *this); | |
| } | |
| // transform a null object into an object | |
| if (is_null()) | |
| { | |
| convert_null_to<object_t>(); | |
| } | |
| // add the element to the object | |
| const auto old_capacity = container_capacity(); | |
| auto res = m_data.m_value.object->insert(val); | |
| set_parent_after_insert(res.first->second, old_capacity); | |
| } | |
| /// @brief add an object to an object | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ | |
| reference operator+=(const typename object_t::value_type& val) | |
| { | |
| push_back(val); | |
| return *this; | |
| } | |
| /// @brief add an object to an object | |
| /// @sa https://json.nlohmann.me/api/basic_json/push_back/ | |
| void push_back(initializer_list_t init) | |
| { | |
| if (is_object() && init.size() == 2 && (*init.begin())->is_string()) | |
| { | |
| basic_json&& key = init.begin()->moved_or_copied(); | |
| push_back(typename object_t::value_type( | |
| std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied())); | |
| } | |
| else | |
| { | |
| push_back(basic_json(init)); | |
| } | |
| } | |
| /// @brief add an object to an object | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ | |
| reference operator+=(initializer_list_t init) | |
| { | |
| push_back(init); | |
| return *this; | |
| } | |
| /// @brief add an object to an array | |
| /// @sa https://json.nlohmann.me/api/basic_json/emplace_back/ | |
| template<class... Args> | |
| reference emplace_back(Args&& ... args) | |
| { | |
| // emplace_back only works for null objects or arrays | |
| if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::emplace_wrong_type, "emplace_back()", *this); | |
| } | |
| // transform a null object into an array | |
| if (is_null()) | |
| { | |
| convert_null_to<array_t>(); | |
| } | |
| // add the element to the array (perfect forwarding) | |
| const auto old_capacity = container_capacity(); | |
| m_data.m_value.array->emplace_back(std::forward<Args>(args)...); | |
| return set_parent_after_insert(m_data.m_value.array->back(), old_capacity); | |
| } | |
| /// @brief add an object to an object if key does not exist | |
| /// @sa https://json.nlohmann.me/api/basic_json/emplace/ | |
| template<class... Args> | |
| std::pair<iterator, bool> emplace(Args&& ... args) | |
| { | |
| // emplace only works for null objects or arrays | |
| if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::emplace_wrong_type, "emplace()", *this); | |
| } | |
| // transform a null object into an object | |
| if (is_null()) | |
| { | |
| convert_null_to<object_t>(); | |
| } | |
| // add the element to the array (perfect forwarding) | |
| const auto old_capacity = container_capacity(); | |
| auto res = m_data.m_value.object->emplace(std::forward<Args>(args)...); | |
| set_parent_after_insert(res.first->second, old_capacity); | |
| // create a result iterator and set iterator to the result of emplace | |
| auto it = begin(); | |
| it.m_it.object_iterator = res.first; | |
| // return pair of iterator and boolean | |
| return {it, res.second}; | |
| } | |
| /// Helper for insertion of an iterator | |
| /// @note: This uses std::distance to support GCC 4.8, | |
| /// see https://github.com/nlohmann/json/pull/1257 | |
| template<typename... Args> | |
| iterator insert_iterator(const_iterator pos, Args&& ... args) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| iterator result(this); | |
| JSON_ASSERT(m_data.m_value.array != nullptr); | |
| auto insert_pos = std::distance(m_data.m_value.array->begin(), pos.m_it.array_iterator); | |
| m_data.m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...); | |
| result.m_it.array_iterator = m_data.m_value.array->begin() + insert_pos; | |
| // This could have been written as: | |
| // result.m_it.array_iterator = m_data.m_value.array->insert(pos.m_it.array_iterator, cnt, val); | |
| // but the return value of insert is missing in GCC 4.8, so it is written this way instead. | |
| set_parents(); | |
| return result; | |
| } | |
| /// @brief inserts element into array | |
| /// @sa https://json.nlohmann.me/api/basic_json/insert/ | |
| iterator insert(const_iterator pos, const basic_json& val) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| // insert only works for arrays | |
| if (JSON_HEDLEY_UNLIKELY(!is_array())) | |
| { | |
| throw_insert_wrong_type(*this); | |
| } | |
| // check if iterator pos fits to this JSON value | |
| if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) | |
| { | |
| throw_iterator_from_other_value(this); | |
| } | |
| // insert to array and return iterator | |
| return insert_iterator(pos, val); | |
| } | |
| /// @brief inserts element into array | |
| /// @sa https://json.nlohmann.me/api/basic_json/insert/ | |
| iterator insert(const_iterator pos, basic_json&& val) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| // insert only works for arrays | |
| if (JSON_HEDLEY_UNLIKELY(!is_array())) | |
| { | |
| throw_insert_wrong_type(*this); | |
| } | |
| // check if iterator pos fits to this JSON value | |
| if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) | |
| { | |
| throw_iterator_from_other_value(this); | |
| } | |
| // moving into a local first keeps this safe even if val aliases | |
| // an element of this array | |
| basic_json tmp(std::move(val)); | |
| return insert_iterator(pos, std::move(tmp)); | |
| } | |
| /// @brief inserts copies of element into array | |
| /// @sa https://json.nlohmann.me/api/basic_json/insert/ | |
| iterator insert(const_iterator pos, size_type cnt, const basic_json& val) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| // insert only works for arrays | |
| if (JSON_HEDLEY_UNLIKELY(!is_array())) | |
| { | |
| throw_insert_wrong_type(*this); | |
| } | |
| // check if iterator pos fits to this JSON value | |
| if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) | |
| { | |
| throw_iterator_from_other_value(this); | |
| } | |
| // insert to array and return iterator | |
| return insert_iterator(pos, cnt, val); | |
| } | |
| /// @brief inserts range of elements into array | |
| /// @sa https://json.nlohmann.me/api/basic_json/insert/ | |
| iterator insert(const_iterator pos, const_iterator first, const_iterator last) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| // insert only works for arrays | |
| if (JSON_HEDLEY_UNLIKELY(!is_array())) | |
| { | |
| throw_insert_wrong_type(*this); | |
| } | |
| // check if iterator pos fits to this JSON value | |
| if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) | |
| { | |
| throw_iterator_from_other_value(this); | |
| } | |
| // check if range iterators belong to the same JSON object | |
| if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) | |
| { | |
| detail::throw_literal<invalid_iterator>(detail::exception_id::insert_range_incompatible, "iterators do not fit", this); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(first.m_object == this)) | |
| { | |
| detail::throw_literal<invalid_iterator>(detail::exception_id::insert_range_into_itself, "passed iterators may not belong to container", this); | |
| } | |
| // passed iterators must belong to arrays | |
| if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_array())) | |
| { | |
| detail::throw_literal<invalid_iterator>(detail::exception_id::iterator_from_other_value, "iterators first and last must point to arrays", this); | |
| } | |
| // insert to array and return iterator | |
| return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator); | |
| } | |
| /// @brief inserts elements from initializer list into array | |
| /// @sa https://json.nlohmann.me/api/basic_json/insert/ | |
| iterator insert(const_iterator pos, initializer_list_t ilist) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| // insert only works for arrays | |
| if (JSON_HEDLEY_UNLIKELY(!is_array())) | |
| { | |
| throw_insert_wrong_type(*this); | |
| } | |
| // check if iterator pos fits to this JSON value | |
| if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) | |
| { | |
| throw_iterator_from_other_value(this); | |
| } | |
| // copy the values first: ilist may refer to elements of this array | |
| array_t values; | |
| detail::reserve_array(values, ilist.size(), detail::priority_tag<1> {}); | |
| for (const auto& element : ilist) | |
| { | |
| values.push_back(element.moved_or_copied()); | |
| } | |
| // insert to array and return iterator | |
| return insert_iterator(pos, std::make_move_iterator(values.begin()), std::make_move_iterator(values.end())); | |
| } | |
| /// @brief inserts range of elements into object | |
| /// @sa https://json.nlohmann.me/api/basic_json/insert/ | |
| void insert(const_iterator first, const_iterator last) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| // insert only works for objects | |
| if (JSON_HEDLEY_UNLIKELY(!is_object())) | |
| { | |
| throw_insert_wrong_type(*this); | |
| } | |
| // check if range iterators belong to the same JSON object | |
| if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) | |
| { | |
| detail::throw_literal<invalid_iterator>(detail::exception_id::insert_range_incompatible, "iterators do not fit", this); | |
| } | |
| // passed iterators must belong to objects | |
| if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) | |
| { | |
| detail::throw_literal<invalid_iterator>(detail::exception_id::iterator_from_other_value, "iterators first and last must point to objects", this); | |
| } | |
| m_data.m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); | |
| set_parents(); | |
| } | |
| /// @brief updates a JSON object from another object, overwriting existing keys | |
| /// @sa https://json.nlohmann.me/api/basic_json/update/ | |
| void update(const_reference j, bool merge_objects = false) | |
| { | |
| prepare_update(); | |
| // passed value must be an object (checked here so a type_error names | |
| // j, not the copy made below) | |
| if (JSON_HEDLEY_UNLIKELY(!j.is_object())) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::update_wrong_type, "update()", j); | |
| } | |
| // copy first: j may be *this or one of its descendants, and is | |
| // iterated (and moved from) below to update *this | |
| basic_json source = j; | |
| update_from(source, merge_objects); | |
| } | |
| /// @brief updates a JSON object from another object, overwriting existing keys | |
| /// @sa https://json.nlohmann.me/api/basic_json/update/ | |
| void update(const_iterator first, const_iterator last, bool merge_objects = false) // NOLINT(performance-unnecessary-value-param) | |
| { | |
| prepare_update(); | |
| // check if range iterators belong to the same JSON object | |
| if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) | |
| { | |
| detail::throw_literal<invalid_iterator>(detail::exception_id::insert_range_incompatible, "iterators do not fit", this); | |
| } | |
| // passed iterators must belong to objects | |
| if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::update_wrong_type, "update()", *first.m_object); | |
| } | |
| // copy first: the range may belong to *this or one of its | |
| // descendants, and is iterated (and moved from) below to update | |
| // *this | |
| basic_json source(first, last); | |
| update_from(source, merge_objects); | |
| } | |
| private: | |
| /// @brief an object @ref update_members_iteratively or @ref | |
| /// merge_patch_iteratively is merging into, and the members still to merge | |
| struct merge_frame | |
| { | |
| merge_frame(basic_json* target_, iterator position_, iterator last_) noexcept | |
| : target(target_), position(std::move(position_)), last(std::move(last_)) | |
| {} | |
| basic_json* target; | |
| iterator position; | |
| iterator last; | |
| }; | |
| /// @brief converts a null value to an empty object and checks that this | |
| /// value is an object; called first by both @ref update overloads | |
| void prepare_update() | |
| { | |
| // implicitly convert a null value to an empty object | |
| if (is_null()) | |
| { | |
| convert_null_to<object_t>(); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(!is_object())) | |
| { | |
| detail::throw_cannot_use_with(detail::exception_id::update_wrong_type, "update()", *this); | |
| } | |
| } | |
| /// @brief starts the @ref update_members loop over an already-copied @a | |
| /// source; called by both @ref update overloads | |
| void update_from(basic_json& source, const bool merge_objects) | |
| { | |
| update_members(source.begin(), source.end(), merge_objects, 0); | |
| } | |
| /*! | |
| @brief the members loop of @ref update, for this object and range | |
| Merging a nested object calls this function again, once per nesting | |
| level, so a value nested deeply enough used to exhaust the call stack and | |
| terminate the process. The descent is bounded here: once @ref | |
| detail::recursion_depth_limit levels have been entered, @ref | |
| update_members_iteratively merges what is left without the call stack. | |
| @param[in] depth nesting level of this object, counted from the object | |
| @ref update was called on | |
| */ | |
| void update_members(const iterator& first, const iterator& last, const bool merge_objects, const std::size_t depth) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(depth >= detail::recursion_depth_limit())) | |
| { | |
| update_members_iteratively(first, last); | |
| return; | |
| } | |
| for (auto it = first; it != last; ++it) | |
| { | |
| if (merge_objects && it.value().is_object()) | |
| { | |
| const auto it2 = m_data.m_value.object->find(it.key()); | |
| // Only recurse when the existing value is itself an object. | |
| // Otherwise overwrite, matching the documented "all other values | |
| // are overwritten as usual" behavior (see #5402). | |
| if (it2 != m_data.m_value.object->end() && it2->second.is_object()) | |
| { | |
| it2->second.update_members(it.value().begin(), it.value().end(), true, depth + 1); | |
| continue; | |
| } | |
| } | |
| // operator[] repairs the other members if the object type moves | |
| // them; assigning through it keeps this O(1) per key | |
| operator[](it.key()) = std::move(it.value()); | |
| } | |
| } | |
| /*! | |
| @brief merge @a first to @a last into this object without the call stack | |
| Does the same as @ref update_members with `merge_objects` set, keeping the | |
| objects whose merge was interrupted by a nested one on an explicit stack | |
| instead of descending into them. A nested object is still merged | |
| completely before the next member, in the same order as the recursive | |
| version. Only reached for values nested deeper than @ref | |
| detail::recursion_depth_limit. | |
| */ | |
| void update_members_iteratively(iterator first, iterator last) | |
| { | |
| std::vector<merge_frame> stack; | |
| basic_json* target = this; | |
| while (true) | |
| { | |
| if (first == last) | |
| { | |
| if (stack.empty()) | |
| { | |
| break; | |
| } | |
| // a nested object is merged: continue with its parent | |
| target = stack.back().target; | |
| first = stack.back().position; | |
| last = stack.back().last; | |
| stack.pop_back(); | |
| continue; | |
| } | |
| if (first.value().is_object()) | |
| { | |
| const auto it2 = target->m_data.m_value.object->find(first.key()); | |
| if (it2 != target->m_data.m_value.object->end() && it2->second.is_object()) | |
| { | |
| basic_json& source = first.value(); | |
| ++first; | |
| stack.emplace_back(target, first, last); | |
| target = &it2->second; | |
| first = source.begin(); | |
| last = source.end(); | |
| continue; | |
| } | |
| } | |
| // operator[] repairs the other members if the object type moves them | |
| target->operator[](first.key()) = std::move(first.value()); | |
| ++first; | |
| } | |
| } | |
| public: | |
| /// @brief exchanges the values | |
| /// @sa https://json.nlohmann.me/api/basic_json/swap/ | |
| void swap(reference other) noexcept ( | |
| std::is_nothrow_move_constructible<value_t>::value&& | |
| std::is_nothrow_move_assignable<value_t>::value&& | |
| std::is_nothrow_move_constructible<json_value>::value&& // NOLINT(cppcoreguidelines-noexcept-swap,performance-noexcept-swap) | |
| std::is_nothrow_move_assignable<json_value>::value&& | |
| std::is_nothrow_move_constructible<json_base_class_t>::value&& | |
| std::is_nothrow_move_assignable<json_base_class_t>::value | |
| ) | |
| { | |
| std::swap(m_data.m_type, other.m_data.m_type); | |
| std::swap(m_data.m_value, other.m_data.m_value); | |
| // the custom base class travels with the value when it is copied or | |
| // moved, so it is exchanged along with it | |
| { | |
| using std::swap; | |
| swap(static_cast<json_base_class_t&>(*this), static_cast<json_base_class_t&>(other)); | |
| } | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| std::swap(start_position, other.start_position); | |
| std::swap(end_position, other.end_position); | |
| #endif | |
| set_parents(); | |
| other.set_parents(); | |
| assert_invariant(); | |
| } | |
| /// @brief exchanges the values | |
| /// @sa https://json.nlohmann.me/api/basic_json/swap/ | |
| friend void swap(reference left, reference right) noexcept ( | |
| std::is_nothrow_move_constructible<value_t>::value&& | |
| std::is_nothrow_move_assignable<value_t>::value&& | |
| std::is_nothrow_move_constructible<json_value>::value&& // NOLINT(cppcoreguidelines-noexcept-swap,performance-noexcept-swap) | |
| std::is_nothrow_move_assignable<json_value>::value&& | |
| std::is_nothrow_move_constructible<json_base_class_t>::value&& | |
| std::is_nothrow_move_assignable<json_base_class_t>::value | |
| ) | |
| { | |
| left.swap(right); | |
| } | |
| /// @brief exchanges the values | |
| /// @sa https://json.nlohmann.me/api/basic_json/swap/ | |
| void swap(array_t& other) // NOLINT(bugprone-exception-escape,cppcoreguidelines-noexcept-swap,performance-noexcept-swap) | |
| { | |
| swap_impl<array_t>(other, "swap(array_t&)"); | |
| set_parents(); | |
| } | |
| /// @brief exchanges the values | |
| /// @sa https://json.nlohmann.me/api/basic_json/swap/ | |
| void swap(object_t& other) // NOLINT(bugprone-exception-escape,cppcoreguidelines-noexcept-swap,performance-noexcept-swap) | |
| { | |
| swap_impl<object_t>(other, "swap(object_t&)"); | |
| set_parents(); | |
| } | |
| /// @brief exchanges the values | |
| /// @sa https://json.nlohmann.me/api/basic_json/swap/ | |
| void swap(string_t& other) // NOLINT(bugprone-exception-escape,cppcoreguidelines-noexcept-swap,performance-noexcept-swap) | |
| { | |
| swap_impl<string_t>(other, "swap(string_t&)"); | |
| } | |
| /// @brief exchanges the values | |
| /// @sa https://json.nlohmann.me/api/basic_json/swap/ | |
| void swap(binary_t& other) // NOLINT(bugprone-exception-escape,cppcoreguidelines-noexcept-swap,performance-noexcept-swap) | |
| { | |
| swap_impl<binary_t>(other, "swap(binary_t&)"); | |
| } | |
| /// @brief exchanges the values | |
| /// @sa https://json.nlohmann.me/api/basic_json/swap/ | |
| void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape) | |
| { | |
| swap_impl<binary_t>(other, "swap(binary_t::container_type&)"); | |
| } | |
| /// @} | |
| ////////////////////////////////////////// | |
| // lexicographical comparison operators // | |
| ////////////////////////////////////////// | |
| /// @name lexicographical comparison operators | |
| /// @{ | |
| // the same-type cases for non-owning scalars, shared by JSON_IMPLEMENT_OPERATOR | |
| // and JSON_IMPLEMENT_SCALAR_FAST | |
| #define JSON_IMPLEMENT_SCALAR_CASES(op, null_result) \ | |
| case value_t::null: \ | |
| return (null_result); \ | |
| case value_t::boolean: \ | |
| return lhs.m_data.m_value.boolean op rhs.m_data.m_value.boolean; \ | |
| case value_t::number_integer: \ | |
| return lhs.m_data.m_value.number_integer op rhs.m_data.m_value.number_integer; \ | |
| case value_t::number_unsigned: \ | |
| return lhs.m_data.m_value.number_unsigned op rhs.m_data.m_value.number_unsigned; \ | |
| case value_t::number_float: \ | |
| return lhs.m_data.m_value.number_float op rhs.m_data.m_value.number_float; | |
| // note parentheses around the container operands are necessary, because | |
| // GCC otherwise parses `array <` as std::array; see | |
| // https://github.com/nlohmann/json/issues/1530 | |
| // Mixed signed/unsigned integer comparisons check whether the signed value | |
| // is negative before casting. If it is, the comparison is performed with | |
| // the fixed values -1 and 1, which preserves the ordering relationship | |
| // because any negative signed value is smaller than any unsigned value. | |
| // Otherwise, the non-negative signed value is cast to unsigned before the | |
| // comparison to avoid wraparound. | |
| #define JSON_IMPLEMENT_OPERATOR(op, null_result, unordered_result, default_result, deep_result, may_descend) \ | |
| const auto lhs_type = lhs.type(); \ | |
| const auto rhs_type = rhs.type(); \ | |
| \ | |
| if (lhs_type == rhs_type) /* NOLINT(readability/braces) */ \ | |
| { \ | |
| switch (lhs_type) \ | |
| { \ | |
| case value_t::array: \ | |
| { \ | |
| if (JSON_HEDLEY_UNLIKELY(nesting_depth_exhausted(may_descend))) \ | |
| { \ | |
| return (deep_result); \ | |
| } \ | |
| const nesting_depth_guard guard; \ | |
| return (*lhs.m_data.m_value.array) op (*rhs.m_data.m_value.array); \ | |
| } \ | |
| \ | |
| case value_t::object: \ | |
| { \ | |
| if (JSON_HEDLEY_UNLIKELY(nesting_depth_exhausted(may_descend))) \ | |
| { \ | |
| return (deep_result); \ | |
| } \ | |
| const nesting_depth_guard guard; \ | |
| return (*lhs.m_data.m_value.object) op (*rhs.m_data.m_value.object); \ | |
| } \ | |
| \ | |
| JSON_IMPLEMENT_SCALAR_CASES(op, null_result) \ | |
| \ | |
| case value_t::string: \ | |
| return (*lhs.m_data.m_value.string) op (*rhs.m_data.m_value.string); \ | |
| \ | |
| case value_t::binary: \ | |
| return (*lhs.m_data.m_value.binary) op (*rhs.m_data.m_value.binary); \ | |
| \ | |
| case value_t::discarded: \ | |
| default: \ | |
| return (unordered_result); \ | |
| } \ | |
| } \ | |
| else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) \ | |
| { \ | |
| return (detail::compare_integer_with_float(lhs.m_data.m_value.number_integer, rhs.m_data.m_value.number_float)) op (static_cast<number_float_t>(0)); \ | |
| } \ | |
| else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) \ | |
| { \ | |
| return (static_cast<number_float_t>(0)) op (detail::compare_integer_with_float(rhs.m_data.m_value.number_integer, lhs.m_data.m_value.number_float)); \ | |
| } \ | |
| else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) \ | |
| { \ | |
| return (detail::compare_integer_with_float(lhs.m_data.m_value.number_unsigned, rhs.m_data.m_value.number_float)) op (static_cast<number_float_t>(0)); \ | |
| } \ | |
| else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) \ | |
| { \ | |
| return (static_cast<number_float_t>(0)) op (detail::compare_integer_with_float(rhs.m_data.m_value.number_unsigned, lhs.m_data.m_value.number_float)); \ | |
| } \ | |
| else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) \ | |
| { \ | |
| return (rhs.m_data.m_value.number_integer < 0) \ | |
| ? (number_integer_t(1) op number_integer_t(-1)) \ | |
| : (lhs.m_data.m_value.number_unsigned op static_cast<number_unsigned_t>(rhs.m_data.m_value.number_integer)); \ | |
| } \ | |
| else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) \ | |
| { \ | |
| return (lhs.m_data.m_value.number_integer < 0) \ | |
| ? (number_integer_t(-1) op number_integer_t(1)) \ | |
| : (static_cast<number_unsigned_t>(lhs.m_data.m_value.number_integer) op rhs.m_data.m_value.number_unsigned); \ | |
| } \ | |
| else if(compares_unordered(lhs, rhs))\ | |
| {\ | |
| return (unordered_result);\ | |
| }\ | |
| \ | |
| return (default_result); | |
| // inline fast path for two values of the same non-owning scalar type; anything | |
| // else falls through to the out-of-line general comparison | |
| #define JSON_IMPLEMENT_SCALAR_FAST(op, null_result) \ | |
| if (lhs.m_data.m_type == rhs.m_data.m_type) /* NOLINT(readability/braces) */ \ | |
| { \ | |
| switch (lhs.m_data.m_type) \ | |
| { \ | |
| JSON_IMPLEMENT_SCALAR_CASES(op, null_result) \ | |
| case value_t::object: \ | |
| case value_t::array: \ | |
| case value_t::string: \ | |
| case value_t::binary: \ | |
| case value_t::discarded: \ | |
| default: \ | |
| break; \ | |
| } \ | |
| } | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| // returns true if: | |
| // - any operand is NaN and the other operand is of number type | |
| // - any operand is discarded | |
| // in legacy mode, discarded values are considered ordered if | |
| // an operation is computed as an odd number of inverses of others | |
| static bool compares_unordered(const_reference lhs, const_reference rhs, bool inverse = false) noexcept | |
| { | |
| if ((lhs.is_number_float() && std::isnan(lhs.m_data.m_value.number_float) && rhs.is_number()) | |
| || (rhs.is_number_float() && std::isnan(rhs.m_data.m_value.number_float) && lhs.is_number())) | |
| { | |
| return true; | |
| } | |
| #if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON | |
| return (lhs.is_discarded() || rhs.is_discarded()) && !inverse; | |
| #else | |
| static_cast<void>(inverse); | |
| return lhs.is_discarded() || rhs.is_discarded(); | |
| #endif | |
| } | |
| private: | |
| bool compares_unordered(const_reference rhs, bool inverse = false) const noexcept | |
| { | |
| return compares_unordered(*this, rhs, inverse); | |
| } | |
| /// @brief whether objects and arrays are the standard containers, whose | |
| /// elements equal_bounded() may therefore compare itself | |
| using standard_object_t = std::map<StringType, basic_json, default_object_comparator_t, | |
| AllocatorType<std::pair<const StringType, basic_json>>>; | |
| using standard_array_t = std::vector<basic_json, AllocatorType<basic_json>>; | |
| using equal_bounded_containers = detail::conjunction<std::is_same<object_t, standard_object_t>, std::is_same<array_t, standard_array_t>>; | |
| // out-of-line general comparisons; the operators below handle same-type | |
| // scalars inline and fall through to these | |
| JSON_HEDLEY_NEVER_INLINE | |
| static bool equal_general(const_reference lhs, const_reference rhs) noexcept | |
| { | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") | |
| #endif | |
| JSON_IMPLEMENT_OPERATOR( ==, true, false, false, | |
| compare_iteratively<false>(lhs, rhs, false) == compare_result::equal, true) | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| } | |
| #if JSON_HAS_THREE_WAY_COMPARISON | |
| JSON_HEDLEY_NEVER_INLINE | |
| static std::partial_ordering three_way_general(const_reference lhs, const_reference rhs) noexcept // *NOPAD* | |
| { | |
| // default_result is used if we cannot compare values. In that case, | |
| // we compare types. | |
| JSON_IMPLEMENT_OPERATOR(<=>, // *NOPAD* | |
| std::partial_ordering::equivalent, | |
| std::partial_ordering::unordered, | |
| lhs_type <=> rhs_type, // *NOPAD* | |
| to_partial_ordering(compare_iteratively<true>(lhs, rhs, false)), true) | |
| } | |
| #else | |
| JSON_HEDLEY_NEVER_INLINE | |
| static bool less_general(const_reference lhs, const_reference rhs) noexcept | |
| { | |
| // default_result is used if we cannot compare values. In that case, | |
| // we compare types. Note we have to call the operator explicitly, | |
| // because MSVC has problems otherwise. | |
| JSON_IMPLEMENT_OPERATOR( <, false, false, operator<(lhs_type, rhs_type), | |
| compare_iteratively<true>(lhs, rhs, true) == compare_result::less, false) | |
| } | |
| #endif | |
| /// @brief compare two leaves of the same type inside equal_structured() | |
| /// @return 1 if they are equal, 0 if they are not, and -1 if the values are | |
| /// of different types or are not handled here, which this leaves to | |
| /// equal_structured() | |
| /// @note Unlike JSON_IMPLEMENT_SCALAR_FAST, this also compares strings: | |
| /// they are the most common leaves in a document, so comparing them | |
| /// inline pays off in the container walk, while the operators keep | |
| /// their inlined code at each call site small. Binary values are | |
| /// rare and left to equal_general(). | |
| JSON_HEDLEY_ALWAYS_INLINE | |
| static int equal_leaf(const_reference lhs, const_reference rhs) noexcept | |
| { | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") | |
| #endif | |
| if (lhs.m_data.m_type == rhs.m_data.m_type) | |
| { | |
| switch (lhs.m_data.m_type) | |
| { | |
| case value_t::null: | |
| return 1; | |
| case value_t::boolean: | |
| return lhs.m_data.m_value.boolean == rhs.m_data.m_value.boolean; | |
| case value_t::number_integer: | |
| return lhs.m_data.m_value.number_integer == rhs.m_data.m_value.number_integer; | |
| case value_t::number_unsigned: | |
| return lhs.m_data.m_value.number_unsigned == rhs.m_data.m_value.number_unsigned; | |
| case value_t::number_float: | |
| return lhs.m_data.m_value.number_float == rhs.m_data.m_value.number_float; | |
| case value_t::string: | |
| return *lhs.m_data.m_value.string == *rhs.m_data.m_value.string; | |
| case value_t::object: | |
| case value_t::array: | |
| case value_t::binary: | |
| case value_t::discarded: | |
| default: | |
| break; | |
| } | |
| } | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| return -1; | |
| } | |
| /// @brief compare for equality, walking objects and arrays here instead of | |
| /// in their containers so that the depth is a parameter and needs no | |
| /// thread-local count; only used for the standard containers | |
| static bool equal_bounded(const_reference lhs, const_reference rhs, std::size_t depth) noexcept | |
| { | |
| const int leaf = equal_leaf(lhs, rhs); | |
| return leaf < 0 ? equal_structured(lhs, rhs, depth) : leaf != 0; | |
| } | |
| static bool equal_structured(const_reference lhs, const_reference rhs, std::size_t depth) noexcept | |
| { | |
| const auto type = lhs.m_data.m_type; | |
| if (type != rhs.m_data.m_type || (type != value_t::array && type != value_t::object)) | |
| { | |
| return equal_general(lhs, rhs); | |
| } | |
| if (JSON_HEDLEY_UNLIKELY(depth >= detail::recursion_depth_limit())) | |
| { | |
| return compare_iteratively<false>(lhs, rhs, false) == compare_result::equal; | |
| } | |
| if (type == value_t::array) | |
| { | |
| const auto& a = *lhs.m_data.m_value.array; | |
| const auto& b = *rhs.m_data.m_value.array; | |
| if (a.size() != b.size()) | |
| { | |
| return false; | |
| } | |
| auto it_b = b.cbegin(); | |
| for (auto it_a = a.cbegin(); it_a != a.cend(); ++it_a, ++it_b) | |
| { | |
| const int leaf = equal_leaf(*it_a, *it_b); | |
| if (leaf < 0 ? !equal_structured(*it_a, *it_b, depth + 1) : leaf == 0) | |
| { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| const auto& a = *lhs.m_data.m_value.object; | |
| const auto& b = *rhs.m_data.m_value.object; | |
| if (a.size() != b.size()) | |
| { | |
| return false; | |
| } | |
| auto it_b = b.cbegin(); | |
| for (auto it_a = a.cbegin(); it_a != a.cend(); ++it_a, ++it_b) | |
| { | |
| if (!(it_a->first == it_b->first)) | |
| { | |
| return false; | |
| } | |
| const int leaf = equal_leaf(it_a->second, it_b->second); | |
| if (leaf < 0 ? !equal_structured(it_a->second, it_b->second, depth + 1) : leaf == 0) | |
| { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| static bool equal_dispatch(const_reference lhs, const_reference rhs, std::true_type /*standard containers*/) noexcept | |
| { | |
| return equal_bounded(lhs, rhs, 0); | |
| } | |
| static bool equal_dispatch(const_reference lhs, const_reference rhs, std::false_type /*other containers*/) noexcept | |
| { | |
| return equal_general(lhs, rhs); | |
| } | |
| public: | |
| #if JSON_HAS_THREE_WAY_COMPARISON | |
| /// @brief comparison: equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ | |
| bool operator==(const_reference rhs) const noexcept | |
| { | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") | |
| #endif | |
| const_reference lhs = *this; | |
| JSON_IMPLEMENT_SCALAR_FAST( ==, true) | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| return equal_dispatch(lhs, rhs, equal_bounded_containers {}); | |
| } | |
| /// @brief comparison: equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ | |
| template<typename ScalarType> | |
| requires std::is_scalar_v<ScalarType> | |
| bool operator==(ScalarType rhs) const noexcept(std::is_nothrow_constructible<basic_json, ScalarType>::value) | |
| { | |
| return *this == basic_json(rhs); | |
| } | |
| /// @brief comparison: 3-way | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_spaceship/ | |
| std::partial_ordering operator<=>(const_reference rhs) const noexcept // *NOPAD* | |
| { | |
| const_reference lhs = *this; | |
| JSON_IMPLEMENT_SCALAR_FAST(<=>, std::partial_ordering::equivalent) // *NOPAD* | |
| return three_way_general(lhs, rhs); | |
| } | |
| /// @brief comparison: 3-way | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_spaceship/ | |
| template<typename ScalarType> | |
| requires std::is_scalar_v<ScalarType> | |
| std::partial_ordering operator<=>(ScalarType rhs) const noexcept(std::is_nothrow_constructible<basic_json, ScalarType>::value) // *NOPAD* | |
| { | |
| return *this <=> basic_json(rhs); // *NOPAD* | |
| } | |
| #if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON | |
| // all operators that are computed as an odd number of inverses of others | |
| // need to be overloaded to emulate the legacy comparison behavior | |
| /// @brief comparison: less than or equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.0, undef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON) | |
| bool operator<=(const_reference rhs) const noexcept | |
| { | |
| if (compares_unordered(rhs, true)) | |
| { | |
| return false; | |
| } | |
| return !(rhs < *this); | |
| } | |
| /// @brief comparison: less than or equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ | |
| template<typename ScalarType> | |
| requires std::is_scalar_v<ScalarType> | |
| bool operator<=(ScalarType rhs) const noexcept(std::is_nothrow_constructible<basic_json, ScalarType>::value) | |
| { | |
| return *this <= basic_json(rhs); | |
| } | |
| /// @brief comparison: greater than or equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.0, undef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON) | |
| bool operator>=(const_reference rhs) const noexcept | |
| { | |
| if (compares_unordered(rhs, true)) | |
| { | |
| return false; | |
| } | |
| return !(*this < rhs); | |
| } | |
| /// @brief comparison: greater than or equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ | |
| template<typename ScalarType> | |
| requires std::is_scalar_v<ScalarType> | |
| bool operator>=(ScalarType rhs) const noexcept(std::is_nothrow_constructible<basic_json, ScalarType>::value) | |
| { | |
| return *this >= basic_json(rhs); | |
| } | |
| // a scalar on the left-hand side would otherwise select the candidate | |
| // rewritten from operator<=>, which does not emulate the legacy behavior | |
| /// @brief comparison: less than or equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ | |
| template<typename ScalarType> | |
| requires std::is_scalar_v<ScalarType> | |
| friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(rhs)>, ScalarType>::value) | |
| { | |
| return basic_json(lhs) <= rhs; | |
| } | |
| /// @brief comparison: greater than or equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ | |
| template<typename ScalarType> | |
| requires std::is_scalar_v<ScalarType> | |
| friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(rhs)>, ScalarType>::value) | |
| { | |
| return basic_json(lhs) >= rhs; | |
| } | |
| #endif | |
| #else | |
| /// @brief comparison: equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ | |
| friend bool operator==(const_reference lhs, const_reference rhs) noexcept | |
| { | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| JSON_HEDLEY_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") | |
| #endif | |
| JSON_IMPLEMENT_SCALAR_FAST( ==, true) | |
| #ifdef __GNUC__ | |
| JSON_HEDLEY_DIAGNOSTIC_POP | |
| #endif | |
| return equal_dispatch(lhs, rhs, equal_bounded_containers {}); | |
| } | |
| // The friend comparisons with a scalar name the JSON type via decltype of | |
| // their parameter in noexcept, because older MSVC versions do not see the | |
| // class scope there: MSVC 2015 and 2017 take basic_json as the template, | |
| // and MSVC 2019 16.0 rejects member types and template parameters. | |
| /// @brief comparison: equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ | |
| template<typename ScalarType, typename std::enable_if< | |
| std::is_scalar<ScalarType>::value, int>::type = 0> | |
| friend bool operator==(const_reference lhs, ScalarType rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(lhs)>, ScalarType>::value) | |
| { | |
| return lhs == basic_json(rhs); | |
| } | |
| /// @brief comparison: equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ | |
| template<typename ScalarType, typename std::enable_if< | |
| std::is_scalar<ScalarType>::value, int>::type = 0> | |
| friend bool operator==(ScalarType lhs, const_reference rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(rhs)>, ScalarType>::value) | |
| { | |
| return basic_json(lhs) == rhs; | |
| } | |
| /// @brief comparison: not equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ | |
| friend bool operator!=(const_reference lhs, const_reference rhs) noexcept | |
| { | |
| return !(lhs == rhs); | |
| } | |
| /// @brief comparison: not equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ | |
| template<typename ScalarType, typename std::enable_if< | |
| std::is_scalar<ScalarType>::value, int>::type = 0> | |
| friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(lhs)>, ScalarType>::value) | |
| { | |
| return lhs != basic_json(rhs); | |
| } | |
| /// @brief comparison: not equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ | |
| template<typename ScalarType, typename std::enable_if< | |
| std::is_scalar<ScalarType>::value, int>::type = 0> | |
| friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(rhs)>, ScalarType>::value) | |
| { | |
| return basic_json(lhs) != rhs; | |
| } | |
| /// @brief comparison: less than | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ | |
| friend bool operator<(const_reference lhs, const_reference rhs) noexcept | |
| { | |
| JSON_IMPLEMENT_SCALAR_FAST( <, false) | |
| return less_general(lhs, rhs); | |
| } | |
| /// @brief comparison: less than | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ | |
| template<typename ScalarType, typename std::enable_if< | |
| std::is_scalar<ScalarType>::value, int>::type = 0> | |
| friend bool operator<(const_reference lhs, ScalarType rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(lhs)>, ScalarType>::value) | |
| { | |
| return lhs < basic_json(rhs); | |
| } | |
| /// @brief comparison: less than | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ | |
| template<typename ScalarType, typename std::enable_if< | |
| std::is_scalar<ScalarType>::value, int>::type = 0> | |
| friend bool operator<(ScalarType lhs, const_reference rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(rhs)>, ScalarType>::value) | |
| { | |
| return basic_json(lhs) < rhs; | |
| } | |
| /// @brief comparison: less than or equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ | |
| friend bool operator<=(const_reference lhs, const_reference rhs) noexcept | |
| { | |
| if (compares_unordered(lhs, rhs, true)) | |
| { | |
| return false; | |
| } | |
| return !(rhs < lhs); | |
| } | |
| /// @brief comparison: less than or equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ | |
| template<typename ScalarType, typename std::enable_if< | |
| std::is_scalar<ScalarType>::value, int>::type = 0> | |
| friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(lhs)>, ScalarType>::value) | |
| { | |
| return lhs <= basic_json(rhs); | |
| } | |
| /// @brief comparison: less than or equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ | |
| template<typename ScalarType, typename std::enable_if< | |
| std::is_scalar<ScalarType>::value, int>::type = 0> | |
| friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(rhs)>, ScalarType>::value) | |
| { | |
| return basic_json(lhs) <= rhs; | |
| } | |
| /// @brief comparison: greater than | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ | |
| friend bool operator>(const_reference lhs, const_reference rhs) noexcept | |
| { | |
| // double inverse | |
| if (compares_unordered(lhs, rhs)) | |
| { | |
| return false; | |
| } | |
| return !(lhs <= rhs); | |
| } | |
| /// @brief comparison: greater than | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ | |
| template<typename ScalarType, typename std::enable_if< | |
| std::is_scalar<ScalarType>::value, int>::type = 0> | |
| friend bool operator>(const_reference lhs, ScalarType rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(lhs)>, ScalarType>::value) | |
| { | |
| return lhs > basic_json(rhs); | |
| } | |
| /// @brief comparison: greater than | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ | |
| template<typename ScalarType, typename std::enable_if< | |
| std::is_scalar<ScalarType>::value, int>::type = 0> | |
| friend bool operator>(ScalarType lhs, const_reference rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(rhs)>, ScalarType>::value) | |
| { | |
| return basic_json(lhs) > rhs; | |
| } | |
| /// @brief comparison: greater than or equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ | |
| friend bool operator>=(const_reference lhs, const_reference rhs) noexcept | |
| { | |
| if (compares_unordered(lhs, rhs, true)) | |
| { | |
| return false; | |
| } | |
| return !(lhs < rhs); | |
| } | |
| /// @brief comparison: greater than or equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ | |
| template<typename ScalarType, typename std::enable_if< | |
| std::is_scalar<ScalarType>::value, int>::type = 0> | |
| friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(lhs)>, ScalarType>::value) | |
| { | |
| return lhs >= basic_json(rhs); | |
| } | |
| /// @brief comparison: greater than or equal | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ | |
| template<typename ScalarType, typename std::enable_if< | |
| std::is_scalar<ScalarType>::value, int>::type = 0> | |
| friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept(std::is_nothrow_constructible<detail::uncvref_t<decltype(rhs)>, ScalarType>::value) | |
| { | |
| return basic_json(lhs) >= rhs; | |
| } | |
| #endif | |
| #undef JSON_IMPLEMENT_OPERATOR | |
| #undef JSON_IMPLEMENT_SCALAR_FAST | |
| #undef JSON_IMPLEMENT_SCALAR_CASES | |
| /// @} | |
| /////////////////// | |
| // serialization // | |
| /////////////////// | |
| /// @name serialization | |
| /// @{ | |
| #ifndef JSON_NO_IO | |
| /// @brief serialize to stream | |
| /// @sa https://json.nlohmann.me/api/operator_ltlt/ | |
| friend std::ostream& operator<<(std::ostream& o, const basic_json& j) | |
| { | |
| // read width member and use it as the indentation parameter if nonzero | |
| const bool pretty_print = o.width() > 0; | |
| const auto indentation = pretty_print ? o.width() : 0; | |
| // reset width to 0 for subsequent calls to this stream | |
| o.width(0); | |
| // do the actual serialization | |
| detail::output_stream_adapter<char> stream_adapter(o); | |
| serializer s(stream_adapter, o.fill(), | |
| pretty_print, false, static_cast<std::size_t>(indentation)); | |
| s.dump(j); | |
| return o; | |
| } | |
| #if !JSON_DELETE_DEPRECATED_FUNCTIONS | |
| // the deleted version is a function template after the class, because | |
| // GCC < 5 and Clang < 10 reject deleted friend functions in class templates | |
| /// @brief serialize to stream | |
| /// @sa https://json.nlohmann.me/api/operator_ltlt/ | |
| /// @deprecated This function is deprecated since 3.0.0 and will be removed in | |
| /// version 4.0.0 of the library. Please use | |
| /// operator<<(std::ostream&, const basic_json&) instead; that is, | |
| /// replace calls like `j >> o;` with `o << j;`. | |
| JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&)) | |
| friend std::ostream& operator>>(const basic_json& j, std::ostream& o) | |
| { | |
| return o << j; | |
| } | |
| #endif | |
| #endif // JSON_NO_IO | |
| /// @} | |
| ///////////////////// | |
| // deserialization // | |
| ///////////////////// | |
| /// @name deserialization | |
| /// @{ | |
| /// @brief deserialize from a compatible input | |
| /// @sa https://json.nlohmann.me/api/basic_json/parse/ | |
| template<typename InputType> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json parse(InputType&& i, | |
| parser_callback_t cb = nullptr, | |
| const bool allow_exceptions = true, | |
| const bool ignore_comments = false, | |
| const bool ignore_trailing_commas = false) | |
| { | |
| return parse_impl(detail::input_adapter(std::forward<InputType>(i)), std::move(cb), allow_exceptions, ignore_comments, ignore_trailing_commas); | |
| } | |
| /// @brief deserialize from a pair of character iterators (or an iterator+sentinel pair, C++20 ranges support) | |
| /// @sa https://json.nlohmann.me/api/basic_json/parse/ | |
| template<typename IteratorType, typename SentinelType = IteratorType, | |
| detail::enable_if_t<detail::can_compare_ne<IteratorType, SentinelType>::value, int> = 0> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json parse(IteratorType first, | |
| SentinelType last, | |
| parser_callback_t cb = nullptr, | |
| const bool allow_exceptions = true, | |
| const bool ignore_comments = false, | |
| const bool ignore_trailing_commas = false) | |
| { | |
| return parse_impl(detail::input_adapter(std::move(first), std::move(last)), std::move(cb), allow_exceptions, ignore_comments, ignore_trailing_commas); | |
| } | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len)) | |
| static basic_json parse(detail::span_input_adapter&& i, | |
| parser_callback_t cb = nullptr, | |
| const bool allow_exceptions = true, | |
| const bool ignore_comments = false, | |
| const bool ignore_trailing_commas = false) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return parse_impl(i.get(), std::move(cb), allow_exceptions, ignore_comments, ignore_trailing_commas); | |
| } | |
| #endif | |
| /// @brief check if the input is valid JSON | |
| /// @sa https://json.nlohmann.me/api/basic_json/accept/ | |
| template<typename InputType> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static bool accept(InputType&& i, | |
| const bool ignore_comments = false, | |
| const bool ignore_trailing_commas = false) | |
| { | |
| return accept_impl(detail::input_adapter(std::forward<InputType>(i)), ignore_comments, ignore_trailing_commas); | |
| } | |
| /// @brief check if the input is valid JSON (iterator pair, or iterator+sentinel pair for C++20 ranges support) | |
| /// @sa https://json.nlohmann.me/api/basic_json/accept/ | |
| template<typename IteratorType, typename SentinelType = IteratorType, | |
| detail::enable_if_t<detail::can_compare_ne<IteratorType, SentinelType>::value, int> = 0> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static bool accept(IteratorType first, SentinelType last, | |
| const bool ignore_comments = false, | |
| const bool ignore_trailing_commas = false) | |
| { | |
| return accept_impl(detail::input_adapter(std::move(first), std::move(last)), ignore_comments, ignore_trailing_commas); | |
| } | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len)) | |
| static bool accept(detail::span_input_adapter&& i, | |
| const bool ignore_comments = false, | |
| const bool ignore_trailing_commas = false) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return accept_impl(i.get(), ignore_comments, ignore_trailing_commas); | |
| } | |
| #endif | |
| /// @brief generate SAX events | |
| /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ | |
| template <typename InputType, typename SAX> | |
| JSON_HEDLEY_NON_NULL(2) | |
| static bool sax_parse(InputType&& i, SAX* sax, | |
| input_format_t format = input_format_t::json, | |
| const bool strict = true, | |
| const bool ignore_comments = false, | |
| const bool ignore_trailing_commas = false, | |
| const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) | |
| { | |
| return sax_parse_impl(detail::input_adapter(std::forward<InputType>(i)), sax, format, strict, ignore_comments, ignore_trailing_commas, tag_handler); | |
| } | |
| /// @brief generate SAX events (iterator pair, or iterator+sentinel pair for C++20 ranges support) | |
| /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ | |
| template<class IteratorType, class SAX, class SentinelType = IteratorType, | |
| detail::enable_if_t<detail::can_compare_ne<IteratorType, SentinelType>::value, int> = 0> | |
| JSON_HEDLEY_NON_NULL(3) | |
| static bool sax_parse(IteratorType first, SentinelType last, SAX* sax, | |
| input_format_t format = input_format_t::json, | |
| const bool strict = true, | |
| const bool ignore_comments = false, | |
| const bool ignore_trailing_commas = false, | |
| const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) | |
| { | |
| return sax_parse_impl(detail::input_adapter(std::move(first), std::move(last)), sax, format, strict, ignore_comments, ignore_trailing_commas, tag_handler); | |
| } | |
| /// @brief generate SAX events | |
| /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ | |
| /// @deprecated This function is deprecated since 3.8.0 and will be removed in | |
| /// version 4.0.0 of the library. Please use | |
| /// sax_parse(ptr, ptr + len) instead. | |
| // | |
| // Clang reports "declaration is marked with '@deprecated' command but does | |
| // not have a deprecation attribute" for this overload even though | |
| // JSON_HEDLEY_DEPRECATED_FOR below does expand to __attribute__((deprecated)); | |
| // isolated reproductions of this exact declaration shape (doc comment, | |
| // template<>, two stacked __attribute__ lines, an overload set of the same | |
| // name) do not reproduce it, so this looks like a Clang comment/declaration | |
| // association quirk specific to this overload within basic_json, not a | |
| // genuine documentation bug. See #5725 item 2. | |
| #if defined(__clang__) | |
| #pragma clang diagnostic push | |
| #pragma clang diagnostic ignored "-Wdocumentation-deprecated-sync" | |
| #endif | |
| template <typename SAX> | |
| JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...)) | |
| JSON_HEDLEY_NON_NULL(2) | |
| static bool sax_parse(detail::span_input_adapter&& i, SAX* sax, | |
| input_format_t format = input_format_t::json, | |
| const bool strict = true, | |
| const bool ignore_comments = false, | |
| const bool ignore_trailing_commas = false, | |
| const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return sax_parse_impl(i.get(), sax, format, strict, ignore_comments, ignore_trailing_commas, tag_handler); | |
| } | |
| #endif | |
| #if defined(__clang__) | |
| #pragma clang diagnostic pop | |
| #endif | |
| #ifndef JSON_NO_IO | |
| #if !JSON_DELETE_DEPRECATED_FUNCTIONS | |
| // the deleted version is a function template after the class, because | |
| // GCC < 5 and Clang < 10 reject deleted friend functions in class templates | |
| /// @brief deserialize from stream | |
| /// @sa https://json.nlohmann.me/api/operator_gtgt/ | |
| /// @deprecated This stream operator is deprecated since 3.0.0 and will be removed in | |
| /// version 4.0.0 of the library. Please use | |
| /// operator>>(std::istream&, basic_json&) instead; that is, | |
| /// replace calls like `j << i;` with `i >> j;`. | |
| JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&)) | |
| friend std::istream& operator<<(basic_json& j, std::istream& i) | |
| { | |
| return operator>>(i, j); | |
| } | |
| #endif | |
| /// @brief deserialize from stream | |
| /// @sa https://json.nlohmann.me/api/operator_gtgt/ | |
| friend std::istream& operator>>(std::istream& i, basic_json& j) | |
| { | |
| // parse into a temporary so that j is left unchanged if parsing fails | |
| basic_json result; | |
| parser(detail::input_adapter(i)).parse(false, result); | |
| j = std::move(result); | |
| return i; | |
| } | |
| #endif // JSON_NO_IO | |
| /// @} | |
| /////////////////////////// | |
| // convenience functions // | |
| /////////////////////////// | |
| /// @brief return the type as string | |
| /// @sa https://json.nlohmann.me/api/basic_json/type_name/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_RETURNS_NON_NULL | |
| const char* type_name() const noexcept | |
| { | |
| return detail::value_type_name(m_data.m_type); | |
| } | |
| JSON_PRIVATE_UNLESS_TESTED: | |
| ////////////////////// | |
| // member variables // | |
| ////////////////////// | |
| struct data | |
| { | |
| /// the type of the current element | |
| value_t m_type = value_t::null; | |
| /// the value of the current element | |
| json_value m_value = {}; | |
| data(const value_t v) | |
| : m_type(v), m_value(v) | |
| { | |
| } | |
| data(size_type cnt, const basic_json& val) | |
| : m_type(value_t::array) | |
| { | |
| m_value.array = create<array_t>(cnt, val); | |
| } | |
| data() noexcept = default; | |
| data(data&&) noexcept = default; | |
| data(const data&) noexcept = delete; | |
| data& operator=(data&&) noexcept = delete; | |
| data& operator=(const data&) noexcept = delete; | |
| ~data() noexcept | |
| { | |
| m_value.destroy(m_type); | |
| } | |
| }; | |
| data m_data = {}; // NOLINT(readability-redundant-member-init) | |
| #if JSON_DIAGNOSTICS | |
| /// a pointer to a parent value (for debugging purposes) | |
| basic_json* m_parent = nullptr; | |
| #endif | |
| #if JSON_DIAGNOSTIC_POSITIONS | |
| /// the start position of the value | |
| std::size_t start_position = std::string::npos; | |
| /// the end position of the value | |
| std::size_t end_position = std::string::npos; | |
| public: | |
| constexpr std::size_t start_pos() const noexcept | |
| { | |
| return start_position; | |
| } | |
| constexpr std::size_t end_pos() const noexcept | |
| { | |
| return end_position; | |
| } | |
| #endif | |
| private: | |
| /*! | |
| @brief shared implementation of the binary from_cbor/from_msgpack/ | |
| from_ubjson/from_bjdata/from_bon8/from_bson overloads | |
| Building the @ref binary_reader as a named local, rather than as a | |
| temporary that @ref detail::json_sax_dom_binary_parser::parse is called on in | |
| the same expression, avoids a false-positive cppcheck accessMoved | |
| warning in each of the 16 callers. | |
| */ | |
| template<typename InputAdapterType> | |
| static basic_json from_binary_impl(InputAdapterType ia, const input_format_t format, | |
| const bool strict, const bool allow_exceptions, | |
| const error_handler_t error_handler = error_handler_t::keep, | |
| const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) | |
| { | |
| basic_json result; | |
| detail::json_sax_dom_binary_parser<basic_json, InputAdapterType> sdp(result, allow_exceptions); | |
| binary_reader<InputAdapterType> reader(std::move(ia), format, error_handler); | |
| if (!reader.sax_parse(&sdp, strict, tag_handler)) | |
| { | |
| result = value_t::discarded; | |
| } | |
| return result; | |
| } | |
| ////////////////////////////////////////// | |
| // binary serialization/deserialization // | |
| ////////////////////////////////////////// | |
| /// @name binary serialization/deserialization support | |
| /// @{ | |
| public: | |
| /// @brief create a CBOR serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ | |
| static std::vector<std::uint8_t> to_cbor(const basic_json& j, | |
| const error_handler_t error_handler = detail::binary_writer_default_error_handler()) | |
| { | |
| return to_binary_vector(j, error_handler, [&](vector_binary_writer<std::uint8_t>& w) | |
| { | |
| w.write_cbor(j); | |
| }); | |
| } | |
| /// @brief create a CBOR serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ | |
| static void to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o, | |
| const error_handler_t error_handler = detail::binary_writer_default_error_handler()) | |
| { | |
| binary_writer<std::uint8_t> writer(o, error_handler); | |
| writer.write_cbor(j); | |
| writer.flush(); | |
| } | |
| /// @brief create a CBOR serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ | |
| static void to_cbor(const basic_json& j, detail::output_adapter<char> o, | |
| const error_handler_t error_handler = detail::binary_writer_default_error_handler()) | |
| { | |
| binary_writer<char> writer(o, error_handler); | |
| writer.write_cbor(j); | |
| writer.flush(); | |
| } | |
| /// @brief create a MessagePack serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ | |
| static std::vector<std::uint8_t> to_msgpack(const basic_json& j, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| return to_binary_vector(j, error_handler, [&](vector_binary_writer<std::uint8_t>& w) | |
| { | |
| w.write_msgpack(j); | |
| }); | |
| } | |
| /// @brief create a MessagePack serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ | |
| static void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| binary_writer<std::uint8_t> writer(o, error_handler); | |
| writer.write_msgpack(j); | |
| writer.flush(); | |
| } | |
| /// @brief create a MessagePack serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ | |
| static void to_msgpack(const basic_json& j, detail::output_adapter<char> o, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| binary_writer<char> writer(o, error_handler); | |
| writer.write_msgpack(j); | |
| writer.flush(); | |
| } | |
| /// @brief create a UBJSON serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ | |
| static std::vector<std::uint8_t> to_ubjson(const basic_json& j, | |
| const bool use_size = false, | |
| const bool use_type = false, | |
| const error_handler_t error_handler = detail::binary_writer_default_error_handler()) | |
| { | |
| return to_binary_vector(j, error_handler, [&](vector_binary_writer<std::uint8_t>& w) | |
| { | |
| w.write_ubjson(j, use_size, use_type); | |
| }); | |
| } | |
| /// @brief create a UBJSON serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ | |
| static void to_ubjson(const basic_json& j, detail::output_adapter<std::uint8_t> o, | |
| const bool use_size = false, const bool use_type = false, | |
| const error_handler_t error_handler = detail::binary_writer_default_error_handler()) | |
| { | |
| binary_writer<std::uint8_t> writer(o, error_handler); | |
| writer.write_ubjson(j, use_size, use_type); | |
| writer.flush(); | |
| } | |
| /// @brief create a UBJSON serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ | |
| static void to_ubjson(const basic_json& j, detail::output_adapter<char> o, | |
| const bool use_size = false, const bool use_type = false, | |
| const error_handler_t error_handler = detail::binary_writer_default_error_handler()) | |
| { | |
| binary_writer<char> writer(o, error_handler); | |
| writer.write_ubjson(j, use_size, use_type); | |
| writer.flush(); | |
| } | |
| /// @brief create a BJData serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_bjdata/ | |
| static std::vector<std::uint8_t> to_bjdata(const basic_json& j, | |
| const bool use_size = false, | |
| const bool use_type = false, | |
| const bjdata_version_t version = bjdata_version_t::draft2, | |
| const error_handler_t error_handler = detail::binary_writer_default_error_handler()) | |
| { | |
| return to_binary_vector(j, error_handler, [&](vector_binary_writer<std::uint8_t>& w) | |
| { | |
| w.write_ubjson(j, use_size, use_type, true, true, version); | |
| }); | |
| } | |
| /// @brief create a BJData serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_bjdata/ | |
| static void to_bjdata(const basic_json& j, detail::output_adapter<std::uint8_t> o, | |
| const bool use_size = false, const bool use_type = false, | |
| const bjdata_version_t version = bjdata_version_t::draft2, | |
| const error_handler_t error_handler = detail::binary_writer_default_error_handler()) | |
| { | |
| binary_writer<std::uint8_t> writer(o, error_handler); | |
| writer.write_ubjson(j, use_size, use_type, true, true, version); | |
| writer.flush(); | |
| } | |
| /// @brief create a BJData serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_bjdata/ | |
| static void to_bjdata(const basic_json& j, detail::output_adapter<char> o, | |
| const bool use_size = false, const bool use_type = false, | |
| const bjdata_version_t version = bjdata_version_t::draft2, | |
| const error_handler_t error_handler = detail::binary_writer_default_error_handler()) | |
| { | |
| binary_writer<char> writer(o, error_handler); | |
| writer.write_ubjson(j, use_size, use_type, true, true, version); | |
| writer.flush(); | |
| } | |
| /// @brief create a BSON serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ | |
| static std::vector<std::uint8_t> to_bson(const basic_json& j, | |
| const error_handler_t error_handler = detail::binary_writer_default_error_handler()) | |
| { | |
| return to_binary_vector(j, error_handler, [&](vector_binary_writer<std::uint8_t>& w) | |
| { | |
| w.write_bson(j); | |
| }); | |
| } | |
| /// @brief create a BSON serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ | |
| static void to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o, | |
| const error_handler_t error_handler = detail::binary_writer_default_error_handler()) | |
| { | |
| binary_writer<std::uint8_t> writer(o, error_handler); | |
| writer.write_bson(j); | |
| writer.flush(); | |
| } | |
| /// @brief create a BSON serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ | |
| static void to_bson(const basic_json& j, detail::output_adapter<char> o, | |
| const error_handler_t error_handler = detail::binary_writer_default_error_handler()) | |
| { | |
| binary_writer<char> writer(o, error_handler); | |
| writer.write_bson(j); | |
| writer.flush(); | |
| } | |
| /// @brief create a BON8 serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_bon8/ | |
| static std::vector<std::uint8_t> to_bon8(const basic_json& j) | |
| { | |
| return to_binary_vector(j, detail::binary_writer_default_error_handler(), [&](vector_binary_writer<std::uint8_t>& w) | |
| { | |
| w.write_bon8(j); | |
| }); | |
| } | |
| /// @brief create a BON8 serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_bon8/ | |
| static void to_bon8(const basic_json& j, detail::output_adapter<std::uint8_t> o) | |
| { | |
| binary_writer<std::uint8_t> writer(o); | |
| writer.write_bon8(j); | |
| writer.flush(); | |
| } | |
| /// @brief create a BON8 serialization of a given JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_bon8/ | |
| static void to_bon8(const basic_json& j, detail::output_adapter<char> o) | |
| { | |
| binary_writer<char> writer(o); | |
| writer.write_bon8(j); | |
| writer.flush(); | |
| } | |
| /// @brief create a JSON value from an input in CBOR format | |
| /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/ | |
| template<typename InputType> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json from_cbor(InputType&& i, | |
| const bool strict = true, | |
| const bool allow_exceptions = true, | |
| const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| return from_binary_impl(detail::input_adapter(std::forward<InputType>(i)), input_format_t::cbor, strict, allow_exceptions, error_handler, tag_handler); | |
| } | |
| /// @brief create a JSON value from an input in CBOR format (iterator pair, or iterator+sentinel pair for C++20 ranges support) | |
| /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/ | |
| template<typename IteratorType, typename SentinelType = IteratorType, | |
| detail::enable_if_t<detail::can_compare_ne<IteratorType, SentinelType>::value, int> = 0> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json from_cbor(IteratorType first, SentinelType last, | |
| const bool strict = true, | |
| const bool allow_exceptions = true, | |
| const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| return from_binary_impl(detail::input_adapter(std::move(first), std::move(last)), input_format_t::cbor, strict, allow_exceptions, error_handler, tag_handler); | |
| } | |
| template<typename T> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) | |
| static basic_json from_cbor(const T* ptr, std::size_t len, | |
| const bool strict = true, | |
| const bool allow_exceptions = true, | |
| const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler); | |
| } | |
| #endif | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) | |
| static basic_json from_cbor(detail::span_input_adapter&& i, | |
| const bool strict = true, | |
| const bool allow_exceptions = true, | |
| const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return from_binary_impl(i.get(), input_format_t::cbor, strict, allow_exceptions, error_handler_t::keep, tag_handler); | |
| } | |
| #endif | |
| /// @brief create a JSON value from an input in MessagePack format | |
| /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/ | |
| template<typename InputType> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json from_msgpack(InputType&& i, | |
| const bool strict = true, | |
| const bool allow_exceptions = true, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| return from_binary_impl(detail::input_adapter(std::forward<InputType>(i)), input_format_t::msgpack, strict, allow_exceptions, error_handler); | |
| } | |
| /// @brief create a JSON value from an input in MessagePack format (iterator pair, or iterator+sentinel pair for C++20 ranges support) | |
| /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/ | |
| template<typename IteratorType, typename SentinelType = IteratorType, | |
| detail::enable_if_t<detail::can_compare_ne<IteratorType, SentinelType>::value, int> = 0> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json from_msgpack(IteratorType first, SentinelType last, | |
| const bool strict = true, | |
| const bool allow_exceptions = true, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| return from_binary_impl(detail::input_adapter(std::move(first), std::move(last)), input_format_t::msgpack, strict, allow_exceptions, error_handler); | |
| } | |
| template<typename T> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) | |
| static basic_json from_msgpack(const T* ptr, std::size_t len, | |
| const bool strict = true, | |
| const bool allow_exceptions = true) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return from_msgpack(ptr, ptr + len, strict, allow_exceptions); | |
| } | |
| #endif | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) | |
| static basic_json from_msgpack(detail::span_input_adapter&& i, | |
| const bool strict = true, | |
| const bool allow_exceptions = true) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return from_binary_impl(i.get(), input_format_t::msgpack, strict, allow_exceptions); | |
| } | |
| #endif | |
| /// @brief create a JSON value from an input in UBJSON format | |
| /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/ | |
| template<typename InputType> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json from_ubjson(InputType&& i, | |
| const bool strict = true, | |
| const bool allow_exceptions = true, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| return from_binary_impl(detail::input_adapter(std::forward<InputType>(i)), input_format_t::ubjson, strict, allow_exceptions, error_handler); | |
| } | |
| /// @brief create a JSON value from an input in UBJSON format (iterator pair, or iterator+sentinel pair for C++20 ranges support) | |
| /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/ | |
| template<typename IteratorType, typename SentinelType = IteratorType, | |
| detail::enable_if_t<detail::can_compare_ne<IteratorType, SentinelType>::value, int> = 0> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json from_ubjson(IteratorType first, SentinelType last, | |
| const bool strict = true, | |
| const bool allow_exceptions = true, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| return from_binary_impl(detail::input_adapter(std::move(first), std::move(last)), input_format_t::ubjson, strict, allow_exceptions, error_handler); | |
| } | |
| template<typename T> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) | |
| static basic_json from_ubjson(const T* ptr, std::size_t len, | |
| const bool strict = true, | |
| const bool allow_exceptions = true) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return from_ubjson(ptr, ptr + len, strict, allow_exceptions); | |
| } | |
| #endif | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) | |
| static basic_json from_ubjson(detail::span_input_adapter&& i, | |
| const bool strict = true, | |
| const bool allow_exceptions = true) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return from_binary_impl(i.get(), input_format_t::ubjson, strict, allow_exceptions); | |
| } | |
| #endif | |
| /// @brief create a JSON value from an input in BJData format | |
| /// @sa https://json.nlohmann.me/api/basic_json/from_bjdata/ | |
| template<typename InputType> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json from_bjdata(InputType&& i, | |
| const bool strict = true, | |
| const bool allow_exceptions = true, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| return from_binary_impl(detail::input_adapter(std::forward<InputType>(i)), input_format_t::bjdata, strict, allow_exceptions, error_handler); | |
| } | |
| /// @brief create a JSON value from an input in BJData format (iterator pair, or iterator+sentinel pair for C++20 ranges support) | |
| /// @sa https://json.nlohmann.me/api/basic_json/from_bjdata/ | |
| template<typename IteratorType, typename SentinelType = IteratorType, | |
| detail::enable_if_t<detail::can_compare_ne<IteratorType, SentinelType>::value, int> = 0> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json from_bjdata(IteratorType first, SentinelType last, | |
| const bool strict = true, | |
| const bool allow_exceptions = true, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| return from_binary_impl(detail::input_adapter(std::move(first), std::move(last)), input_format_t::bjdata, strict, allow_exceptions, error_handler); | |
| } | |
| template<typename T> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.13.0, from_bjdata(ptr, ptr + len)) | |
| static basic_json from_bjdata(const T* ptr, std::size_t len, | |
| const bool strict = true, | |
| const bool allow_exceptions = true) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return from_bjdata(ptr, ptr + len, strict, allow_exceptions); | |
| } | |
| #endif | |
| /// @brief create a JSON value from an input in BON8 format | |
| /// @sa https://json.nlohmann.me/api/basic_json/from_bon8/ | |
| template<typename InputType> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json from_bon8(InputType&& i, | |
| const bool strict = true, | |
| const bool allow_exceptions = true) | |
| { | |
| return from_binary_impl(detail::input_adapter(std::forward<InputType>(i)), input_format_t::bon8, strict, allow_exceptions); | |
| } | |
| /// @brief create a JSON value from an input in BON8 format (iterator pair, or iterator+sentinel pair for C++20 ranges support) | |
| /// @sa https://json.nlohmann.me/api/basic_json/from_bon8/ | |
| template<typename IteratorType, typename SentinelType = IteratorType, | |
| detail::enable_if_t<detail::can_compare_ne<IteratorType, SentinelType>::value, int> = 0> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json from_bon8(IteratorType first, SentinelType last, | |
| const bool strict = true, | |
| const bool allow_exceptions = true) | |
| { | |
| return from_binary_impl(detail::input_adapter(std::move(first), std::move(last)), input_format_t::bon8, strict, allow_exceptions); | |
| } | |
| template<typename T> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.13.0, from_bon8(ptr, ptr + len)) | |
| static basic_json from_bon8(const T* ptr, std::size_t len, | |
| const bool strict = true, | |
| const bool allow_exceptions = true) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return from_bon8(ptr, ptr + len, strict, allow_exceptions); | |
| } | |
| #endif | |
| /// @brief create a JSON value from an input in BSON format | |
| /// @sa https://json.nlohmann.me/api/basic_json/from_bson/ | |
| template<typename InputType> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json from_bson(InputType&& i, | |
| const bool strict = true, | |
| const bool allow_exceptions = true, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| return from_binary_impl(detail::input_adapter(std::forward<InputType>(i)), input_format_t::bson, strict, allow_exceptions, error_handler); | |
| } | |
| /// @brief create a JSON value from an input in BSON format (iterator pair, or iterator+sentinel pair for C++20 ranges support) | |
| /// @sa https://json.nlohmann.me/api/basic_json/from_bson/ | |
| template<typename IteratorType, typename SentinelType = IteratorType, | |
| detail::enable_if_t<detail::can_compare_ne<IteratorType, SentinelType>::value, int> = 0> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json from_bson(IteratorType first, SentinelType last, | |
| const bool strict = true, | |
| const bool allow_exceptions = true, | |
| const error_handler_t error_handler = error_handler_t::keep) | |
| { | |
| return from_binary_impl(detail::input_adapter(std::move(first), std::move(last)), input_format_t::bson, strict, allow_exceptions, error_handler); | |
| } | |
| template<typename T> | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) | |
| static basic_json from_bson(const T* ptr, std::size_t len, | |
| const bool strict = true, | |
| const bool allow_exceptions = true) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return from_bson(ptr, ptr + len, strict, allow_exceptions); | |
| } | |
| #endif | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) | |
| static basic_json from_bson(detail::span_input_adapter&& i, | |
| const bool strict = true, | |
| const bool allow_exceptions = true) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return from_binary_impl(i.get(), input_format_t::bson, strict, allow_exceptions); | |
| } | |
| #endif | |
| /// @} | |
| ////////////////////////// | |
| // JSON Pointer support // | |
| ////////////////////////// | |
| /// @name JSON Pointer functions | |
| /// @{ | |
| /// @brief access specified element via JSON Pointer | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ | |
| reference operator[](const json_pointer& ptr) | |
| { | |
| return ptr.get_unchecked(this); | |
| } | |
| template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0> | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens) | |
| reference operator[](const ::nlohmann::json_pointer<BasicJsonType>& ptr) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return ptr.get_unchecked(this); | |
| } | |
| #endif | |
| /// @brief access specified element via JSON Pointer | |
| /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ | |
| const_reference operator[](const json_pointer& ptr) const | |
| { | |
| return ptr.get_unchecked(this); | |
| } | |
| template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0> | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens) | |
| const_reference operator[](const ::nlohmann::json_pointer<BasicJsonType>& ptr) const | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return ptr.get_unchecked(this); | |
| } | |
| #endif | |
| /// @brief access specified element via JSON Pointer | |
| /// @sa https://json.nlohmann.me/api/basic_json/at/ | |
| reference at(const json_pointer& ptr) | |
| { | |
| return ptr.get_checked(this); | |
| } | |
| template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0> | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens) | |
| reference at(const ::nlohmann::json_pointer<BasicJsonType>& ptr) | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return ptr.get_checked(this); | |
| } | |
| #endif | |
| /// @brief access specified element via JSON Pointer | |
| /// @sa https://json.nlohmann.me/api/basic_json/at/ | |
| const_reference at(const json_pointer& ptr) const | |
| { | |
| return ptr.get_checked(this); | |
| } | |
| template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0> | |
| JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens) | |
| const_reference at(const ::nlohmann::json_pointer<BasicJsonType>& ptr) const | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS | |
| = delete; | |
| #else | |
| { | |
| return ptr.get_checked(this); | |
| } | |
| #endif | |
| /// @brief return flattened JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/flatten/ | |
| basic_json flatten() const | |
| { | |
| basic_json result(value_t::object); | |
| json_pointer::flatten("", *this, result); | |
| return result; | |
| } | |
| /// @brief unflatten a previously flattened JSON value | |
| /// @sa https://json.nlohmann.me/api/basic_json/unflatten/ | |
| basic_json unflatten() const | |
| { | |
| return json_pointer::unflatten(*this); | |
| } | |
| /// @} | |
| ////////////////////////// | |
| // JSON Patch functions // | |
| ////////////////////////// | |
| /// @name JSON Patch functions | |
| /// @{ | |
| private: | |
| /// the members of an operation of a JSON patch that are of interest | |
| struct patch_members | |
| { | |
| basic_json* op = nullptr; | |
| basic_json* path = nullptr; | |
| basic_json* value = nullptr; | |
| basic_json* from = nullptr; | |
| }; | |
| /// @brief find the members "op", "path", "value", and "from" of the object @a val in one pass | |
| static patch_members find_patch_members(const basic_json& val, std::true_type /*key_type is string_t*/) | |
| { | |
| patch_members members; | |
| for (auto& member : *val.m_data.m_value.object) | |
| { | |
| const string_t& key = member.first; | |
| switch (key.size()) | |
| { | |
| case 2: | |
| if (key == "op") | |
| { | |
| members.op = &member.second; | |
| } | |
| break; | |
| case 4: | |
| if (key == "path") | |
| { | |
| members.path = &member.second; | |
| } | |
| else if (key == "from") | |
| { | |
| members.from = &member.second; | |
| } | |
| break; | |
| case 5: | |
| if (key == "value") | |
| { | |
| members.value = &member.second; | |
| } | |
| break; | |
| default: | |
| break; | |
| } | |
| } | |
| return members; | |
| } | |
| /// @brief find the members by lookup for key types other than string_t | |
| static patch_members find_patch_members(const basic_json& val, std::false_type /*key_type is not string_t*/) | |
| { | |
| const auto find_member = [&val](const char* name) -> basic_json * | |
| { | |
| const auto it = val.m_data.m_value.object->find(string_t(name)); | |
| return it != val.m_data.m_value.object->end() ? &it->second : nullptr; | |
| }; | |
| patch_members members; | |
| members.op = find_member("op"); | |
| members.path = find_member("path"); | |
| members.value = find_member("value"); | |
| members.from = find_member("from"); | |
| return members; | |
| } | |
| public: | |
| /// @brief applies a JSON patch in-place without copying the object | |
| /// @sa https://json.nlohmann.me/api/basic_json/patch/ | |
| void patch_inplace(const basic_json& json_patch) | |
| { | |
| basic_json& result = *this; | |
| // the valid JSON Patch operations | |
| enum class patch_operations {add, remove, replace, move, copy, test, invalid}; | |
| const auto get_op = [](const string_t& op) | |
| { | |
| if (op == "add") | |
| { | |
| return patch_operations::add; | |
| } | |
| if (op == "remove") | |
| { | |
| return patch_operations::remove; | |
| } | |
| if (op == "replace") | |
| { | |
| return patch_operations::replace; | |
| } | |
| if (op == "move") | |
| { | |
| return patch_operations::move; | |
| } | |
| if (op == "copy") | |
| { | |
| return patch_operations::copy; | |
| } | |
| if (op == "test") | |
| { | |
| return patch_operations::test; | |
| } | |
| return patch_operations::invalid; | |
| }; | |
| // wrapper for "add" operation; add value at ptr | |
| const auto operation_add = [&result](json_pointer & ptr, basic_json val) | |
| { | |
| // adding to the root of the target document means replacing it | |
| if (ptr.empty()) | |
| { | |
| result = std::move(val); | |
| return; | |
| } | |
| // get reference to the parent of the JSON pointer ptr; a missing | |
| // parent (or one of its ancestors) is reported by at() | |
| auto last_path = std::move(ptr.reference_tokens.back()); | |
| ptr.pop_back(); | |
| // parent must exist when performing patch add per RFC6902 specs | |
| basic_json& parent = result.at(ptr); | |
| switch (parent.m_data.m_type) | |
| { | |
| case value_t::null: | |
| case value_t::object: | |
| { | |
| // use operator[] to add value | |
| parent[std::move(last_path)] = std::move(val); | |
| break; | |
| } | |
| case value_t::array: | |
| { | |
| if (last_path == "-") | |
| { | |
| // special case: append to back | |
| parent.push_back(std::move(val)); | |
| } | |
| else | |
| { | |
| const auto idx = json_pointer::template array_index<basic_json_t>(last_path); | |
| if (JSON_HEDLEY_UNLIKELY(idx > parent.size())) | |
| { | |
| // avoid undefined behavior | |
| throw_array_index_out_of_range(idx, parent); | |
| } | |
| // default case: insert add offset | |
| parent.insert(parent.begin() + static_cast<difference_type>(idx), std::move(val)); | |
| } | |
| break; | |
| } | |
| // the parent of an "add" target must be an object or array | |
| // (see #4292) | |
| case value_t::string: | |
| case value_t::boolean: | |
| case value_t::number_integer: | |
| case value_t::number_unsigned: | |
| case value_t::number_float: | |
| case value_t::binary: | |
| case value_t::discarded: | |
| default: | |
| detail::throw_patch_add_parent(parent); | |
| } | |
| }; | |
| // wrapper for "remove" operation; remove value at ptr | |
| const auto operation_remove = [this, & result](json_pointer & ptr) | |
| { | |
| // get reference to the parent of the JSON pointer ptr | |
| static_cast<void>(ptr.back()); // throws out_of_range.405 if ptr is the root | |
| const auto last_path = std::move(ptr.reference_tokens.back()); | |
| ptr.pop_back(); | |
| basic_json& parent = result.at(ptr); | |
| // remove child | |
| if (parent.is_object()) | |
| { | |
| // perform range check | |
| auto it = parent.find(last_path); | |
| if (JSON_HEDLEY_LIKELY(it != parent.end())) | |
| { | |
| parent.erase(it); | |
| } | |
| else | |
| { | |
| throw_key_not_found(last_path, *this); | |
| } | |
| } | |
| else if (parent.is_array()) | |
| { | |
| // note erase performs range check | |
| parent.erase(json_pointer::template array_index<basic_json_t>(last_path)); | |
| } | |
| else | |
| { | |
| // the parent of a "remove" target must be an object or array | |
| // (see #5396) | |
| detail::throw_patch_remove_parent(parent); | |
| } | |
| }; | |
| // RFC 6902 (section 4.4) forbids "from" from being a proper prefix | |
| // of "path" for a "move" operation: a location cannot be moved into | |
| // one of its own children. Compares reference tokens (already | |
| // unescaped by json_pointer's parser) rather than the raw pointer | |
| // strings, since a token may itself contain an escaped '/' or '~' | |
| // that would defeat a naive string-prefix comparison. "from" equal | |
| // to "path" is *not* a proper prefix and must return false. | |
| const auto is_proper_prefix = [](const json_pointer & from, const json_pointer & to) | |
| { | |
| const auto from_size = from.reference_tokens.size(); | |
| if (from_size >= to.reference_tokens.size()) | |
| { | |
| return false; | |
| } | |
| for (std::size_t i = 0; i < from_size; ++i) | |
| { | |
| if (!(from.reference_tokens[i] == to.reference_tokens[i])) | |
| { | |
| return false; | |
| } | |
| } | |
| return true; | |
| }; | |
| // type check: top level value must be an array | |
| if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array())) | |
| { | |
| detail::throw_patch_not_an_array(json_patch); | |
| } | |
| // the usual patch operations "add", "remove", "replace" and "test" on | |
| // a pointer without escapes that denotes existing array elements and | |
| // object members (as "add" does for the parent of the new value), as | |
| // a diff creates them: apply the operation and return true; return | |
| // false, with nothing changed, for all others | |
| string_t token; | |
| typename json_pointer::template plain_steps<basic_json> steps; | |
| const auto try_plain = [&result, &token, &steps](patch_operations operation, const string_t& path, const patch_members & members, const basic_json & val) | |
| { | |
| if (path.empty()) | |
| { | |
| return false; | |
| } | |
| // a missing "value" is reported below | |
| const basic_json* const value_ptr = members.value; | |
| const basic_json& value = value_ptr != nullptr ? *value_ptr : val; | |
| if (operation != patch_operations::remove && value_ptr == nullptr) | |
| { | |
| return false; | |
| } | |
| switch (operation) | |
| { | |
| case patch_operations::replace: | |
| { | |
| basic_json* const target = json_pointer::resolve_plain(&result, path, path.size(), token, steps); | |
| if (target == nullptr) | |
| { | |
| return false; | |
| } | |
| *target = value; | |
| return true; | |
| } | |
| case patch_operations::test: | |
| { | |
| const basic_json* const target = json_pointer::resolve_plain(&result, path, path.size(), token, steps); | |
| // a failing test is reported below | |
| return target != nullptr && *target == value; | |
| } | |
| case patch_operations::add: | |
| case patch_operations::remove: | |
| { | |
| // the parent of the pointer and its last reference token | |
| std::size_t slash = path.size(); | |
| while (slash > 0 && path[slash - 1] != '/') | |
| { | |
| --slash; | |
| } | |
| if (slash == 0) | |
| { | |
| return false; | |
| } | |
| --slash; | |
| basic_json* const parent = json_pointer::resolve_plain(&result, path, slash, token, steps); | |
| if (parent == nullptr) | |
| { | |
| return false; | |
| } | |
| token.clear(); | |
| token.append(path.data() + slash + 1, path.size() - slash - 1); | |
| if (token.find_first_of('~') != string_t::npos) | |
| { | |
| return false; | |
| } | |
| if (operation == patch_operations::add) | |
| { | |
| if (parent->is_object()) | |
| { | |
| (*parent)[token] = value; | |
| return true; | |
| } | |
| if (parent->is_array()) | |
| { | |
| typename basic_json::size_type idx{}; | |
| if (token == "-") | |
| { | |
| parent->push_back(value); | |
| return true; | |
| } | |
| if (json_pointer::template parse_array_index<basic_json_t>(token, idx) == json_pointer::array_index_status::ok && idx <= parent->size()) | |
| { | |
| parent->insert(parent->begin() + static_cast<difference_type>(idx), value); | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| if (parent->is_object()) | |
| { | |
| const auto it = parent->find(token); | |
| if (it == parent->end()) | |
| { | |
| return false; | |
| } | |
| parent->erase(it); | |
| return true; | |
| } | |
| if (parent->is_array()) | |
| { | |
| typename basic_json::size_type idx{}; | |
| if (json_pointer::template parse_array_index<basic_json_t>(token, idx) == json_pointer::array_index_status::ok && idx < parent->size()) | |
| { | |
| parent->erase(idx); | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| case patch_operations::move: | |
| case patch_operations::copy: | |
| case patch_operations::invalid: | |
| default: | |
| return false; | |
| } | |
| }; | |
| // the name of the first member to check | |
| const string_t op_member = "op"; | |
| // iterate and apply the operations | |
| for (const auto& val : json_patch) | |
| { | |
| // wrapper to get a value for an operation | |
| const auto get_value = [&val](basic_json * found, | |
| const string_t& op, | |
| const char* member, | |
| bool string_type) -> basic_json & | |
| { | |
| // check if the desired value is present | |
| if (JSON_HEDLEY_UNLIKELY(found == nullptr)) | |
| { | |
| detail::throw_patch_missing_member(op, string_t(member), false, val); | |
| } | |
| // check if the result is of type string | |
| if (JSON_HEDLEY_UNLIKELY(string_type && !found->is_string())) | |
| { | |
| detail::throw_patch_missing_member(op, string_t(member), true, val); | |
| } | |
| // no error: return value | |
| return *found; | |
| }; | |
| // type check: every element of the array must be an object | |
| if (JSON_HEDLEY_UNLIKELY(!val.is_object())) | |
| { | |
| detail::throw_patch_not_an_array(val); | |
| } | |
| const patch_members members = find_patch_members(val, std::is_same<typename object_t::key_type, string_t> {}); | |
| // collect mandatory members | |
| const string_t& op = *get_value(members.op, op_member, "op", true).m_data.m_value.string; | |
| const string_t& path = *get_value(members.path, op, "path", true).m_data.m_value.string; | |
| const patch_operations operation = get_op(op); | |
| // the usual operations on a plain pointer are applied without | |
| // building the pointer's reference tokens; anything else (and | |
| // every error) is handled below | |
| if (try_plain(operation, path, members, val)) | |
| { | |
| continue; | |
| } | |
| // the general operations may change any container | |
| steps.reset(); | |
| json_pointer ptr(path); | |
| switch (operation) | |
| { | |
| case patch_operations::add: | |
| { | |
| operation_add(ptr, get_value(members.value, "add", "value", false)); | |
| break; | |
| } | |
| case patch_operations::remove: | |
| { | |
| operation_remove(ptr); | |
| break; | |
| } | |
| case patch_operations::replace: | |
| { | |
| // the "path" location must exist - use at() | |
| result.at(ptr) = get_value(members.value, "replace", "value", false); | |
| break; | |
| } | |
| case patch_operations::move: | |
| { | |
| const string_t& from_path = *get_value(members.from, "move", "from", true).m_data.m_value.string; | |
| json_pointer from_ptr(from_path); | |
| if (JSON_HEDLEY_UNLIKELY(is_proper_prefix(from_ptr, ptr))) | |
| { | |
| detail::throw_patch_move_into_child(from_path, path, result); | |
| } | |
| // the "from" location must exist - use at() | |
| // a root "from" is rejected by operation_remove below, which must leave result intact | |
| basic_json v = from_ptr.empty() ? basic_json(result) : std::move(result.at(from_ptr)); | |
| // The move operation is functionally identical to a | |
| // "remove" operation on the "from" location, followed | |
| // immediately by an "add" operation at the target | |
| // location with the value that was just removed. | |
| operation_remove(from_ptr); | |
| operation_add(ptr, std::move(v)); | |
| break; | |
| } | |
| case patch_operations::copy: | |
| { | |
| const string_t& from_path = *get_value(members.from, "copy", "from", true).m_data.m_value.string; | |
| const json_pointer from_ptr(from_path); | |
| // The copy is functionally identical to an "add" | |
| // operation at the target location using the value | |
| // specified in the "from" member; the "from" location | |
| // must exist - use at() | |
| operation_add(ptr, result.at(from_ptr)); | |
| break; | |
| } | |
| case patch_operations::test: | |
| { | |
| bool success = false; | |
| JSON_TRY | |
| { | |
| // check if "value" matches the one at "path" | |
| // the "path" location must exist - use at() | |
| success = (result.at(ptr) == get_value(members.value, "test", "value", false)); | |
| } | |
| JSON_INTERNAL_CATCH (out_of_range&) | |
| { | |
| // ignore out of range errors: success remains false | |
| } | |
| // throw an exception if the test fails | |
| if (JSON_HEDLEY_UNLIKELY(!success)) | |
| { | |
| detail::throw_patch_test_failed(val); | |
| } | |
| break; | |
| } | |
| case patch_operations::invalid: | |
| default: | |
| { | |
| // op must be "add", "remove", "replace", "move", "copy", or | |
| // "test" | |
| detail::throw_patch_invalid_operation(op, val); | |
| } | |
| } | |
| } | |
| } | |
| /// @brief applies a JSON patch to a copy of the current object | |
| /// @sa https://json.nlohmann.me/api/basic_json/patch/ | |
| basic_json patch(const basic_json& json_patch) const | |
| { | |
| basic_json result = *this; | |
| result.patch_inplace(json_patch); | |
| return result; | |
| } | |
| /// @brief creates a diff as a JSON patch | |
| /// @sa https://json.nlohmann.me/api/basic_json/diff/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json diff(const basic_json& source, const basic_json& target, | |
| const string_t& path = "") | |
| { | |
| // the patch | |
| basic_json result(value_t::array); | |
| string_t buffer = path; | |
| diff_recursively(result, source, target, buffer, 0); | |
| return result; | |
| } | |
| private: | |
| /// @brief two arrays or two objects @ref diff_iteratively is diffing | |
| struct diff_frame | |
| { | |
| diff_frame(const basic_json* source_, const basic_json* target_, const std::size_t path_length_) noexcept | |
| : source(source_), target(target_), path_length(path_length_) | |
| {} | |
| // declared for GCC's -Weffc++, which asks for them in a class with | |
| // pointer members and a non-trivial destructor; the exception | |
| // specifications are left implicit, as GCC 4.8 rejects explicit ones | |
| // that differ from them | |
| diff_frame(const diff_frame&) = default; | |
| diff_frame(diff_frame&&) = default; | |
| diff_frame& operator=(const diff_frame&) = default; | |
| diff_frame& operator=(diff_frame&&) = default; | |
| ~diff_frame() = default; | |
| /// the values being diffed, both arrays or both objects | |
| const basic_json* source; | |
| const basic_json* target; | |
| /// the length of their path in `current_path` | |
| std::size_t path_length; | |
| /// arrays: the next index to diff | |
| std::size_t index = 0; | |
| /// objects: the next member of source to look at | |
| const_iterator member{}; // NOLINT(readability-redundant-member-init) | |
| /// objects: for each member of source (in order), its value in | |
| /// target, or nullptr if target has no such key; `index` is the next | |
| std::vector<const basic_json*> target_values{}; // NOLINT(readability-redundant-member-init) | |
| /// objects: the members only target has, in target's order | |
| std::vector<const_iterator> added{}; // NOLINT(readability-redundant-member-init) | |
| }; | |
| // The operations of a diff are built by the functions below rather than | |
| // where they are needed: building one takes several temporaries, and | |
| // unoptimized builds give each temporary a stack slot of its own in the | |
| // function it appears in. In diff_recursively, which is on the call stack | |
| // once per nesting level, that made every level cost kilobytes of stack. | |
| /// @brief append an operation @a op for @a path to @a result, with @a value if it is not null | |
| static void diff_operation(basic_json& result, const char* op, const string_t& path, const basic_json* value) | |
| { | |
| // the keys are distinct and in the order of std::map; the members are | |
| // added without looking them up | |
| basic_json entry(value_t::object); | |
| auto& members = *entry.m_data.m_value.object; | |
| auto hint = members.end(); | |
| json_pointer::add_flattened(members, hint, string_t("op"), string_t(op), detail::priority_tag<2> {}); | |
| json_pointer::add_flattened(members, hint, string_t("path"), path, detail::priority_tag<2> {}); | |
| if (value != nullptr) | |
| { | |
| json_pointer::add_flattened(members, hint, string_t("value"), *value, detail::priority_tag<2> {}); | |
| } | |
| entry.set_parents(); | |
| result.push_back(std::move(entry)); | |
| } | |
| /// @brief append a "replace" operation for @a path with @a value to @a result | |
| static void diff_replace(basic_json& result, const string_t& path, const basic_json& value) | |
| { | |
| diff_operation(result, "replace", path, &value); | |
| } | |
| /// @brief append a "remove" operation for @a path to @a result | |
| static void diff_remove(basic_json& result, const string_t& path) | |
| { | |
| diff_operation(result, "remove", path, nullptr); | |
| } | |
| /// @brief append an "add" operation for @a path with @a value to @a result | |
| static void diff_add(basic_json& result, const string_t& path, const basic_json& value) | |
| { | |
| diff_operation(result, "add", path, &value); | |
| } | |
| /// @brief the values in the target of the members of a source object, for the | |
| /// objects of up to 16 members without allocating | |
| /// | |
| /// reserve() must be called with the number of values that are added. | |
| class diff_target_values | |
| { | |
| public: | |
| diff_target_values() noexcept | |
| : inline_items() // NOLINT(readability-redundant-member-init) | |
| {} | |
| diff_target_values(const diff_target_values&) = delete; | |
| diff_target_values& operator=(const diff_target_values&) = delete; | |
| diff_target_values(diff_target_values&&) = delete; | |
| diff_target_values& operator=(diff_target_values&&) = delete; | |
| ~diff_target_values() = default; | |
| void reserve(const std::size_t n) | |
| { | |
| if (n > inline_size) | |
| { | |
| large.resize(n); | |
| items = large.data(); | |
| } | |
| } | |
| void push_back(const basic_json* value) | |
| { | |
| items[count++] = value; | |
| } | |
| std::size_t size() const noexcept | |
| { | |
| return count; | |
| } | |
| const basic_json* operator[](const std::size_t i) const noexcept | |
| { | |
| return items[i]; | |
| } | |
| private: | |
| static constexpr std::size_t inline_size = 16; | |
| /// the values of a small object, left uninitialized: they are written | |
| /// before they are read (the user-provided constructor keeps the | |
| /// member initialization, which -Weffc++ asks for, from zeroing them) | |
| struct uninitialized_items : std::array<const basic_json*, inline_size> | |
| { | |
| uninitialized_items() noexcept {} // NOLINT(modernize-use-equals-default,hicpp-use-equals-default,cppcoreguidelines-pro-type-member-init,hicpp-member-init): see above | |
| }; | |
| std::size_t count = 0; | |
| std::vector<const basic_json*> large{}; // NOLINT(readability-redundant-member-init) | |
| uninitialized_items inline_items; | |
| const basic_json** items = inline_items.data(); | |
| }; | |
| /// @brief append "/" and the decimal representation of @a index to @a path | |
| static void diff_append_index(string_t& path, std::size_t index) | |
| { | |
| path.push_back('/'); | |
| json_pointer::append_index(path, index); | |
| } | |
| /// @brief append "/" and the escaped @a key to @a path | |
| static void diff_append_key(string_t& path, const string_t& key) | |
| { | |
| path.push_back('/'); | |
| detail::escape_into(path, key); | |
| } | |
| /// @brief the path of the member @a key of the value at @a path | |
| static string_t diff_key_path(const string_t& path, const string_t& key) | |
| { | |
| string_t result; | |
| result.reserve(path.size() + key.size() + 1); | |
| result.append(path.data(), path.size()); | |
| diff_append_key(result, key); | |
| return result; | |
| } | |
| /// @brief the path of the element @a index of the value at @a path | |
| static string_t diff_index_path(const string_t& path, const std::size_t index) | |
| { | |
| string_t result; | |
| result.reserve(path.size() + 8); | |
| result.append(path.data(), path.size()); | |
| diff_append_index(result, index); | |
| return result; | |
| } | |
| /// @brief append the "remove" operations for the elements of array | |
| /// @a source from @a index on, and the "add" operations for the | |
| /// elements of array @a target from source's size on, to @a result | |
| static void diff_array_tails(basic_json& result, const basic_json& source, const basic_json& target, | |
| const string_t& path, const std::size_t index) | |
| { | |
| // remove my remaining elements, highest index first; appending | |
| // in that order avoids the quadratic reinsertion done before | |
| for (std::size_t j = source.size(); j > index; --j) | |
| { | |
| diff_remove(result, diff_index_path(path, j - 1)); | |
| } | |
| // add other remaining elements | |
| if (source.size() < target.size()) | |
| { | |
| string_t tail_path = path; | |
| tail_path.append("/-", 2); | |
| for (std::size_t i = source.size(); i < target.size(); ++i) | |
| { | |
| diff_add(result, tail_path, target[i]); | |
| } | |
| } | |
| } | |
| /// @brief appends the "add" operations for the members @a added to @a result | |
| static void diff_added(basic_json& result, const std::vector<const_iterator>& added, const string_t& path) | |
| { | |
| for (const auto& it : added) | |
| { | |
| diff_add(result, diff_key_path(path, it.key()), it.value()); | |
| } | |
| } | |
| /*! | |
| @brief compare the keys of objects @a source and @a target | |
| If object_t does not keep its members in insertion order, or if the keys | |
| both objects have are in the same order in both, and the keys only | |
| @a target has come after them, stores in @a target_values, for each member | |
| of source in order, its value in target (nullptr for a key target does not | |
| have), stores the members only target has in @a added, and returns true: | |
| the caller then diffs the objects member by member. Otherwise, appends | |
| operations that remove every member of @a source and add every member of | |
| @a target to @a result, and returns false. | |
| */ | |
| template<typename TargetValues> | |
| static bool diff_object_keys(basic_json& result, const basic_json& source, const basic_json& target, | |
| const string_t& path, TargetValues& target_values, | |
| std::vector<const_iterator>& added) | |
| { | |
| // first pass: one lookup per source key | |
| // Objects of the same size usually have the same keys, in the same | |
| // order: walk them together as long as that holds, which takes no lookups. | |
| target_values.reserve(source.size()); | |
| std::size_t common = 0; | |
| bool together = source.size() == target.size(); | |
| for (auto it = source.cbegin(), partner = target.cbegin(); it != source.cend(); ++it) | |
| { | |
| if (together) | |
| { | |
| if (it.key() == partner.key()) | |
| { | |
| target_values.push_back(&partner.value()); | |
| ++common; | |
| ++partner; | |
| continue; | |
| } | |
| together = false; | |
| } | |
| const auto found = target.find(it.key()); | |
| if (found != target.cend()) | |
| { | |
| target_values.push_back(&found.value()); | |
| ++common; | |
| } | |
| else | |
| { | |
| target_values.push_back(nullptr); | |
| } | |
| } | |
| // the same keys in the same order | |
| if (together) | |
| { | |
| return true; | |
| } | |
| // second pass: find the keys only target has. An object type that | |
| // keeps its members in insertion order, such as the one backing | |
| // ordered_json, also needs the common keys to be in the same order | |
| // in both objects, and the new keys to come after them, as patch() | |
| // appends a new member at the end of such an object. Any other | |
| // object type places its members itself, so a member-by-member diff | |
| // always reproduces target there. | |
| #ifdef JSON_HEDLEY_MSVC_VERSION | |
| #pragma warning(push ) | |
| #pragma warning(disable : 4127) // ignore warning to replace if with if constexpr | |
| #endif | |
| bool fast_path = true; | |
| if (detail::is_ordered_map<object_t>::value) | |
| { | |
| // walk the common keys of source in lockstep with target: a key | |
| // of target that is not the next one is either new or out of order | |
| auto src = source.cbegin(); | |
| std::size_t next = 0; | |
| bool seen_new = false; | |
| for (auto it = target.cbegin(); it != target.cend() && fast_path; ++it) | |
| { | |
| while (next < target_values.size() && target_values[next] == nullptr) | |
| { | |
| ++src; | |
| ++next; | |
| } | |
| if (next < target_values.size() && src.key() == it.key()) | |
| { | |
| // a common key after a new one: new keys are no suffix | |
| fast_path = !seen_new; | |
| ++src; | |
| ++next; | |
| } | |
| else if (source.find(it.key()) == source.cend()) | |
| { | |
| seen_new = true; | |
| added.push_back(it); | |
| } | |
| else | |
| { | |
| // a common key out of order | |
| fast_path = false; | |
| } | |
| } | |
| } | |
| else if (target.size() != common) | |
| { | |
| for (auto it = target.cbegin(); it != target.cend(); ++it) | |
| { | |
| if (source.find(it.key()) == source.cend()) | |
| { | |
| added.push_back(it); | |
| } | |
| } | |
| } | |
| #ifdef JSON_HEDLEY_MSVC_VERSION | |
| #pragma warning( pop ) | |
| #endif | |
| if (fast_path) | |
| { | |
| return true; | |
| } | |
| // equal objects, whose members are in a different order, need no | |
| // operations | |
| if (source == target) | |
| { | |
| return false; | |
| } | |
| // slow path: the common keys are in a different relative | |
| // order in source and target (only possible for a | |
| // reorderable object_t like ordered_map). Building a | |
| // minimal reordering patch is a nontrivial (LCS-like) | |
| // problem; instead, remove every source key -- both | |
| // deleted keys (which must be removed regardless) and | |
| // common keys (removed so they can be re-added in | |
| // target's order) -- and re-add every key that should | |
| // remain, with its final target value, in target's | |
| // order. basic_json::patch()'s "add" operation on an | |
| // object uses operator[], which appends at the end for a | |
| // vector-backed insertion-ordered map when the key does | |
| // not already exist -- so removing a key and then adding | |
| // it moves it to the end, fixing its position. | |
| for (auto it = source.cbegin(); it != source.cend(); ++it) | |
| { | |
| diff_remove(result, diff_key_path(path, it.key())); | |
| } | |
| // add every key that is either common (just removed | |
| // above) or brand new, in target's iteration order, so | |
| // that the final order after applying the patch matches | |
| // target exactly | |
| for (auto it = target.cbegin(); it != target.cend(); ++it) | |
| { | |
| diff_add(result, diff_key_path(path, it.key()), it.value()); | |
| } | |
| return false; | |
| } | |
| /*! | |
| @brief @ref diff, for values at nesting level @a depth, appending the | |
| operations to @a result | |
| @a path is the path of the values; it is a buffer that is extended and | |
| shortened again below, and is the same when the function returns. | |
| Diffing two arrays or objects calls this function again, once per nesting | |
| level, so values nested deeply enough used to exhaust the call stack and | |
| terminate the process. The descent is bounded here: once @ref | |
| detail::recursion_depth_limit levels have been entered, @ref | |
| diff_iteratively diffs what is left without the call stack. | |
| */ | |
| static void diff_recursively(basic_json& result, const basic_json& source, const basic_json& target, | |
| string_t& path, const std::size_t depth) | |
| { | |
| // if the values are the same, there is nothing to do | |
| if (source == target) | |
| { | |
| return; | |
| } | |
| diff_unequal(result, source, target, path, depth); | |
| } | |
| /// @brief @ref diff_recursively for values known to be unequal; callers | |
| /// compare first so they extend the path only for unequal ones | |
| static void diff_unequal(basic_json& result, const basic_json& source, const basic_json& target, | |
| string_t& path, const std::size_t depth) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(depth >= detail::recursion_depth_limit())) | |
| { | |
| diff_iteratively(result, source, target, path); | |
| return; | |
| } | |
| if (source.type() != target.type()) | |
| { | |
| // different types: replace value | |
| diff_replace(result, path, target); | |
| return; | |
| } | |
| if (detail::is_primitive(source.type())) | |
| { | |
| // both primitive types: replace value | |
| diff_replace(result, path, target); | |
| return; | |
| } | |
| if (source.is_array()) | |
| { | |
| const std::size_t path_length = path.size(); | |
| // first pass: traverse common elements | |
| std::size_t i = 0; | |
| while (i < source.size() && i < target.size()) | |
| { | |
| // recursive call to compare array values at index i | |
| if (!(source[i] == target[i])) | |
| { | |
| diff_append_index(path, i); | |
| diff_unequal(result, source[i], target[i], path, depth + 1); | |
| path.resize(path_length); | |
| } | |
| ++i; | |
| } | |
| // We now reached the end of at least one array | |
| // in a second pass, traverse the remaining elements | |
| diff_array_tails(result, source, target, path, i); | |
| } | |
| else | |
| { | |
| diff_target_values target_values; | |
| std::vector<const_iterator> added; | |
| if (diff_object_keys(result, source, target, path, target_values, added)) | |
| { | |
| // fast path: target_values holds, for every member of | |
| // source in order, its value in target -- so no further | |
| // lookup is needed. Deleted keys are interleaved here | |
| // too, in source's original order, to match the | |
| // historical (pre-reordering-aware) output order. | |
| const std::size_t path_length = path.size(); | |
| std::size_t i = 0; | |
| for (auto it = source.cbegin(); it != source.cend(); ++it, ++i) | |
| { | |
| if (target_values[i] != nullptr) | |
| { | |
| if (!(it.value() == *target_values[i])) | |
| { | |
| diff_append_key(path, it.key()); | |
| diff_unequal(result, it.value(), *target_values[i], path, depth + 1); | |
| path.resize(path_length); | |
| } | |
| } | |
| else | |
| { | |
| // found a key that is not in target -> remove it | |
| diff_remove(result, diff_key_path(path, it.key())); | |
| } | |
| } | |
| // append the "add" operations for brand-new keys | |
| diff_added(result, added, path); | |
| } | |
| } | |
| } | |
| /*! | |
| @brief @ref diff without the call stack, appending the operations to | |
| @a result | |
| Produces the same operations as @ref diff_recursively. Only reached for | |
| values nested more deeply than @ref detail::recursion_depth_limit. | |
| */ | |
| static void diff_iteratively(basic_json& result, const basic_json& source, const basic_json& target, | |
| const string_t& path) | |
| { | |
| // The arrays and objects being diffed are kept on an explicit stack, | |
| // and every pair of elements is still diffed completely before the | |
| // next one, so the operations come out in the same order as in | |
| // diff_recursively. The path of the values being diffed is kept in | |
| // one buffer that grows and shrinks with the stack, rather than in a | |
| // new string per level. | |
| std::vector<diff_frame> stack; | |
| string_t current_path = path; | |
| // diff `s` against `t`, whose path is current_path: primitives, | |
| // values of different types, and objects whose members were reordered | |
| // are handled right away; arrays and other objects get a frame | |
| const auto enter = [&result, &stack, ¤t_path](const basic_json & s, const basic_json & t) | |
| { | |
| // if the values are the same, there is nothing to do. Arrays and | |
| // objects are not compared up front: comparing them visits | |
| // everything below them, so doing that at every level would take | |
| // quadratic time in the nesting depth - equal ones yield no | |
| // operations anyway. | |
| if ((!s.is_structured() || !t.is_structured()) && s == t) | |
| { | |
| return; | |
| } | |
| if (s.type() != t.type()) | |
| { | |
| // different types: replace value | |
| diff_replace(result, current_path, t); | |
| return; | |
| } | |
| if (detail::is_primitive(s.type())) | |
| { | |
| // both primitive types: replace value | |
| diff_replace(result, current_path, t); | |
| return; | |
| } | |
| if (s.is_array()) | |
| { | |
| stack.emplace_back(&s, &t, current_path.size()); | |
| return; | |
| } | |
| std::vector<const basic_json*> target_values; | |
| std::vector<const_iterator> added; | |
| if (diff_object_keys(result, s, t, current_path, target_values, added)) | |
| { | |
| // fast path: the frame walks source in lockstep with | |
| // common_keys, as diff_recursively does, and appends | |
| // added_ops once all members are done | |
| stack.emplace_back(&s, &t, current_path.size()); | |
| stack.back().member = s.cbegin(); | |
| stack.back().target_values = std::move(target_values); | |
| stack.back().added = std::move(added); | |
| } | |
| return; | |
| }; | |
| enter(source, target); | |
| while (!stack.empty()) | |
| { | |
| // the frame is copied out member by member and changed through | |
| // stack.back(): enter() may push a frame and the end of the loop | |
| // pops it, either of which would invalidate a reference to it | |
| const basic_json* const s = stack.back().source; | |
| const basic_json* const t = stack.back().target; | |
| const std::size_t path_length = stack.back().path_length; | |
| const std::size_t depth = stack.size(); | |
| if (s->is_array()) | |
| { | |
| const auto& source_array = *s->m_data.m_value.array; | |
| const auto& target_array = *t->m_data.m_value.array; | |
| // first pass: traverse common elements | |
| const std::size_t i = stack.back().index; | |
| if (i < source_array.size() && i < target_array.size()) | |
| { | |
| ++stack.back().index; | |
| diff_append_index(current_path, i); | |
| enter(source_array[i], target_array[i]); | |
| if (stack.size() == depth) | |
| { | |
| current_path.resize(path_length); | |
| } | |
| continue; | |
| } | |
| // We now reached the end of at least one array | |
| // in a second pass, traverse the remaining elements | |
| diff_array_tails(result, *s, *t, current_path, i); | |
| } | |
| else | |
| { | |
| const const_iterator it = stack.back().member; | |
| if (it != s->cend()) | |
| { | |
| ++stack.back().member; | |
| const basic_json* const target_value_ptr = stack.back().target_values[stack.back().index++]; | |
| if (target_value_ptr != nullptr) | |
| { | |
| const basic_json& target_value = *target_value_ptr; | |
| diff_append_key(current_path, it.key()); | |
| enter(it.value(), target_value); | |
| if (stack.size() == depth) | |
| { | |
| current_path.resize(path_length); | |
| } | |
| } | |
| else | |
| { | |
| // found a key that is not in target -> remove it | |
| diff_remove(result, diff_key_path(current_path, it.key())); | |
| } | |
| continue; | |
| } | |
| // append the "add" ops for brand-new keys collected when the | |
| // object was entered | |
| diff_added(result, stack.back().added, current_path); | |
| } | |
| // this array or object is done: continue with the one it is in | |
| stack.pop_back(); | |
| if (!stack.empty()) | |
| { | |
| current_path.resize(stack.back().path_length); | |
| } | |
| } | |
| } | |
| public: | |
| /// @} | |
| //////////////////////////////// | |
| // JSON Merge Patch functions // | |
| //////////////////////////////// | |
| /// @name JSON Merge Patch functions | |
| /// @{ | |
| /// @brief applies a JSON Merge Patch | |
| /// @sa https://json.nlohmann.me/api/basic_json/merge_patch/ | |
| void merge_patch(const basic_json& apply_patch) | |
| { | |
| // copy first: apply_patch may be *this or one of its descendants, | |
| // and is iterated (and moved from) below to patch *this | |
| basic_json patch = apply_patch; | |
| apply_merge_patch(patch, 0); | |
| } | |
| private: | |
| /*! | |
| @brief @ref merge_patch, for a patch at nesting level @a depth | |
| Applying a nested object calls this function again, once per nesting | |
| level, so a patch nested deeply enough used to exhaust the call stack and | |
| terminate the process. The descent is bounded here: once @ref | |
| detail::recursion_depth_limit levels have been entered, @ref | |
| merge_patch_iteratively applies what is left without the call stack. | |
| */ | |
| void apply_merge_patch(basic_json& apply_patch, const std::size_t depth) | |
| { | |
| if (apply_patch.is_object()) | |
| { | |
| if (JSON_HEDLEY_UNLIKELY(depth >= detail::recursion_depth_limit())) | |
| { | |
| merge_patch_iteratively(apply_patch); | |
| return; | |
| } | |
| if (!is_object()) | |
| { | |
| *this = object(); | |
| } | |
| for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it) | |
| { | |
| if (it.value().is_null()) | |
| { | |
| erase(it.key()); | |
| } | |
| else | |
| { | |
| operator[](it.key()).apply_merge_patch(it.value(), depth + 1); | |
| } | |
| } | |
| } | |
| else | |
| { | |
| *this = std::move(apply_patch); | |
| } | |
| } | |
| /*! | |
| @brief apply @a apply_patch to this value without the call stack | |
| Does the same as @ref merge_patch, keeping the objects being patched on an | |
| explicit stack instead of descending into them. A nested object is still | |
| patched completely before the next member, in the same order as the | |
| recursive version. Only reached for patches nested deeper than @ref | |
| detail::recursion_depth_limit. | |
| */ | |
| void merge_patch_iteratively(basic_json& apply_patch) | |
| { | |
| std::vector<merge_frame> stack; | |
| // patch `target` with `patch`, or start patching it member by member | |
| const auto apply = [&stack](basic_json & target, basic_json & patch) | |
| { | |
| if (patch.is_object()) | |
| { | |
| if (!target.is_object()) | |
| { | |
| target = basic_json::object(); | |
| } | |
| stack.emplace_back(&target, patch.begin(), patch.end()); | |
| } | |
| else | |
| { | |
| target = std::move(patch); | |
| } | |
| }; | |
| apply(*this, apply_patch); | |
| while (!stack.empty()) | |
| { | |
| // a copy, as applying a member below can reallocate the stack; | |
| // the frame itself is only changed through stack.back() | |
| const merge_frame frame = stack.back(); | |
| if (frame.position == frame.last) | |
| { | |
| stack.pop_back(); | |
| continue; | |
| } | |
| const iterator member = frame.position; | |
| ++stack.back().position; | |
| if (member.value().is_null()) | |
| { | |
| frame.target->erase(member.key()); | |
| } | |
| else | |
| { | |
| apply(frame.target->operator[](member.key()), member.value()); | |
| } | |
| } | |
| } | |
| public: | |
| /// @brief creates a diff as a JSON Merge Patch | |
| /// @sa https://json.nlohmann.me/api/basic_json/merge_diff/ | |
| JSON_HEDLEY_WARN_UNUSED_RESULT | |
| static basic_json merge_diff(const basic_json& source, const basic_json& target) | |
| { | |
| // unless both are objects, the patch is the target itself | |
| if (!source.is_object() || !target.is_object()) | |
| { | |
| return target; | |
| } | |
| return merge_diff_recursively(source, target, 0); | |
| } | |
| private: | |
| /// @brief two objects @ref merge_diff_iteratively is diffing | |
| struct merge_diff_frame | |
| { | |
| merge_diff_frame(const basic_json* source_, const basic_json* target_) | |
| : source(source_), target(target_), member(source_->cbegin()), patch(value_t::object) | |
| {} | |
| // declared for GCC's -Weffc++, as in diff_frame | |
| merge_diff_frame(const merge_diff_frame&) = default; | |
| merge_diff_frame(merge_diff_frame&&) = default; | |
| merge_diff_frame& operator=(const merge_diff_frame&) = default; | |
| merge_diff_frame& operator=(merge_diff_frame&&) = default; | |
| ~merge_diff_frame() = default; | |
| /// the objects being diffed | |
| const basic_json* source; | |
| const basic_json* target; | |
| /// the member of source being diffed; advanced once it is done | |
| const_iterator member; | |
| /// the patch for the members of source diffed so far | |
| basic_json patch; | |
| }; | |
| /// @brief add the members of object @a target that @a source does not | |
| /// have to the merge patch @a result | |
| static void merge_diff_added_members(basic_json& result, const basic_json& source, const basic_json& target) | |
| { | |
| for (auto it = target.begin(); it != target.end(); ++it) | |
| { | |
| auto itf = source.find(it.key()); | |
| if (itf == source.end()) | |
| { | |
| result[it.key()] = it.value(); | |
| } | |
| } | |
| } | |
| /*! | |
| @brief @ref merge_diff of two objects at nesting level @a depth | |
| Diffing two nested objects calls this function again, once per nesting | |
| level, so values nested deeply enough would exhaust the call stack and | |
| terminate the process. The descent is bounded here: once @ref | |
| detail::recursion_depth_limit levels have been entered, @ref | |
| merge_diff_iteratively diffs what is left without the call stack. | |
| */ | |
| static basic_json merge_diff_recursively(const basic_json& source, const basic_json& target, const std::size_t depth) | |
| { | |
| JSON_ASSERT(source.is_object() && target.is_object()); | |
| if (JSON_HEDLEY_UNLIKELY(depth >= detail::recursion_depth_limit())) | |
| { | |
| return merge_diff_iteratively(source, target); | |
| } | |
| basic_json result(value_t::object); | |
| for (auto it = source.begin(); it != source.end(); ++it) | |
| { | |
| auto itf = target.find(it.key()); | |
| if (itf != target.end()) | |
| { | |
| if (it.value().is_object() && itf.value().is_object()) | |
| { | |
| auto diff = merge_diff_recursively(it.value(), itf.value(), depth + 1); | |
| if (!diff.empty()) | |
| { | |
| result[it.key()] = std::move(diff); | |
| } | |
| } | |
| else if (it.value() != itf.value()) | |
| { | |
| result[it.key()] = itf.value(); | |
| } | |
| } | |
| else | |
| { | |
| result[it.key()] = value_t::null; | |
| } | |
| } | |
| merge_diff_added_members(result, source, target); | |
| return result; | |
| } | |
| /*! | |
| @brief @ref merge_diff of two objects without the call stack | |
| Produces the same patch as @ref merge_diff_recursively, keeping the objects | |
| being diffed on an explicit stack instead of descending into them. Two | |
| nested objects are still diffed completely before the next member, so the | |
| patch has its members in the same order as in the recursive version. Only | |
| reached for objects nested more deeply than @ref | |
| detail::recursion_depth_limit. | |
| */ | |
| static basic_json merge_diff_iteratively(const basic_json& source, const basic_json& target) | |
| { | |
| // the patch of source and target, set once their frame is popped | |
| basic_json result; | |
| std::vector<merge_diff_frame> stack; | |
| stack.emplace_back(&source, &target); | |
| while (!stack.empty()) | |
| { | |
| // the frame's members are copied out and it is changed through | |
| // stack.back(): pushing a frame for nested objects or popping | |
| // this one would invalidate a reference to it | |
| const basic_json* const s = stack.back().source; | |
| const basic_json* const t = stack.back().target; | |
| const const_iterator it = stack.back().member; | |
| if (it != s->cend()) | |
| { | |
| const const_iterator itf = t->find(it.key()); | |
| if (itf != t->cend()) | |
| { | |
| if (it.value().is_object() && itf.value().is_object()) | |
| { | |
| // member is advanced once their patch is under its key | |
| stack.emplace_back(&it.value(), &itf.value()); | |
| continue; | |
| } | |
| if (it.value() != itf.value()) | |
| { | |
| stack.back().patch[it.key()] = itf.value(); | |
| } | |
| } | |
| else | |
| { | |
| stack.back().patch[it.key()] = value_t::null; | |
| } | |
| ++stack.back().member; | |
| continue; | |
| } | |
| merge_diff_added_members(stack.back().patch, *s, *t); | |
| // these objects are done: continue with the ones they are in | |
| basic_json patch = std::move(stack.back().patch); | |
| stack.pop_back(); | |
| if (stack.empty()) | |
| { | |
| result = std::move(patch); | |
| } | |
| else | |
| { | |
| if (!patch.empty()) | |
| { | |
| stack.back().patch[stack.back().member.key()] = std::move(patch); | |
| } | |
| ++stack.back().member; | |
| } | |
| } | |
| return result; | |
| } | |
| /// @} | |
| }; | |
| /// @brief user-defined to_string function for JSON values | |
| /// @sa https://json.nlohmann.me/api/basic_json/to_string/ | |
| NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
| std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j) | |
| { | |
| return j.dump(); | |
| } | |
| /// @brief user-defined format_as function for JSON values (fmt <= 11.0.x support) | |
| /// @sa https://json.nlohmann.me/api/basic_json/format_as/ | |
| NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
| std::string format_as(const NLOHMANN_BASIC_JSON_TPL& j) | |
| { | |
| return j.dump(); | |
| } | |
| #if JSON_DELETE_DEPRECATED_FUNCTIONS && !defined(JSON_NO_IO) | |
| /// @brief serialize to stream (deleted; use operator<<(std::ostream&, const basic_json&)) | |
| /// @sa https://json.nlohmann.me/api/operator_ltlt/ | |
| NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
| std::ostream& operator>>(const NLOHMANN_BASIC_JSON_TPL& j, std::ostream& o) = delete; | |
| /// @brief deserialize from stream (deleted; use operator>>(std::istream&, basic_json&)) | |
| /// @sa https://json.nlohmann.me/api/operator_gtgt/ | |
| NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
| std::istream& operator<<(NLOHMANN_BASIC_JSON_TPL& j, std::istream& i) = delete; | |
| #endif | |
| NLOHMANN_JSON_NAMESPACE_END | |
| /////////////////////// | |
| // nonmember support // | |
| /////////////////////// | |
| namespace std // NOLINT(cert-dcl58-cpp) | |
| { | |
| /// @brief hash value for JSON objects | |
| /// @sa https://json.nlohmann.me/api/basic_json/std_hash/ | |
| NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
| struct hash<nlohmann::NLOHMANN_BASIC_JSON_TPL> // NOLINT(cert-dcl58-cpp,bugprone-std-namespace-modification) | |
| { | |
| std::size_t operator()(const nlohmann::NLOHMANN_BASIC_JSON_TPL& j) const | |
| { | |
| return nlohmann::detail::hash(j); | |
| } | |
| }; | |
| // specialization for std::less<value_t> | |
| template<> | |
| struct less< ::nlohmann::detail::value_t> // do not remove the space after '<', see https://github.com/nlohmann/json/pull/679 | |
| { | |
| /*! | |
| @brief compare two value_t enum values | |
| @since version 3.0.0 | |
| */ | |
| bool operator()(::nlohmann::detail::value_t lhs, | |
| ::nlohmann::detail::value_t rhs) const noexcept | |
| { | |
| #if JSON_HAS_THREE_WAY_COMPARISON | |
| return std::is_lt(lhs <=> rhs); // *NOPAD* | |
| #else | |
| return ::nlohmann::detail::operator<(lhs, rhs); | |
| #endif | |
| } | |
| }; | |
| // C++20 prohibit function specialization in the std namespace. | |
| #ifndef JSON_HAS_CPP_20 | |
| /// @brief exchanges the values of two JSON objects | |
| /// @sa https://json.nlohmann.me/api/basic_json/std_swap/ | |
| NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
| inline void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL& j1, nlohmann::NLOHMANN_BASIC_JSON_TPL& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name, cert-dcl58-cpp,bugprone-std-namespace-modification) | |
| is_nothrow_move_constructible<nlohmann::NLOHMANN_BASIC_JSON_TPL>::value&& // NOLINT(misc-redundant-expression,cppcoreguidelines-noexcept-swap,performance-noexcept-swap) | |
| is_nothrow_move_assignable<nlohmann::NLOHMANN_BASIC_JSON_TPL>::value) | |
| { | |
| j1.swap(j2); | |
| } | |
| #endif | |
| #if JSON_HAS_STD_FORMAT | |
| /// @brief std::formatter specialization for JSON values | |
| /// @sa https://json.nlohmann.me/api/basic_json/std_formatter/ | |
| NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
| struct formatter<nlohmann::NLOHMANN_BASIC_JSON_TPL, char> // NOLINT(cert-dcl58-cpp,bugprone-std-namespace-modification) | |
| { | |
| // -1 means compact output (dump()); any value >= 0 means pretty-printed | |
| // output with that many spaces (or indent_char) per level (dump(indent, indent_char)). | |
| int indent = -1; | |
| char indent_char = ' '; | |
| constexpr format_parse_context::iterator parse(format_parse_context& ctx) | |
| { | |
| format_parse_context::iterator it = ctx.begin(); | |
| const format_parse_context::iterator end = ctx.end(); | |
| constexpr auto is_align = [](char c) | |
| { | |
| return c == '<' || c == '>' || c == '^'; | |
| }; | |
| // [[fill] align] - repurposed here to pick a custom indent character, | |
| // e.g. "{:.>#4}" pretty-prints with '.' as the indent character | |
| if (it != end && it + 1 != end && is_align(it[1])) | |
| { | |
| indent_char = *it; | |
| it += 2; | |
| } | |
| else if (it != end && is_align(*it)) | |
| { | |
| ++it; | |
| } | |
| // ['#'] - "alternate form", used here to request pretty-printing with a | |
| // default indent of 4 (overridden by an explicit width below, if given) | |
| if (it != end && *it == '#') | |
| { | |
| indent = 4; | |
| ++it; | |
| } | |
| // [width] - repurposed here to pick the indent size for pretty-printing, | |
| // e.g. "{:2}" or "{:#2}" pretty-print with an indent of 2; a width without | |
| // '#' implies pretty-printing since an indent otherwise has no meaning | |
| if (it != end && *it >= '1' && *it <= '9') | |
| { | |
| indent = 0; | |
| while (it != end && *it >= '0' && *it <= '9') | |
| { | |
| indent = (indent * 10) + (*it - '0'); | |
| ++it; | |
| } | |
| } | |
| // sign, the '0' flag, precision, locale-specific formatting ('L'), dynamic | |
| // width/precision ("{...}"), and type characters all have no meaning for | |
| // JSON values; none of them are consumed above, so they all end up rejected | |
| // by this single check along with any other unrecognized trailing spec. | |
| if (it != end && *it != '}') | |
| { | |
| JSON_THROW(format_error("invalid format args for nlohmann::json")); | |
| } | |
| return it; | |
| } | |
| template<typename FormatContext> | |
| auto format(const nlohmann::NLOHMANN_BASIC_JSON_TPL& j, FormatContext& ctx) const -> decltype(ctx.out()) | |
| { | |
| // dump()'s own default (indent = -1) already means compact output, so this | |
| // covers both the compact and pretty-printed cases without a branch. | |
| const auto dumped = j.dump(indent, indent_char); | |
| return std::copy(dumped.begin(), dumped.end(), ctx.out()); | |
| } | |
| }; | |
| #endif | |
| } // namespace std | |
| // keep: undoes the macros defined via detail/macro_scope.hpp at the top of this file; removing it | |
| // (nothing in this file *uses* a symbol from it) would leak JSON_* macros into every translation | |
| // unit that includes this header. | |
| // #include <nlohmann/detail/macro_unscope.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| // clean up | |
| #undef JSON_ASSERT | |
| #undef JSON_INTERNAL_CATCH | |
| #undef JSON_THROW | |
| #undef JSON_PRIVATE_UNLESS_TESTED | |
| #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION | |
| #undef NLOHMANN_BASIC_JSON_TPL | |
| #undef JSON_EXPLICIT | |
| #undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL | |
| #undef JSON_INLINE_VARIABLE | |
| #undef JSON_NO_UNIQUE_ADDRESS | |
| #undef JSON_DISABLE_ENUM_SERIALIZATION | |
| #undef JSON_DISABLE_TUPLE_REFERENCE_CONVERSION | |
| #undef JSON_UNLOCKED_FILE_IO | |
| #undef JSON_DTOA_SSE2 | |
| #undef JSON_DTOA_NEON | |
| #undef JSON_LITTLE_ENDIAN_TARGET | |
| #undef JSON_BIG_ENDIAN_TARGET | |
| #undef JSON_SCAN_NEON | |
| #undef JSON_SCAN_SSE2 | |
| #undef JSON_SCAN_SSSE3 | |
| #undef JSON_SCAN_SSSE3_DISPATCH | |
| #undef JSON_SCAN_SSSE3_TARGET | |
| #undef JSON_SCAN_VECTOR | |
| #undef JSON_SCAN_VECTOR_UTF8 | |
| #ifndef JSON_TEST_KEEP_MACROS | |
| #undef JSON_CATCH | |
| #undef JSON_TRY | |
| #undef JSON_HAS_CPP_11 | |
| #undef JSON_HAS_CPP_14 | |
| #undef JSON_HAS_CPP_17 | |
| #undef JSON_HAS_CPP_20 | |
| #undef JSON_HAS_CPP_23 | |
| #undef JSON_HAS_CPP_26 | |
| #undef JSON_HAS_FILESYSTEM | |
| #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM | |
| #undef JSON_HAS_THREE_WAY_COMPARISON | |
| #undef JSON_HAS_RANGES | |
| #undef JSON_HAS_RANGE_VIEW_CONVERSION | |
| #undef JSON_HAS_STD_FORMAT | |
| #undef JSON_HAS_STATIC_RTTI | |
| #undef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON | |
| #undef JSON_BRACE_INIT_COPY_SEMANTICS | |
| #undef JSON_PRECISE_STREAM_POSITION | |
| #undef JSON_STRICT_NUL_HANDLING | |
| #undef JSON_STRICT_BINARY_UTF8 | |
| #undef JSON_DELETE_DEPRECATED_FUNCTIONS | |
| #undef JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS | |
| #undef JSON_DISABLE_STREAM_BULK_SCAN | |
| #undef JSON_DISABLE_UNLOCKED_FILE_IO | |
| #endif | |
| // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #undef JSON_HEDLEY_ALWAYS_INLINE | |
| #undef JSON_HEDLEY_ARM_VERSION | |
| #undef JSON_HEDLEY_ARM_VERSION_CHECK | |
| #undef JSON_HEDLEY_ARRAY_PARAM | |
| #undef JSON_HEDLEY_ASSUME | |
| #undef JSON_HEDLEY_BEGIN_C_DECLS | |
| #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE | |
| #undef JSON_HEDLEY_CLANG_HAS_BUILTIN | |
| #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE | |
| #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE | |
| #undef JSON_HEDLEY_CLANG_HAS_EXTENSION | |
| #undef JSON_HEDLEY_CLANG_HAS_FEATURE | |
| #undef JSON_HEDLEY_CLANG_HAS_WARNING | |
| #undef JSON_HEDLEY_COMPCERT_VERSION | |
| #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK | |
| #undef JSON_HEDLEY_CONCAT | |
| #undef JSON_HEDLEY_CONCAT3 | |
| #undef JSON_HEDLEY_CONCAT3_EX | |
| #undef JSON_HEDLEY_CONCAT_EX | |
| #undef JSON_HEDLEY_CONST | |
| #undef JSON_HEDLEY_CONSTEXPR | |
| #undef JSON_HEDLEY_CONST_CAST | |
| #undef JSON_HEDLEY_CPP_CAST | |
| #undef JSON_HEDLEY_CRAY_VERSION | |
| #undef JSON_HEDLEY_CRAY_VERSION_CHECK | |
| #undef JSON_HEDLEY_C_DECL | |
| #undef JSON_HEDLEY_DEPRECATED | |
| #undef JSON_HEDLEY_DEPRECATED_FOR | |
| #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL | |
| #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ | |
| #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED | |
| #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES | |
| #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS | |
| #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION | |
| #undef JSON_HEDLEY_DIAGNOSTIC_POP | |
| #undef JSON_HEDLEY_DIAGNOSTIC_PUSH | |
| #undef JSON_HEDLEY_DMC_VERSION | |
| #undef JSON_HEDLEY_DMC_VERSION_CHECK | |
| #undef JSON_HEDLEY_EMPTY_BASES | |
| #undef JSON_HEDLEY_EMSCRIPTEN_VERSION | |
| #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK | |
| #undef JSON_HEDLEY_END_C_DECLS | |
| #undef JSON_HEDLEY_FLAGS | |
| #undef JSON_HEDLEY_FLAGS_CAST | |
| #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE | |
| #undef JSON_HEDLEY_GCC_HAS_BUILTIN | |
| #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE | |
| #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE | |
| #undef JSON_HEDLEY_GCC_HAS_EXTENSION | |
| #undef JSON_HEDLEY_GCC_HAS_FEATURE | |
| #undef JSON_HEDLEY_GCC_HAS_WARNING | |
| #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK | |
| #undef JSON_HEDLEY_GCC_VERSION | |
| #undef JSON_HEDLEY_GCC_VERSION_CHECK | |
| #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE | |
| #undef JSON_HEDLEY_GNUC_HAS_BUILTIN | |
| #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE | |
| #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE | |
| #undef JSON_HEDLEY_GNUC_HAS_EXTENSION | |
| #undef JSON_HEDLEY_GNUC_HAS_FEATURE | |
| #undef JSON_HEDLEY_GNUC_HAS_WARNING | |
| #undef JSON_HEDLEY_GNUC_VERSION | |
| #undef JSON_HEDLEY_GNUC_VERSION_CHECK | |
| #undef JSON_HEDLEY_HAS_ATTRIBUTE | |
| #undef JSON_HEDLEY_HAS_BUILTIN | |
| #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE | |
| #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS | |
| #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE | |
| #undef JSON_HEDLEY_HAS_EXTENSION | |
| #undef JSON_HEDLEY_HAS_FEATURE | |
| #undef JSON_HEDLEY_HAS_WARNING | |
| #undef JSON_HEDLEY_IAR_VERSION | |
| #undef JSON_HEDLEY_IAR_VERSION_CHECK | |
| #undef JSON_HEDLEY_IBM_VERSION | |
| #undef JSON_HEDLEY_IBM_VERSION_CHECK | |
| #undef JSON_HEDLEY_IMPORT | |
| #undef JSON_HEDLEY_INLINE | |
| #undef JSON_HEDLEY_INTEL_CL_VERSION | |
| #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK | |
| #undef JSON_HEDLEY_INTEL_VERSION | |
| #undef JSON_HEDLEY_INTEL_VERSION_CHECK | |
| #undef JSON_HEDLEY_IS_CONSTANT | |
| #undef JSON_HEDLEY_IS_CONSTEXPR_ | |
| #undef JSON_HEDLEY_LIKELY | |
| #undef JSON_HEDLEY_MALLOC | |
| #undef JSON_HEDLEY_MCST_LCC_VERSION | |
| #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK | |
| #undef JSON_HEDLEY_MESSAGE | |
| #undef JSON_HEDLEY_MSVC_VERSION | |
| #undef JSON_HEDLEY_MSVC_VERSION_CHECK | |
| #undef JSON_HEDLEY_NEVER_INLINE | |
| #undef JSON_HEDLEY_NON_NULL | |
| #undef JSON_HEDLEY_NO_ESCAPE | |
| #undef JSON_HEDLEY_NO_RETURN | |
| #undef JSON_HEDLEY_NO_THROW | |
| #undef JSON_HEDLEY_NULL | |
| #undef JSON_HEDLEY_PELLES_VERSION | |
| #undef JSON_HEDLEY_PELLES_VERSION_CHECK | |
| #undef JSON_HEDLEY_PGI_VERSION | |
| #undef JSON_HEDLEY_PGI_VERSION_CHECK | |
| #undef JSON_HEDLEY_PRAGMA | |
| #undef JSON_HEDLEY_PREDICT | |
| #undef JSON_HEDLEY_PREDICT_FALSE | |
| #undef JSON_HEDLEY_PREDICT_TRUE | |
| #undef JSON_HEDLEY_PRINTF_FORMAT | |
| #undef JSON_HEDLEY_PRIVATE | |
| #undef JSON_HEDLEY_PUBLIC | |
| #undef JSON_HEDLEY_PURE | |
| #undef JSON_HEDLEY_REINTERPRET_CAST | |
| #undef JSON_HEDLEY_REQUIRE | |
| #undef JSON_HEDLEY_REQUIRE_CONSTEXPR | |
| #undef JSON_HEDLEY_REQUIRE_MSG | |
| #undef JSON_HEDLEY_RESTRICT | |
| #undef JSON_HEDLEY_RETURNS_NON_NULL | |
| #undef JSON_HEDLEY_SENTINEL | |
| #undef JSON_HEDLEY_STATIC_ASSERT | |
| #undef JSON_HEDLEY_STATIC_CAST | |
| #undef JSON_HEDLEY_STRINGIFY | |
| #undef JSON_HEDLEY_STRINGIFY_EX | |
| #undef JSON_HEDLEY_SUNPRO_VERSION | |
| #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK | |
| #undef JSON_HEDLEY_TINYC_VERSION | |
| #undef JSON_HEDLEY_TINYC_VERSION_CHECK | |
| #undef JSON_HEDLEY_TI_ARMCL_VERSION | |
| #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK | |
| #undef JSON_HEDLEY_TI_CL2000_VERSION | |
| #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK | |
| #undef JSON_HEDLEY_TI_CL430_VERSION | |
| #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK | |
| #undef JSON_HEDLEY_TI_CL6X_VERSION | |
| #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK | |
| #undef JSON_HEDLEY_TI_CL7X_VERSION | |
| #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK | |
| #undef JSON_HEDLEY_TI_CLPRU_VERSION | |
| #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK | |
| #undef JSON_HEDLEY_TI_VERSION | |
| #undef JSON_HEDLEY_TI_VERSION_CHECK | |
| #undef JSON_HEDLEY_UNAVAILABLE | |
| #undef JSON_HEDLEY_UNLIKELY | |
| #undef JSON_HEDLEY_UNPREDICTABLE | |
| #undef JSON_HEDLEY_UNREACHABLE | |
| #undef JSON_HEDLEY_UNREACHABLE_RETURN | |
| #undef JSON_HEDLEY_VERSION | |
| #undef JSON_HEDLEY_VERSION_DECODE_MAJOR | |
| #undef JSON_HEDLEY_VERSION_DECODE_MINOR | |
| #undef JSON_HEDLEY_VERSION_DECODE_REVISION | |
| #undef JSON_HEDLEY_VERSION_ENCODE | |
| #undef JSON_HEDLEY_WARNING | |
| #undef JSON_HEDLEY_WARN_UNUSED_RESULT | |
| #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG | |
| #undef JSON_HEDLEY_FALL_THROUGH | |
| // IWYU pragma: keep | |
| // The user-defined string literals are in a separate header, because their | |
| // bodies instantiate the parser in every translation unit that includes them. | |
| // Define JSON_NO_AUTOMATIC_UDLS to include <nlohmann/json_literals.hpp> only | |
| // where needed. | |
| #ifndef JSON_NO_AUTOMATIC_UDLS | |
| // NOLINTNEXTLINE(misc-header-include-cycle): json_literals.hpp includes this header | |
| // #include <nlohmann/json_literals.hpp> | |
| // __ _____ _____ _____ | |
| // __| | __| | | | JSON for Modern C++ | |
| // | | |__ | | | | | | version 3.12.0 | |
| // |_____|_____|_____|_|___| https://github.com/nlohmann/json | |
| // | |
| // SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me> | |
| // SPDX-License-Identifier: MIT | |
| #ifndef INCLUDE_NLOHMANN_JSON_LITERALS_HPP_ | |
| #define INCLUDE_NLOHMANN_JSON_LITERALS_HPP_ | |
| #include <cstddef> // size_t | |
| #include <string> // string | |
| // NOLINTNEXTLINE(misc-header-include-cycle): json.hpp includes this header at its end | |
| // #include <nlohmann/json.hpp> | |
| // This header is included at the end of <nlohmann/json.hpp> unless | |
| // JSON_NO_AUTOMATIC_UDLS is defined, and can be included on its own after that. | |
| // Either way, the library's internal macros are no longer defined here (and the | |
| // amalgamation inlines macro_scope.hpp only once), so only standard and public | |
| // macros may be used below. | |
| // declares the literal operator for the given suffix; GCC 4.8 requires a space | |
| // between "" and the suffix, which newer compilers deprecate (CWG 2521) | |
| #if !defined(__GNUC__) || defined(__clang__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9) | |
| #define NLOHMANN_JSON_LITERAL_OPERATOR(suffix) operator""##suffix | |
| #else | |
| #define NLOHMANN_JSON_LITERAL_OPERATOR(suffix) operator"" suffix | |
| #endif | |
| NLOHMANN_JSON_NAMESPACE_BEGIN | |
| inline namespace literals | |
| { | |
| inline namespace json_literals | |
| { | |
| /// @brief user-defined string literal for JSON values | |
| /// @sa https://json.nlohmann.me/api/operator_literal_json/ | |
| inline nlohmann::json NLOHMANN_JSON_LITERAL_OPERATOR(_json)(const char* s, std::size_t n) | |
| { | |
| return nlohmann::json::parse(s, s + n); | |
| } | |
| #if defined(__cpp_char8_t) | |
| inline nlohmann::json operator""_json(const char8_t* s, std::size_t n) | |
| { | |
| return nlohmann::json::parse(reinterpret_cast<const char*>(s), | |
| reinterpret_cast<const char*>(s) + n); | |
| } | |
| #endif | |
| /// @brief user-defined string literal for JSON pointer | |
| /// @sa https://json.nlohmann.me/api/operator_literal_json_pointer/ | |
| inline nlohmann::json::json_pointer NLOHMANN_JSON_LITERAL_OPERATOR(_json_pointer)(const char* s, std::size_t n) | |
| { | |
| return nlohmann::json::json_pointer(std::string(s, n)); | |
| } | |
| #if defined(__cpp_char8_t) | |
| inline nlohmann::json::json_pointer operator""_json_pointer(const char8_t* s, std::size_t n) | |
| { | |
| return nlohmann::json::json_pointer(std::string(reinterpret_cast<const char*>(s), n)); | |
| } | |
| #endif | |
| } // namespace json_literals | |
| } // namespace literals | |
| NLOHMANN_JSON_NAMESPACE_END | |
| #if !defined(JSON_USE_GLOBAL_UDLS) || JSON_USE_GLOBAL_UDLS | |
| using nlohmann::literals::json_literals::NLOHMANN_JSON_LITERAL_OPERATOR(_json); // NOLINT(misc-unused-using-decls,google-global-names-in-headers) | |
| using nlohmann::literals::json_literals::NLOHMANN_JSON_LITERAL_OPERATOR(_json_pointer); //NOLINT(misc-unused-using-decls,google-global-names-in-headers) | |
| #endif | |
| #undef NLOHMANN_JSON_LITERAL_OPERATOR | |
| #endif // INCLUDE_NLOHMANN_JSON_LITERALS_HPP_ | |
| // IWYU pragma: export | |
| #endif | |
| #endif // INCLUDE_NLOHMANN_JSON_HPP_ |