🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

22091 lines
785 KiB

  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.10.5
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. SPDX-License-Identifier: MIT
  8. Copyright (c) 2013-2022 Niels Lohmann <http://nlohmann.me>.
  9. Permission is hereby granted, free of charge, to any person obtaining a copy
  10. of this software and associated documentation files (the "Software"), to deal
  11. in the Software without restriction, including without limitation the rights
  12. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. copies of the Software, and to permit persons to whom the Software is
  14. furnished to do so, subject to the following conditions:
  15. The above copyright notice and this permission notice shall be included in all
  16. copies or substantial portions of the Software.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24. */
  25. /****************************************************************************\
  26. * Note on documentation: The source files contain links to the online *
  27. * documentation of the public API at https://json.nlohmann.me. This URL *
  28. * contains the most recent documentation and should also be applicable to *
  29. * previous versions; documentation for deprecated functions is not *
  30. * removed, but marked deprecated. See "Generate documentation" section in *
  31. * file doc/README.md. *
  32. \****************************************************************************/
  33. #ifndef INCLUDE_NLOHMANN_JSON_HPP_
  34. #define INCLUDE_NLOHMANN_JSON_HPP_
  35. #define NLOHMANN_JSON_VERSION_MAJOR 3
  36. #define NLOHMANN_JSON_VERSION_MINOR 10
  37. #define NLOHMANN_JSON_VERSION_PATCH 5
  38. #include <algorithm> // all_of, find, for_each
  39. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  40. #include <functional> // hash, less
  41. #include <initializer_list> // initializer_list
  42. #ifndef JSON_NO_IO
  43. #include <iosfwd> // istream, ostream
  44. #endif // JSON_NO_IO
  45. #include <iterator> // random_access_iterator_tag
  46. #include <memory> // unique_ptr
  47. #include <numeric> // accumulate
  48. #include <string> // string, stoi, to_string
  49. #include <utility> // declval, forward, move, pair, swap
  50. #include <vector> // vector
  51. // #include <nlohmann/adl_serializer.hpp>
  52. #include <type_traits>
  53. #include <utility>
  54. // #include <nlohmann/detail/conversions/from_json.hpp>
  55. #include <algorithm> // transform
  56. #include <array> // array
  57. #include <forward_list> // forward_list
  58. #include <iterator> // inserter, front_inserter, end
  59. #include <map> // map
  60. #include <string> // string
  61. #include <tuple> // tuple, make_tuple
  62. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  63. #include <unordered_map> // unordered_map
  64. #include <utility> // pair, declval
  65. #include <valarray> // valarray
  66. // #include <nlohmann/detail/exceptions.hpp>
  67. #include <exception> // exception
  68. #include <stdexcept> // runtime_error
  69. #include <string> // to_string
  70. #include <vector> // vector
  71. // #include <nlohmann/detail/value_t.hpp>
  72. #include <array> // array
  73. #include <cstddef> // size_t
  74. #include <cstdint> // uint8_t
  75. #include <string> // string
  76. namespace nlohmann
  77. {
  78. namespace detail
  79. {
  80. ///////////////////////////
  81. // JSON type enumeration //
  82. ///////////////////////////
  83. /*!
  84. @brief the JSON type enumeration
  85. This enumeration collects the different JSON types. It is internally used to
  86. distinguish the stored values, and the functions @ref basic_json::is_null(),
  87. @ref basic_json::is_object(), @ref basic_json::is_array(),
  88. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  89. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  90. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  91. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  92. @ref basic_json::is_structured() rely on it.
  93. @note There are three enumeration entries (number_integer, number_unsigned, and
  94. number_float), because the library distinguishes these three types for numbers:
  95. @ref basic_json::number_unsigned_t is used for unsigned integers,
  96. @ref basic_json::number_integer_t is used for signed integers, and
  97. @ref basic_json::number_float_t is used for floating-point numbers or to
  98. approximate integers which do not fit in the limits of their respective type.
  99. @sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  100. value with the default value for a given type
  101. @since version 1.0.0
  102. */
  103. enum class value_t : std::uint8_t
  104. {
  105. null, ///< null value
  106. object, ///< object (unordered set of name/value pairs)
  107. array, ///< array (ordered collection of values)
  108. string, ///< string value
  109. boolean, ///< boolean value
  110. number_integer, ///< number value (signed integer)
  111. number_unsigned, ///< number value (unsigned integer)
  112. number_float, ///< number value (floating-point)
  113. binary, ///< binary array (ordered collection of bytes)
  114. discarded ///< discarded by the parser callback function
  115. };
  116. /*!
  117. @brief comparison operator for JSON types
  118. Returns an ordering that is similar to Python:
  119. - order: null < boolean < number < object < array < string < binary
  120. - furthermore, each type is not smaller than itself
  121. - discarded values are not comparable
  122. - binary is represented as a b"" string in python and directly comparable to a
  123. string; however, making a binary array directly comparable with a string would
  124. be surprising behavior in a JSON file.
  125. @since version 1.0.0
  126. */
  127. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  128. {
  129. static constexpr std::array<std::uint8_t, 9> order = {{
  130. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  131. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */,
  132. 6 /* binary */
  133. }
  134. };
  135. const auto l_index = static_cast<std::size_t>(lhs);
  136. const auto r_index = static_cast<std::size_t>(rhs);
  137. return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index];
  138. }
  139. } // namespace detail
  140. } // namespace nlohmann
  141. // #include <nlohmann/detail/string_escape.hpp>
  142. #include <string>
  143. // #include <nlohmann/detail/macro_scope.hpp>
  144. #include <utility> // declval, pair
  145. // #include <nlohmann/thirdparty/hedley/hedley.hpp>
  146. /* Hedley - https://nemequ.github.io/hedley
  147. * Created by Evan Nemerson <evan@nemerson.com>
  148. *
  149. * To the extent possible under law, the author(s) have dedicated all
  150. * copyright and related and neighboring rights to this software to
  151. * the public domain worldwide. This software is distributed without
  152. * any warranty.
  153. *
  154. * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
  155. * SPDX-License-Identifier: CC0-1.0
  156. */
  157. #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15)
  158. #if defined(JSON_HEDLEY_VERSION)
  159. #undef JSON_HEDLEY_VERSION
  160. #endif
  161. #define JSON_HEDLEY_VERSION 15
  162. #if defined(JSON_HEDLEY_STRINGIFY_EX)
  163. #undef JSON_HEDLEY_STRINGIFY_EX
  164. #endif
  165. #define JSON_HEDLEY_STRINGIFY_EX(x) #x
  166. #if defined(JSON_HEDLEY_STRINGIFY)
  167. #undef JSON_HEDLEY_STRINGIFY
  168. #endif
  169. #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
  170. #if defined(JSON_HEDLEY_CONCAT_EX)
  171. #undef JSON_HEDLEY_CONCAT_EX
  172. #endif
  173. #define JSON_HEDLEY_CONCAT_EX(a,b) a##b
  174. #if defined(JSON_HEDLEY_CONCAT)
  175. #undef JSON_HEDLEY_CONCAT
  176. #endif
  177. #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b)
  178. #if defined(JSON_HEDLEY_CONCAT3_EX)
  179. #undef JSON_HEDLEY_CONCAT3_EX
  180. #endif
  181. #define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c
  182. #if defined(JSON_HEDLEY_CONCAT3)
  183. #undef JSON_HEDLEY_CONCAT3
  184. #endif
  185. #define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c)
  186. #if defined(JSON_HEDLEY_VERSION_ENCODE)
  187. #undef JSON_HEDLEY_VERSION_ENCODE
  188. #endif
  189. #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
  190. #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
  191. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  192. #endif
  193. #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
  194. #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
  195. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  196. #endif
  197. #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
  198. #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
  199. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  200. #endif
  201. #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
  202. #if defined(JSON_HEDLEY_GNUC_VERSION)
  203. #undef JSON_HEDLEY_GNUC_VERSION
  204. #endif
  205. #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
  206. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
  207. #elif defined(__GNUC__)
  208. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
  209. #endif
  210. #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
  211. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  212. #endif
  213. #if defined(JSON_HEDLEY_GNUC_VERSION)
  214. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  215. #else
  216. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
  217. #endif
  218. #if defined(JSON_HEDLEY_MSVC_VERSION)
  219. #undef JSON_HEDLEY_MSVC_VERSION
  220. #endif
  221. #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL)
  222. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
  223. #elif defined(_MSC_FULL_VER) && !defined(__ICL)
  224. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
  225. #elif defined(_MSC_VER) && !defined(__ICL)
  226. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
  227. #endif
  228. #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
  229. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  230. #endif
  231. #if !defined(JSON_HEDLEY_MSVC_VERSION)
  232. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
  233. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  234. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
  235. #elif defined(_MSC_VER) && (_MSC_VER >= 1200)
  236. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
  237. #else
  238. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
  239. #endif
  240. #if defined(JSON_HEDLEY_INTEL_VERSION)
  241. #undef JSON_HEDLEY_INTEL_VERSION
  242. #endif
  243. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL)
  244. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
  245. #elif defined(__INTEL_COMPILER) && !defined(__ICL)
  246. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
  247. #endif
  248. #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
  249. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  250. #endif
  251. #if defined(JSON_HEDLEY_INTEL_VERSION)
  252. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  253. #else
  254. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
  255. #endif
  256. #if defined(JSON_HEDLEY_INTEL_CL_VERSION)
  257. #undef JSON_HEDLEY_INTEL_CL_VERSION
  258. #endif
  259. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL)
  260. #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0)
  261. #endif
  262. #if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK)
  263. #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK
  264. #endif
  265. #if defined(JSON_HEDLEY_INTEL_CL_VERSION)
  266. #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  267. #else
  268. #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0)
  269. #endif
  270. #if defined(JSON_HEDLEY_PGI_VERSION)
  271. #undef JSON_HEDLEY_PGI_VERSION
  272. #endif
  273. #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
  274. #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
  275. #endif
  276. #if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
  277. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  278. #endif
  279. #if defined(JSON_HEDLEY_PGI_VERSION)
  280. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  281. #else
  282. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
  283. #endif
  284. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  285. #undef JSON_HEDLEY_SUNPRO_VERSION
  286. #endif
  287. #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
  288. #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)
  289. #elif defined(__SUNPRO_C)
  290. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
  291. #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
  292. #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)
  293. #elif defined(__SUNPRO_CC)
  294. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
  295. #endif
  296. #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
  297. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  298. #endif
  299. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  300. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  301. #else
  302. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
  303. #endif
  304. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  305. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  306. #endif
  307. #if defined(__EMSCRIPTEN__)
  308. #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
  309. #endif
  310. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
  311. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  312. #endif
  313. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  314. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  315. #else
  316. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
  317. #endif
  318. #if defined(JSON_HEDLEY_ARM_VERSION)
  319. #undef JSON_HEDLEY_ARM_VERSION
  320. #endif
  321. #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
  322. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
  323. #elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
  324. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
  325. #endif
  326. #if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
  327. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  328. #endif
  329. #if defined(JSON_HEDLEY_ARM_VERSION)
  330. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  331. #else
  332. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
  333. #endif
  334. #if defined(JSON_HEDLEY_IBM_VERSION)
  335. #undef JSON_HEDLEY_IBM_VERSION
  336. #endif
  337. #if defined(__ibmxl__)
  338. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
  339. #elif defined(__xlC__) && defined(__xlC_ver__)
  340. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
  341. #elif defined(__xlC__)
  342. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
  343. #endif
  344. #if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
  345. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  346. #endif
  347. #if defined(JSON_HEDLEY_IBM_VERSION)
  348. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  349. #else
  350. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
  351. #endif
  352. #if defined(JSON_HEDLEY_TI_VERSION)
  353. #undef JSON_HEDLEY_TI_VERSION
  354. #endif
  355. #if \
  356. defined(__TI_COMPILER_VERSION__) && \
  357. ( \
  358. defined(__TMS470__) || defined(__TI_ARM__) || \
  359. defined(__MSP430__) || \
  360. defined(__TMS320C2000__) \
  361. )
  362. #if (__TI_COMPILER_VERSION__ >= 16000000)
  363. #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  364. #endif
  365. #endif
  366. #if defined(JSON_HEDLEY_TI_VERSION_CHECK)
  367. #undef JSON_HEDLEY_TI_VERSION_CHECK
  368. #endif
  369. #if defined(JSON_HEDLEY_TI_VERSION)
  370. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  371. #else
  372. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
  373. #endif
  374. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  375. #undef JSON_HEDLEY_TI_CL2000_VERSION
  376. #endif
  377. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__)
  378. #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  379. #endif
  380. #if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK)
  381. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  382. #endif
  383. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  384. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  385. #else
  386. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0)
  387. #endif
  388. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  389. #undef JSON_HEDLEY_TI_CL430_VERSION
  390. #endif
  391. #if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__)
  392. #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  393. #endif
  394. #if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK)
  395. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  396. #endif
  397. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  398. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  399. #else
  400. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0)
  401. #endif
  402. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  403. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  404. #endif
  405. #if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__))
  406. #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  407. #endif
  408. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK)
  409. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  410. #endif
  411. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  412. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  413. #else
  414. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0)
  415. #endif
  416. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  417. #undef JSON_HEDLEY_TI_CL6X_VERSION
  418. #endif
  419. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__)
  420. #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  421. #endif
  422. #if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK)
  423. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  424. #endif
  425. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  426. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  427. #else
  428. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0)
  429. #endif
  430. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  431. #undef JSON_HEDLEY_TI_CL7X_VERSION
  432. #endif
  433. #if defined(__TI_COMPILER_VERSION__) && defined(__C7000__)
  434. #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  435. #endif
  436. #if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK)
  437. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  438. #endif
  439. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  440. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  441. #else
  442. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0)
  443. #endif
  444. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  445. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  446. #endif
  447. #if defined(__TI_COMPILER_VERSION__) && defined(__PRU__)
  448. #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  449. #endif
  450. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK)
  451. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  452. #endif
  453. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  454. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  455. #else
  456. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0)
  457. #endif
  458. #if defined(JSON_HEDLEY_CRAY_VERSION)
  459. #undef JSON_HEDLEY_CRAY_VERSION
  460. #endif
  461. #if defined(_CRAYC)
  462. #if defined(_RELEASE_PATCHLEVEL)
  463. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
  464. #else
  465. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
  466. #endif
  467. #endif
  468. #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
  469. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  470. #endif
  471. #if defined(JSON_HEDLEY_CRAY_VERSION)
  472. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  473. #else
  474. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
  475. #endif
  476. #if defined(JSON_HEDLEY_IAR_VERSION)
  477. #undef JSON_HEDLEY_IAR_VERSION
  478. #endif
  479. #if defined(__IAR_SYSTEMS_ICC__)
  480. #if __VER__ > 1000
  481. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
  482. #else
  483. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0)
  484. #endif
  485. #endif
  486. #if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
  487. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  488. #endif
  489. #if defined(JSON_HEDLEY_IAR_VERSION)
  490. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  491. #else
  492. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
  493. #endif
  494. #if defined(JSON_HEDLEY_TINYC_VERSION)
  495. #undef JSON_HEDLEY_TINYC_VERSION
  496. #endif
  497. #if defined(__TINYC__)
  498. #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
  499. #endif
  500. #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
  501. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  502. #endif
  503. #if defined(JSON_HEDLEY_TINYC_VERSION)
  504. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  505. #else
  506. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
  507. #endif
  508. #if defined(JSON_HEDLEY_DMC_VERSION)
  509. #undef JSON_HEDLEY_DMC_VERSION
  510. #endif
  511. #if defined(__DMC__)
  512. #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
  513. #endif
  514. #if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
  515. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  516. #endif
  517. #if defined(JSON_HEDLEY_DMC_VERSION)
  518. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  519. #else
  520. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
  521. #endif
  522. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  523. #undef JSON_HEDLEY_COMPCERT_VERSION
  524. #endif
  525. #if defined(__COMPCERT_VERSION__)
  526. #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
  527. #endif
  528. #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
  529. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  530. #endif
  531. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  532. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  533. #else
  534. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
  535. #endif
  536. #if defined(JSON_HEDLEY_PELLES_VERSION)
  537. #undef JSON_HEDLEY_PELLES_VERSION
  538. #endif
  539. #if defined(__POCC__)
  540. #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
  541. #endif
  542. #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
  543. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  544. #endif
  545. #if defined(JSON_HEDLEY_PELLES_VERSION)
  546. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  547. #else
  548. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
  549. #endif
  550. #if defined(JSON_HEDLEY_MCST_LCC_VERSION)
  551. #undef JSON_HEDLEY_MCST_LCC_VERSION
  552. #endif
  553. #if defined(__LCC__) && defined(__LCC_MINOR__)
  554. #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__)
  555. #endif
  556. #if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK)
  557. #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK
  558. #endif
  559. #if defined(JSON_HEDLEY_MCST_LCC_VERSION)
  560. #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  561. #else
  562. #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0)
  563. #endif
  564. #if defined(JSON_HEDLEY_GCC_VERSION)
  565. #undef JSON_HEDLEY_GCC_VERSION
  566. #endif
  567. #if \
  568. defined(JSON_HEDLEY_GNUC_VERSION) && \
  569. !defined(__clang__) && \
  570. !defined(JSON_HEDLEY_INTEL_VERSION) && \
  571. !defined(JSON_HEDLEY_PGI_VERSION) && \
  572. !defined(JSON_HEDLEY_ARM_VERSION) && \
  573. !defined(JSON_HEDLEY_CRAY_VERSION) && \
  574. !defined(JSON_HEDLEY_TI_VERSION) && \
  575. !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \
  576. !defined(JSON_HEDLEY_TI_CL430_VERSION) && \
  577. !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \
  578. !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \
  579. !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \
  580. !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \
  581. !defined(__COMPCERT__) && \
  582. !defined(JSON_HEDLEY_MCST_LCC_VERSION)
  583. #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
  584. #endif
  585. #if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
  586. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  587. #endif
  588. #if defined(JSON_HEDLEY_GCC_VERSION)
  589. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  590. #else
  591. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
  592. #endif
  593. #if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
  594. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  595. #endif
  596. #if \
  597. defined(__has_attribute) && \
  598. ( \
  599. (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \
  600. )
  601. # define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
  602. #else
  603. # define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
  604. #endif
  605. #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
  606. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  607. #endif
  608. #if defined(__has_attribute)
  609. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  610. #else
  611. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  612. #endif
  613. #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
  614. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  615. #endif
  616. #if defined(__has_attribute)
  617. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  618. #else
  619. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  620. #endif
  621. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
  622. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  623. #endif
  624. #if \
  625. defined(__has_cpp_attribute) && \
  626. defined(__cplusplus) && \
  627. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0))
  628. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
  629. #else
  630. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
  631. #endif
  632. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS)
  633. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  634. #endif
  635. #if !defined(__cplusplus) || !defined(__has_cpp_attribute)
  636. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  637. #elif \
  638. !defined(JSON_HEDLEY_PGI_VERSION) && \
  639. !defined(JSON_HEDLEY_IAR_VERSION) && \
  640. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
  641. (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0))
  642. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute)
  643. #else
  644. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  645. #endif
  646. #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
  647. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  648. #endif
  649. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  650. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  651. #else
  652. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  653. #endif
  654. #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
  655. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  656. #endif
  657. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  658. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  659. #else
  660. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  661. #endif
  662. #if defined(JSON_HEDLEY_HAS_BUILTIN)
  663. #undef JSON_HEDLEY_HAS_BUILTIN
  664. #endif
  665. #if defined(__has_builtin)
  666. #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
  667. #else
  668. #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
  669. #endif
  670. #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
  671. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  672. #endif
  673. #if defined(__has_builtin)
  674. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  675. #else
  676. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  677. #endif
  678. #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
  679. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  680. #endif
  681. #if defined(__has_builtin)
  682. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  683. #else
  684. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  685. #endif
  686. #if defined(JSON_HEDLEY_HAS_FEATURE)
  687. #undef JSON_HEDLEY_HAS_FEATURE
  688. #endif
  689. #if defined(__has_feature)
  690. #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
  691. #else
  692. #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
  693. #endif
  694. #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
  695. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  696. #endif
  697. #if defined(__has_feature)
  698. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  699. #else
  700. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  701. #endif
  702. #if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
  703. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  704. #endif
  705. #if defined(__has_feature)
  706. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  707. #else
  708. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  709. #endif
  710. #if defined(JSON_HEDLEY_HAS_EXTENSION)
  711. #undef JSON_HEDLEY_HAS_EXTENSION
  712. #endif
  713. #if defined(__has_extension)
  714. #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
  715. #else
  716. #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
  717. #endif
  718. #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
  719. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  720. #endif
  721. #if defined(__has_extension)
  722. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  723. #else
  724. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  725. #endif
  726. #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
  727. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  728. #endif
  729. #if defined(__has_extension)
  730. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  731. #else
  732. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  733. #endif
  734. #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
  735. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  736. #endif
  737. #if defined(__has_declspec_attribute)
  738. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
  739. #else
  740. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
  741. #endif
  742. #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
  743. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  744. #endif
  745. #if defined(__has_declspec_attribute)
  746. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  747. #else
  748. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  749. #endif
  750. #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
  751. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  752. #endif
  753. #if defined(__has_declspec_attribute)
  754. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  755. #else
  756. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  757. #endif
  758. #if defined(JSON_HEDLEY_HAS_WARNING)
  759. #undef JSON_HEDLEY_HAS_WARNING
  760. #endif
  761. #if defined(__has_warning)
  762. #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
  763. #else
  764. #define JSON_HEDLEY_HAS_WARNING(warning) (0)
  765. #endif
  766. #if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
  767. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  768. #endif
  769. #if defined(__has_warning)
  770. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  771. #else
  772. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  773. #endif
  774. #if defined(JSON_HEDLEY_GCC_HAS_WARNING)
  775. #undef JSON_HEDLEY_GCC_HAS_WARNING
  776. #endif
  777. #if defined(__has_warning)
  778. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  779. #else
  780. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  781. #endif
  782. #if \
  783. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  784. defined(__clang__) || \
  785. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  786. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  787. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  788. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  789. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  790. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  791. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  792. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  793. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  794. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \
  795. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  796. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  797. JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
  798. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
  799. JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
  800. (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
  801. #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
  802. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  803. #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
  804. #else
  805. #define JSON_HEDLEY_PRAGMA(value)
  806. #endif
  807. #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
  808. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  809. #endif
  810. #if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
  811. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  812. #endif
  813. #if defined(__clang__)
  814. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
  815. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
  816. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  817. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  818. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  819. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  820. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
  821. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
  822. #elif \
  823. JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \
  824. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  825. #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
  826. #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
  827. #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
  828. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
  829. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
  830. #elif \
  831. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  832. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  833. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \
  834. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  835. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  836. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  837. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
  838. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
  839. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  840. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  841. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  842. #else
  843. #define JSON_HEDLEY_DIAGNOSTIC_PUSH
  844. #define JSON_HEDLEY_DIAGNOSTIC_POP
  845. #endif
  846. /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for
  847. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  848. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  849. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  850. #endif
  851. #if defined(__cplusplus)
  852. # if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat")
  853. # if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions")
  854. # if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions")
  855. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  856. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  857. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  858. _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
  859. _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \
  860. xpr \
  861. JSON_HEDLEY_DIAGNOSTIC_POP
  862. # else
  863. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  864. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  865. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  866. _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
  867. xpr \
  868. JSON_HEDLEY_DIAGNOSTIC_POP
  869. # endif
  870. # else
  871. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  872. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  873. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  874. xpr \
  875. JSON_HEDLEY_DIAGNOSTIC_POP
  876. # endif
  877. # endif
  878. #endif
  879. #if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  880. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x
  881. #endif
  882. #if defined(JSON_HEDLEY_CONST_CAST)
  883. #undef JSON_HEDLEY_CONST_CAST
  884. #endif
  885. #if defined(__cplusplus)
  886. # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
  887. #elif \
  888. JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
  889. JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
  890. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  891. # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
  892. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  893. JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
  894. ((T) (expr)); \
  895. JSON_HEDLEY_DIAGNOSTIC_POP \
  896. }))
  897. #else
  898. # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
  899. #endif
  900. #if defined(JSON_HEDLEY_REINTERPRET_CAST)
  901. #undef JSON_HEDLEY_REINTERPRET_CAST
  902. #endif
  903. #if defined(__cplusplus)
  904. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
  905. #else
  906. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr))
  907. #endif
  908. #if defined(JSON_HEDLEY_STATIC_CAST)
  909. #undef JSON_HEDLEY_STATIC_CAST
  910. #endif
  911. #if defined(__cplusplus)
  912. #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
  913. #else
  914. #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
  915. #endif
  916. #if defined(JSON_HEDLEY_CPP_CAST)
  917. #undef JSON_HEDLEY_CPP_CAST
  918. #endif
  919. #if defined(__cplusplus)
  920. # if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast")
  921. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  922. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  923. _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \
  924. ((T) (expr)) \
  925. JSON_HEDLEY_DIAGNOSTIC_POP
  926. # elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0)
  927. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  928. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  929. _Pragma("diag_suppress=Pe137") \
  930. JSON_HEDLEY_DIAGNOSTIC_POP
  931. # else
  932. # define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr))
  933. # endif
  934. #else
  935. # define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
  936. #endif
  937. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
  938. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  939. #endif
  940. #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
  941. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
  942. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  943. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
  944. #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  945. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786))
  946. #elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0)
  947. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445")
  948. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  949. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  950. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  951. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  952. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  953. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
  954. #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  955. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  956. #elif \
  957. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  958. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  959. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  960. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  961. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  962. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  963. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  964. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  965. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  966. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  967. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  968. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
  969. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
  970. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
  971. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
  972. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
  973. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  974. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
  975. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  976. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
  977. #else
  978. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  979. #endif
  980. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
  981. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  982. #endif
  983. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  984. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
  985. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  986. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
  987. #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  988. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161))
  989. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  990. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
  991. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  992. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
  993. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  994. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
  995. #elif \
  996. JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \
  997. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  998. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  999. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0)
  1000. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  1001. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0)
  1002. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  1003. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1004. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
  1005. #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1006. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161")
  1007. #else
  1008. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  1009. #endif
  1010. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES)
  1011. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  1012. #endif
  1013. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes")
  1014. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"")
  1015. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  1016. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  1017. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0)
  1018. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)")
  1019. #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1020. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292))
  1021. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0)
  1022. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030))
  1023. #elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0)
  1024. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098")
  1025. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1026. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
  1027. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)
  1028. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)")
  1029. #elif \
  1030. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  1031. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  1032. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0)
  1033. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173")
  1034. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1035. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097")
  1036. #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1037. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
  1038. #else
  1039. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  1040. #endif
  1041. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
  1042. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  1043. #endif
  1044. #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
  1045. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
  1046. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1047. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
  1048. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
  1049. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
  1050. #else
  1051. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  1052. #endif
  1053. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION)
  1054. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
  1055. #endif
  1056. #if JSON_HEDLEY_HAS_WARNING("-Wunused-function")
  1057. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"")
  1058. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0)
  1059. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"")
  1060. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0)
  1061. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505))
  1062. #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1063. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142")
  1064. #else
  1065. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
  1066. #endif
  1067. #if defined(JSON_HEDLEY_DEPRECATED)
  1068. #undef JSON_HEDLEY_DEPRECATED
  1069. #endif
  1070. #if defined(JSON_HEDLEY_DEPRECATED_FOR)
  1071. #undef JSON_HEDLEY_DEPRECATED_FOR
  1072. #endif
  1073. #if \
  1074. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1075. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1076. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
  1077. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
  1078. #elif \
  1079. (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1080. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  1081. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1082. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  1083. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
  1084. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1085. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  1086. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \
  1087. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  1088. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1089. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \
  1090. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1091. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
  1092. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
  1093. #elif defined(__cplusplus) && (__cplusplus >= 201402L)
  1094. #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]])
  1095. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]])
  1096. #elif \
  1097. JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
  1098. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1099. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1100. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1101. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1102. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1103. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1104. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1105. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1106. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1107. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1108. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1109. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1110. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1111. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \
  1112. JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
  1113. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
  1114. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
  1115. #elif \
  1116. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1117. JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \
  1118. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1119. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated)
  1120. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
  1121. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1122. #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
  1123. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
  1124. #else
  1125. #define JSON_HEDLEY_DEPRECATED(since)
  1126. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
  1127. #endif
  1128. #if defined(JSON_HEDLEY_UNAVAILABLE)
  1129. #undef JSON_HEDLEY_UNAVAILABLE
  1130. #endif
  1131. #if \
  1132. JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
  1133. JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
  1134. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1135. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1136. #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
  1137. #else
  1138. #define JSON_HEDLEY_UNAVAILABLE(available_since)
  1139. #endif
  1140. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
  1141. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  1142. #endif
  1143. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG)
  1144. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  1145. #endif
  1146. #if \
  1147. JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
  1148. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1149. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1150. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1151. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1152. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1153. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1154. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1155. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1156. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1157. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1158. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1159. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1160. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1161. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1162. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1163. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1164. #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
  1165. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__))
  1166. #elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L)
  1167. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1168. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]])
  1169. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard)
  1170. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1171. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1172. #elif defined(_Check_return_) /* SAL */
  1173. #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
  1174. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_
  1175. #else
  1176. #define JSON_HEDLEY_WARN_UNUSED_RESULT
  1177. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg)
  1178. #endif
  1179. #if defined(JSON_HEDLEY_SENTINEL)
  1180. #undef JSON_HEDLEY_SENTINEL
  1181. #endif
  1182. #if \
  1183. JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
  1184. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1185. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1186. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1187. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1188. #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
  1189. #else
  1190. #define JSON_HEDLEY_SENTINEL(position)
  1191. #endif
  1192. #if defined(JSON_HEDLEY_NO_RETURN)
  1193. #undef JSON_HEDLEY_NO_RETURN
  1194. #endif
  1195. #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1196. #define JSON_HEDLEY_NO_RETURN __noreturn
  1197. #elif \
  1198. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1199. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1200. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1201. #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
  1202. #define JSON_HEDLEY_NO_RETURN _Noreturn
  1203. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  1204. #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]])
  1205. #elif \
  1206. JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
  1207. JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
  1208. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1209. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1210. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1211. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1212. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1213. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1214. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1215. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1216. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1217. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1218. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1219. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1220. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1221. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1222. JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
  1223. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1224. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1225. #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return")
  1226. #elif \
  1227. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1228. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1229. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1230. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1231. #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
  1232. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1233. #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
  1234. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1235. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1236. #else
  1237. #define JSON_HEDLEY_NO_RETURN
  1238. #endif
  1239. #if defined(JSON_HEDLEY_NO_ESCAPE)
  1240. #undef JSON_HEDLEY_NO_ESCAPE
  1241. #endif
  1242. #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape)
  1243. #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__))
  1244. #else
  1245. #define JSON_HEDLEY_NO_ESCAPE
  1246. #endif
  1247. #if defined(JSON_HEDLEY_UNREACHABLE)
  1248. #undef JSON_HEDLEY_UNREACHABLE
  1249. #endif
  1250. #if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  1251. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  1252. #endif
  1253. #if defined(JSON_HEDLEY_ASSUME)
  1254. #undef JSON_HEDLEY_ASSUME
  1255. #endif
  1256. #if \
  1257. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1258. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1259. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1260. #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
  1261. #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
  1262. #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
  1263. #elif \
  1264. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1265. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1266. #if defined(__cplusplus)
  1267. #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
  1268. #else
  1269. #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
  1270. #endif
  1271. #endif
  1272. #if \
  1273. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
  1274. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  1275. JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \
  1276. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1277. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \
  1278. JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \
  1279. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1280. #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
  1281. #elif defined(JSON_HEDLEY_ASSUME)
  1282. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1283. #endif
  1284. #if !defined(JSON_HEDLEY_ASSUME)
  1285. #if defined(JSON_HEDLEY_UNREACHABLE)
  1286. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1)))
  1287. #else
  1288. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr)
  1289. #endif
  1290. #endif
  1291. #if defined(JSON_HEDLEY_UNREACHABLE)
  1292. #if \
  1293. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1294. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1295. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value))
  1296. #else
  1297. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
  1298. #endif
  1299. #else
  1300. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value)
  1301. #endif
  1302. #if !defined(JSON_HEDLEY_UNREACHABLE)
  1303. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1304. #endif
  1305. JSON_HEDLEY_DIAGNOSTIC_PUSH
  1306. #if JSON_HEDLEY_HAS_WARNING("-Wpedantic")
  1307. #pragma clang diagnostic ignored "-Wpedantic"
  1308. #endif
  1309. #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus)
  1310. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  1311. #endif
  1312. #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0)
  1313. #if defined(__clang__)
  1314. #pragma clang diagnostic ignored "-Wvariadic-macros"
  1315. #elif defined(JSON_HEDLEY_GCC_VERSION)
  1316. #pragma GCC diagnostic ignored "-Wvariadic-macros"
  1317. #endif
  1318. #endif
  1319. #if defined(JSON_HEDLEY_NON_NULL)
  1320. #undef JSON_HEDLEY_NON_NULL
  1321. #endif
  1322. #if \
  1323. JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
  1324. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1325. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1326. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1327. #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
  1328. #else
  1329. #define JSON_HEDLEY_NON_NULL(...)
  1330. #endif
  1331. JSON_HEDLEY_DIAGNOSTIC_POP
  1332. #if defined(JSON_HEDLEY_PRINTF_FORMAT)
  1333. #undef JSON_HEDLEY_PRINTF_FORMAT
  1334. #endif
  1335. #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
  1336. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
  1337. #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
  1338. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
  1339. #elif \
  1340. JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
  1341. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1342. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1343. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  1344. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1345. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1346. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1347. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1348. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1349. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1350. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1351. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1352. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1353. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1354. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1355. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1356. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1357. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
  1358. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
  1359. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
  1360. #else
  1361. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
  1362. #endif
  1363. #if defined(JSON_HEDLEY_CONSTEXPR)
  1364. #undef JSON_HEDLEY_CONSTEXPR
  1365. #endif
  1366. #if defined(__cplusplus)
  1367. #if __cplusplus >= 201103L
  1368. #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr)
  1369. #endif
  1370. #endif
  1371. #if !defined(JSON_HEDLEY_CONSTEXPR)
  1372. #define JSON_HEDLEY_CONSTEXPR
  1373. #endif
  1374. #if defined(JSON_HEDLEY_PREDICT)
  1375. #undef JSON_HEDLEY_PREDICT
  1376. #endif
  1377. #if defined(JSON_HEDLEY_LIKELY)
  1378. #undef JSON_HEDLEY_LIKELY
  1379. #endif
  1380. #if defined(JSON_HEDLEY_UNLIKELY)
  1381. #undef JSON_HEDLEY_UNLIKELY
  1382. #endif
  1383. #if defined(JSON_HEDLEY_UNPREDICTABLE)
  1384. #undef JSON_HEDLEY_UNPREDICTABLE
  1385. #endif
  1386. #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
  1387. #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr))
  1388. #endif
  1389. #if \
  1390. (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \
  1391. JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \
  1392. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1393. # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability))
  1394. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability))
  1395. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability))
  1396. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 )
  1397. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 )
  1398. #elif \
  1399. (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \
  1400. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  1401. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1402. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1403. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1404. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1405. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1406. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  1407. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1408. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  1409. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1410. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1411. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1412. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \
  1413. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1414. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1415. # define JSON_HEDLEY_PREDICT(expr, expected, probability) \
  1416. (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)))
  1417. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
  1418. (__extension__ ({ \
  1419. double hedley_probability_ = (probability); \
  1420. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
  1421. }))
  1422. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
  1423. (__extension__ ({ \
  1424. double hedley_probability_ = (probability); \
  1425. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
  1426. }))
  1427. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  1428. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  1429. #else
  1430. # define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))
  1431. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
  1432. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
  1433. # define JSON_HEDLEY_LIKELY(expr) (!!(expr))
  1434. # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
  1435. #endif
  1436. #if !defined(JSON_HEDLEY_UNPREDICTABLE)
  1437. #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
  1438. #endif
  1439. #if defined(JSON_HEDLEY_MALLOC)
  1440. #undef JSON_HEDLEY_MALLOC
  1441. #endif
  1442. #if \
  1443. JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
  1444. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1445. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1446. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1447. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1448. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1449. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1450. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1451. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1452. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1453. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1454. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1455. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1456. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1457. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1458. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1459. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1460. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1461. #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
  1462. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1463. #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory")
  1464. #elif \
  1465. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1466. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1467. #define JSON_HEDLEY_MALLOC __declspec(restrict)
  1468. #else
  1469. #define JSON_HEDLEY_MALLOC
  1470. #endif
  1471. #if defined(JSON_HEDLEY_PURE)
  1472. #undef JSON_HEDLEY_PURE
  1473. #endif
  1474. #if \
  1475. JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
  1476. JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
  1477. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1478. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1479. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1480. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1481. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1482. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1483. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1484. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1485. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1486. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1487. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1488. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1489. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1490. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1491. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1492. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1493. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1494. # define JSON_HEDLEY_PURE __attribute__((__pure__))
  1495. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1496. # define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data")
  1497. #elif defined(__cplusplus) && \
  1498. ( \
  1499. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  1500. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \
  1501. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \
  1502. )
  1503. # define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
  1504. #else
  1505. # define JSON_HEDLEY_PURE
  1506. #endif
  1507. #if defined(JSON_HEDLEY_CONST)
  1508. #undef JSON_HEDLEY_CONST
  1509. #endif
  1510. #if \
  1511. JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
  1512. JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
  1513. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1514. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1515. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1516. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1517. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1518. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1519. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1520. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1521. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1522. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1523. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1524. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1525. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1526. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1527. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1528. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1529. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1530. #define JSON_HEDLEY_CONST __attribute__((__const__))
  1531. #elif \
  1532. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1533. #define JSON_HEDLEY_CONST _Pragma("no_side_effect")
  1534. #else
  1535. #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
  1536. #endif
  1537. #if defined(JSON_HEDLEY_RESTRICT)
  1538. #undef JSON_HEDLEY_RESTRICT
  1539. #endif
  1540. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
  1541. #define JSON_HEDLEY_RESTRICT restrict
  1542. #elif \
  1543. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1544. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1545. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1546. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \
  1547. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1548. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1549. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1550. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1551. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \
  1552. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  1553. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1554. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
  1555. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  1556. defined(__clang__) || \
  1557. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1558. #define JSON_HEDLEY_RESTRICT __restrict
  1559. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
  1560. #define JSON_HEDLEY_RESTRICT _Restrict
  1561. #else
  1562. #define JSON_HEDLEY_RESTRICT
  1563. #endif
  1564. #if defined(JSON_HEDLEY_INLINE)
  1565. #undef JSON_HEDLEY_INLINE
  1566. #endif
  1567. #if \
  1568. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  1569. (defined(__cplusplus) && (__cplusplus >= 199711L))
  1570. #define JSON_HEDLEY_INLINE inline
  1571. #elif \
  1572. defined(JSON_HEDLEY_GCC_VERSION) || \
  1573. JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
  1574. #define JSON_HEDLEY_INLINE __inline__
  1575. #elif \
  1576. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1577. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \
  1578. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1579. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \
  1580. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1581. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1582. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  1583. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1584. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1585. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1586. #define JSON_HEDLEY_INLINE __inline
  1587. #else
  1588. #define JSON_HEDLEY_INLINE
  1589. #endif
  1590. #if defined(JSON_HEDLEY_ALWAYS_INLINE)
  1591. #undef JSON_HEDLEY_ALWAYS_INLINE
  1592. #endif
  1593. #if \
  1594. JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
  1595. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1596. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1597. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1598. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1599. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1600. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1601. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1602. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1603. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1604. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1605. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1606. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1607. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1608. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1609. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1610. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1611. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \
  1612. JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
  1613. # define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
  1614. #elif \
  1615. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1616. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1617. # define JSON_HEDLEY_ALWAYS_INLINE __forceinline
  1618. #elif defined(__cplusplus) && \
  1619. ( \
  1620. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1621. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1622. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1623. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1624. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1625. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \
  1626. )
  1627. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
  1628. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1629. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
  1630. #else
  1631. # define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
  1632. #endif
  1633. #if defined(JSON_HEDLEY_NEVER_INLINE)
  1634. #undef JSON_HEDLEY_NEVER_INLINE
  1635. #endif
  1636. #if \
  1637. JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
  1638. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1639. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1640. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1641. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1642. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1643. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1644. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1645. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1646. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1647. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1648. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1649. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1650. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1651. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1652. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1653. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1654. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \
  1655. JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
  1656. #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
  1657. #elif \
  1658. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1659. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1660. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1661. #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
  1662. #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
  1663. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1664. #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
  1665. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1666. #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
  1667. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1668. #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
  1669. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1670. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1671. #else
  1672. #define JSON_HEDLEY_NEVER_INLINE
  1673. #endif
  1674. #if defined(JSON_HEDLEY_PRIVATE)
  1675. #undef JSON_HEDLEY_PRIVATE
  1676. #endif
  1677. #if defined(JSON_HEDLEY_PUBLIC)
  1678. #undef JSON_HEDLEY_PUBLIC
  1679. #endif
  1680. #if defined(JSON_HEDLEY_IMPORT)
  1681. #undef JSON_HEDLEY_IMPORT
  1682. #endif
  1683. #if defined(_WIN32) || defined(__CYGWIN__)
  1684. # define JSON_HEDLEY_PRIVATE
  1685. # define JSON_HEDLEY_PUBLIC __declspec(dllexport)
  1686. # define JSON_HEDLEY_IMPORT __declspec(dllimport)
  1687. #else
  1688. # if \
  1689. JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
  1690. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1691. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1692. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1693. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1694. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1695. ( \
  1696. defined(__TI_EABI__) && \
  1697. ( \
  1698. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1699. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \
  1700. ) \
  1701. ) || \
  1702. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1703. # define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
  1704. # define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default")))
  1705. # else
  1706. # define JSON_HEDLEY_PRIVATE
  1707. # define JSON_HEDLEY_PUBLIC
  1708. # endif
  1709. # define JSON_HEDLEY_IMPORT extern
  1710. #endif
  1711. #if defined(JSON_HEDLEY_NO_THROW)
  1712. #undef JSON_HEDLEY_NO_THROW
  1713. #endif
  1714. #if \
  1715. JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
  1716. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1717. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1718. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1719. #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
  1720. #elif \
  1721. JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
  1722. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \
  1723. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1724. #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
  1725. #else
  1726. #define JSON_HEDLEY_NO_THROW
  1727. #endif
  1728. #if defined(JSON_HEDLEY_FALL_THROUGH)
  1729. #undef JSON_HEDLEY_FALL_THROUGH
  1730. #endif
  1731. #if \
  1732. JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \
  1733. JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \
  1734. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1735. #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
  1736. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough)
  1737. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]])
  1738. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough)
  1739. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]])
  1740. #elif defined(__fallthrough) /* SAL */
  1741. #define JSON_HEDLEY_FALL_THROUGH __fallthrough
  1742. #else
  1743. #define JSON_HEDLEY_FALL_THROUGH
  1744. #endif
  1745. #if defined(JSON_HEDLEY_RETURNS_NON_NULL)
  1746. #undef JSON_HEDLEY_RETURNS_NON_NULL
  1747. #endif
  1748. #if \
  1749. JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
  1750. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1751. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1752. #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
  1753. #elif defined(_Ret_notnull_) /* SAL */
  1754. #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
  1755. #else
  1756. #define JSON_HEDLEY_RETURNS_NON_NULL
  1757. #endif
  1758. #if defined(JSON_HEDLEY_ARRAY_PARAM)
  1759. #undef JSON_HEDLEY_ARRAY_PARAM
  1760. #endif
  1761. #if \
  1762. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
  1763. !defined(__STDC_NO_VLA__) && \
  1764. !defined(__cplusplus) && \
  1765. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1766. !defined(JSON_HEDLEY_TINYC_VERSION)
  1767. #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
  1768. #else
  1769. #define JSON_HEDLEY_ARRAY_PARAM(name)
  1770. #endif
  1771. #if defined(JSON_HEDLEY_IS_CONSTANT)
  1772. #undef JSON_HEDLEY_IS_CONSTANT
  1773. #endif
  1774. #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
  1775. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  1776. #endif
  1777. /* JSON_HEDLEY_IS_CONSTEXPR_ is for
  1778. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  1779. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1780. #undef JSON_HEDLEY_IS_CONSTEXPR_
  1781. #endif
  1782. #if \
  1783. JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
  1784. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1785. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1786. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
  1787. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1788. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1789. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1790. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \
  1791. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1792. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1793. #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
  1794. #endif
  1795. #if !defined(__cplusplus)
  1796. # if \
  1797. JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
  1798. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1799. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1800. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1801. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1802. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1803. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
  1804. #if defined(__INTPTR_TYPE__)
  1805. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
  1806. #else
  1807. #include <stdint.h>
  1808. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
  1809. #endif
  1810. # elif \
  1811. ( \
  1812. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \
  1813. !defined(JSON_HEDLEY_SUNPRO_VERSION) && \
  1814. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1815. !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1816. (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1817. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1818. JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
  1819. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1820. JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
  1821. #if defined(__INTPTR_TYPE__)
  1822. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
  1823. #else
  1824. #include <stdint.h>
  1825. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
  1826. #endif
  1827. # elif \
  1828. defined(JSON_HEDLEY_GCC_VERSION) || \
  1829. defined(JSON_HEDLEY_INTEL_VERSION) || \
  1830. defined(JSON_HEDLEY_TINYC_VERSION) || \
  1831. defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \
  1832. JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \
  1833. defined(JSON_HEDLEY_TI_CL2000_VERSION) || \
  1834. defined(JSON_HEDLEY_TI_CL6X_VERSION) || \
  1835. defined(JSON_HEDLEY_TI_CL7X_VERSION) || \
  1836. defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \
  1837. defined(__clang__)
  1838. # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \
  1839. sizeof(void) != \
  1840. sizeof(*( \
  1841. 1 ? \
  1842. ((void*) ((expr) * 0L) ) : \
  1843. ((struct { char v[sizeof(void) * 2]; } *) 1) \
  1844. ) \
  1845. ) \
  1846. )
  1847. # endif
  1848. #endif
  1849. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1850. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1851. #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr)
  1852. #endif
  1853. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1))
  1854. #else
  1855. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1856. #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
  1857. #endif
  1858. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
  1859. #endif
  1860. #if defined(JSON_HEDLEY_BEGIN_C_DECLS)
  1861. #undef JSON_HEDLEY_BEGIN_C_DECLS
  1862. #endif
  1863. #if defined(JSON_HEDLEY_END_C_DECLS)
  1864. #undef JSON_HEDLEY_END_C_DECLS
  1865. #endif
  1866. #if defined(JSON_HEDLEY_C_DECL)
  1867. #undef JSON_HEDLEY_C_DECL
  1868. #endif
  1869. #if defined(__cplusplus)
  1870. #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
  1871. #define JSON_HEDLEY_END_C_DECLS }
  1872. #define JSON_HEDLEY_C_DECL extern "C"
  1873. #else
  1874. #define JSON_HEDLEY_BEGIN_C_DECLS
  1875. #define JSON_HEDLEY_END_C_DECLS
  1876. #define JSON_HEDLEY_C_DECL
  1877. #endif
  1878. #if defined(JSON_HEDLEY_STATIC_ASSERT)
  1879. #undef JSON_HEDLEY_STATIC_ASSERT
  1880. #endif
  1881. #if \
  1882. !defined(__cplusplus) && ( \
  1883. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
  1884. (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \
  1885. JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
  1886. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1887. defined(_Static_assert) \
  1888. )
  1889. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
  1890. #elif \
  1891. (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
  1892. JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \
  1893. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1894. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message))
  1895. #else
  1896. # define JSON_HEDLEY_STATIC_ASSERT(expr, message)
  1897. #endif
  1898. #if defined(JSON_HEDLEY_NULL)
  1899. #undef JSON_HEDLEY_NULL
  1900. #endif
  1901. #if defined(__cplusplus)
  1902. #if __cplusplus >= 201103L
  1903. #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr)
  1904. #elif defined(NULL)
  1905. #define JSON_HEDLEY_NULL NULL
  1906. #else
  1907. #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0)
  1908. #endif
  1909. #elif defined(NULL)
  1910. #define JSON_HEDLEY_NULL NULL
  1911. #else
  1912. #define JSON_HEDLEY_NULL ((void*) 0)
  1913. #endif
  1914. #if defined(JSON_HEDLEY_MESSAGE)
  1915. #undef JSON_HEDLEY_MESSAGE
  1916. #endif
  1917. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1918. # define JSON_HEDLEY_MESSAGE(msg) \
  1919. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1920. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1921. JSON_HEDLEY_PRAGMA(message msg) \
  1922. JSON_HEDLEY_DIAGNOSTIC_POP
  1923. #elif \
  1924. JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
  1925. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1926. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
  1927. #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
  1928. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
  1929. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1930. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1931. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
  1932. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1933. #else
  1934. # define JSON_HEDLEY_MESSAGE(msg)
  1935. #endif
  1936. #if defined(JSON_HEDLEY_WARNING)
  1937. #undef JSON_HEDLEY_WARNING
  1938. #endif
  1939. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1940. # define JSON_HEDLEY_WARNING(msg) \
  1941. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1942. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1943. JSON_HEDLEY_PRAGMA(clang warning msg) \
  1944. JSON_HEDLEY_DIAGNOSTIC_POP
  1945. #elif \
  1946. JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
  1947. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  1948. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1949. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
  1950. #elif \
  1951. JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \
  1952. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1953. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1954. #else
  1955. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
  1956. #endif
  1957. #if defined(JSON_HEDLEY_REQUIRE)
  1958. #undef JSON_HEDLEY_REQUIRE
  1959. #endif
  1960. #if defined(JSON_HEDLEY_REQUIRE_MSG)
  1961. #undef JSON_HEDLEY_REQUIRE_MSG
  1962. #endif
  1963. #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
  1964. # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
  1965. # define JSON_HEDLEY_REQUIRE(expr) \
  1966. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1967. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1968. __attribute__((diagnose_if(!(expr), #expr, "error"))) \
  1969. JSON_HEDLEY_DIAGNOSTIC_POP
  1970. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \
  1971. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1972. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1973. __attribute__((diagnose_if(!(expr), msg, "error"))) \
  1974. JSON_HEDLEY_DIAGNOSTIC_POP
  1975. # else
  1976. # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error")))
  1977. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error")))
  1978. # endif
  1979. #else
  1980. # define JSON_HEDLEY_REQUIRE(expr)
  1981. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg)
  1982. #endif
  1983. #if defined(JSON_HEDLEY_FLAGS)
  1984. #undef JSON_HEDLEY_FLAGS
  1985. #endif
  1986. #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion"))
  1987. #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
  1988. #else
  1989. #define JSON_HEDLEY_FLAGS
  1990. #endif
  1991. #if defined(JSON_HEDLEY_FLAGS_CAST)
  1992. #undef JSON_HEDLEY_FLAGS_CAST
  1993. #endif
  1994. #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
  1995. # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
  1996. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1997. _Pragma("warning(disable:188)") \
  1998. ((T) (expr)); \
  1999. JSON_HEDLEY_DIAGNOSTIC_POP \
  2000. }))
  2001. #else
  2002. # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
  2003. #endif
  2004. #if defined(JSON_HEDLEY_EMPTY_BASES)
  2005. #undef JSON_HEDLEY_EMPTY_BASES
  2006. #endif
  2007. #if \
  2008. (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \
  2009. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  2010. #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases)
  2011. #else
  2012. #define JSON_HEDLEY_EMPTY_BASES
  2013. #endif
  2014. /* Remaining macros are deprecated. */
  2015. #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
  2016. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  2017. #endif
  2018. #if defined(__clang__)
  2019. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
  2020. #else
  2021. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  2022. #endif
  2023. #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
  2024. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  2025. #endif
  2026. #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  2027. #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
  2028. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  2029. #endif
  2030. #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
  2031. #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
  2032. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  2033. #endif
  2034. #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
  2035. #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
  2036. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  2037. #endif
  2038. #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
  2039. #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
  2040. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  2041. #endif
  2042. #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
  2043. #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
  2044. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  2045. #endif
  2046. #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
  2047. #if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
  2048. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  2049. #endif
  2050. #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
  2051. #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
  2052. // #include <nlohmann/detail/meta/detected.hpp>
  2053. #include <type_traits>
  2054. // #include <nlohmann/detail/meta/void_t.hpp>
  2055. namespace nlohmann
  2056. {
  2057. namespace detail
  2058. {
  2059. template<typename ...Ts> struct make_void
  2060. {
  2061. using type = void;
  2062. };
  2063. template<typename ...Ts> using void_t = typename make_void<Ts...>::type;
  2064. } // namespace detail
  2065. } // namespace nlohmann
  2066. // https://en.cppreference.com/w/cpp/experimental/is_detected
  2067. namespace nlohmann
  2068. {
  2069. namespace detail
  2070. {
  2071. struct nonesuch
  2072. {
  2073. nonesuch() = delete;
  2074. ~nonesuch() = delete;
  2075. nonesuch(nonesuch const&) = delete;
  2076. nonesuch(nonesuch const&&) = delete;
  2077. void operator=(nonesuch const&) = delete;
  2078. void operator=(nonesuch&&) = delete;
  2079. };
  2080. template<class Default,
  2081. class AlwaysVoid,
  2082. template<class...> class Op,
  2083. class... Args>
  2084. struct detector
  2085. {
  2086. using value_t = std::false_type;
  2087. using type = Default;
  2088. };
  2089. template<class Default, template<class...> class Op, class... Args>
  2090. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  2091. {
  2092. using value_t = std::true_type;
  2093. using type = Op<Args...>;
  2094. };
  2095. template<template<class...> class Op, class... Args>
  2096. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  2097. template<template<class...> class Op, class... Args>
  2098. struct is_detected_lazy : is_detected<Op, Args...> { };
  2099. template<template<class...> class Op, class... Args>
  2100. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  2101. template<class Default, template<class...> class Op, class... Args>
  2102. using detected_or = detector<Default, void, Op, Args...>;
  2103. template<class Default, template<class...> class Op, class... Args>
  2104. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  2105. template<class Expected, template<class...> class Op, class... Args>
  2106. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  2107. template<class To, template<class...> class Op, class... Args>
  2108. using is_detected_convertible =
  2109. std::is_convertible<detected_t<Op, Args...>, To>;
  2110. } // namespace detail
  2111. } // namespace nlohmann
  2112. // This file contains all internal macro definitions
  2113. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  2114. // exclude unsupported compilers
  2115. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  2116. #if defined(__clang__)
  2117. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  2118. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  2119. #endif
  2120. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  2121. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  2122. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  2123. #endif
  2124. #endif
  2125. #endif
  2126. // C++ language standard detection
  2127. // if the user manually specified the used c++ version this is skipped
  2128. #if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11)
  2129. #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L)
  2130. #define JSON_HAS_CPP_20
  2131. #define JSON_HAS_CPP_17
  2132. #define JSON_HAS_CPP_14
  2133. #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  2134. #define JSON_HAS_CPP_17
  2135. #define JSON_HAS_CPP_14
  2136. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  2137. #define JSON_HAS_CPP_14
  2138. #endif
  2139. // the cpp 11 flag is always specified because it is the minimal required version
  2140. #define JSON_HAS_CPP_11
  2141. #endif
  2142. #if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM)
  2143. #ifdef JSON_HAS_CPP_17
  2144. #if defined(__cpp_lib_filesystem)
  2145. #define JSON_HAS_FILESYSTEM 1
  2146. #elif defined(__cpp_lib_experimental_filesystem)
  2147. #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1
  2148. #elif !defined(__has_include)
  2149. #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1
  2150. #elif __has_include(<filesystem>)
  2151. #define JSON_HAS_FILESYSTEM 1
  2152. #elif __has_include(<experimental/filesystem>)
  2153. #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1
  2154. #endif
  2155. // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/
  2156. #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8
  2157. #undef JSON_HAS_FILESYSTEM
  2158. #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
  2159. #endif
  2160. // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support
  2161. #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8
  2162. #undef JSON_HAS_FILESYSTEM
  2163. #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
  2164. #endif
  2165. // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support
  2166. #if defined(__clang_major__) && __clang_major__ < 7
  2167. #undef JSON_HAS_FILESYSTEM
  2168. #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
  2169. #endif
  2170. // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support
  2171. #if defined(_MSC_VER) && _MSC_VER < 1940
  2172. #undef JSON_HAS_FILESYSTEM
  2173. #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
  2174. #endif
  2175. // no filesystem support before iOS 13
  2176. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
  2177. #undef JSON_HAS_FILESYSTEM
  2178. #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
  2179. #endif
  2180. // no filesystem support before macOS Catalina
  2181. #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500
  2182. #undef JSON_HAS_FILESYSTEM
  2183. #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
  2184. #endif
  2185. #endif
  2186. #endif
  2187. #ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM
  2188. #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0
  2189. #endif
  2190. #ifndef JSON_HAS_FILESYSTEM
  2191. #define JSON_HAS_FILESYSTEM 0
  2192. #endif
  2193. // disable documentation warnings on clang
  2194. #if defined(__clang__)
  2195. #pragma clang diagnostic push
  2196. #pragma clang diagnostic ignored "-Wdocumentation"
  2197. #pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
  2198. #endif
  2199. // allow disabling exceptions
  2200. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  2201. #define JSON_THROW(exception) throw exception
  2202. #define JSON_TRY try
  2203. #define JSON_CATCH(exception) catch(exception)
  2204. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  2205. #else
  2206. #include <cstdlib>
  2207. #define JSON_THROW(exception) std::abort()
  2208. #define JSON_TRY if(true)
  2209. #define JSON_CATCH(exception) if(false)
  2210. #define JSON_INTERNAL_CATCH(exception) if(false)
  2211. #endif
  2212. // override exception macros
  2213. #if defined(JSON_THROW_USER)
  2214. #undef JSON_THROW
  2215. #define JSON_THROW JSON_THROW_USER
  2216. #endif
  2217. #if defined(JSON_TRY_USER)
  2218. #undef JSON_TRY
  2219. #define JSON_TRY JSON_TRY_USER
  2220. #endif
  2221. #if defined(JSON_CATCH_USER)
  2222. #undef JSON_CATCH
  2223. #define JSON_CATCH JSON_CATCH_USER
  2224. #undef JSON_INTERNAL_CATCH
  2225. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  2226. #endif
  2227. #if defined(JSON_INTERNAL_CATCH_USER)
  2228. #undef JSON_INTERNAL_CATCH
  2229. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  2230. #endif
  2231. // allow overriding assert
  2232. #if !defined(JSON_ASSERT)
  2233. #include <cassert> // assert
  2234. #define JSON_ASSERT(x) assert(x)
  2235. #endif
  2236. // allow to access some private functions (needed by the test suite)
  2237. #if defined(JSON_TESTS_PRIVATE)
  2238. #define JSON_PRIVATE_UNLESS_TESTED public
  2239. #else
  2240. #define JSON_PRIVATE_UNLESS_TESTED private
  2241. #endif
  2242. /*!
  2243. @brief macro to briefly define a mapping between an enum and JSON
  2244. @def NLOHMANN_JSON_SERIALIZE_ENUM
  2245. @since version 3.4.0
  2246. */
  2247. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  2248. template<typename BasicJsonType> \
  2249. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  2250. { \
  2251. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  2252. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  2253. auto it = std::find_if(std::begin(m), std::end(m), \
  2254. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  2255. { \
  2256. return ej_pair.first == e; \
  2257. }); \
  2258. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  2259. } \
  2260. template<typename BasicJsonType> \
  2261. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  2262. { \
  2263. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  2264. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  2265. auto it = std::find_if(std::begin(m), std::end(m), \
  2266. [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  2267. { \
  2268. return ej_pair.second == j; \
  2269. }); \
  2270. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  2271. }
  2272. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  2273. // may be removed in the future once the class is split.
  2274. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  2275. template<template<typename, typename, typename...> class ObjectType, \
  2276. template<typename, typename...> class ArrayType, \
  2277. class StringType, class BooleanType, class NumberIntegerType, \
  2278. class NumberUnsignedType, class NumberFloatType, \
  2279. template<typename> class AllocatorType, \
  2280. template<typename, typename = void> class JSONSerializer, \
  2281. class BinaryType>
  2282. #define NLOHMANN_BASIC_JSON_TPL \
  2283. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  2284. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  2285. AllocatorType, JSONSerializer, BinaryType>
  2286. // Macros to simplify conversion from/to types
  2287. #define NLOHMANN_JSON_EXPAND( x ) x
  2288. #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
  2289. #define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \
  2290. NLOHMANN_JSON_PASTE64, \
  2291. NLOHMANN_JSON_PASTE63, \
  2292. NLOHMANN_JSON_PASTE62, \
  2293. NLOHMANN_JSON_PASTE61, \
  2294. NLOHMANN_JSON_PASTE60, \
  2295. NLOHMANN_JSON_PASTE59, \
  2296. NLOHMANN_JSON_PASTE58, \
  2297. NLOHMANN_JSON_PASTE57, \
  2298. NLOHMANN_JSON_PASTE56, \
  2299. NLOHMANN_JSON_PASTE55, \
  2300. NLOHMANN_JSON_PASTE54, \
  2301. NLOHMANN_JSON_PASTE53, \
  2302. NLOHMANN_JSON_PASTE52, \
  2303. NLOHMANN_JSON_PASTE51, \
  2304. NLOHMANN_JSON_PASTE50, \
  2305. NLOHMANN_JSON_PASTE49, \
  2306. NLOHMANN_JSON_PASTE48, \
  2307. NLOHMANN_JSON_PASTE47, \
  2308. NLOHMANN_JSON_PASTE46, \
  2309. NLOHMANN_JSON_PASTE45, \
  2310. NLOHMANN_JSON_PASTE44, \
  2311. NLOHMANN_JSON_PASTE43, \
  2312. NLOHMANN_JSON_PASTE42, \
  2313. NLOHMANN_JSON_PASTE41, \
  2314. NLOHMANN_JSON_PASTE40, \
  2315. NLOHMANN_JSON_PASTE39, \
  2316. NLOHMANN_JSON_PASTE38, \
  2317. NLOHMANN_JSON_PASTE37, \
  2318. NLOHMANN_JSON_PASTE36, \
  2319. NLOHMANN_JSON_PASTE35, \
  2320. NLOHMANN_JSON_PASTE34, \
  2321. NLOHMANN_JSON_PASTE33, \
  2322. NLOHMANN_JSON_PASTE32, \
  2323. NLOHMANN_JSON_PASTE31, \
  2324. NLOHMANN_JSON_PASTE30, \
  2325. NLOHMANN_JSON_PASTE29, \
  2326. NLOHMANN_JSON_PASTE28, \
  2327. NLOHMANN_JSON_PASTE27, \
  2328. NLOHMANN_JSON_PASTE26, \
  2329. NLOHMANN_JSON_PASTE25, \
  2330. NLOHMANN_JSON_PASTE24, \
  2331. NLOHMANN_JSON_PASTE23, \
  2332. NLOHMANN_JSON_PASTE22, \
  2333. NLOHMANN_JSON_PASTE21, \
  2334. NLOHMANN_JSON_PASTE20, \
  2335. NLOHMANN_JSON_PASTE19, \
  2336. NLOHMANN_JSON_PASTE18, \
  2337. NLOHMANN_JSON_PASTE17, \
  2338. NLOHMANN_JSON_PASTE16, \
  2339. NLOHMANN_JSON_PASTE15, \
  2340. NLOHMANN_JSON_PASTE14, \
  2341. NLOHMANN_JSON_PASTE13, \
  2342. NLOHMANN_JSON_PASTE12, \
  2343. NLOHMANN_JSON_PASTE11, \
  2344. NLOHMANN_JSON_PASTE10, \
  2345. NLOHMANN_JSON_PASTE9, \
  2346. NLOHMANN_JSON_PASTE8, \
  2347. NLOHMANN_JSON_PASTE7, \
  2348. NLOHMANN_JSON_PASTE6, \
  2349. NLOHMANN_JSON_PASTE5, \
  2350. NLOHMANN_JSON_PASTE4, \
  2351. NLOHMANN_JSON_PASTE3, \
  2352. NLOHMANN_JSON_PASTE2, \
  2353. NLOHMANN_JSON_PASTE1)(__VA_ARGS__))
  2354. #define NLOHMANN_JSON_PASTE2(func, v1) func(v1)
  2355. #define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2)
  2356. #define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3)
  2357. #define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4)
  2358. #define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5)
  2359. #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)
  2360. #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)
  2361. #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)
  2362. #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)
  2363. #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)
  2364. #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)
  2365. #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)
  2366. #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)
  2367. #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)
  2368. #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)
  2369. #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)
  2370. #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)
  2371. #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)
  2372. #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)
  2373. #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)
  2374. #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)
  2375. #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)
  2376. #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)
  2377. #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)
  2378. #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)
  2379. #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)
  2380. #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)
  2381. #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)
  2382. #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)
  2383. #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)
  2384. #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)
  2385. #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)
  2386. #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)
  2387. #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)
  2388. #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)
  2389. #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)
  2390. #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)
  2391. #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)
  2392. #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)
  2393. #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)
  2394. #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)
  2395. #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)
  2396. #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)
  2397. #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)
  2398. #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)
  2399. #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)
  2400. #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)
  2401. #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)
  2402. #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)
  2403. #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)
  2404. #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)
  2405. #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)
  2406. #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)
  2407. #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)
  2408. #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)
  2409. #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)
  2410. #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)
  2411. #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)
  2412. #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)
  2413. #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)
  2414. #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)
  2415. #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)
  2416. #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)
  2417. #define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1;
  2418. #define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1);
  2419. /*!
  2420. @brief macro
  2421. @def NLOHMANN_DEFINE_TYPE_INTRUSIVE
  2422. @since version 3.9.0
  2423. */
  2424. #define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \
  2425. friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \
  2426. friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }
  2427. /*!
  2428. @brief macro
  2429. @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE
  2430. @since version 3.9.0
  2431. */
  2432. #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \
  2433. inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \
  2434. inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }
  2435. // inspired from https://stackoverflow.com/a/26745591
  2436. // allows to call any std function as if (e.g. with begin):
  2437. // using std::begin; begin(x);
  2438. //
  2439. // it allows using the detected idiom to retrieve the return type
  2440. // of such an expression
  2441. #define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \
  2442. namespace detail { \
  2443. using std::std_name; \
  2444. \
  2445. template<typename... T> \
  2446. using result_of_##std_name = decltype(std_name(std::declval<T>()...)); \
  2447. } \
  2448. \
  2449. namespace detail2 { \
  2450. struct std_name##_tag \
  2451. { \
  2452. }; \
  2453. \
  2454. template<typename... T> \
  2455. std_name##_tag std_name(T&&...); \
  2456. \
  2457. template<typename... T> \
  2458. using result_of_##std_name = decltype(std_name(std::declval<T>()...)); \
  2459. \
  2460. template<typename... T> \
  2461. struct would_call_std_##std_name \
  2462. { \
  2463. static constexpr auto const value = ::nlohmann::detail:: \
  2464. is_detected_exact<std_name##_tag, result_of_##std_name, T...>::value; \
  2465. }; \
  2466. } /* namespace detail2 */ \
  2467. \
  2468. template<typename... T> \
  2469. struct would_call_std_##std_name : detail2::would_call_std_##std_name<T...> \
  2470. { \
  2471. }
  2472. #ifndef JSON_USE_IMPLICIT_CONVERSIONS
  2473. #define JSON_USE_IMPLICIT_CONVERSIONS 1
  2474. #endif
  2475. #if JSON_USE_IMPLICIT_CONVERSIONS
  2476. #define JSON_EXPLICIT
  2477. #else
  2478. #define JSON_EXPLICIT explicit
  2479. #endif
  2480. #ifndef JSON_DIAGNOSTICS
  2481. #define JSON_DIAGNOSTICS 0
  2482. #endif
  2483. namespace nlohmann
  2484. {
  2485. namespace detail
  2486. {
  2487. /*!
  2488. @brief replace all occurrences of a substring by another string
  2489. @param[in,out] s the string to manipulate; changed so that all
  2490. occurrences of @a f are replaced with @a t
  2491. @param[in] f the substring to replace with @a t
  2492. @param[in] t the string to replace @a f
  2493. @pre The search string @a f must not be empty. **This precondition is
  2494. enforced with an assertion.**
  2495. @since version 2.0.0
  2496. */
  2497. inline void replace_substring(std::string& s, const std::string& f,
  2498. const std::string& t)
  2499. {
  2500. JSON_ASSERT(!f.empty());
  2501. for (auto pos = s.find(f); // find first occurrence of f
  2502. pos != std::string::npos; // make sure f was found
  2503. s.replace(pos, f.size(), t), // replace with t, and
  2504. pos = s.find(f, pos + t.size())) // find next occurrence of f
  2505. {}
  2506. }
  2507. /*!
  2508. * @brief string escaping as described in RFC 6901 (Sect. 4)
  2509. * @param[in] s string to escape
  2510. * @return escaped string
  2511. *
  2512. * Note the order of escaping "~" to "~0" and "/" to "~1" is important.
  2513. */
  2514. inline std::string escape(std::string s)
  2515. {
  2516. replace_substring(s, "~", "~0");
  2517. replace_substring(s, "/", "~1");
  2518. return s;
  2519. }
  2520. /*!
  2521. * @brief string unescaping as described in RFC 6901 (Sect. 4)
  2522. * @param[in] s string to unescape
  2523. * @return unescaped string
  2524. *
  2525. * Note the order of escaping "~1" to "/" and "~0" to "~" is important.
  2526. */
  2527. static void unescape(std::string& s)
  2528. {
  2529. replace_substring(s, "~1", "/");
  2530. replace_substring(s, "~0", "~");
  2531. }
  2532. } // namespace detail
  2533. } // namespace nlohmann
  2534. // #include <nlohmann/detail/input/position_t.hpp>
  2535. #include <cstddef> // size_t
  2536. namespace nlohmann
  2537. {
  2538. namespace detail
  2539. {
  2540. /// struct to capture the start position of the current token
  2541. struct position_t
  2542. {
  2543. /// the total number of characters read
  2544. std::size_t chars_read_total = 0;
  2545. /// the number of characters read in the current line
  2546. std::size_t chars_read_current_line = 0;
  2547. /// the number of lines read
  2548. std::size_t lines_read = 0;
  2549. /// conversion to size_t to preserve SAX interface
  2550. constexpr operator size_t() const
  2551. {
  2552. return chars_read_total;
  2553. }
  2554. };
  2555. } // namespace detail
  2556. } // namespace nlohmann
  2557. // #include <nlohmann/detail/macro_scope.hpp>
  2558. namespace nlohmann
  2559. {
  2560. namespace detail
  2561. {
  2562. ////////////////
  2563. // exceptions //
  2564. ////////////////
  2565. /// @brief general exception of the @ref basic_json class
  2566. /// @sa https://json.nlohmann.me/api/basic_json/exception/
  2567. class exception : public std::exception
  2568. {
  2569. public:
  2570. /// returns the explanatory string
  2571. const char* what() const noexcept override
  2572. {
  2573. return m.what();
  2574. }
  2575. /// the id of the exception
  2576. const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes)
  2577. protected:
  2578. JSON_HEDLEY_NON_NULL(3)
  2579. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} // NOLINT(bugprone-throw-keyword-missing)
  2580. static std::string name(const std::string& ename, int id_)
  2581. {
  2582. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  2583. }
  2584. template<typename BasicJsonType>
  2585. static std::string diagnostics(const BasicJsonType& leaf_element)
  2586. {
  2587. #if JSON_DIAGNOSTICS
  2588. std::vector<std::string> tokens;
  2589. for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent)
  2590. {
  2591. switch (current->m_parent->type())
  2592. {
  2593. case value_t::array:
  2594. {
  2595. for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i)
  2596. {
  2597. if (&current->m_parent->m_value.array->operator[](i) == current)
  2598. {
  2599. tokens.emplace_back(std::to_string(i));
  2600. break;
  2601. }
  2602. }
  2603. break;
  2604. }
  2605. case value_t::object:
  2606. {
  2607. for (const auto& element : *current->m_parent->m_value.object)
  2608. {
  2609. if (&element.second == current)
  2610. {
  2611. tokens.emplace_back(element.first.c_str());
  2612. break;
  2613. }
  2614. }
  2615. break;
  2616. }
  2617. case value_t::null: // LCOV_EXCL_LINE
  2618. case value_t::string: // LCOV_EXCL_LINE
  2619. case value_t::boolean: // LCOV_EXCL_LINE
  2620. case value_t::number_integer: // LCOV_EXCL_LINE
  2621. case value_t::number_unsigned: // LCOV_EXCL_LINE
  2622. case value_t::number_float: // LCOV_EXCL_LINE
  2623. case value_t::binary: // LCOV_EXCL_LINE
  2624. case value_t::discarded: // LCOV_EXCL_LINE
  2625. default: // LCOV_EXCL_LINE
  2626. break; // LCOV_EXCL_LINE
  2627. }
  2628. }
  2629. if (tokens.empty())
  2630. {
  2631. return "";
  2632. }
  2633. return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{},
  2634. [](const std::string & a, const std::string & b)
  2635. {
  2636. return a + "/" + detail::escape(b);
  2637. }) + ") ";
  2638. #else
  2639. static_cast<void>(leaf_element);
  2640. return "";
  2641. #endif
  2642. }
  2643. private:
  2644. /// an exception object as storage for error messages
  2645. std::runtime_error m;
  2646. };
  2647. /// @brief exception indicating a parse error
  2648. /// @sa https://json.nlohmann.me/api/basic_json/parse_error/
  2649. class parse_error : public exception
  2650. {
  2651. public:
  2652. /*!
  2653. @brief create a parse error exception
  2654. @param[in] id_ the id of the exception
  2655. @param[in] pos the position where the error occurred (or with
  2656. chars_read_total=0 if the position cannot be
  2657. determined)
  2658. @param[in] what_arg the explanatory string
  2659. @return parse_error object
  2660. */
  2661. template<typename BasicJsonType>
  2662. static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context)
  2663. {
  2664. std::string w = exception::name("parse_error", id_) + "parse error" +
  2665. position_string(pos) + ": " + exception::diagnostics(context) + what_arg;
  2666. return {id_, pos.chars_read_total, w.c_str()};
  2667. }
  2668. template<typename BasicJsonType>
  2669. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context)
  2670. {
  2671. std::string w = exception::name("parse_error", id_) + "parse error" +
  2672. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  2673. ": " + exception::diagnostics(context) + what_arg;
  2674. return {id_, byte_, w.c_str()};
  2675. }
  2676. /*!
  2677. @brief byte index of the parse error
  2678. The byte index of the last read character in the input file.
  2679. @note For an input with n bytes, 1 is the index of the first character and
  2680. n+1 is the index of the terminating null byte or the end of file.
  2681. This also holds true when reading a byte vector (CBOR or MessagePack).
  2682. */
  2683. const std::size_t byte;
  2684. private:
  2685. parse_error(int id_, std::size_t byte_, const char* what_arg)
  2686. : exception(id_, what_arg), byte(byte_) {}
  2687. static std::string position_string(const position_t& pos)
  2688. {
  2689. return " at line " + std::to_string(pos.lines_read + 1) +
  2690. ", column " + std::to_string(pos.chars_read_current_line);
  2691. }
  2692. };
  2693. /// @brief exception indicating errors with iterators
  2694. /// @sa https://json.nlohmann.me/api/basic_json/invalid_iterator/
  2695. class invalid_iterator : public exception
  2696. {
  2697. public:
  2698. template<typename BasicJsonType>
  2699. static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context)
  2700. {
  2701. std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg;
  2702. return {id_, w.c_str()};
  2703. }
  2704. private:
  2705. JSON_HEDLEY_NON_NULL(3)
  2706. invalid_iterator(int id_, const char* what_arg)
  2707. : exception(id_, what_arg) {}
  2708. };
  2709. /// @brief exception indicating executing a member function with a wrong type
  2710. /// @sa https://json.nlohmann.me/api/basic_json/type_error/
  2711. class type_error : public exception
  2712. {
  2713. public:
  2714. template<typename BasicJsonType>
  2715. static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context)
  2716. {
  2717. std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg;
  2718. return {id_, w.c_str()};
  2719. }
  2720. private:
  2721. JSON_HEDLEY_NON_NULL(3)
  2722. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2723. };
  2724. /// @brief exception indicating access out of the defined range
  2725. /// @sa https://json.nlohmann.me/api/basic_json/out_of_range/
  2726. class out_of_range : public exception
  2727. {
  2728. public:
  2729. template<typename BasicJsonType>
  2730. static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context)
  2731. {
  2732. std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg;
  2733. return {id_, w.c_str()};
  2734. }
  2735. private:
  2736. JSON_HEDLEY_NON_NULL(3)
  2737. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2738. };
  2739. /// @brief exception indicating other library errors
  2740. /// @sa https://json.nlohmann.me/api/basic_json/other_error/
  2741. class other_error : public exception
  2742. {
  2743. public:
  2744. template<typename BasicJsonType>
  2745. static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context)
  2746. {
  2747. std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg;
  2748. return {id_, w.c_str()};
  2749. }
  2750. private:
  2751. JSON_HEDLEY_NON_NULL(3)
  2752. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2753. };
  2754. } // namespace detail
  2755. } // namespace nlohmann
  2756. // #include <nlohmann/detail/macro_scope.hpp>
  2757. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2758. #include <cstddef> // size_t
  2759. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  2760. #include <utility> // index_sequence, make_index_sequence, index_sequence_for
  2761. // #include <nlohmann/detail/macro_scope.hpp>
  2762. namespace nlohmann
  2763. {
  2764. namespace detail
  2765. {
  2766. template<typename T>
  2767. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  2768. #ifdef JSON_HAS_CPP_14
  2769. // the following utilities are natively available in C++14
  2770. using std::enable_if_t;
  2771. using std::index_sequence;
  2772. using std::make_index_sequence;
  2773. using std::index_sequence_for;
  2774. #else
  2775. // alias templates to reduce boilerplate
  2776. template<bool B, typename T = void>
  2777. using enable_if_t = typename std::enable_if<B, T>::type;
  2778. // The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h
  2779. // which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0.
  2780. //// START OF CODE FROM GOOGLE ABSEIL
  2781. // integer_sequence
  2782. //
  2783. // Class template representing a compile-time integer sequence. An instantiation
  2784. // of `integer_sequence<T, Ints...>` has a sequence of integers encoded in its
  2785. // type through its template arguments (which is a common need when
  2786. // working with C++11 variadic templates). `absl::integer_sequence` is designed
  2787. // to be a drop-in replacement for C++14's `std::integer_sequence`.
  2788. //
  2789. // Example:
  2790. //
  2791. // template< class T, T... Ints >
  2792. // void user_function(integer_sequence<T, Ints...>);
  2793. //
  2794. // int main()
  2795. // {
  2796. // // user_function's `T` will be deduced to `int` and `Ints...`
  2797. // // will be deduced to `0, 1, 2, 3, 4`.
  2798. // user_function(make_integer_sequence<int, 5>());
  2799. // }
  2800. template <typename T, T... Ints>
  2801. struct integer_sequence
  2802. {
  2803. using value_type = T;
  2804. static constexpr std::size_t size() noexcept
  2805. {
  2806. return sizeof...(Ints);
  2807. }
  2808. };
  2809. // index_sequence
  2810. //
  2811. // A helper template for an `integer_sequence` of `size_t`,
  2812. // `absl::index_sequence` is designed to be a drop-in replacement for C++14's
  2813. // `std::index_sequence`.
  2814. template <size_t... Ints>
  2815. using index_sequence = integer_sequence<size_t, Ints...>;
  2816. namespace utility_internal
  2817. {
  2818. template <typename Seq, size_t SeqSize, size_t Rem>
  2819. struct Extend;
  2820. // Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency.
  2821. template <typename T, T... Ints, size_t SeqSize>
  2822. struct Extend<integer_sequence<T, Ints...>, SeqSize, 0>
  2823. {
  2824. using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >;
  2825. };
  2826. template <typename T, T... Ints, size_t SeqSize>
  2827. struct Extend<integer_sequence<T, Ints...>, SeqSize, 1>
  2828. {
  2829. using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >;
  2830. };
  2831. // Recursion helper for 'make_integer_sequence<T, N>'.
  2832. // 'Gen<T, N>::type' is an alias for 'integer_sequence<T, 0, 1, ... N-1>'.
  2833. template <typename T, size_t N>
  2834. struct Gen
  2835. {
  2836. using type =
  2837. typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type;
  2838. };
  2839. template <typename T>
  2840. struct Gen<T, 0>
  2841. {
  2842. using type = integer_sequence<T>;
  2843. };
  2844. } // namespace utility_internal
  2845. // Compile-time sequences of integers
  2846. // make_integer_sequence
  2847. //
  2848. // This template alias is equivalent to
  2849. // `integer_sequence<int, 0, 1, ..., N-1>`, and is designed to be a drop-in
  2850. // replacement for C++14's `std::make_integer_sequence`.
  2851. template <typename T, T N>
  2852. using make_integer_sequence = typename utility_internal::Gen<T, N>::type;
  2853. // make_index_sequence
  2854. //
  2855. // This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`,
  2856. // and is designed to be a drop-in replacement for C++14's
  2857. // `std::make_index_sequence`.
  2858. template <size_t N>
  2859. using make_index_sequence = make_integer_sequence<size_t, N>;
  2860. // index_sequence_for
  2861. //
  2862. // Converts a typename pack into an index sequence of the same length, and
  2863. // is designed to be a drop-in replacement for C++14's
  2864. // `std::index_sequence_for()`
  2865. template <typename... Ts>
  2866. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  2867. //// END OF CODE FROM GOOGLE ABSEIL
  2868. #endif
  2869. // dispatch utility (taken from ranges-v3)
  2870. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  2871. template<> struct priority_tag<0> {};
  2872. // taken from ranges-v3
  2873. template<typename T>
  2874. struct static_const
  2875. {
  2876. static constexpr T value{};
  2877. };
  2878. template<typename T>
  2879. constexpr T static_const<T>::value; // NOLINT(readability-redundant-declaration)
  2880. } // namespace detail
  2881. } // namespace nlohmann
  2882. // #include <nlohmann/detail/meta/identity_tag.hpp>
  2883. namespace nlohmann
  2884. {
  2885. namespace detail
  2886. {
  2887. // dispatching helper struct
  2888. template <class T> struct identity_tag {};
  2889. } // namespace detail
  2890. } // namespace nlohmann
  2891. // #include <nlohmann/detail/meta/type_traits.hpp>
  2892. #include <limits> // numeric_limits
  2893. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  2894. #include <utility> // declval
  2895. #include <tuple> // tuple
  2896. // #include <nlohmann/detail/macro_scope.hpp>
  2897. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  2898. #include <iterator> // random_access_iterator_tag
  2899. // #include <nlohmann/detail/meta/void_t.hpp>
  2900. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2901. namespace nlohmann
  2902. {
  2903. namespace detail
  2904. {
  2905. template<typename It, typename = void>
  2906. struct iterator_types {};
  2907. template<typename It>
  2908. struct iterator_types <
  2909. It,
  2910. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  2911. typename It::reference, typename It::iterator_category >>
  2912. {
  2913. using difference_type = typename It::difference_type;
  2914. using value_type = typename It::value_type;
  2915. using pointer = typename It::pointer;
  2916. using reference = typename It::reference;
  2917. using iterator_category = typename It::iterator_category;
  2918. };
  2919. // This is required as some compilers implement std::iterator_traits in a way that
  2920. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  2921. template<typename T, typename = void>
  2922. struct iterator_traits
  2923. {
  2924. };
  2925. template<typename T>
  2926. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  2927. : iterator_types<T>
  2928. {
  2929. };
  2930. template<typename T>
  2931. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  2932. {
  2933. using iterator_category = std::random_access_iterator_tag;
  2934. using value_type = T;
  2935. using difference_type = ptrdiff_t;
  2936. using pointer = T*;
  2937. using reference = T&;
  2938. };
  2939. } // namespace detail
  2940. } // namespace nlohmann
  2941. // #include <nlohmann/detail/meta/call_std/begin.hpp>
  2942. // #include <nlohmann/detail/macro_scope.hpp>
  2943. namespace nlohmann
  2944. {
  2945. NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin);
  2946. } // namespace nlohmann
  2947. // #include <nlohmann/detail/meta/call_std/end.hpp>
  2948. // #include <nlohmann/detail/macro_scope.hpp>
  2949. namespace nlohmann
  2950. {
  2951. NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end);
  2952. } // namespace nlohmann
  2953. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2954. // #include <nlohmann/detail/meta/detected.hpp>
  2955. // #include <nlohmann/json_fwd.hpp>
  2956. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2957. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2958. #include <cstdint> // int64_t, uint64_t
  2959. #include <map> // map
  2960. #include <memory> // allocator
  2961. #include <string> // string
  2962. #include <vector> // vector
  2963. /*!
  2964. @brief namespace for Niels Lohmann
  2965. @see https://github.com/nlohmann
  2966. @since version 1.0.0
  2967. */
  2968. namespace nlohmann
  2969. {
  2970. /*!
  2971. @brief default JSONSerializer template argument
  2972. This serializer ignores the template arguments and uses ADL
  2973. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  2974. for serialization.
  2975. */
  2976. template<typename T = void, typename SFINAE = void>
  2977. struct adl_serializer;
  2978. /// a class to store JSON values
  2979. /// @sa https://json.nlohmann.me/api/basic_json/
  2980. template<template<typename U, typename V, typename... Args> class ObjectType =
  2981. std::map,
  2982. template<typename U, typename... Args> class ArrayType = std::vector,
  2983. class StringType = std::string, class BooleanType = bool,
  2984. class NumberIntegerType = std::int64_t,
  2985. class NumberUnsignedType = std::uint64_t,
  2986. class NumberFloatType = double,
  2987. template<typename U> class AllocatorType = std::allocator,
  2988. template<typename T, typename SFINAE = void> class JSONSerializer =
  2989. adl_serializer,
  2990. class BinaryType = std::vector<std::uint8_t>>
  2991. class basic_json;
  2992. /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document
  2993. /// @sa https://json.nlohmann.me/api/json_pointer/
  2994. template<typename BasicJsonType>
  2995. class json_pointer;
  2996. /*!
  2997. @brief default specialization
  2998. @sa https://json.nlohmann.me/api/json/
  2999. */
  3000. using json = basic_json<>;
  3001. /// @brief a minimal map-like container that preserves insertion order
  3002. /// @sa https://json.nlohmann.me/api/ordered_map/
  3003. template<class Key, class T, class IgnoredLess, class Allocator>
  3004. struct ordered_map;
  3005. /// @brief specialization that maintains the insertion order of object keys
  3006. /// @sa https://json.nlohmann.me/api/ordered_json/
  3007. using ordered_json = basic_json<nlohmann::ordered_map>;
  3008. } // namespace nlohmann
  3009. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  3010. namespace nlohmann
  3011. {
  3012. /*!
  3013. @brief detail namespace with internal helper functions
  3014. This namespace collects functions that should not be exposed,
  3015. implementations of some @ref basic_json methods, and meta-programming helpers.
  3016. @since version 2.1.0
  3017. */
  3018. namespace detail
  3019. {
  3020. /////////////
  3021. // helpers //
  3022. /////////////
  3023. // Note to maintainers:
  3024. //
  3025. // Every trait in this file expects a non CV-qualified type.
  3026. // The only exceptions are in the 'aliases for detected' section
  3027. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  3028. //
  3029. // In this case, T has to be properly CV-qualified to constraint the function arguments
  3030. // (e.g. to_json(BasicJsonType&, const T&))
  3031. template<typename> struct is_basic_json : std::false_type {};
  3032. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  3033. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  3034. //////////////////////
  3035. // json_ref helpers //
  3036. //////////////////////
  3037. template<typename>
  3038. class json_ref;
  3039. template<typename>
  3040. struct is_json_ref : std::false_type {};
  3041. template<typename T>
  3042. struct is_json_ref<json_ref<T>> : std::true_type {};
  3043. //////////////////////////
  3044. // aliases for detected //
  3045. //////////////////////////
  3046. template<typename T>
  3047. using mapped_type_t = typename T::mapped_type;
  3048. template<typename T>
  3049. using key_type_t = typename T::key_type;
  3050. template<typename T>
  3051. using value_type_t = typename T::value_type;
  3052. template<typename T>
  3053. using difference_type_t = typename T::difference_type;
  3054. template<typename T>
  3055. using pointer_t = typename T::pointer;
  3056. template<typename T>
  3057. using reference_t = typename T::reference;
  3058. template<typename T>
  3059. using iterator_category_t = typename T::iterator_category;
  3060. template<typename T, typename... Args>
  3061. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  3062. template<typename T, typename... Args>
  3063. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  3064. template<typename T, typename U>
  3065. using get_template_function = decltype(std::declval<T>().template get<U>());
  3066. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  3067. template<typename BasicJsonType, typename T, typename = void>
  3068. struct has_from_json : std::false_type {};
  3069. // trait checking if j.get<T> is valid
  3070. // use this trait instead of std::is_constructible or std::is_convertible,
  3071. // both rely on, or make use of implicit conversions, and thus fail when T
  3072. // has several constructors/operator= (see https://github.com/nlohmann/json/issues/958)
  3073. template <typename BasicJsonType, typename T>
  3074. struct is_getable
  3075. {
  3076. static constexpr bool value = is_detected<get_template_function, const BasicJsonType&, T>::value;
  3077. };
  3078. template<typename BasicJsonType, typename T>
  3079. struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  3080. {
  3081. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  3082. static constexpr bool value =
  3083. is_detected_exact<void, from_json_function, serializer,
  3084. const BasicJsonType&, T&>::value;
  3085. };
  3086. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  3087. // this overload is used for non-default-constructible user-defined-types
  3088. template<typename BasicJsonType, typename T, typename = void>
  3089. struct has_non_default_from_json : std::false_type {};
  3090. template<typename BasicJsonType, typename T>
  3091. struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  3092. {
  3093. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  3094. static constexpr bool value =
  3095. is_detected_exact<T, from_json_function, serializer,
  3096. const BasicJsonType&>::value;
  3097. };
  3098. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  3099. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  3100. template<typename BasicJsonType, typename T, typename = void>
  3101. struct has_to_json : std::false_type {};
  3102. template<typename BasicJsonType, typename T>
  3103. struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  3104. {
  3105. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  3106. static constexpr bool value =
  3107. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  3108. T>::value;
  3109. };
  3110. ///////////////////
  3111. // is_ functions //
  3112. ///////////////////
  3113. // https://en.cppreference.com/w/cpp/types/conjunction
  3114. template<class...> struct conjunction : std::true_type { };
  3115. template<class B1> struct conjunction<B1> : B1 { };
  3116. template<class B1, class... Bn>
  3117. struct conjunction<B1, Bn...>
  3118. : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  3119. // https://en.cppreference.com/w/cpp/types/negation
  3120. template<class B> struct negation : std::integral_constant < bool, !B::value > { };
  3121. // Reimplementation of is_constructible and is_default_constructible, due to them being broken for
  3122. // std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367).
  3123. // This causes compile errors in e.g. clang 3.5 or gcc 4.9.
  3124. template <typename T>
  3125. struct is_default_constructible : std::is_default_constructible<T> {};
  3126. template <typename T1, typename T2>
  3127. struct is_default_constructible<std::pair<T1, T2>>
  3128. : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {};
  3129. template <typename T1, typename T2>
  3130. struct is_default_constructible<const std::pair<T1, T2>>
  3131. : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {};
  3132. template <typename... Ts>
  3133. struct is_default_constructible<std::tuple<Ts...>>
  3134. : conjunction<is_default_constructible<Ts>...> {};
  3135. template <typename... Ts>
  3136. struct is_default_constructible<const std::tuple<Ts...>>
  3137. : conjunction<is_default_constructible<Ts>...> {};
  3138. template <typename T, typename... Args>
  3139. struct is_constructible : std::is_constructible<T, Args...> {};
  3140. template <typename T1, typename T2>
  3141. struct is_constructible<std::pair<T1, T2>> : is_default_constructible<std::pair<T1, T2>> {};
  3142. template <typename T1, typename T2>
  3143. struct is_constructible<const std::pair<T1, T2>> : is_default_constructible<const std::pair<T1, T2>> {};
  3144. template <typename... Ts>
  3145. struct is_constructible<std::tuple<Ts...>> : is_default_constructible<std::tuple<Ts...>> {};
  3146. template <typename... Ts>
  3147. struct is_constructible<const std::tuple<Ts...>> : is_default_constructible<const std::tuple<Ts...>> {};
  3148. template<typename T, typename = void>
  3149. struct is_iterator_traits : std::false_type {};
  3150. template<typename T>
  3151. struct is_iterator_traits<iterator_traits<T>>
  3152. {
  3153. private:
  3154. using traits = iterator_traits<T>;
  3155. public:
  3156. static constexpr auto value =
  3157. is_detected<value_type_t, traits>::value &&
  3158. is_detected<difference_type_t, traits>::value &&
  3159. is_detected<pointer_t, traits>::value &&
  3160. is_detected<iterator_category_t, traits>::value &&
  3161. is_detected<reference_t, traits>::value;
  3162. };
  3163. template<typename T>
  3164. struct is_range
  3165. {
  3166. private:
  3167. using t_ref = typename std::add_lvalue_reference<T>::type;
  3168. using iterator = detected_t<result_of_begin, t_ref>;
  3169. using sentinel = detected_t<result_of_end, t_ref>;
  3170. // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator
  3171. // and https://en.cppreference.com/w/cpp/iterator/sentinel_for
  3172. // but reimplementing these would be too much work, as a lot of other concepts are used underneath
  3173. static constexpr auto is_iterator_begin =
  3174. is_iterator_traits<iterator_traits<iterator>>::value;
  3175. public:
  3176. static constexpr bool value = !std::is_same<iterator, nonesuch>::value && !std::is_same<sentinel, nonesuch>::value && is_iterator_begin;
  3177. };
  3178. template<typename R>
  3179. using iterator_t = enable_if_t<is_range<R>::value, result_of_begin<decltype(std::declval<R&>())>>;
  3180. template<typename T>
  3181. using range_value_t = value_type_t<iterator_traits<iterator_t<T>>>;
  3182. // The following implementation of is_complete_type is taken from
  3183. // https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/
  3184. // and is written by Xiang Fan who agreed to using it in this library.
  3185. template<typename T, typename = void>
  3186. struct is_complete_type : std::false_type {};
  3187. template<typename T>
  3188. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  3189. template<typename BasicJsonType, typename CompatibleObjectType,
  3190. typename = void>
  3191. struct is_compatible_object_type_impl : std::false_type {};
  3192. template<typename BasicJsonType, typename CompatibleObjectType>
  3193. struct is_compatible_object_type_impl <
  3194. BasicJsonType, CompatibleObjectType,
  3195. enable_if_t < is_detected<mapped_type_t, CompatibleObjectType>::value&&
  3196. is_detected<key_type_t, CompatibleObjectType>::value >>
  3197. {
  3198. using object_t = typename BasicJsonType::object_t;
  3199. // macOS's is_constructible does not play well with nonesuch...
  3200. static constexpr bool value =
  3201. is_constructible<typename object_t::key_type,
  3202. typename CompatibleObjectType::key_type>::value &&
  3203. is_constructible<typename object_t::mapped_type,
  3204. typename CompatibleObjectType::mapped_type>::value;
  3205. };
  3206. template<typename BasicJsonType, typename CompatibleObjectType>
  3207. struct is_compatible_object_type
  3208. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  3209. template<typename BasicJsonType, typename ConstructibleObjectType,
  3210. typename = void>
  3211. struct is_constructible_object_type_impl : std::false_type {};
  3212. template<typename BasicJsonType, typename ConstructibleObjectType>
  3213. struct is_constructible_object_type_impl <
  3214. BasicJsonType, ConstructibleObjectType,
  3215. enable_if_t < is_detected<mapped_type_t, ConstructibleObjectType>::value&&
  3216. is_detected<key_type_t, ConstructibleObjectType>::value >>
  3217. {
  3218. using object_t = typename BasicJsonType::object_t;
  3219. static constexpr bool value =
  3220. (is_default_constructible<ConstructibleObjectType>::value &&
  3221. (std::is_move_assignable<ConstructibleObjectType>::value ||
  3222. std::is_copy_assignable<ConstructibleObjectType>::value) &&
  3223. (is_constructible<typename ConstructibleObjectType::key_type,
  3224. typename object_t::key_type>::value &&
  3225. std::is_same <
  3226. typename object_t::mapped_type,
  3227. typename ConstructibleObjectType::mapped_type >::value)) ||
  3228. (has_from_json<BasicJsonType,
  3229. typename ConstructibleObjectType::mapped_type>::value ||
  3230. has_non_default_from_json <
  3231. BasicJsonType,
  3232. typename ConstructibleObjectType::mapped_type >::value);
  3233. };
  3234. template<typename BasicJsonType, typename ConstructibleObjectType>
  3235. struct is_constructible_object_type
  3236. : is_constructible_object_type_impl<BasicJsonType,
  3237. ConstructibleObjectType> {};
  3238. template<typename BasicJsonType, typename CompatibleStringType>
  3239. struct is_compatible_string_type
  3240. {
  3241. static constexpr auto value =
  3242. is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  3243. };
  3244. template<typename BasicJsonType, typename ConstructibleStringType>
  3245. struct is_constructible_string_type
  3246. {
  3247. static constexpr auto value =
  3248. is_constructible<ConstructibleStringType,
  3249. typename BasicJsonType::string_t>::value;
  3250. };
  3251. template<typename BasicJsonType, typename CompatibleArrayType, typename = void>
  3252. struct is_compatible_array_type_impl : std::false_type {};
  3253. template<typename BasicJsonType, typename CompatibleArrayType>
  3254. struct is_compatible_array_type_impl <
  3255. BasicJsonType, CompatibleArrayType,
  3256. enable_if_t <
  3257. is_detected<iterator_t, CompatibleArrayType>::value&&
  3258. is_iterator_traits<iterator_traits<detected_t<iterator_t, CompatibleArrayType>>>::value&&
  3259. // special case for types like std::filesystem::path whose iterator's value_type are themselves
  3260. // c.f. https://github.com/nlohmann/json/pull/3073
  3261. !std::is_same<CompatibleArrayType, detected_t<range_value_t, CompatibleArrayType>>::value >>
  3262. {
  3263. static constexpr bool value =
  3264. is_constructible<BasicJsonType,
  3265. range_value_t<CompatibleArrayType>>::value;
  3266. };
  3267. template<typename BasicJsonType, typename CompatibleArrayType>
  3268. struct is_compatible_array_type
  3269. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  3270. template<typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  3271. struct is_constructible_array_type_impl : std::false_type {};
  3272. template<typename BasicJsonType, typename ConstructibleArrayType>
  3273. struct is_constructible_array_type_impl <
  3274. BasicJsonType, ConstructibleArrayType,
  3275. enable_if_t<std::is_same<ConstructibleArrayType,
  3276. typename BasicJsonType::value_type>::value >>
  3277. : std::true_type {};
  3278. template<typename BasicJsonType, typename ConstructibleArrayType>
  3279. struct is_constructible_array_type_impl <
  3280. BasicJsonType, ConstructibleArrayType,
  3281. enable_if_t < !std::is_same<ConstructibleArrayType,
  3282. typename BasicJsonType::value_type>::value&&
  3283. !is_compatible_string_type<BasicJsonType, ConstructibleArrayType>::value&&
  3284. is_default_constructible<ConstructibleArrayType>::value&&
  3285. (std::is_move_assignable<ConstructibleArrayType>::value ||
  3286. std::is_copy_assignable<ConstructibleArrayType>::value)&&
  3287. is_detected<iterator_t, ConstructibleArrayType>::value&&
  3288. is_iterator_traits<iterator_traits<detected_t<iterator_t, ConstructibleArrayType>>>::value&&
  3289. is_detected<range_value_t, ConstructibleArrayType>::value&&
  3290. // special case for types like std::filesystem::path whose iterator's value_type are themselves
  3291. // c.f. https://github.com/nlohmann/json/pull/3073
  3292. !std::is_same<ConstructibleArrayType, detected_t<range_value_t, ConstructibleArrayType>>::value&&
  3293. is_complete_type <
  3294. detected_t<range_value_t, ConstructibleArrayType >>::value >>
  3295. {
  3296. using value_type = range_value_t<ConstructibleArrayType>;
  3297. static constexpr bool value =
  3298. std::is_same<value_type,
  3299. typename BasicJsonType::array_t::value_type>::value ||
  3300. has_from_json<BasicJsonType,
  3301. value_type>::value ||
  3302. has_non_default_from_json <
  3303. BasicJsonType,
  3304. value_type >::value;
  3305. };
  3306. template<typename BasicJsonType, typename ConstructibleArrayType>
  3307. struct is_constructible_array_type
  3308. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  3309. template<typename RealIntegerType, typename CompatibleNumberIntegerType,
  3310. typename = void>
  3311. struct is_compatible_integer_type_impl : std::false_type {};
  3312. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  3313. struct is_compatible_integer_type_impl <
  3314. RealIntegerType, CompatibleNumberIntegerType,
  3315. enable_if_t < std::is_integral<RealIntegerType>::value&&
  3316. std::is_integral<CompatibleNumberIntegerType>::value&&
  3317. !std::is_same<bool, CompatibleNumberIntegerType>::value >>
  3318. {
  3319. // is there an assert somewhere on overflows?
  3320. using RealLimits = std::numeric_limits<RealIntegerType>;
  3321. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  3322. static constexpr auto value =
  3323. is_constructible<RealIntegerType,
  3324. CompatibleNumberIntegerType>::value &&
  3325. CompatibleLimits::is_integer &&
  3326. RealLimits::is_signed == CompatibleLimits::is_signed;
  3327. };
  3328. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  3329. struct is_compatible_integer_type
  3330. : is_compatible_integer_type_impl<RealIntegerType,
  3331. CompatibleNumberIntegerType> {};
  3332. template<typename BasicJsonType, typename CompatibleType, typename = void>
  3333. struct is_compatible_type_impl: std::false_type {};
  3334. template<typename BasicJsonType, typename CompatibleType>
  3335. struct is_compatible_type_impl <
  3336. BasicJsonType, CompatibleType,
  3337. enable_if_t<is_complete_type<CompatibleType>::value >>
  3338. {
  3339. static constexpr bool value =
  3340. has_to_json<BasicJsonType, CompatibleType>::value;
  3341. };
  3342. template<typename BasicJsonType, typename CompatibleType>
  3343. struct is_compatible_type
  3344. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  3345. template<typename T1, typename T2>
  3346. struct is_constructible_tuple : std::false_type {};
  3347. template<typename T1, typename... Args>
  3348. struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<is_constructible<T1, Args>...> {};
  3349. // a naive helper to check if a type is an ordered_map (exploits the fact that
  3350. // ordered_map inherits capacity() from std::vector)
  3351. template <typename T>
  3352. struct is_ordered_map
  3353. {
  3354. using one = char;
  3355. struct two
  3356. {
  3357. char x[2]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  3358. };
  3359. template <typename C> static one test( decltype(&C::capacity) ) ;
  3360. template <typename C> static two test(...);
  3361. enum { value = sizeof(test<T>(nullptr)) == sizeof(char) }; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  3362. };
  3363. // to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324)
  3364. template < typename T, typename U, enable_if_t < !std::is_same<T, U>::value, int > = 0 >
  3365. T conditional_static_cast(U value)
  3366. {
  3367. return static_cast<T>(value);
  3368. }
  3369. template<typename T, typename U, enable_if_t<std::is_same<T, U>::value, int> = 0>
  3370. T conditional_static_cast(U value)
  3371. {
  3372. return value;
  3373. }
  3374. } // namespace detail
  3375. } // namespace nlohmann
  3376. // #include <nlohmann/detail/value_t.hpp>
  3377. #if JSON_HAS_EXPERIMENTAL_FILESYSTEM
  3378. #include <experimental/filesystem>
  3379. namespace nlohmann::detail
  3380. {
  3381. namespace std_fs = std::experimental::filesystem;
  3382. } // namespace nlohmann::detail
  3383. #elif JSON_HAS_FILESYSTEM
  3384. #include <filesystem>
  3385. namespace nlohmann::detail
  3386. {
  3387. namespace std_fs = std::filesystem;
  3388. } // namespace nlohmann::detail
  3389. #endif
  3390. namespace nlohmann
  3391. {
  3392. namespace detail
  3393. {
  3394. template<typename BasicJsonType>
  3395. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  3396. {
  3397. if (JSON_HEDLEY_UNLIKELY(!j.is_null()))
  3398. {
  3399. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j));
  3400. }
  3401. n = nullptr;
  3402. }
  3403. // overloads for basic_json template parameters
  3404. template < typename BasicJsonType, typename ArithmeticType,
  3405. enable_if_t < std::is_arithmetic<ArithmeticType>::value&&
  3406. !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3407. int > = 0 >
  3408. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  3409. {
  3410. switch (static_cast<value_t>(j))
  3411. {
  3412. case value_t::number_unsigned:
  3413. {
  3414. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3415. break;
  3416. }
  3417. case value_t::number_integer:
  3418. {
  3419. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3420. break;
  3421. }
  3422. case value_t::number_float:
  3423. {
  3424. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3425. break;
  3426. }
  3427. case value_t::null:
  3428. case value_t::object:
  3429. case value_t::array:
  3430. case value_t::string:
  3431. case value_t::boolean:
  3432. case value_t::binary:
  3433. case value_t::discarded:
  3434. default:
  3435. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j));
  3436. }
  3437. }
  3438. template<typename BasicJsonType>
  3439. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  3440. {
  3441. if (JSON_HEDLEY_UNLIKELY(!j.is_boolean()))
  3442. {
  3443. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j));
  3444. }
  3445. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  3446. }
  3447. template<typename BasicJsonType>
  3448. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  3449. {
  3450. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3451. {
  3452. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
  3453. }
  3454. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3455. }
  3456. template <
  3457. typename BasicJsonType, typename ConstructibleStringType,
  3458. enable_if_t <
  3459. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value&&
  3460. !std::is_same<typename BasicJsonType::string_t,
  3461. ConstructibleStringType>::value,
  3462. int > = 0 >
  3463. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  3464. {
  3465. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3466. {
  3467. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
  3468. }
  3469. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3470. }
  3471. template<typename BasicJsonType>
  3472. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  3473. {
  3474. get_arithmetic_value(j, val);
  3475. }
  3476. template<typename BasicJsonType>
  3477. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  3478. {
  3479. get_arithmetic_value(j, val);
  3480. }
  3481. template<typename BasicJsonType>
  3482. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  3483. {
  3484. get_arithmetic_value(j, val);
  3485. }
  3486. template<typename BasicJsonType, typename EnumType,
  3487. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3488. void from_json(const BasicJsonType& j, EnumType& e)
  3489. {
  3490. typename std::underlying_type<EnumType>::type val;
  3491. get_arithmetic_value(j, val);
  3492. e = static_cast<EnumType>(val);
  3493. }
  3494. // forward_list doesn't have an insert method
  3495. template<typename BasicJsonType, typename T, typename Allocator,
  3496. enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
  3497. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  3498. {
  3499. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3500. {
  3501. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3502. }
  3503. l.clear();
  3504. std::transform(j.rbegin(), j.rend(),
  3505. std::front_inserter(l), [](const BasicJsonType & i)
  3506. {
  3507. return i.template get<T>();
  3508. });
  3509. }
  3510. // valarray doesn't have an insert method
  3511. template<typename BasicJsonType, typename T,
  3512. enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
  3513. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  3514. {
  3515. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3516. {
  3517. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3518. }
  3519. l.resize(j.size());
  3520. std::transform(j.begin(), j.end(), std::begin(l),
  3521. [](const BasicJsonType & elem)
  3522. {
  3523. return elem.template get<T>();
  3524. });
  3525. }
  3526. template<typename BasicJsonType, typename T, std::size_t N>
  3527. auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  3528. -> decltype(j.template get<T>(), void())
  3529. {
  3530. for (std::size_t i = 0; i < N; ++i)
  3531. {
  3532. arr[i] = j.at(i).template get<T>();
  3533. }
  3534. }
  3535. template<typename BasicJsonType>
  3536. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  3537. {
  3538. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  3539. }
  3540. template<typename BasicJsonType, typename T, std::size_t N>
  3541. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  3542. priority_tag<2> /*unused*/)
  3543. -> decltype(j.template get<T>(), void())
  3544. {
  3545. for (std::size_t i = 0; i < N; ++i)
  3546. {
  3547. arr[i] = j.at(i).template get<T>();
  3548. }
  3549. }
  3550. template<typename BasicJsonType, typename ConstructibleArrayType,
  3551. enable_if_t<
  3552. std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
  3553. int> = 0>
  3554. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  3555. -> decltype(
  3556. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  3557. j.template get<typename ConstructibleArrayType::value_type>(),
  3558. void())
  3559. {
  3560. using std::end;
  3561. ConstructibleArrayType ret;
  3562. ret.reserve(j.size());
  3563. std::transform(j.begin(), j.end(),
  3564. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  3565. {
  3566. // get<BasicJsonType>() returns *this, this won't call a from_json
  3567. // method when value_type is BasicJsonType
  3568. return i.template get<typename ConstructibleArrayType::value_type>();
  3569. });
  3570. arr = std::move(ret);
  3571. }
  3572. template<typename BasicJsonType, typename ConstructibleArrayType,
  3573. enable_if_t<
  3574. std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
  3575. int> = 0>
  3576. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  3577. priority_tag<0> /*unused*/)
  3578. {
  3579. using std::end;
  3580. ConstructibleArrayType ret;
  3581. std::transform(
  3582. j.begin(), j.end(), std::inserter(ret, end(ret)),
  3583. [](const BasicJsonType & i)
  3584. {
  3585. // get<BasicJsonType>() returns *this, this won't call a from_json
  3586. // method when value_type is BasicJsonType
  3587. return i.template get<typename ConstructibleArrayType::value_type>();
  3588. });
  3589. arr = std::move(ret);
  3590. }
  3591. template < typename BasicJsonType, typename ConstructibleArrayType,
  3592. enable_if_t <
  3593. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value&&
  3594. !is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value&&
  3595. !is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value&&
  3596. !std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value&&
  3597. !is_basic_json<ConstructibleArrayType>::value,
  3598. int > = 0 >
  3599. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  3600. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  3601. j.template get<typename ConstructibleArrayType::value_type>(),
  3602. void())
  3603. {
  3604. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3605. {
  3606. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3607. }
  3608. from_json_array_impl(j, arr, priority_tag<3> {});
  3609. }
  3610. template < typename BasicJsonType, typename T, std::size_t... Idx >
  3611. std::array<T, sizeof...(Idx)> from_json_inplace_array_impl(BasicJsonType&& j,
  3612. identity_tag<std::array<T, sizeof...(Idx)>> /*unused*/, index_sequence<Idx...> /*unused*/)
  3613. {
  3614. return { { std::forward<BasicJsonType>(j).at(Idx).template get<T>()... } };
  3615. }
  3616. template < typename BasicJsonType, typename T, std::size_t N >
  3617. auto from_json(BasicJsonType&& j, identity_tag<std::array<T, N>> tag)
  3618. -> decltype(from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {}))
  3619. {
  3620. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3621. {
  3622. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3623. }
  3624. return from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {});
  3625. }
  3626. template<typename BasicJsonType>
  3627. void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin)
  3628. {
  3629. if (JSON_HEDLEY_UNLIKELY(!j.is_binary()))
  3630. {
  3631. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j));
  3632. }
  3633. bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>();
  3634. }
  3635. template<typename BasicJsonType, typename ConstructibleObjectType,
  3636. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  3637. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  3638. {
  3639. if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
  3640. {
  3641. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j));
  3642. }
  3643. ConstructibleObjectType ret;
  3644. const auto* inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  3645. using value_type = typename ConstructibleObjectType::value_type;
  3646. std::transform(
  3647. inner_object->begin(), inner_object->end(),
  3648. std::inserter(ret, ret.begin()),
  3649. [](typename BasicJsonType::object_t::value_type const & p)
  3650. {
  3651. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  3652. });
  3653. obj = std::move(ret);
  3654. }
  3655. // overload for arithmetic types, not chosen for basic_json template arguments
  3656. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  3657. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  3658. // an arithmetic type?
  3659. template < typename BasicJsonType, typename ArithmeticType,
  3660. enable_if_t <
  3661. std::is_arithmetic<ArithmeticType>::value&&
  3662. !std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value&&
  3663. !std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value&&
  3664. !std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value&&
  3665. !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3666. int > = 0 >
  3667. void from_json(const BasicJsonType& j, ArithmeticType& val)
  3668. {
  3669. switch (static_cast<value_t>(j))
  3670. {
  3671. case value_t::number_unsigned:
  3672. {
  3673. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3674. break;
  3675. }
  3676. case value_t::number_integer:
  3677. {
  3678. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3679. break;
  3680. }
  3681. case value_t::number_float:
  3682. {
  3683. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3684. break;
  3685. }
  3686. case value_t::boolean:
  3687. {
  3688. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  3689. break;
  3690. }
  3691. case value_t::null:
  3692. case value_t::object:
  3693. case value_t::array:
  3694. case value_t::string:
  3695. case value_t::binary:
  3696. case value_t::discarded:
  3697. default:
  3698. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j));
  3699. }
  3700. }
  3701. template<typename BasicJsonType, typename... Args, std::size_t... Idx>
  3702. std::tuple<Args...> from_json_tuple_impl_base(BasicJsonType&& j, index_sequence<Idx...> /*unused*/)
  3703. {
  3704. return std::make_tuple(std::forward<BasicJsonType>(j).at(Idx).template get<Args>()...);
  3705. }
  3706. template < typename BasicJsonType, class A1, class A2 >
  3707. std::pair<A1, A2> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::pair<A1, A2>> /*unused*/, priority_tag<0> /*unused*/)
  3708. {
  3709. return {std::forward<BasicJsonType>(j).at(0).template get<A1>(),
  3710. std::forward<BasicJsonType>(j).at(1).template get<A2>()};
  3711. }
  3712. template<typename BasicJsonType, typename A1, typename A2>
  3713. void from_json_tuple_impl(BasicJsonType&& j, std::pair<A1, A2>& p, priority_tag<1> /*unused*/)
  3714. {
  3715. p = from_json_tuple_impl(std::forward<BasicJsonType>(j), identity_tag<std::pair<A1, A2>> {}, priority_tag<0> {});
  3716. }
  3717. template<typename BasicJsonType, typename... Args>
  3718. std::tuple<Args...> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::tuple<Args...>> /*unused*/, priority_tag<2> /*unused*/)
  3719. {
  3720. return from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {});
  3721. }
  3722. template<typename BasicJsonType, typename... Args>
  3723. void from_json_tuple_impl(BasicJsonType&& j, std::tuple<Args...>& t, priority_tag<3> /*unused*/)
  3724. {
  3725. t = from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {});
  3726. }
  3727. template<typename BasicJsonType, typename TupleRelated>
  3728. auto from_json(BasicJsonType&& j, TupleRelated&& t)
  3729. -> decltype(from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {}))
  3730. {
  3731. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3732. {
  3733. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3734. }
  3735. return from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {});
  3736. }
  3737. template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  3738. typename = enable_if_t < !std::is_constructible <
  3739. typename BasicJsonType::string_t, Key >::value >>
  3740. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  3741. {
  3742. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3743. {
  3744. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3745. }
  3746. m.clear();
  3747. for (const auto& p : j)
  3748. {
  3749. if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
  3750. {
  3751. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j));
  3752. }
  3753. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3754. }
  3755. }
  3756. template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  3757. typename = enable_if_t < !std::is_constructible <
  3758. typename BasicJsonType::string_t, Key >::value >>
  3759. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  3760. {
  3761. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3762. {
  3763. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3764. }
  3765. m.clear();
  3766. for (const auto& p : j)
  3767. {
  3768. if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
  3769. {
  3770. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j));
  3771. }
  3772. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3773. }
  3774. }
  3775. #if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
  3776. template<typename BasicJsonType>
  3777. void from_json(const BasicJsonType& j, std_fs::path& p)
  3778. {
  3779. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3780. {
  3781. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
  3782. }
  3783. p = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3784. }
  3785. #endif
  3786. struct from_json_fn
  3787. {
  3788. template<typename BasicJsonType, typename T>
  3789. auto operator()(const BasicJsonType& j, T&& val) const
  3790. noexcept(noexcept(from_json(j, std::forward<T>(val))))
  3791. -> decltype(from_json(j, std::forward<T>(val)))
  3792. {
  3793. return from_json(j, std::forward<T>(val));
  3794. }
  3795. };
  3796. } // namespace detail
  3797. /// namespace to hold default `from_json` function
  3798. /// to see why this is required:
  3799. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  3800. namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
  3801. {
  3802. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; // NOLINT(misc-definitions-in-headers)
  3803. } // namespace
  3804. } // namespace nlohmann
  3805. // #include <nlohmann/detail/conversions/to_json.hpp>
  3806. #include <algorithm> // copy
  3807. #include <iterator> // begin, end
  3808. #include <string> // string
  3809. #include <tuple> // tuple, get
  3810. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  3811. #include <utility> // move, forward, declval, pair
  3812. #include <valarray> // valarray
  3813. #include <vector> // vector
  3814. // #include <nlohmann/detail/macro_scope.hpp>
  3815. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  3816. #include <cstddef> // size_t
  3817. #include <iterator> // input_iterator_tag
  3818. #include <string> // string, to_string
  3819. #include <tuple> // tuple_size, get, tuple_element
  3820. #include <utility> // move
  3821. // #include <nlohmann/detail/meta/type_traits.hpp>
  3822. // #include <nlohmann/detail/value_t.hpp>
  3823. namespace nlohmann
  3824. {
  3825. namespace detail
  3826. {
  3827. template<typename string_type>
  3828. void int_to_string( string_type& target, std::size_t value )
  3829. {
  3830. // For ADL
  3831. using std::to_string;
  3832. target = to_string(value);
  3833. }
  3834. template<typename IteratorType> class iteration_proxy_value
  3835. {
  3836. public:
  3837. using difference_type = std::ptrdiff_t;
  3838. using value_type = iteration_proxy_value;
  3839. using pointer = value_type * ;
  3840. using reference = value_type & ;
  3841. using iterator_category = std::input_iterator_tag;
  3842. using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type;
  3843. private:
  3844. /// the iterator
  3845. IteratorType anchor;
  3846. /// an index for arrays (used to create key names)
  3847. std::size_t array_index = 0;
  3848. /// last stringified array index
  3849. mutable std::size_t array_index_last = 0;
  3850. /// a string representation of the array index
  3851. mutable string_type array_index_str = "0";
  3852. /// an empty string (to return a reference for primitive values)
  3853. const string_type empty_str{};
  3854. public:
  3855. explicit iteration_proxy_value(IteratorType it) noexcept
  3856. : anchor(std::move(it))
  3857. {}
  3858. /// dereference operator (needed for range-based for)
  3859. iteration_proxy_value& operator*()
  3860. {
  3861. return *this;
  3862. }
  3863. /// increment operator (needed for range-based for)
  3864. iteration_proxy_value& operator++()
  3865. {
  3866. ++anchor;
  3867. ++array_index;
  3868. return *this;
  3869. }
  3870. /// equality operator (needed for InputIterator)
  3871. bool operator==(const iteration_proxy_value& o) const
  3872. {
  3873. return anchor == o.anchor;
  3874. }
  3875. /// inequality operator (needed for range-based for)
  3876. bool operator!=(const iteration_proxy_value& o) const
  3877. {
  3878. return anchor != o.anchor;
  3879. }
  3880. /// return key of the iterator
  3881. const string_type& key() const
  3882. {
  3883. JSON_ASSERT(anchor.m_object != nullptr);
  3884. switch (anchor.m_object->type())
  3885. {
  3886. // use integer array index as key
  3887. case value_t::array:
  3888. {
  3889. if (array_index != array_index_last)
  3890. {
  3891. int_to_string( array_index_str, array_index );
  3892. array_index_last = array_index;
  3893. }
  3894. return array_index_str;
  3895. }
  3896. // use key from the object
  3897. case value_t::object:
  3898. return anchor.key();
  3899. // use an empty key for all primitive types
  3900. case value_t::null:
  3901. case value_t::string:
  3902. case value_t::boolean:
  3903. case value_t::number_integer:
  3904. case value_t::number_unsigned:
  3905. case value_t::number_float:
  3906. case value_t::binary:
  3907. case value_t::discarded:
  3908. default:
  3909. return empty_str;
  3910. }
  3911. }
  3912. /// return value of the iterator
  3913. typename IteratorType::reference value() const
  3914. {
  3915. return anchor.value();
  3916. }
  3917. };
  3918. /// proxy class for the items() function
  3919. template<typename IteratorType> class iteration_proxy
  3920. {
  3921. private:
  3922. /// the container to iterate
  3923. typename IteratorType::reference container;
  3924. public:
  3925. /// construct iteration proxy from a container
  3926. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  3927. : container(cont) {}
  3928. /// return iterator begin (needed for range-based for)
  3929. iteration_proxy_value<IteratorType> begin() noexcept
  3930. {
  3931. return iteration_proxy_value<IteratorType>(container.begin());
  3932. }
  3933. /// return iterator end (needed for range-based for)
  3934. iteration_proxy_value<IteratorType> end() noexcept
  3935. {
  3936. return iteration_proxy_value<IteratorType>(container.end());
  3937. }
  3938. };
  3939. // Structured Bindings Support
  3940. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3941. // And see https://github.com/nlohmann/json/pull/1391
  3942. template<std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  3943. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  3944. {
  3945. return i.key();
  3946. }
  3947. // Structured Bindings Support
  3948. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3949. // And see https://github.com/nlohmann/json/pull/1391
  3950. template<std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  3951. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  3952. {
  3953. return i.value();
  3954. }
  3955. } // namespace detail
  3956. } // namespace nlohmann
  3957. // The Addition to the STD Namespace is required to add
  3958. // Structured Bindings Support to the iteration_proxy_value class
  3959. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3960. // And see https://github.com/nlohmann/json/pull/1391
  3961. namespace std
  3962. {
  3963. #if defined(__clang__)
  3964. // Fix: https://github.com/nlohmann/json/issues/1401
  3965. #pragma clang diagnostic push
  3966. #pragma clang diagnostic ignored "-Wmismatched-tags"
  3967. #endif
  3968. template<typename IteratorType>
  3969. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  3970. : public std::integral_constant<std::size_t, 2> {};
  3971. template<std::size_t N, typename IteratorType>
  3972. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  3973. {
  3974. public:
  3975. using type = decltype(
  3976. get<N>(std::declval <
  3977. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  3978. };
  3979. #if defined(__clang__)
  3980. #pragma clang diagnostic pop
  3981. #endif
  3982. } // namespace std
  3983. // #include <nlohmann/detail/meta/cpp_future.hpp>
  3984. // #include <nlohmann/detail/meta/type_traits.hpp>
  3985. // #include <nlohmann/detail/value_t.hpp>
  3986. #if JSON_HAS_EXPERIMENTAL_FILESYSTEM
  3987. #include <experimental/filesystem>
  3988. namespace nlohmann::detail
  3989. {
  3990. namespace std_fs = std::experimental::filesystem;
  3991. } // namespace nlohmann::detail
  3992. #elif JSON_HAS_FILESYSTEM
  3993. #include <filesystem>
  3994. namespace nlohmann::detail
  3995. {
  3996. namespace std_fs = std::filesystem;
  3997. } // namespace nlohmann::detail
  3998. #endif
  3999. namespace nlohmann
  4000. {
  4001. namespace detail
  4002. {
  4003. //////////////////
  4004. // constructors //
  4005. //////////////////
  4006. /*
  4007. * Note all external_constructor<>::construct functions need to call
  4008. * j.m_value.destroy(j.m_type) to avoid a memory leak in case j contains an
  4009. * allocated value (e.g., a string). See bug issue
  4010. * https://github.com/nlohmann/json/issues/2865 for more information.
  4011. */
  4012. template<value_t> struct external_constructor;
  4013. template<>
  4014. struct external_constructor<value_t::boolean>
  4015. {
  4016. template<typename BasicJsonType>
  4017. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  4018. {
  4019. j.m_value.destroy(j.m_type);
  4020. j.m_type = value_t::boolean;
  4021. j.m_value = b;
  4022. j.assert_invariant();
  4023. }
  4024. };
  4025. template<>
  4026. struct external_constructor<value_t::string>
  4027. {
  4028. template<typename BasicJsonType>
  4029. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  4030. {
  4031. j.m_value.destroy(j.m_type);
  4032. j.m_type = value_t::string;
  4033. j.m_value = s;
  4034. j.assert_invariant();
  4035. }
  4036. template<typename BasicJsonType>
  4037. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  4038. {
  4039. j.m_value.destroy(j.m_type);
  4040. j.m_type = value_t::string;
  4041. j.m_value = std::move(s);
  4042. j.assert_invariant();
  4043. }
  4044. template < typename BasicJsonType, typename CompatibleStringType,
  4045. enable_if_t < !std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  4046. int > = 0 >
  4047. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  4048. {
  4049. j.m_value.destroy(j.m_type);
  4050. j.m_type = value_t::string;
  4051. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  4052. j.assert_invariant();
  4053. }
  4054. };
  4055. template<>
  4056. struct external_constructor<value_t::binary>
  4057. {
  4058. template<typename BasicJsonType>
  4059. static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b)
  4060. {
  4061. j.m_value.destroy(j.m_type);
  4062. j.m_type = value_t::binary;
  4063. j.m_value = typename BasicJsonType::binary_t(b);
  4064. j.assert_invariant();
  4065. }
  4066. template<typename BasicJsonType>
  4067. static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b)
  4068. {
  4069. j.m_value.destroy(j.m_type);
  4070. j.m_type = value_t::binary;
  4071. j.m_value = typename BasicJsonType::binary_t(std::move(b));
  4072. j.assert_invariant();
  4073. }
  4074. };
  4075. template<>
  4076. struct external_constructor<value_t::number_float>
  4077. {
  4078. template<typename BasicJsonType>
  4079. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  4080. {
  4081. j.m_value.destroy(j.m_type);
  4082. j.m_type = value_t::number_float;
  4083. j.m_value = val;
  4084. j.assert_invariant();
  4085. }
  4086. };
  4087. template<>
  4088. struct external_constructor<value_t::number_unsigned>
  4089. {
  4090. template<typename BasicJsonType>
  4091. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  4092. {
  4093. j.m_value.destroy(j.m_type);
  4094. j.m_type = value_t::number_unsigned;
  4095. j.m_value = val;
  4096. j.assert_invariant();
  4097. }
  4098. };
  4099. template<>
  4100. struct external_constructor<value_t::number_integer>
  4101. {
  4102. template<typename BasicJsonType>
  4103. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  4104. {
  4105. j.m_value.destroy(j.m_type);
  4106. j.m_type = value_t::number_integer;
  4107. j.m_value = val;
  4108. j.assert_invariant();
  4109. }
  4110. };
  4111. template<>
  4112. struct external_constructor<value_t::array>
  4113. {
  4114. template<typename BasicJsonType>
  4115. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  4116. {
  4117. j.m_value.destroy(j.m_type);
  4118. j.m_type = value_t::array;
  4119. j.m_value = arr;
  4120. j.set_parents();
  4121. j.assert_invariant();
  4122. }
  4123. template<typename BasicJsonType>
  4124. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  4125. {
  4126. j.m_value.destroy(j.m_type);
  4127. j.m_type = value_t::array;
  4128. j.m_value = std::move(arr);
  4129. j.set_parents();
  4130. j.assert_invariant();
  4131. }
  4132. template < typename BasicJsonType, typename CompatibleArrayType,
  4133. enable_if_t < !std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  4134. int > = 0 >
  4135. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  4136. {
  4137. using std::begin;
  4138. using std::end;
  4139. j.m_value.destroy(j.m_type);
  4140. j.m_type = value_t::array;
  4141. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  4142. j.set_parents();
  4143. j.assert_invariant();
  4144. }
  4145. template<typename BasicJsonType>
  4146. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  4147. {
  4148. j.m_value.destroy(j.m_type);
  4149. j.m_type = value_t::array;
  4150. j.m_value = value_t::array;
  4151. j.m_value.array->reserve(arr.size());
  4152. for (const bool x : arr)
  4153. {
  4154. j.m_value.array->push_back(x);
  4155. j.set_parent(j.m_value.array->back());
  4156. }
  4157. j.assert_invariant();
  4158. }
  4159. template<typename BasicJsonType, typename T,
  4160. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  4161. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  4162. {
  4163. j.m_value.destroy(j.m_type);
  4164. j.m_type = value_t::array;
  4165. j.m_value = value_t::array;
  4166. j.m_value.array->resize(arr.size());
  4167. if (arr.size() > 0)
  4168. {
  4169. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  4170. }
  4171. j.set_parents();
  4172. j.assert_invariant();
  4173. }
  4174. };
  4175. template<>
  4176. struct external_constructor<value_t::object>
  4177. {
  4178. template<typename BasicJsonType>
  4179. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  4180. {
  4181. j.m_value.destroy(j.m_type);
  4182. j.m_type = value_t::object;
  4183. j.m_value = obj;
  4184. j.set_parents();
  4185. j.assert_invariant();
  4186. }
  4187. template<typename BasicJsonType>
  4188. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  4189. {
  4190. j.m_value.destroy(j.m_type);
  4191. j.m_type = value_t::object;
  4192. j.m_value = std::move(obj);
  4193. j.set_parents();
  4194. j.assert_invariant();
  4195. }
  4196. template < typename BasicJsonType, typename CompatibleObjectType,
  4197. enable_if_t < !std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int > = 0 >
  4198. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  4199. {
  4200. using std::begin;
  4201. using std::end;
  4202. j.m_value.destroy(j.m_type);
  4203. j.m_type = value_t::object;
  4204. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  4205. j.set_parents();
  4206. j.assert_invariant();
  4207. }
  4208. };
  4209. /////////////
  4210. // to_json //
  4211. /////////////
  4212. template<typename BasicJsonType, typename T,
  4213. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  4214. void to_json(BasicJsonType& j, T b) noexcept
  4215. {
  4216. external_constructor<value_t::boolean>::construct(j, b);
  4217. }
  4218. template<typename BasicJsonType, typename CompatibleString,
  4219. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  4220. void to_json(BasicJsonType& j, const CompatibleString& s)
  4221. {
  4222. external_constructor<value_t::string>::construct(j, s);
  4223. }
  4224. template<typename BasicJsonType>
  4225. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  4226. {
  4227. external_constructor<value_t::string>::construct(j, std::move(s));
  4228. }
  4229. template<typename BasicJsonType, typename FloatType,
  4230. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  4231. void to_json(BasicJsonType& j, FloatType val) noexcept
  4232. {
  4233. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  4234. }
  4235. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  4236. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  4237. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  4238. {
  4239. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  4240. }
  4241. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  4242. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  4243. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  4244. {
  4245. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  4246. }
  4247. template<typename BasicJsonType, typename EnumType,
  4248. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  4249. void to_json(BasicJsonType& j, EnumType e) noexcept
  4250. {
  4251. using underlying_type = typename std::underlying_type<EnumType>::type;
  4252. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  4253. }
  4254. template<typename BasicJsonType>
  4255. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  4256. {
  4257. external_constructor<value_t::array>::construct(j, e);
  4258. }
  4259. template < typename BasicJsonType, typename CompatibleArrayType,
  4260. enable_if_t < is_compatible_array_type<BasicJsonType,
  4261. CompatibleArrayType>::value&&
  4262. !is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value&&
  4263. !is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value&&
  4264. !std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value&&
  4265. !is_basic_json<CompatibleArrayType>::value,
  4266. int > = 0 >
  4267. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  4268. {
  4269. external_constructor<value_t::array>::construct(j, arr);
  4270. }
  4271. template<typename BasicJsonType>
  4272. void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin)
  4273. {
  4274. external_constructor<value_t::binary>::construct(j, bin);
  4275. }
  4276. template<typename BasicJsonType, typename T,
  4277. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  4278. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  4279. {
  4280. external_constructor<value_t::array>::construct(j, std::move(arr));
  4281. }
  4282. template<typename BasicJsonType>
  4283. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  4284. {
  4285. external_constructor<value_t::array>::construct(j, std::move(arr));
  4286. }
  4287. template < typename BasicJsonType, typename CompatibleObjectType,
  4288. enable_if_t < is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value&& !is_basic_json<CompatibleObjectType>::value, int > = 0 >
  4289. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  4290. {
  4291. external_constructor<value_t::object>::construct(j, obj);
  4292. }
  4293. template<typename BasicJsonType>
  4294. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  4295. {
  4296. external_constructor<value_t::object>::construct(j, std::move(obj));
  4297. }
  4298. template <
  4299. typename BasicJsonType, typename T, std::size_t N,
  4300. enable_if_t < !std::is_constructible<typename BasicJsonType::string_t,
  4301. const T(&)[N]>::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  4302. int > = 0 >
  4303. void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  4304. {
  4305. external_constructor<value_t::array>::construct(j, arr);
  4306. }
  4307. template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 >
  4308. void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
  4309. {
  4310. j = { p.first, p.second };
  4311. }
  4312. // for https://github.com/nlohmann/json/pull/1134
  4313. template<typename BasicJsonType, typename T,
  4314. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  4315. void to_json(BasicJsonType& j, const T& b)
  4316. {
  4317. j = { {b.key(), b.value()} };
  4318. }
  4319. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  4320. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  4321. {
  4322. j = { std::get<Idx>(t)... };
  4323. }
  4324. template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0>
  4325. void to_json(BasicJsonType& j, const T& t)
  4326. {
  4327. to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {});
  4328. }
  4329. #if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
  4330. template<typename BasicJsonType>
  4331. void to_json(BasicJsonType& j, const std_fs::path& p)
  4332. {
  4333. j = p.string();
  4334. }
  4335. #endif
  4336. struct to_json_fn
  4337. {
  4338. template<typename BasicJsonType, typename T>
  4339. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  4340. -> decltype(to_json(j, std::forward<T>(val)), void())
  4341. {
  4342. return to_json(j, std::forward<T>(val));
  4343. }
  4344. };
  4345. } // namespace detail
  4346. /// namespace to hold default `to_json` function
  4347. /// to see why this is required:
  4348. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  4349. namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
  4350. {
  4351. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value; // NOLINT(misc-definitions-in-headers)
  4352. } // namespace
  4353. } // namespace nlohmann
  4354. // #include <nlohmann/detail/meta/identity_tag.hpp>
  4355. // #include <nlohmann/detail/meta/type_traits.hpp>
  4356. namespace nlohmann
  4357. {
  4358. /// @sa https://json.nlohmann.me/api/adl_serializer/
  4359. template<typename ValueType, typename>
  4360. struct adl_serializer
  4361. {
  4362. /// @brief convert a JSON value to any value type
  4363. /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/
  4364. template<typename BasicJsonType, typename TargetType = ValueType>
  4365. static auto from_json(BasicJsonType && j, TargetType& val) noexcept(
  4366. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  4367. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  4368. {
  4369. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  4370. }
  4371. /// @brief convert a JSON value to any value type
  4372. /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/
  4373. template<typename BasicJsonType, typename TargetType = ValueType>
  4374. static auto from_json(BasicJsonType && j) noexcept(
  4375. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))
  4376. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))
  4377. {
  4378. return ::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {});
  4379. }
  4380. /// @brief convert any value type to a JSON value
  4381. /// @sa https://json.nlohmann.me/api/adl_serializer/to_json/
  4382. template<typename BasicJsonType, typename TargetType = ValueType>
  4383. static auto to_json(BasicJsonType& j, TargetType && val) noexcept(
  4384. noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))
  4385. -> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void())
  4386. {
  4387. ::nlohmann::to_json(j, std::forward<TargetType>(val));
  4388. }
  4389. };
  4390. } // namespace nlohmann
  4391. // #include <nlohmann/byte_container_with_subtype.hpp>
  4392. #include <cstdint> // uint8_t, uint64_t
  4393. #include <tuple> // tie
  4394. #include <utility> // move
  4395. namespace nlohmann
  4396. {
  4397. /// @brief an internal type for a backed binary type
  4398. /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/
  4399. template<typename BinaryType>
  4400. class byte_container_with_subtype : public BinaryType
  4401. {
  4402. public:
  4403. using container_type = BinaryType;
  4404. using subtype_type = std::uint64_t;
  4405. /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
  4406. byte_container_with_subtype() noexcept(noexcept(container_type()))
  4407. : container_type()
  4408. {}
  4409. /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
  4410. byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b)))
  4411. : container_type(b)
  4412. {}
  4413. /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
  4414. byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b))))
  4415. : container_type(std::move(b))
  4416. {}
  4417. /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
  4418. byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b)))
  4419. : container_type(b)
  4420. , m_subtype(subtype_)
  4421. , m_has_subtype(true)
  4422. {}
  4423. /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
  4424. byte_container_with_subtype(container_type&& b, subtype_type subtype_) noexcept(noexcept(container_type(std::move(b))))
  4425. : container_type(std::move(b))
  4426. , m_subtype(subtype_)
  4427. , m_has_subtype(true)
  4428. {}
  4429. bool operator==(const byte_container_with_subtype& rhs) const
  4430. {
  4431. return std::tie(static_cast<const BinaryType&>(*this), m_subtype, m_has_subtype) ==
  4432. std::tie(static_cast<const BinaryType&>(rhs), rhs.m_subtype, rhs.m_has_subtype);
  4433. }
  4434. bool operator!=(const byte_container_with_subtype& rhs) const
  4435. {
  4436. return !(rhs == *this);
  4437. }
  4438. /// @brief sets the binary subtype
  4439. /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/set_subtype/
  4440. void set_subtype(subtype_type subtype_) noexcept
  4441. {
  4442. m_subtype = subtype_;
  4443. m_has_subtype = true;
  4444. }
  4445. /// @brief return the binary subtype
  4446. /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/subtype/
  4447. constexpr subtype_type subtype() const noexcept
  4448. {
  4449. return m_has_subtype ? m_subtype : static_cast<subtype_type>(-1);
  4450. }
  4451. /// @brief return whether the value has a subtype
  4452. /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/has_subtype/
  4453. constexpr bool has_subtype() const noexcept
  4454. {
  4455. return m_has_subtype;
  4456. }
  4457. /// @brief clears the binary subtype
  4458. /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/clear_subtype/
  4459. void clear_subtype() noexcept
  4460. {
  4461. m_subtype = 0;
  4462. m_has_subtype = false;
  4463. }
  4464. private:
  4465. subtype_type m_subtype = 0;
  4466. bool m_has_subtype = false;
  4467. };
  4468. } // namespace nlohmann
  4469. // #include <nlohmann/detail/conversions/from_json.hpp>
  4470. // #include <nlohmann/detail/conversions/to_json.hpp>
  4471. // #include <nlohmann/detail/exceptions.hpp>
  4472. // #include <nlohmann/detail/hash.hpp>
  4473. #include <cstdint> // uint8_t
  4474. #include <cstddef> // size_t
  4475. #include <functional> // hash
  4476. // #include <nlohmann/detail/macro_scope.hpp>
  4477. // #include <nlohmann/detail/value_t.hpp>
  4478. namespace nlohmann
  4479. {
  4480. namespace detail
  4481. {
  4482. // boost::hash_combine
  4483. inline std::size_t combine(std::size_t seed, std::size_t h) noexcept
  4484. {
  4485. seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U);
  4486. return seed;
  4487. }
  4488. /*!
  4489. @brief hash a JSON value
  4490. The hash function tries to rely on std::hash where possible. Furthermore, the
  4491. type of the JSON value is taken into account to have different hash values for
  4492. null, 0, 0U, and false, etc.
  4493. @tparam BasicJsonType basic_json specialization
  4494. @param j JSON value to hash
  4495. @return hash value of j
  4496. */
  4497. template<typename BasicJsonType>
  4498. std::size_t hash(const BasicJsonType& j)
  4499. {
  4500. using string_t = typename BasicJsonType::string_t;
  4501. using number_integer_t = typename BasicJsonType::number_integer_t;
  4502. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4503. using number_float_t = typename BasicJsonType::number_float_t;
  4504. const auto type = static_cast<std::size_t>(j.type());
  4505. switch (j.type())
  4506. {
  4507. case BasicJsonType::value_t::null:
  4508. case BasicJsonType::value_t::discarded:
  4509. {
  4510. return combine(type, 0);
  4511. }
  4512. case BasicJsonType::value_t::object:
  4513. {
  4514. auto seed = combine(type, j.size());
  4515. for (const auto& element : j.items())
  4516. {
  4517. const auto h = std::hash<string_t> {}(element.key());
  4518. seed = combine(seed, h);
  4519. seed = combine(seed, hash(element.value()));
  4520. }
  4521. return seed;
  4522. }
  4523. case BasicJsonType::value_t::array:
  4524. {
  4525. auto seed = combine(type, j.size());
  4526. for (const auto& element : j)
  4527. {
  4528. seed = combine(seed, hash(element));
  4529. }
  4530. return seed;
  4531. }
  4532. case BasicJsonType::value_t::string:
  4533. {
  4534. const auto h = std::hash<string_t> {}(j.template get_ref<const string_t&>());
  4535. return combine(type, h);
  4536. }
  4537. case BasicJsonType::value_t::boolean:
  4538. {
  4539. const auto h = std::hash<bool> {}(j.template get<bool>());
  4540. return combine(type, h);
  4541. }
  4542. case BasicJsonType::value_t::number_integer:
  4543. {
  4544. const auto h = std::hash<number_integer_t> {}(j.template get<number_integer_t>());
  4545. return combine(type, h);
  4546. }
  4547. case BasicJsonType::value_t::number_unsigned:
  4548. {
  4549. const auto h = std::hash<number_unsigned_t> {}(j.template get<number_unsigned_t>());
  4550. return combine(type, h);
  4551. }
  4552. case BasicJsonType::value_t::number_float:
  4553. {
  4554. const auto h = std::hash<number_float_t> {}(j.template get<number_float_t>());
  4555. return combine(type, h);
  4556. }
  4557. case BasicJsonType::value_t::binary:
  4558. {
  4559. auto seed = combine(type, j.get_binary().size());
  4560. const auto h = std::hash<bool> {}(j.get_binary().has_subtype());
  4561. seed = combine(seed, h);
  4562. seed = combine(seed, static_cast<std::size_t>(j.get_binary().subtype()));
  4563. for (const auto byte : j.get_binary())
  4564. {
  4565. seed = combine(seed, std::hash<std::uint8_t> {}(byte));
  4566. }
  4567. return seed;
  4568. }
  4569. default: // LCOV_EXCL_LINE
  4570. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  4571. return 0; // LCOV_EXCL_LINE
  4572. }
  4573. }
  4574. } // namespace detail
  4575. } // namespace nlohmann
  4576. // #include <nlohmann/detail/input/binary_reader.hpp>
  4577. #include <algorithm> // generate_n
  4578. #include <array> // array
  4579. #include <cmath> // ldexp
  4580. #include <cstddef> // size_t
  4581. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  4582. #include <cstdio> // snprintf
  4583. #include <cstring> // memcpy
  4584. #include <iterator> // back_inserter
  4585. #include <limits> // numeric_limits
  4586. #include <string> // char_traits, string
  4587. #include <utility> // make_pair, move
  4588. #include <vector> // vector
  4589. // #include <nlohmann/detail/exceptions.hpp>
  4590. // #include <nlohmann/detail/input/input_adapters.hpp>
  4591. #include <array> // array
  4592. #include <cstddef> // size_t
  4593. #include <cstring> // strlen
  4594. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  4595. #include <memory> // shared_ptr, make_shared, addressof
  4596. #include <numeric> // accumulate
  4597. #include <string> // string, char_traits
  4598. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  4599. #include <utility> // pair, declval
  4600. #ifndef JSON_NO_IO
  4601. #include <cstdio> // FILE *
  4602. #include <istream> // istream
  4603. #endif // JSON_NO_IO
  4604. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  4605. // #include <nlohmann/detail/macro_scope.hpp>
  4606. namespace nlohmann
  4607. {
  4608. namespace detail
  4609. {
  4610. /// the supported input formats
  4611. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  4612. ////////////////////
  4613. // input adapters //
  4614. ////////////////////
  4615. #ifndef JSON_NO_IO
  4616. /*!
  4617. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  4618. buffer. This adapter is a very low level adapter.
  4619. */
  4620. class file_input_adapter
  4621. {
  4622. public:
  4623. using char_type = char;
  4624. JSON_HEDLEY_NON_NULL(2)
  4625. explicit file_input_adapter(std::FILE* f) noexcept
  4626. : m_file(f)
  4627. {}
  4628. // make class move-only
  4629. file_input_adapter(const file_input_adapter&) = delete;
  4630. file_input_adapter(file_input_adapter&&) noexcept = default;
  4631. file_input_adapter& operator=(const file_input_adapter&) = delete;
  4632. file_input_adapter& operator=(file_input_adapter&&) = delete;
  4633. ~file_input_adapter() = default;
  4634. std::char_traits<char>::int_type get_character() noexcept
  4635. {
  4636. return std::fgetc(m_file);
  4637. }
  4638. private:
  4639. /// the file pointer to read from
  4640. std::FILE* m_file;
  4641. };
  4642. /*!
  4643. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  4644. beginning of input. Does not support changing the underlying std::streambuf
  4645. in mid-input. Maintains underlying std::istream and std::streambuf to support
  4646. subsequent use of standard std::istream operations to process any input
  4647. characters following those used in parsing the JSON input. Clears the
  4648. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  4649. subsequent call for input from the std::istream.
  4650. */
  4651. class input_stream_adapter
  4652. {
  4653. public:
  4654. using char_type = char;
  4655. ~input_stream_adapter()
  4656. {
  4657. // clear stream flags; we use underlying streambuf I/O, do not
  4658. // maintain ifstream flags, except eof
  4659. if (is != nullptr)
  4660. {
  4661. is->clear(is->rdstate() & std::ios::eofbit);
  4662. }
  4663. }
  4664. explicit input_stream_adapter(std::istream& i)
  4665. : is(&i), sb(i.rdbuf())
  4666. {}
  4667. // delete because of pointer members
  4668. input_stream_adapter(const input_stream_adapter&) = delete;
  4669. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  4670. input_stream_adapter& operator=(input_stream_adapter&&) = delete;
  4671. input_stream_adapter(input_stream_adapter&& rhs) noexcept
  4672. : is(rhs.is), sb(rhs.sb)
  4673. {
  4674. rhs.is = nullptr;
  4675. rhs.sb = nullptr;
  4676. }
  4677. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  4678. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  4679. // end up as the same value, e.g. 0xFFFFFFFF.
  4680. std::char_traits<char>::int_type get_character()
  4681. {
  4682. auto res = sb->sbumpc();
  4683. // set eof manually, as we don't use the istream interface.
  4684. if (JSON_HEDLEY_UNLIKELY(res == std::char_traits<char>::eof()))
  4685. {
  4686. is->clear(is->rdstate() | std::ios::eofbit);
  4687. }
  4688. return res;
  4689. }
  4690. private:
  4691. /// the associated input stream
  4692. std::istream* is = nullptr;
  4693. std::streambuf* sb = nullptr;
  4694. };
  4695. #endif // JSON_NO_IO
  4696. // General-purpose iterator-based adapter. It might not be as fast as
  4697. // theoretically possible for some containers, but it is extremely versatile.
  4698. template<typename IteratorType>
  4699. class iterator_input_adapter
  4700. {
  4701. public:
  4702. using char_type = typename std::iterator_traits<IteratorType>::value_type;
  4703. iterator_input_adapter(IteratorType first, IteratorType last)
  4704. : current(std::move(first)), end(std::move(last))
  4705. {}
  4706. typename std::char_traits<char_type>::int_type get_character()
  4707. {
  4708. if (JSON_HEDLEY_LIKELY(current != end))
  4709. {
  4710. auto result = std::char_traits<char_type>::to_int_type(*current);
  4711. std::advance(current, 1);
  4712. return result;
  4713. }
  4714. return std::char_traits<char_type>::eof();
  4715. }
  4716. private:
  4717. IteratorType current;
  4718. IteratorType end;
  4719. template<typename BaseInputAdapter, size_t T>
  4720. friend struct wide_string_input_helper;
  4721. bool empty() const
  4722. {
  4723. return current == end;
  4724. }
  4725. };
  4726. template<typename BaseInputAdapter, size_t T>
  4727. struct wide_string_input_helper;
  4728. template<typename BaseInputAdapter>
  4729. struct wide_string_input_helper<BaseInputAdapter, 4>
  4730. {
  4731. // UTF-32
  4732. static void fill_buffer(BaseInputAdapter& input,
  4733. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4734. size_t& utf8_bytes_index,
  4735. size_t& utf8_bytes_filled)
  4736. {
  4737. utf8_bytes_index = 0;
  4738. if (JSON_HEDLEY_UNLIKELY(input.empty()))
  4739. {
  4740. utf8_bytes[0] = std::char_traits<char>::eof();
  4741. utf8_bytes_filled = 1;
  4742. }
  4743. else
  4744. {
  4745. // get the current character
  4746. const auto wc = input.get_character();
  4747. // UTF-32 to UTF-8 encoding
  4748. if (wc < 0x80)
  4749. {
  4750. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4751. utf8_bytes_filled = 1;
  4752. }
  4753. else if (wc <= 0x7FF)
  4754. {
  4755. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u) & 0x1Fu));
  4756. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4757. utf8_bytes_filled = 2;
  4758. }
  4759. else if (wc <= 0xFFFF)
  4760. {
  4761. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u) & 0x0Fu));
  4762. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4763. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4764. utf8_bytes_filled = 3;
  4765. }
  4766. else if (wc <= 0x10FFFF)
  4767. {
  4768. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((static_cast<unsigned int>(wc) >> 18u) & 0x07u));
  4769. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 12u) & 0x3Fu));
  4770. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4771. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4772. utf8_bytes_filled = 4;
  4773. }
  4774. else
  4775. {
  4776. // unknown character
  4777. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4778. utf8_bytes_filled = 1;
  4779. }
  4780. }
  4781. }
  4782. };
  4783. template<typename BaseInputAdapter>
  4784. struct wide_string_input_helper<BaseInputAdapter, 2>
  4785. {
  4786. // UTF-16
  4787. static void fill_buffer(BaseInputAdapter& input,
  4788. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4789. size_t& utf8_bytes_index,
  4790. size_t& utf8_bytes_filled)
  4791. {
  4792. utf8_bytes_index = 0;
  4793. if (JSON_HEDLEY_UNLIKELY(input.empty()))
  4794. {
  4795. utf8_bytes[0] = std::char_traits<char>::eof();
  4796. utf8_bytes_filled = 1;
  4797. }
  4798. else
  4799. {
  4800. // get the current character
  4801. const auto wc = input.get_character();
  4802. // UTF-16 to UTF-8 encoding
  4803. if (wc < 0x80)
  4804. {
  4805. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4806. utf8_bytes_filled = 1;
  4807. }
  4808. else if (wc <= 0x7FF)
  4809. {
  4810. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u)));
  4811. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4812. utf8_bytes_filled = 2;
  4813. }
  4814. else if (0xD800 > wc || wc >= 0xE000)
  4815. {
  4816. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u)));
  4817. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4818. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4819. utf8_bytes_filled = 3;
  4820. }
  4821. else
  4822. {
  4823. if (JSON_HEDLEY_UNLIKELY(!input.empty()))
  4824. {
  4825. const auto wc2 = static_cast<unsigned int>(input.get_character());
  4826. const auto charcode = 0x10000u + (((static_cast<unsigned int>(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  4827. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  4828. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  4829. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  4830. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  4831. utf8_bytes_filled = 4;
  4832. }
  4833. else
  4834. {
  4835. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4836. utf8_bytes_filled = 1;
  4837. }
  4838. }
  4839. }
  4840. }
  4841. };
  4842. // Wraps another input apdater to convert wide character types into individual bytes.
  4843. template<typename BaseInputAdapter, typename WideCharType>
  4844. class wide_string_input_adapter
  4845. {
  4846. public:
  4847. using char_type = char;
  4848. wide_string_input_adapter(BaseInputAdapter base)
  4849. : base_adapter(base) {}
  4850. typename std::char_traits<char>::int_type get_character() noexcept
  4851. {
  4852. // check if buffer needs to be filled
  4853. if (utf8_bytes_index == utf8_bytes_filled)
  4854. {
  4855. fill_buffer<sizeof(WideCharType)>();
  4856. JSON_ASSERT(utf8_bytes_filled > 0);
  4857. JSON_ASSERT(utf8_bytes_index == 0);
  4858. }
  4859. // use buffer
  4860. JSON_ASSERT(utf8_bytes_filled > 0);
  4861. JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled);
  4862. return utf8_bytes[utf8_bytes_index++];
  4863. }
  4864. private:
  4865. BaseInputAdapter base_adapter;
  4866. template<size_t T>
  4867. void fill_buffer()
  4868. {
  4869. wide_string_input_helper<BaseInputAdapter, T>::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  4870. }
  4871. /// a buffer for UTF-8 bytes
  4872. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  4873. /// index to the utf8_codes array for the next valid byte
  4874. std::size_t utf8_bytes_index = 0;
  4875. /// number of valid bytes in the utf8_codes array
  4876. std::size_t utf8_bytes_filled = 0;
  4877. };
  4878. template<typename IteratorType, typename Enable = void>
  4879. struct iterator_input_adapter_factory
  4880. {
  4881. using iterator_type = IteratorType;
  4882. using char_type = typename std::iterator_traits<iterator_type>::value_type;
  4883. using adapter_type = iterator_input_adapter<iterator_type>;
  4884. static adapter_type create(IteratorType first, IteratorType last)
  4885. {
  4886. return adapter_type(std::move(first), std::move(last));
  4887. }
  4888. };
  4889. template<typename T>
  4890. struct is_iterator_of_multibyte
  4891. {
  4892. using value_type = typename std::iterator_traits<T>::value_type;
  4893. enum
  4894. {
  4895. value = sizeof(value_type) > 1
  4896. };
  4897. };
  4898. template<typename IteratorType>
  4899. struct iterator_input_adapter_factory<IteratorType, enable_if_t<is_iterator_of_multibyte<IteratorType>::value>>
  4900. {
  4901. using iterator_type = IteratorType;
  4902. using char_type = typename std::iterator_traits<iterator_type>::value_type;
  4903. using base_adapter_type = iterator_input_adapter<iterator_type>;
  4904. using adapter_type = wide_string_input_adapter<base_adapter_type, char_type>;
  4905. static adapter_type create(IteratorType first, IteratorType last)
  4906. {
  4907. return adapter_type(base_adapter_type(std::move(first), std::move(last)));
  4908. }
  4909. };
  4910. // General purpose iterator-based input
  4911. template<typename IteratorType>
  4912. typename iterator_input_adapter_factory<IteratorType>::adapter_type input_adapter(IteratorType first, IteratorType last)
  4913. {
  4914. using factory_type = iterator_input_adapter_factory<IteratorType>;
  4915. return factory_type::create(first, last);
  4916. }
  4917. // Convenience shorthand from container to iterator
  4918. // Enables ADL on begin(container) and end(container)
  4919. // Encloses the using declarations in namespace for not to leak them to outside scope
  4920. namespace container_input_adapter_factory_impl
  4921. {
  4922. using std::begin;
  4923. using std::end;
  4924. template<typename ContainerType, typename Enable = void>
  4925. struct container_input_adapter_factory {};
  4926. template<typename ContainerType>
  4927. struct container_input_adapter_factory< ContainerType,
  4928. void_t<decltype(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>()))>>
  4929. {
  4930. using adapter_type = decltype(input_adapter(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>())));
  4931. static adapter_type create(const ContainerType& container)
  4932. {
  4933. return input_adapter(begin(container), end(container));
  4934. }
  4935. };
  4936. } // namespace container_input_adapter_factory_impl
  4937. template<typename ContainerType>
  4938. typename container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::adapter_type input_adapter(const ContainerType& container)
  4939. {
  4940. return container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::create(container);
  4941. }
  4942. #ifndef JSON_NO_IO
  4943. // Special cases with fast paths
  4944. inline file_input_adapter input_adapter(std::FILE* file)
  4945. {
  4946. return file_input_adapter(file);
  4947. }
  4948. inline input_stream_adapter input_adapter(std::istream& stream)
  4949. {
  4950. return input_stream_adapter(stream);
  4951. }
  4952. inline input_stream_adapter input_adapter(std::istream&& stream)
  4953. {
  4954. return input_stream_adapter(stream);
  4955. }
  4956. #endif // JSON_NO_IO
  4957. using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval<const char*>(), std::declval<const char*>()));
  4958. // Null-delimited strings, and the like.
  4959. template < typename CharT,
  4960. typename std::enable_if <
  4961. std::is_pointer<CharT>::value&&
  4962. !std::is_array<CharT>::value&&
  4963. std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
  4964. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4965. int >::type = 0 >
  4966. contiguous_bytes_input_adapter input_adapter(CharT b)
  4967. {
  4968. auto length = std::strlen(reinterpret_cast<const char*>(b));
  4969. const auto* ptr = reinterpret_cast<const char*>(b);
  4970. return input_adapter(ptr, ptr + length);
  4971. }
  4972. template<typename T, std::size_t N>
  4973. 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)
  4974. {
  4975. return input_adapter(array, array + N);
  4976. }
  4977. // This class only handles inputs of input_buffer_adapter type.
  4978. // It's required so that expressions like {ptr, len} can be implicitly cast
  4979. // to the correct adapter.
  4980. class span_input_adapter
  4981. {
  4982. public:
  4983. template < typename CharT,
  4984. typename std::enable_if <
  4985. std::is_pointer<CharT>::value&&
  4986. std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
  4987. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4988. int >::type = 0 >
  4989. span_input_adapter(CharT b, std::size_t l)
  4990. : ia(reinterpret_cast<const char*>(b), reinterpret_cast<const char*>(b) + l) {}
  4991. template<class IteratorType,
  4992. typename std::enable_if<
  4993. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  4994. int>::type = 0>
  4995. span_input_adapter(IteratorType first, IteratorType last)
  4996. : ia(input_adapter(first, last)) {}
  4997. contiguous_bytes_input_adapter&& get()
  4998. {
  4999. return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg)
  5000. }
  5001. private:
  5002. contiguous_bytes_input_adapter ia;
  5003. };
  5004. } // namespace detail
  5005. } // namespace nlohmann
  5006. // #include <nlohmann/detail/input/json_sax.hpp>
  5007. #include <cstddef>
  5008. #include <string> // string
  5009. #include <utility> // move
  5010. #include <vector> // vector
  5011. // #include <nlohmann/detail/exceptions.hpp>
  5012. // #include <nlohmann/detail/macro_scope.hpp>
  5013. namespace nlohmann
  5014. {
  5015. /*!
  5016. @brief SAX interface
  5017. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  5018. Each function is called in different situations while the input is parsed. The
  5019. boolean return value informs the parser whether to continue processing the
  5020. input.
  5021. */
  5022. template<typename BasicJsonType>
  5023. struct json_sax
  5024. {
  5025. using number_integer_t = typename BasicJsonType::number_integer_t;
  5026. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5027. using number_float_t = typename BasicJsonType::number_float_t;
  5028. using string_t = typename BasicJsonType::string_t;
  5029. using binary_t = typename BasicJsonType::binary_t;
  5030. /*!
  5031. @brief a null value was read
  5032. @return whether parsing should proceed
  5033. */
  5034. virtual bool null() = 0;
  5035. /*!
  5036. @brief a boolean value was read
  5037. @param[in] val boolean value
  5038. @return whether parsing should proceed
  5039. */
  5040. virtual bool boolean(bool val) = 0;
  5041. /*!
  5042. @brief an integer number was read
  5043. @param[in] val integer value
  5044. @return whether parsing should proceed
  5045. */
  5046. virtual bool number_integer(number_integer_t val) = 0;
  5047. /*!
  5048. @brief an unsigned integer number was read
  5049. @param[in] val unsigned integer value
  5050. @return whether parsing should proceed
  5051. */
  5052. virtual bool number_unsigned(number_unsigned_t val) = 0;
  5053. /*!
  5054. @brief a floating-point number was read
  5055. @param[in] val floating-point value
  5056. @param[in] s raw token value
  5057. @return whether parsing should proceed
  5058. */
  5059. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  5060. /*!
  5061. @brief a string value was read
  5062. @param[in] val string value
  5063. @return whether parsing should proceed
  5064. @note It is safe to move the passed string value.
  5065. */
  5066. virtual bool string(string_t& val) = 0;
  5067. /*!
  5068. @brief a binary value was read
  5069. @param[in] val binary value
  5070. @return whether parsing should proceed
  5071. @note It is safe to move the passed binary value.
  5072. */
  5073. virtual bool binary(binary_t& val) = 0;
  5074. /*!
  5075. @brief the beginning of an object was read
  5076. @param[in] elements number of object elements or -1 if unknown
  5077. @return whether parsing should proceed
  5078. @note binary formats may report the number of elements
  5079. */
  5080. virtual bool start_object(std::size_t elements) = 0;
  5081. /*!
  5082. @brief an object key was read
  5083. @param[in] val object key
  5084. @return whether parsing should proceed
  5085. @note It is safe to move the passed string.
  5086. */
  5087. virtual bool key(string_t& val) = 0;
  5088. /*!
  5089. @brief the end of an object was read
  5090. @return whether parsing should proceed
  5091. */
  5092. virtual bool end_object() = 0;
  5093. /*!
  5094. @brief the beginning of an array was read
  5095. @param[in] elements number of array elements or -1 if unknown
  5096. @return whether parsing should proceed
  5097. @note binary formats may report the number of elements
  5098. */
  5099. virtual bool start_array(std::size_t elements) = 0;
  5100. /*!
  5101. @brief the end of an array was read
  5102. @return whether parsing should proceed
  5103. */
  5104. virtual bool end_array() = 0;
  5105. /*!
  5106. @brief a parse error occurred
  5107. @param[in] position the position in the input where the error occurs
  5108. @param[in] last_token the last read token
  5109. @param[in] ex an exception object describing the error
  5110. @return whether parsing should proceed (must return false)
  5111. */
  5112. virtual bool parse_error(std::size_t position,
  5113. const std::string& last_token,
  5114. const detail::exception& ex) = 0;
  5115. json_sax() = default;
  5116. json_sax(const json_sax&) = default;
  5117. json_sax(json_sax&&) noexcept = default;
  5118. json_sax& operator=(const json_sax&) = default;
  5119. json_sax& operator=(json_sax&&) noexcept = default;
  5120. virtual ~json_sax() = default;
  5121. };
  5122. namespace detail
  5123. {
  5124. /*!
  5125. @brief SAX implementation to create a JSON value from SAX events
  5126. This class implements the @ref json_sax interface and processes the SAX events
  5127. to create a JSON value which makes it basically a DOM parser. The structure or
  5128. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  5129. a pointer to the respective array or object for each recursion depth.
  5130. After successful parsing, the value that is passed by reference to the
  5131. constructor contains the parsed value.
  5132. @tparam BasicJsonType the JSON type
  5133. */
  5134. template<typename BasicJsonType>
  5135. class json_sax_dom_parser
  5136. {
  5137. public:
  5138. using number_integer_t = typename BasicJsonType::number_integer_t;
  5139. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5140. using number_float_t = typename BasicJsonType::number_float_t;
  5141. using string_t = typename BasicJsonType::string_t;
  5142. using binary_t = typename BasicJsonType::binary_t;
  5143. /*!
  5144. @param[in,out] r reference to a JSON value that is manipulated while
  5145. parsing
  5146. @param[in] allow_exceptions_ whether parse errors yield exceptions
  5147. */
  5148. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  5149. : root(r), allow_exceptions(allow_exceptions_)
  5150. {}
  5151. // make class move-only
  5152. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  5153. json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5154. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  5155. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5156. ~json_sax_dom_parser() = default;
  5157. bool null()
  5158. {
  5159. handle_value(nullptr);
  5160. return true;
  5161. }
  5162. bool boolean(bool val)
  5163. {
  5164. handle_value(val);
  5165. return true;
  5166. }
  5167. bool number_integer(number_integer_t val)
  5168. {
  5169. handle_value(val);
  5170. return true;
  5171. }
  5172. bool number_unsigned(number_unsigned_t val)
  5173. {
  5174. handle_value(val);
  5175. return true;
  5176. }
  5177. bool number_float(number_float_t val, const string_t& /*unused*/)
  5178. {
  5179. handle_value(val);
  5180. return true;
  5181. }
  5182. bool string(string_t& val)
  5183. {
  5184. handle_value(val);
  5185. return true;
  5186. }
  5187. bool binary(binary_t& val)
  5188. {
  5189. handle_value(std::move(val));
  5190. return true;
  5191. }
  5192. bool start_object(std::size_t len)
  5193. {
  5194. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  5195. if (JSON_HEDLEY_UNLIKELY(len != static_cast<std::size_t>(-1) && len > ref_stack.back()->max_size()))
  5196. {
  5197. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back()));
  5198. }
  5199. return true;
  5200. }
  5201. bool key(string_t& val)
  5202. {
  5203. // add null at given key and store the reference for later
  5204. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  5205. return true;
  5206. }
  5207. bool end_object()
  5208. {
  5209. ref_stack.back()->set_parents();
  5210. ref_stack.pop_back();
  5211. return true;
  5212. }
  5213. bool start_array(std::size_t len)
  5214. {
  5215. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  5216. if (JSON_HEDLEY_UNLIKELY(len != static_cast<std::size_t>(-1) && len > ref_stack.back()->max_size()))
  5217. {
  5218. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back()));
  5219. }
  5220. return true;
  5221. }
  5222. bool end_array()
  5223. {
  5224. ref_stack.back()->set_parents();
  5225. ref_stack.pop_back();
  5226. return true;
  5227. }
  5228. template<class Exception>
  5229. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  5230. const Exception& ex)
  5231. {
  5232. errored = true;
  5233. static_cast<void>(ex);
  5234. if (allow_exceptions)
  5235. {
  5236. JSON_THROW(ex);
  5237. }
  5238. return false;
  5239. }
  5240. constexpr bool is_errored() const
  5241. {
  5242. return errored;
  5243. }
  5244. private:
  5245. /*!
  5246. @invariant If the ref stack is empty, then the passed value will be the new
  5247. root.
  5248. @invariant If the ref stack contains a value, then it is an array or an
  5249. object to which we can add elements
  5250. */
  5251. template<typename Value>
  5252. JSON_HEDLEY_RETURNS_NON_NULL
  5253. BasicJsonType* handle_value(Value&& v)
  5254. {
  5255. if (ref_stack.empty())
  5256. {
  5257. root = BasicJsonType(std::forward<Value>(v));
  5258. return &root;
  5259. }
  5260. JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
  5261. if (ref_stack.back()->is_array())
  5262. {
  5263. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  5264. return &(ref_stack.back()->m_value.array->back());
  5265. }
  5266. JSON_ASSERT(ref_stack.back()->is_object());
  5267. JSON_ASSERT(object_element);
  5268. *object_element = BasicJsonType(std::forward<Value>(v));
  5269. return object_element;
  5270. }
  5271. /// the parsed JSON value
  5272. BasicJsonType& root;
  5273. /// stack to model hierarchy of values
  5274. std::vector<BasicJsonType*> ref_stack {};
  5275. /// helper to hold the reference for the next object element
  5276. BasicJsonType* object_element = nullptr;
  5277. /// whether a syntax error occurred
  5278. bool errored = false;
  5279. /// whether to throw exceptions in case of errors
  5280. const bool allow_exceptions = true;
  5281. };
  5282. template<typename BasicJsonType>
  5283. class json_sax_dom_callback_parser
  5284. {
  5285. public:
  5286. using number_integer_t = typename BasicJsonType::number_integer_t;
  5287. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5288. using number_float_t = typename BasicJsonType::number_float_t;
  5289. using string_t = typename BasicJsonType::string_t;
  5290. using binary_t = typename BasicJsonType::binary_t;
  5291. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  5292. using parse_event_t = typename BasicJsonType::parse_event_t;
  5293. json_sax_dom_callback_parser(BasicJsonType& r,
  5294. const parser_callback_t cb,
  5295. const bool allow_exceptions_ = true)
  5296. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  5297. {
  5298. keep_stack.push_back(true);
  5299. }
  5300. // make class move-only
  5301. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  5302. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5303. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  5304. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5305. ~json_sax_dom_callback_parser() = default;
  5306. bool null()
  5307. {
  5308. handle_value(nullptr);
  5309. return true;
  5310. }
  5311. bool boolean(bool val)
  5312. {
  5313. handle_value(val);
  5314. return true;
  5315. }
  5316. bool number_integer(number_integer_t val)
  5317. {
  5318. handle_value(val);
  5319. return true;
  5320. }
  5321. bool number_unsigned(number_unsigned_t val)
  5322. {
  5323. handle_value(val);
  5324. return true;
  5325. }
  5326. bool number_float(number_float_t val, const string_t& /*unused*/)
  5327. {
  5328. handle_value(val);
  5329. return true;
  5330. }
  5331. bool string(string_t& val)
  5332. {
  5333. handle_value(val);
  5334. return true;
  5335. }
  5336. bool binary(binary_t& val)
  5337. {
  5338. handle_value(std::move(val));
  5339. return true;
  5340. }
  5341. bool start_object(std::size_t len)
  5342. {
  5343. // check callback for object start
  5344. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  5345. keep_stack.push_back(keep);
  5346. auto val = handle_value(BasicJsonType::value_t::object, true);
  5347. ref_stack.push_back(val.second);
  5348. // check object limit
  5349. if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast<std::size_t>(-1) && len > ref_stack.back()->max_size()))
  5350. {
  5351. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back()));
  5352. }
  5353. return true;
  5354. }
  5355. bool key(string_t& val)
  5356. {
  5357. BasicJsonType k = BasicJsonType(val);
  5358. // check callback for key
  5359. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  5360. key_keep_stack.push_back(keep);
  5361. // add discarded value at given key and store the reference for later
  5362. if (keep && ref_stack.back())
  5363. {
  5364. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  5365. }
  5366. return true;
  5367. }
  5368. bool end_object()
  5369. {
  5370. if (ref_stack.back())
  5371. {
  5372. if (!callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  5373. {
  5374. // discard object
  5375. *ref_stack.back() = discarded;
  5376. }
  5377. else
  5378. {
  5379. ref_stack.back()->set_parents();
  5380. }
  5381. }
  5382. JSON_ASSERT(!ref_stack.empty());
  5383. JSON_ASSERT(!keep_stack.empty());
  5384. ref_stack.pop_back();
  5385. keep_stack.pop_back();
  5386. if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured())
  5387. {
  5388. // remove discarded value
  5389. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  5390. {
  5391. if (it->is_discarded())
  5392. {
  5393. ref_stack.back()->erase(it);
  5394. break;
  5395. }
  5396. }
  5397. }
  5398. return true;
  5399. }
  5400. bool start_array(std::size_t len)
  5401. {
  5402. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  5403. keep_stack.push_back(keep);
  5404. auto val = handle_value(BasicJsonType::value_t::array, true);
  5405. ref_stack.push_back(val.second);
  5406. // check array limit
  5407. if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast<std::size_t>(-1) && len > ref_stack.back()->max_size()))
  5408. {
  5409. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back()));
  5410. }
  5411. return true;
  5412. }
  5413. bool end_array()
  5414. {
  5415. bool keep = true;
  5416. if (ref_stack.back())
  5417. {
  5418. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  5419. if (keep)
  5420. {
  5421. ref_stack.back()->set_parents();
  5422. }
  5423. else
  5424. {
  5425. // discard array
  5426. *ref_stack.back() = discarded;
  5427. }
  5428. }
  5429. JSON_ASSERT(!ref_stack.empty());
  5430. JSON_ASSERT(!keep_stack.empty());
  5431. ref_stack.pop_back();
  5432. keep_stack.pop_back();
  5433. // remove discarded value
  5434. if (!keep && !ref_stack.empty() && ref_stack.back()->is_array())
  5435. {
  5436. ref_stack.back()->m_value.array->pop_back();
  5437. }
  5438. return true;
  5439. }
  5440. template<class Exception>
  5441. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  5442. const Exception& ex)
  5443. {
  5444. errored = true;
  5445. static_cast<void>(ex);
  5446. if (allow_exceptions)
  5447. {
  5448. JSON_THROW(ex);
  5449. }
  5450. return false;
  5451. }
  5452. constexpr bool is_errored() const
  5453. {
  5454. return errored;
  5455. }
  5456. private:
  5457. /*!
  5458. @param[in] v value to add to the JSON value we build during parsing
  5459. @param[in] skip_callback whether we should skip calling the callback
  5460. function; this is required after start_array() and
  5461. start_object() SAX events, because otherwise we would call the
  5462. callback function with an empty array or object, respectively.
  5463. @invariant If the ref stack is empty, then the passed value will be the new
  5464. root.
  5465. @invariant If the ref stack contains a value, then it is an array or an
  5466. object to which we can add elements
  5467. @return pair of boolean (whether value should be kept) and pointer (to the
  5468. passed value in the ref_stack hierarchy; nullptr if not kept)
  5469. */
  5470. template<typename Value>
  5471. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  5472. {
  5473. JSON_ASSERT(!keep_stack.empty());
  5474. // do not handle this value if we know it would be added to a discarded
  5475. // container
  5476. if (!keep_stack.back())
  5477. {
  5478. return {false, nullptr};
  5479. }
  5480. // create value
  5481. auto value = BasicJsonType(std::forward<Value>(v));
  5482. // check callback
  5483. const bool keep = skip_callback || callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  5484. // do not handle this value if we just learnt it shall be discarded
  5485. if (!keep)
  5486. {
  5487. return {false, nullptr};
  5488. }
  5489. if (ref_stack.empty())
  5490. {
  5491. root = std::move(value);
  5492. return {true, &root};
  5493. }
  5494. // skip this value if we already decided to skip the parent
  5495. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  5496. if (!ref_stack.back())
  5497. {
  5498. return {false, nullptr};
  5499. }
  5500. // we now only expect arrays and objects
  5501. JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
  5502. // array
  5503. if (ref_stack.back()->is_array())
  5504. {
  5505. ref_stack.back()->m_value.array->emplace_back(std::move(value));
  5506. return {true, &(ref_stack.back()->m_value.array->back())};
  5507. }
  5508. // object
  5509. JSON_ASSERT(ref_stack.back()->is_object());
  5510. // check if we should store an element for the current key
  5511. JSON_ASSERT(!key_keep_stack.empty());
  5512. const bool store_element = key_keep_stack.back();
  5513. key_keep_stack.pop_back();
  5514. if (!store_element)
  5515. {
  5516. return {false, nullptr};
  5517. }
  5518. JSON_ASSERT(object_element);
  5519. *object_element = std::move(value);
  5520. return {true, object_element};
  5521. }
  5522. /// the parsed JSON value
  5523. BasicJsonType& root;
  5524. /// stack to model hierarchy of values
  5525. std::vector<BasicJsonType*> ref_stack {};
  5526. /// stack to manage which values to keep
  5527. std::vector<bool> keep_stack {};
  5528. /// stack to manage which object keys to keep
  5529. std::vector<bool> key_keep_stack {};
  5530. /// helper to hold the reference for the next object element
  5531. BasicJsonType* object_element = nullptr;
  5532. /// whether a syntax error occurred
  5533. bool errored = false;
  5534. /// callback function
  5535. const parser_callback_t callback = nullptr;
  5536. /// whether to throw exceptions in case of errors
  5537. const bool allow_exceptions = true;
  5538. /// a discarded value for the callback
  5539. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  5540. };
  5541. template<typename BasicJsonType>
  5542. class json_sax_acceptor
  5543. {
  5544. public:
  5545. using number_integer_t = typename BasicJsonType::number_integer_t;
  5546. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5547. using number_float_t = typename BasicJsonType::number_float_t;
  5548. using string_t = typename BasicJsonType::string_t;
  5549. using binary_t = typename BasicJsonType::binary_t;
  5550. bool null()
  5551. {
  5552. return true;
  5553. }
  5554. bool boolean(bool /*unused*/)
  5555. {
  5556. return true;
  5557. }
  5558. bool number_integer(number_integer_t /*unused*/)
  5559. {
  5560. return true;
  5561. }
  5562. bool number_unsigned(number_unsigned_t /*unused*/)
  5563. {
  5564. return true;
  5565. }
  5566. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  5567. {
  5568. return true;
  5569. }
  5570. bool string(string_t& /*unused*/)
  5571. {
  5572. return true;
  5573. }
  5574. bool binary(binary_t& /*unused*/)
  5575. {
  5576. return true;
  5577. }
  5578. bool start_object(std::size_t /*unused*/ = static_cast<std::size_t>(-1))
  5579. {
  5580. return true;
  5581. }
  5582. bool key(string_t& /*unused*/)
  5583. {
  5584. return true;
  5585. }
  5586. bool end_object()
  5587. {
  5588. return true;
  5589. }
  5590. bool start_array(std::size_t /*unused*/ = static_cast<std::size_t>(-1))
  5591. {
  5592. return true;
  5593. }
  5594. bool end_array()
  5595. {
  5596. return true;
  5597. }
  5598. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  5599. {
  5600. return false;
  5601. }
  5602. };
  5603. } // namespace detail
  5604. } // namespace nlohmann
  5605. // #include <nlohmann/detail/input/lexer.hpp>
  5606. #include <array> // array
  5607. #include <clocale> // localeconv
  5608. #include <cstddef> // size_t
  5609. #include <cstdio> // snprintf
  5610. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  5611. #include <initializer_list> // initializer_list
  5612. #include <string> // char_traits, string
  5613. #include <utility> // move
  5614. #include <vector> // vector
  5615. // #include <nlohmann/detail/input/input_adapters.hpp>
  5616. // #include <nlohmann/detail/input/position_t.hpp>
  5617. // #include <nlohmann/detail/macro_scope.hpp>
  5618. namespace nlohmann
  5619. {
  5620. namespace detail
  5621. {
  5622. ///////////
  5623. // lexer //
  5624. ///////////
  5625. template<typename BasicJsonType>
  5626. class lexer_base
  5627. {
  5628. public:
  5629. /// token types for the parser
  5630. enum class token_type
  5631. {
  5632. uninitialized, ///< indicating the scanner is uninitialized
  5633. literal_true, ///< the `true` literal
  5634. literal_false, ///< the `false` literal
  5635. literal_null, ///< the `null` literal
  5636. value_string, ///< a string -- use get_string() for actual value
  5637. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  5638. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  5639. value_float, ///< an floating point number -- use get_number_float() for actual value
  5640. begin_array, ///< the character for array begin `[`
  5641. begin_object, ///< the character for object begin `{`
  5642. end_array, ///< the character for array end `]`
  5643. end_object, ///< the character for object end `}`
  5644. name_separator, ///< the name separator `:`
  5645. value_separator, ///< the value separator `,`
  5646. parse_error, ///< indicating a parse error
  5647. end_of_input, ///< indicating the end of the input buffer
  5648. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  5649. };
  5650. /// return name of values of type token_type (only used for errors)
  5651. JSON_HEDLEY_RETURNS_NON_NULL
  5652. JSON_HEDLEY_CONST
  5653. static const char* token_type_name(const token_type t) noexcept
  5654. {
  5655. switch (t)
  5656. {
  5657. case token_type::uninitialized:
  5658. return "<uninitialized>";
  5659. case token_type::literal_true:
  5660. return "true literal";
  5661. case token_type::literal_false:
  5662. return "false literal";
  5663. case token_type::literal_null:
  5664. return "null literal";
  5665. case token_type::value_string:
  5666. return "string literal";
  5667. case token_type::value_unsigned:
  5668. case token_type::value_integer:
  5669. case token_type::value_float:
  5670. return "number literal";
  5671. case token_type::begin_array:
  5672. return "'['";
  5673. case token_type::begin_object:
  5674. return "'{'";
  5675. case token_type::end_array:
  5676. return "']'";
  5677. case token_type::end_object:
  5678. return "'}'";
  5679. case token_type::name_separator:
  5680. return "':'";
  5681. case token_type::value_separator:
  5682. return "','";
  5683. case token_type::parse_error:
  5684. return "<parse error>";
  5685. case token_type::end_of_input:
  5686. return "end of input";
  5687. case token_type::literal_or_value:
  5688. return "'[', '{', or a literal";
  5689. // LCOV_EXCL_START
  5690. default: // catch non-enum values
  5691. return "unknown token";
  5692. // LCOV_EXCL_STOP
  5693. }
  5694. }
  5695. };
  5696. /*!
  5697. @brief lexical analysis
  5698. This class organizes the lexical analysis during JSON deserialization.
  5699. */
  5700. template<typename BasicJsonType, typename InputAdapterType>
  5701. class lexer : public lexer_base<BasicJsonType>
  5702. {
  5703. using number_integer_t = typename BasicJsonType::number_integer_t;
  5704. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5705. using number_float_t = typename BasicJsonType::number_float_t;
  5706. using string_t = typename BasicJsonType::string_t;
  5707. using char_type = typename InputAdapterType::char_type;
  5708. using char_int_type = typename std::char_traits<char_type>::int_type;
  5709. public:
  5710. using token_type = typename lexer_base<BasicJsonType>::token_type;
  5711. explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept
  5712. : ia(std::move(adapter))
  5713. , ignore_comments(ignore_comments_)
  5714. , decimal_point_char(static_cast<char_int_type>(get_decimal_point()))
  5715. {}
  5716. // delete because of pointer members
  5717. lexer(const lexer&) = delete;
  5718. lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5719. lexer& operator=(lexer&) = delete;
  5720. lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5721. ~lexer() = default;
  5722. private:
  5723. /////////////////////
  5724. // locales
  5725. /////////////////////
  5726. /// return the locale-dependent decimal point
  5727. JSON_HEDLEY_PURE
  5728. static char get_decimal_point() noexcept
  5729. {
  5730. const auto* loc = localeconv();
  5731. JSON_ASSERT(loc != nullptr);
  5732. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  5733. }
  5734. /////////////////////
  5735. // scan functions
  5736. /////////////////////
  5737. /*!
  5738. @brief get codepoint from 4 hex characters following `\u`
  5739. For input "\u c1 c2 c3 c4" the codepoint is:
  5740. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  5741. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  5742. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  5743. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  5744. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  5745. between the ASCII value of the character and the desired integer value.
  5746. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  5747. non-hex character)
  5748. */
  5749. int get_codepoint()
  5750. {
  5751. // this function only makes sense after reading `\u`
  5752. JSON_ASSERT(current == 'u');
  5753. int codepoint = 0;
  5754. const auto factors = { 12u, 8u, 4u, 0u };
  5755. for (const auto factor : factors)
  5756. {
  5757. get();
  5758. if (current >= '0' && current <= '9')
  5759. {
  5760. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  5761. }
  5762. else if (current >= 'A' && current <= 'F')
  5763. {
  5764. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  5765. }
  5766. else if (current >= 'a' && current <= 'f')
  5767. {
  5768. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  5769. }
  5770. else
  5771. {
  5772. return -1;
  5773. }
  5774. }
  5775. JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF);
  5776. return codepoint;
  5777. }
  5778. /*!
  5779. @brief check if the next byte(s) are inside a given range
  5780. Adds the current byte and, for each passed range, reads a new byte and
  5781. checks if it is inside the range. If a violation was detected, set up an
  5782. error message and return false. Otherwise, return true.
  5783. @param[in] ranges list of integers; interpreted as list of pairs of
  5784. inclusive lower and upper bound, respectively
  5785. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  5786. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  5787. @return true if and only if no range violation was detected
  5788. */
  5789. bool next_byte_in_range(std::initializer_list<char_int_type> ranges)
  5790. {
  5791. JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6);
  5792. add(current);
  5793. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  5794. {
  5795. get();
  5796. if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range)))
  5797. {
  5798. add(current);
  5799. }
  5800. else
  5801. {
  5802. error_message = "invalid string: ill-formed UTF-8 byte";
  5803. return false;
  5804. }
  5805. }
  5806. return true;
  5807. }
  5808. /*!
  5809. @brief scan a string literal
  5810. This function scans a string according to Sect. 7 of RFC 8259. While
  5811. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  5812. function returns successfully, token_buffer is *not* null-terminated (as it
  5813. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  5814. string.
  5815. @return token_type::value_string if string could be successfully scanned,
  5816. token_type::parse_error otherwise
  5817. @note In case of errors, variable error_message contains a textual
  5818. description.
  5819. */
  5820. token_type scan_string()
  5821. {
  5822. // reset token_buffer (ignore opening quote)
  5823. reset();
  5824. // we entered the function by reading an open quote
  5825. JSON_ASSERT(current == '\"');
  5826. while (true)
  5827. {
  5828. // get next character
  5829. switch (get())
  5830. {
  5831. // end of file while parsing string
  5832. case std::char_traits<char_type>::eof():
  5833. {
  5834. error_message = "invalid string: missing closing quote";
  5835. return token_type::parse_error;
  5836. }
  5837. // closing quote
  5838. case '\"':
  5839. {
  5840. return token_type::value_string;
  5841. }
  5842. // escapes
  5843. case '\\':
  5844. {
  5845. switch (get())
  5846. {
  5847. // quotation mark
  5848. case '\"':
  5849. add('\"');
  5850. break;
  5851. // reverse solidus
  5852. case '\\':
  5853. add('\\');
  5854. break;
  5855. // solidus
  5856. case '/':
  5857. add('/');
  5858. break;
  5859. // backspace
  5860. case 'b':
  5861. add('\b');
  5862. break;
  5863. // form feed
  5864. case 'f':
  5865. add('\f');
  5866. break;
  5867. // line feed
  5868. case 'n':
  5869. add('\n');
  5870. break;
  5871. // carriage return
  5872. case 'r':
  5873. add('\r');
  5874. break;
  5875. // tab
  5876. case 't':
  5877. add('\t');
  5878. break;
  5879. // unicode escapes
  5880. case 'u':
  5881. {
  5882. const int codepoint1 = get_codepoint();
  5883. int codepoint = codepoint1; // start with codepoint1
  5884. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  5885. {
  5886. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  5887. return token_type::parse_error;
  5888. }
  5889. // check if code point is a high surrogate
  5890. if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF)
  5891. {
  5892. // expect next \uxxxx entry
  5893. if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u'))
  5894. {
  5895. const int codepoint2 = get_codepoint();
  5896. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  5897. {
  5898. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  5899. return token_type::parse_error;
  5900. }
  5901. // check if codepoint2 is a low surrogate
  5902. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF))
  5903. {
  5904. // overwrite codepoint
  5905. codepoint = static_cast<int>(
  5906. // high surrogate occupies the most significant 22 bits
  5907. (static_cast<unsigned int>(codepoint1) << 10u)
  5908. // low surrogate occupies the least significant 15 bits
  5909. + static_cast<unsigned int>(codepoint2)
  5910. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  5911. // in the result, so we have to subtract with:
  5912. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  5913. - 0x35FDC00u);
  5914. }
  5915. else
  5916. {
  5917. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  5918. return token_type::parse_error;
  5919. }
  5920. }
  5921. else
  5922. {
  5923. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  5924. return token_type::parse_error;
  5925. }
  5926. }
  5927. else
  5928. {
  5929. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF))
  5930. {
  5931. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  5932. return token_type::parse_error;
  5933. }
  5934. }
  5935. // result of the above calculation yields a proper codepoint
  5936. JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF);
  5937. // translate codepoint into bytes
  5938. if (codepoint < 0x80)
  5939. {
  5940. // 1-byte characters: 0xxxxxxx (ASCII)
  5941. add(static_cast<char_int_type>(codepoint));
  5942. }
  5943. else if (codepoint <= 0x7FF)
  5944. {
  5945. // 2-byte characters: 110xxxxx 10xxxxxx
  5946. add(static_cast<char_int_type>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  5947. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  5948. }
  5949. else if (codepoint <= 0xFFFF)
  5950. {
  5951. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  5952. add(static_cast<char_int_type>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  5953. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  5954. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  5955. }
  5956. else
  5957. {
  5958. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  5959. add(static_cast<char_int_type>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  5960. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  5961. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  5962. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  5963. }
  5964. break;
  5965. }
  5966. // other characters after escape
  5967. default:
  5968. error_message = "invalid string: forbidden character after backslash";
  5969. return token_type::parse_error;
  5970. }
  5971. break;
  5972. }
  5973. // invalid control characters
  5974. case 0x00:
  5975. {
  5976. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  5977. return token_type::parse_error;
  5978. }
  5979. case 0x01:
  5980. {
  5981. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  5982. return token_type::parse_error;
  5983. }
  5984. case 0x02:
  5985. {
  5986. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  5987. return token_type::parse_error;
  5988. }
  5989. case 0x03:
  5990. {
  5991. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  5992. return token_type::parse_error;
  5993. }
  5994. case 0x04:
  5995. {
  5996. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  5997. return token_type::parse_error;
  5998. }
  5999. case 0x05:
  6000. {
  6001. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  6002. return token_type::parse_error;
  6003. }
  6004. case 0x06:
  6005. {
  6006. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  6007. return token_type::parse_error;
  6008. }
  6009. case 0x07:
  6010. {
  6011. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  6012. return token_type::parse_error;
  6013. }
  6014. case 0x08:
  6015. {
  6016. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  6017. return token_type::parse_error;
  6018. }
  6019. case 0x09:
  6020. {
  6021. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  6022. return token_type::parse_error;
  6023. }
  6024. case 0x0A:
  6025. {
  6026. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  6027. return token_type::parse_error;
  6028. }
  6029. case 0x0B:
  6030. {
  6031. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  6032. return token_type::parse_error;
  6033. }
  6034. case 0x0C:
  6035. {
  6036. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  6037. return token_type::parse_error;
  6038. }
  6039. case 0x0D:
  6040. {
  6041. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  6042. return token_type::parse_error;
  6043. }
  6044. case 0x0E:
  6045. {
  6046. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  6047. return token_type::parse_error;
  6048. }
  6049. case 0x0F:
  6050. {
  6051. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  6052. return token_type::parse_error;
  6053. }
  6054. case 0x10:
  6055. {
  6056. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  6057. return token_type::parse_error;
  6058. }
  6059. case 0x11:
  6060. {
  6061. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  6062. return token_type::parse_error;
  6063. }
  6064. case 0x12:
  6065. {
  6066. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  6067. return token_type::parse_error;
  6068. }
  6069. case 0x13:
  6070. {
  6071. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  6072. return token_type::parse_error;
  6073. }
  6074. case 0x14:
  6075. {
  6076. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  6077. return token_type::parse_error;
  6078. }
  6079. case 0x15:
  6080. {
  6081. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  6082. return token_type::parse_error;
  6083. }
  6084. case 0x16:
  6085. {
  6086. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  6087. return token_type::parse_error;
  6088. }
  6089. case 0x17:
  6090. {
  6091. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  6092. return token_type::parse_error;
  6093. }
  6094. case 0x18:
  6095. {
  6096. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  6097. return token_type::parse_error;
  6098. }
  6099. case 0x19:
  6100. {
  6101. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  6102. return token_type::parse_error;
  6103. }
  6104. case 0x1A:
  6105. {
  6106. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  6107. return token_type::parse_error;
  6108. }
  6109. case 0x1B:
  6110. {
  6111. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  6112. return token_type::parse_error;
  6113. }
  6114. case 0x1C:
  6115. {
  6116. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  6117. return token_type::parse_error;
  6118. }
  6119. case 0x1D:
  6120. {
  6121. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  6122. return token_type::parse_error;
  6123. }
  6124. case 0x1E:
  6125. {
  6126. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  6127. return token_type::parse_error;
  6128. }
  6129. case 0x1F:
  6130. {
  6131. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  6132. return token_type::parse_error;
  6133. }
  6134. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  6135. case 0x20:
  6136. case 0x21:
  6137. case 0x23:
  6138. case 0x24:
  6139. case 0x25:
  6140. case 0x26:
  6141. case 0x27:
  6142. case 0x28:
  6143. case 0x29:
  6144. case 0x2A:
  6145. case 0x2B:
  6146. case 0x2C:
  6147. case 0x2D:
  6148. case 0x2E:
  6149. case 0x2F:
  6150. case 0x30:
  6151. case 0x31:
  6152. case 0x32:
  6153. case 0x33:
  6154. case 0x34:
  6155. case 0x35:
  6156. case 0x36:
  6157. case 0x37:
  6158. case 0x38:
  6159. case 0x39:
  6160. case 0x3A:
  6161. case 0x3B:
  6162. case 0x3C:
  6163. case 0x3D:
  6164. case 0x3E:
  6165. case 0x3F:
  6166. case 0x40:
  6167. case 0x41:
  6168. case 0x42:
  6169. case 0x43:
  6170. case 0x44:
  6171. case 0x45:
  6172. case 0x46:
  6173. case 0x47:
  6174. case 0x48:
  6175. case 0x49:
  6176. case 0x4A:
  6177. case 0x4B:
  6178. case 0x4C:
  6179. case 0x4D:
  6180. case 0x4E:
  6181. case 0x4F:
  6182. case 0x50:
  6183. case 0x51:
  6184. case 0x52:
  6185. case 0x53:
  6186. case 0x54:
  6187. case 0x55:
  6188. case 0x56:
  6189. case 0x57:
  6190. case 0x58:
  6191. case 0x59:
  6192. case 0x5A:
  6193. case 0x5B:
  6194. case 0x5D:
  6195. case 0x5E:
  6196. case 0x5F:
  6197. case 0x60:
  6198. case 0x61:
  6199. case 0x62:
  6200. case 0x63:
  6201. case 0x64:
  6202. case 0x65:
  6203. case 0x66:
  6204. case 0x67:
  6205. case 0x68:
  6206. case 0x69:
  6207. case 0x6A:
  6208. case 0x6B:
  6209. case 0x6C:
  6210. case 0x6D:
  6211. case 0x6E:
  6212. case 0x6F:
  6213. case 0x70:
  6214. case 0x71:
  6215. case 0x72:
  6216. case 0x73:
  6217. case 0x74:
  6218. case 0x75:
  6219. case 0x76:
  6220. case 0x77:
  6221. case 0x78:
  6222. case 0x79:
  6223. case 0x7A:
  6224. case 0x7B:
  6225. case 0x7C:
  6226. case 0x7D:
  6227. case 0x7E:
  6228. case 0x7F:
  6229. {
  6230. add(current);
  6231. break;
  6232. }
  6233. // U+0080..U+07FF: bytes C2..DF 80..BF
  6234. case 0xC2:
  6235. case 0xC3:
  6236. case 0xC4:
  6237. case 0xC5:
  6238. case 0xC6:
  6239. case 0xC7:
  6240. case 0xC8:
  6241. case 0xC9:
  6242. case 0xCA:
  6243. case 0xCB:
  6244. case 0xCC:
  6245. case 0xCD:
  6246. case 0xCE:
  6247. case 0xCF:
  6248. case 0xD0:
  6249. case 0xD1:
  6250. case 0xD2:
  6251. case 0xD3:
  6252. case 0xD4:
  6253. case 0xD5:
  6254. case 0xD6:
  6255. case 0xD7:
  6256. case 0xD8:
  6257. case 0xD9:
  6258. case 0xDA:
  6259. case 0xDB:
  6260. case 0xDC:
  6261. case 0xDD:
  6262. case 0xDE:
  6263. case 0xDF:
  6264. {
  6265. if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF})))
  6266. {
  6267. return token_type::parse_error;
  6268. }
  6269. break;
  6270. }
  6271. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  6272. case 0xE0:
  6273. {
  6274. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  6275. {
  6276. return token_type::parse_error;
  6277. }
  6278. break;
  6279. }
  6280. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  6281. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  6282. case 0xE1:
  6283. case 0xE2:
  6284. case 0xE3:
  6285. case 0xE4:
  6286. case 0xE5:
  6287. case 0xE6:
  6288. case 0xE7:
  6289. case 0xE8:
  6290. case 0xE9:
  6291. case 0xEA:
  6292. case 0xEB:
  6293. case 0xEC:
  6294. case 0xEE:
  6295. case 0xEF:
  6296. {
  6297. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  6298. {
  6299. return token_type::parse_error;
  6300. }
  6301. break;
  6302. }
  6303. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  6304. case 0xED:
  6305. {
  6306. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  6307. {
  6308. return token_type::parse_error;
  6309. }
  6310. break;
  6311. }
  6312. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  6313. case 0xF0:
  6314. {
  6315. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6316. {
  6317. return token_type::parse_error;
  6318. }
  6319. break;
  6320. }
  6321. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  6322. case 0xF1:
  6323. case 0xF2:
  6324. case 0xF3:
  6325. {
  6326. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6327. {
  6328. return token_type::parse_error;
  6329. }
  6330. break;
  6331. }
  6332. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  6333. case 0xF4:
  6334. {
  6335. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  6336. {
  6337. return token_type::parse_error;
  6338. }
  6339. break;
  6340. }
  6341. // remaining bytes (80..C1 and F5..FF) are ill-formed
  6342. default:
  6343. {
  6344. error_message = "invalid string: ill-formed UTF-8 byte";
  6345. return token_type::parse_error;
  6346. }
  6347. }
  6348. }
  6349. }
  6350. /*!
  6351. * @brief scan a comment
  6352. * @return whether comment could be scanned successfully
  6353. */
  6354. bool scan_comment()
  6355. {
  6356. switch (get())
  6357. {
  6358. // single-line comments skip input until a newline or EOF is read
  6359. case '/':
  6360. {
  6361. while (true)
  6362. {
  6363. switch (get())
  6364. {
  6365. case '\n':
  6366. case '\r':
  6367. case std::char_traits<char_type>::eof():
  6368. case '\0':
  6369. return true;
  6370. default:
  6371. break;
  6372. }
  6373. }
  6374. }
  6375. // multi-line comments skip input until */ is read
  6376. case '*':
  6377. {
  6378. while (true)
  6379. {
  6380. switch (get())
  6381. {
  6382. case std::char_traits<char_type>::eof():
  6383. case '\0':
  6384. {
  6385. error_message = "invalid comment; missing closing '*/'";
  6386. return false;
  6387. }
  6388. case '*':
  6389. {
  6390. switch (get())
  6391. {
  6392. case '/':
  6393. return true;
  6394. default:
  6395. {
  6396. unget();
  6397. continue;
  6398. }
  6399. }
  6400. }
  6401. default:
  6402. continue;
  6403. }
  6404. }
  6405. }
  6406. // unexpected character after reading '/'
  6407. default:
  6408. {
  6409. error_message = "invalid comment; expecting '/' or '*' after '/'";
  6410. return false;
  6411. }
  6412. }
  6413. }
  6414. JSON_HEDLEY_NON_NULL(2)
  6415. static void strtof(float& f, const char* str, char** endptr) noexcept
  6416. {
  6417. f = std::strtof(str, endptr);
  6418. }
  6419. JSON_HEDLEY_NON_NULL(2)
  6420. static void strtof(double& f, const char* str, char** endptr) noexcept
  6421. {
  6422. f = std::strtod(str, endptr);
  6423. }
  6424. JSON_HEDLEY_NON_NULL(2)
  6425. static void strtof(long double& f, const char* str, char** endptr) noexcept
  6426. {
  6427. f = std::strtold(str, endptr);
  6428. }
  6429. /*!
  6430. @brief scan a number literal
  6431. This function scans a string according to Sect. 6 of RFC 8259.
  6432. The function is realized with a deterministic finite state machine derived
  6433. from the grammar described in RFC 8259. Starting in state "init", the
  6434. input is read and used to determined the next state. Only state "done"
  6435. accepts the number. State "error" is a trap state to model errors. In the
  6436. table below, "anything" means any character but the ones listed before.
  6437. state | 0 | 1-9 | e E | + | - | . | anything
  6438. ---------|----------|----------|----------|---------|---------|----------|-----------
  6439. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  6440. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  6441. zero | done | done | exponent | done | done | decimal1 | done
  6442. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  6443. decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error]
  6444. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  6445. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  6446. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  6447. any2 | any2 | any2 | done | done | done | done | done
  6448. The state machine is realized with one label per state (prefixed with
  6449. "scan_number_") and `goto` statements between them. The state machine
  6450. contains cycles, but any cycle can be left when EOF is read. Therefore,
  6451. the function is guaranteed to terminate.
  6452. During scanning, the read bytes are stored in token_buffer. This string is
  6453. then converted to a signed integer, an unsigned integer, or a
  6454. floating-point number.
  6455. @return token_type::value_unsigned, token_type::value_integer, or
  6456. token_type::value_float if number could be successfully scanned,
  6457. token_type::parse_error otherwise
  6458. @note The scanner is independent of the current locale. Internally, the
  6459. locale's decimal point is used instead of `.` to work with the
  6460. locale-dependent converters.
  6461. */
  6462. token_type scan_number() // lgtm [cpp/use-of-goto]
  6463. {
  6464. // reset token_buffer to store the number's bytes
  6465. reset();
  6466. // the type of the parsed number; initially set to unsigned; will be
  6467. // changed if minus sign, decimal point or exponent is read
  6468. token_type number_type = token_type::value_unsigned;
  6469. // state (init): we just found out we need to scan a number
  6470. switch (current)
  6471. {
  6472. case '-':
  6473. {
  6474. add(current);
  6475. goto scan_number_minus;
  6476. }
  6477. case '0':
  6478. {
  6479. add(current);
  6480. goto scan_number_zero;
  6481. }
  6482. case '1':
  6483. case '2':
  6484. case '3':
  6485. case '4':
  6486. case '5':
  6487. case '6':
  6488. case '7':
  6489. case '8':
  6490. case '9':
  6491. {
  6492. add(current);
  6493. goto scan_number_any1;
  6494. }
  6495. // all other characters are rejected outside scan_number()
  6496. default: // LCOV_EXCL_LINE
  6497. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  6498. }
  6499. scan_number_minus:
  6500. // state: we just parsed a leading minus sign
  6501. number_type = token_type::value_integer;
  6502. switch (get())
  6503. {
  6504. case '0':
  6505. {
  6506. add(current);
  6507. goto scan_number_zero;
  6508. }
  6509. case '1':
  6510. case '2':
  6511. case '3':
  6512. case '4':
  6513. case '5':
  6514. case '6':
  6515. case '7':
  6516. case '8':
  6517. case '9':
  6518. {
  6519. add(current);
  6520. goto scan_number_any1;
  6521. }
  6522. default:
  6523. {
  6524. error_message = "invalid number; expected digit after '-'";
  6525. return token_type::parse_error;
  6526. }
  6527. }
  6528. scan_number_zero:
  6529. // state: we just parse a zero (maybe with a leading minus sign)
  6530. switch (get())
  6531. {
  6532. case '.':
  6533. {
  6534. add(decimal_point_char);
  6535. goto scan_number_decimal1;
  6536. }
  6537. case 'e':
  6538. case 'E':
  6539. {
  6540. add(current);
  6541. goto scan_number_exponent;
  6542. }
  6543. default:
  6544. goto scan_number_done;
  6545. }
  6546. scan_number_any1:
  6547. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  6548. switch (get())
  6549. {
  6550. case '0':
  6551. case '1':
  6552. case '2':
  6553. case '3':
  6554. case '4':
  6555. case '5':
  6556. case '6':
  6557. case '7':
  6558. case '8':
  6559. case '9':
  6560. {
  6561. add(current);
  6562. goto scan_number_any1;
  6563. }
  6564. case '.':
  6565. {
  6566. add(decimal_point_char);
  6567. goto scan_number_decimal1;
  6568. }
  6569. case 'e':
  6570. case 'E':
  6571. {
  6572. add(current);
  6573. goto scan_number_exponent;
  6574. }
  6575. default:
  6576. goto scan_number_done;
  6577. }
  6578. scan_number_decimal1:
  6579. // state: we just parsed a decimal point
  6580. number_type = token_type::value_float;
  6581. switch (get())
  6582. {
  6583. case '0':
  6584. case '1':
  6585. case '2':
  6586. case '3':
  6587. case '4':
  6588. case '5':
  6589. case '6':
  6590. case '7':
  6591. case '8':
  6592. case '9':
  6593. {
  6594. add(current);
  6595. goto scan_number_decimal2;
  6596. }
  6597. default:
  6598. {
  6599. error_message = "invalid number; expected digit after '.'";
  6600. return token_type::parse_error;
  6601. }
  6602. }
  6603. scan_number_decimal2:
  6604. // we just parsed at least one number after a decimal point
  6605. switch (get())
  6606. {
  6607. case '0':
  6608. case '1':
  6609. case '2':
  6610. case '3':
  6611. case '4':
  6612. case '5':
  6613. case '6':
  6614. case '7':
  6615. case '8':
  6616. case '9':
  6617. {
  6618. add(current);
  6619. goto scan_number_decimal2;
  6620. }
  6621. case 'e':
  6622. case 'E':
  6623. {
  6624. add(current);
  6625. goto scan_number_exponent;
  6626. }
  6627. default:
  6628. goto scan_number_done;
  6629. }
  6630. scan_number_exponent:
  6631. // we just parsed an exponent
  6632. number_type = token_type::value_float;
  6633. switch (get())
  6634. {
  6635. case '+':
  6636. case '-':
  6637. {
  6638. add(current);
  6639. goto scan_number_sign;
  6640. }
  6641. case '0':
  6642. case '1':
  6643. case '2':
  6644. case '3':
  6645. case '4':
  6646. case '5':
  6647. case '6':
  6648. case '7':
  6649. case '8':
  6650. case '9':
  6651. {
  6652. add(current);
  6653. goto scan_number_any2;
  6654. }
  6655. default:
  6656. {
  6657. error_message =
  6658. "invalid number; expected '+', '-', or digit after exponent";
  6659. return token_type::parse_error;
  6660. }
  6661. }
  6662. scan_number_sign:
  6663. // we just parsed an exponent sign
  6664. switch (get())
  6665. {
  6666. case '0':
  6667. case '1':
  6668. case '2':
  6669. case '3':
  6670. case '4':
  6671. case '5':
  6672. case '6':
  6673. case '7':
  6674. case '8':
  6675. case '9':
  6676. {
  6677. add(current);
  6678. goto scan_number_any2;
  6679. }
  6680. default:
  6681. {
  6682. error_message = "invalid number; expected digit after exponent sign";
  6683. return token_type::parse_error;
  6684. }
  6685. }
  6686. scan_number_any2:
  6687. // we just parsed a number after the exponent or exponent sign
  6688. switch (get())
  6689. {
  6690. case '0':
  6691. case '1':
  6692. case '2':
  6693. case '3':
  6694. case '4':
  6695. case '5':
  6696. case '6':
  6697. case '7':
  6698. case '8':
  6699. case '9':
  6700. {
  6701. add(current);
  6702. goto scan_number_any2;
  6703. }
  6704. default:
  6705. goto scan_number_done;
  6706. }
  6707. scan_number_done:
  6708. // unget the character after the number (we only read it to know that
  6709. // we are done scanning a number)
  6710. unget();
  6711. char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  6712. errno = 0;
  6713. // try to parse integers first and fall back to floats
  6714. if (number_type == token_type::value_unsigned)
  6715. {
  6716. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  6717. // we checked the number format before
  6718. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6719. if (errno == 0)
  6720. {
  6721. value_unsigned = static_cast<number_unsigned_t>(x);
  6722. if (value_unsigned == x)
  6723. {
  6724. return token_type::value_unsigned;
  6725. }
  6726. }
  6727. }
  6728. else if (number_type == token_type::value_integer)
  6729. {
  6730. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  6731. // we checked the number format before
  6732. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6733. if (errno == 0)
  6734. {
  6735. value_integer = static_cast<number_integer_t>(x);
  6736. if (value_integer == x)
  6737. {
  6738. return token_type::value_integer;
  6739. }
  6740. }
  6741. }
  6742. // this code is reached if we parse a floating-point number or if an
  6743. // integer conversion above failed
  6744. strtof(value_float, token_buffer.data(), &endptr);
  6745. // we checked the number format before
  6746. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6747. return token_type::value_float;
  6748. }
  6749. /*!
  6750. @param[in] literal_text the literal text to expect
  6751. @param[in] length the length of the passed literal text
  6752. @param[in] return_type the token type to return on success
  6753. */
  6754. JSON_HEDLEY_NON_NULL(2)
  6755. token_type scan_literal(const char_type* literal_text, const std::size_t length,
  6756. token_type return_type)
  6757. {
  6758. JSON_ASSERT(std::char_traits<char_type>::to_char_type(current) == literal_text[0]);
  6759. for (std::size_t i = 1; i < length; ++i)
  6760. {
  6761. if (JSON_HEDLEY_UNLIKELY(std::char_traits<char_type>::to_char_type(get()) != literal_text[i]))
  6762. {
  6763. error_message = "invalid literal";
  6764. return token_type::parse_error;
  6765. }
  6766. }
  6767. return return_type;
  6768. }
  6769. /////////////////////
  6770. // input management
  6771. /////////////////////
  6772. /// reset token_buffer; current character is beginning of token
  6773. void reset() noexcept
  6774. {
  6775. token_buffer.clear();
  6776. token_string.clear();
  6777. token_string.push_back(std::char_traits<char_type>::to_char_type(current));
  6778. }
  6779. /*
  6780. @brief get next character from the input
  6781. This function provides the interface to the used input adapter. It does
  6782. not throw in case the input reached EOF, but returns a
  6783. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  6784. for use in error messages.
  6785. @return character read from the input
  6786. */
  6787. char_int_type get()
  6788. {
  6789. ++position.chars_read_total;
  6790. ++position.chars_read_current_line;
  6791. if (next_unget)
  6792. {
  6793. // just reset the next_unget variable and work with current
  6794. next_unget = false;
  6795. }
  6796. else
  6797. {
  6798. current = ia.get_character();
  6799. }
  6800. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
  6801. {
  6802. token_string.push_back(std::char_traits<char_type>::to_char_type(current));
  6803. }
  6804. if (current == '\n')
  6805. {
  6806. ++position.lines_read;
  6807. position.chars_read_current_line = 0;
  6808. }
  6809. return current;
  6810. }
  6811. /*!
  6812. @brief unget current character (read it again on next get)
  6813. We implement unget by setting variable next_unget to true. The input is not
  6814. changed - we just simulate ungetting by modifying chars_read_total,
  6815. chars_read_current_line, and token_string. The next call to get() will
  6816. behave as if the unget character is read again.
  6817. */
  6818. void unget()
  6819. {
  6820. next_unget = true;
  6821. --position.chars_read_total;
  6822. // in case we "unget" a newline, we have to also decrement the lines_read
  6823. if (position.chars_read_current_line == 0)
  6824. {
  6825. if (position.lines_read > 0)
  6826. {
  6827. --position.lines_read;
  6828. }
  6829. }
  6830. else
  6831. {
  6832. --position.chars_read_current_line;
  6833. }
  6834. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
  6835. {
  6836. JSON_ASSERT(!token_string.empty());
  6837. token_string.pop_back();
  6838. }
  6839. }
  6840. /// add a character to token_buffer
  6841. void add(char_int_type c)
  6842. {
  6843. token_buffer.push_back(static_cast<typename string_t::value_type>(c));
  6844. }
  6845. public:
  6846. /////////////////////
  6847. // value getters
  6848. /////////////////////
  6849. /// return integer value
  6850. constexpr number_integer_t get_number_integer() const noexcept
  6851. {
  6852. return value_integer;
  6853. }
  6854. /// return unsigned integer value
  6855. constexpr number_unsigned_t get_number_unsigned() const noexcept
  6856. {
  6857. return value_unsigned;
  6858. }
  6859. /// return floating-point value
  6860. constexpr number_float_t get_number_float() const noexcept
  6861. {
  6862. return value_float;
  6863. }
  6864. /// return current string value (implicitly resets the token; useful only once)
  6865. string_t& get_string()
  6866. {
  6867. return token_buffer;
  6868. }
  6869. /////////////////////
  6870. // diagnostics
  6871. /////////////////////
  6872. /// return position of last read token
  6873. constexpr position_t get_position() const noexcept
  6874. {
  6875. return position;
  6876. }
  6877. /// return the last read token (for errors only). Will never contain EOF
  6878. /// (an arbitrary value that is not a valid char value, often -1), because
  6879. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  6880. std::string get_token_string() const
  6881. {
  6882. // escape control characters
  6883. std::string result;
  6884. for (const auto c : token_string)
  6885. {
  6886. if (static_cast<unsigned char>(c) <= '\x1F')
  6887. {
  6888. // escape control characters
  6889. std::array<char, 9> cs{{}};
  6890. static_cast<void>((std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  6891. result += cs.data();
  6892. }
  6893. else
  6894. {
  6895. // add character as is
  6896. result.push_back(static_cast<std::string::value_type>(c));
  6897. }
  6898. }
  6899. return result;
  6900. }
  6901. /// return syntax error message
  6902. JSON_HEDLEY_RETURNS_NON_NULL
  6903. constexpr const char* get_error_message() const noexcept
  6904. {
  6905. return error_message;
  6906. }
  6907. /////////////////////
  6908. // actual scanner
  6909. /////////////////////
  6910. /*!
  6911. @brief skip the UTF-8 byte order mark
  6912. @return true iff there is no BOM or the correct BOM has been skipped
  6913. */
  6914. bool skip_bom()
  6915. {
  6916. if (get() == 0xEF)
  6917. {
  6918. // check if we completely parse the BOM
  6919. return get() == 0xBB && get() == 0xBF;
  6920. }
  6921. // the first character is not the beginning of the BOM; unget it to
  6922. // process is later
  6923. unget();
  6924. return true;
  6925. }
  6926. void skip_whitespace()
  6927. {
  6928. do
  6929. {
  6930. get();
  6931. }
  6932. while (current == ' ' || current == '\t' || current == '\n' || current == '\r');
  6933. }
  6934. token_type scan()
  6935. {
  6936. // initially, skip the BOM
  6937. if (position.chars_read_total == 0 && !skip_bom())
  6938. {
  6939. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  6940. return token_type::parse_error;
  6941. }
  6942. // read next character and ignore whitespace
  6943. skip_whitespace();
  6944. // ignore comments
  6945. while (ignore_comments && current == '/')
  6946. {
  6947. if (!scan_comment())
  6948. {
  6949. return token_type::parse_error;
  6950. }
  6951. // skip following whitespace
  6952. skip_whitespace();
  6953. }
  6954. switch (current)
  6955. {
  6956. // structural characters
  6957. case '[':
  6958. return token_type::begin_array;
  6959. case ']':
  6960. return token_type::end_array;
  6961. case '{':
  6962. return token_type::begin_object;
  6963. case '}':
  6964. return token_type::end_object;
  6965. case ':':
  6966. return token_type::name_separator;
  6967. case ',':
  6968. return token_type::value_separator;
  6969. // literals
  6970. case 't':
  6971. {
  6972. std::array<char_type, 4> true_literal = {{static_cast<char_type>('t'), static_cast<char_type>('r'), static_cast<char_type>('u'), static_cast<char_type>('e')}};
  6973. return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true);
  6974. }
  6975. case 'f':
  6976. {
  6977. std::array<char_type, 5> false_literal = {{static_cast<char_type>('f'), static_cast<char_type>('a'), static_cast<char_type>('l'), static_cast<char_type>('s'), static_cast<char_type>('e')}};
  6978. return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false);
  6979. }
  6980. case 'n':
  6981. {
  6982. std::array<char_type, 4> null_literal = {{static_cast<char_type>('n'), static_cast<char_type>('u'), static_cast<char_type>('l'), static_cast<char_type>('l')}};
  6983. return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null);
  6984. }
  6985. // string
  6986. case '\"':
  6987. return scan_string();
  6988. // number
  6989. case '-':
  6990. case '0':
  6991. case '1':
  6992. case '2':
  6993. case '3':
  6994. case '4':
  6995. case '5':
  6996. case '6':
  6997. case '7':
  6998. case '8':
  6999. case '9':
  7000. return scan_number();
  7001. // end of input (the null byte is needed when parsing from
  7002. // string literals)
  7003. case '\0':
  7004. case std::char_traits<char_type>::eof():
  7005. return token_type::end_of_input;
  7006. // error
  7007. default:
  7008. error_message = "invalid literal";
  7009. return token_type::parse_error;
  7010. }
  7011. }
  7012. private:
  7013. /// input adapter
  7014. InputAdapterType ia;
  7015. /// whether comments should be ignored (true) or signaled as errors (false)
  7016. const bool ignore_comments = false;
  7017. /// the current character
  7018. char_int_type current = std::char_traits<char_type>::eof();
  7019. /// whether the next get() call should just return current
  7020. bool next_unget = false;
  7021. /// the start position of the current token
  7022. position_t position {};
  7023. /// raw input token string (for error messages)
  7024. std::vector<char_type> token_string {};
  7025. /// buffer for variable-length tokens (numbers, strings)
  7026. string_t token_buffer {};
  7027. /// a description of occurred lexer errors
  7028. const char* error_message = "";
  7029. // number values
  7030. number_integer_t value_integer = 0;
  7031. number_unsigned_t value_unsigned = 0;
  7032. number_float_t value_float = 0;
  7033. /// the decimal point
  7034. const char_int_type decimal_point_char = '.';
  7035. };
  7036. } // namespace detail
  7037. } // namespace nlohmann
  7038. // #include <nlohmann/detail/macro_scope.hpp>
  7039. // #include <nlohmann/detail/meta/is_sax.hpp>
  7040. #include <cstdint> // size_t
  7041. #include <utility> // declval
  7042. #include <string> // string
  7043. // #include <nlohmann/detail/meta/detected.hpp>
  7044. // #include <nlohmann/detail/meta/type_traits.hpp>
  7045. namespace nlohmann
  7046. {
  7047. namespace detail
  7048. {
  7049. template<typename T>
  7050. using null_function_t = decltype(std::declval<T&>().null());
  7051. template<typename T>
  7052. using boolean_function_t =
  7053. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  7054. template<typename T, typename Integer>
  7055. using number_integer_function_t =
  7056. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  7057. template<typename T, typename Unsigned>
  7058. using number_unsigned_function_t =
  7059. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  7060. template<typename T, typename Float, typename String>
  7061. using number_float_function_t = decltype(std::declval<T&>().number_float(
  7062. std::declval<Float>(), std::declval<const String&>()));
  7063. template<typename T, typename String>
  7064. using string_function_t =
  7065. decltype(std::declval<T&>().string(std::declval<String&>()));
  7066. template<typename T, typename Binary>
  7067. using binary_function_t =
  7068. decltype(std::declval<T&>().binary(std::declval<Binary&>()));
  7069. template<typename T>
  7070. using start_object_function_t =
  7071. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  7072. template<typename T, typename String>
  7073. using key_function_t =
  7074. decltype(std::declval<T&>().key(std::declval<String&>()));
  7075. template<typename T>
  7076. using end_object_function_t = decltype(std::declval<T&>().end_object());
  7077. template<typename T>
  7078. using start_array_function_t =
  7079. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  7080. template<typename T>
  7081. using end_array_function_t = decltype(std::declval<T&>().end_array());
  7082. template<typename T, typename Exception>
  7083. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  7084. std::declval<std::size_t>(), std::declval<const std::string&>(),
  7085. std::declval<const Exception&>()));
  7086. template<typename SAX, typename BasicJsonType>
  7087. struct is_sax
  7088. {
  7089. private:
  7090. static_assert(is_basic_json<BasicJsonType>::value,
  7091. "BasicJsonType must be of type basic_json<...>");
  7092. using number_integer_t = typename BasicJsonType::number_integer_t;
  7093. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7094. using number_float_t = typename BasicJsonType::number_float_t;
  7095. using string_t = typename BasicJsonType::string_t;
  7096. using binary_t = typename BasicJsonType::binary_t;
  7097. using exception_t = typename BasicJsonType::exception;
  7098. public:
  7099. static constexpr bool value =
  7100. is_detected_exact<bool, null_function_t, SAX>::value &&
  7101. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  7102. is_detected_exact<bool, number_integer_function_t, SAX, number_integer_t>::value &&
  7103. is_detected_exact<bool, number_unsigned_function_t, SAX, number_unsigned_t>::value &&
  7104. is_detected_exact<bool, number_float_function_t, SAX, number_float_t, string_t>::value &&
  7105. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  7106. is_detected_exact<bool, binary_function_t, SAX, binary_t>::value &&
  7107. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  7108. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  7109. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  7110. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  7111. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  7112. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  7113. };
  7114. template<typename SAX, typename BasicJsonType>
  7115. struct is_sax_static_asserts
  7116. {
  7117. private:
  7118. static_assert(is_basic_json<BasicJsonType>::value,
  7119. "BasicJsonType must be of type basic_json<...>");
  7120. using number_integer_t = typename BasicJsonType::number_integer_t;
  7121. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7122. using number_float_t = typename BasicJsonType::number_float_t;
  7123. using string_t = typename BasicJsonType::string_t;
  7124. using binary_t = typename BasicJsonType::binary_t;
  7125. using exception_t = typename BasicJsonType::exception;
  7126. public:
  7127. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  7128. "Missing/invalid function: bool null()");
  7129. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  7130. "Missing/invalid function: bool boolean(bool)");
  7131. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  7132. "Missing/invalid function: bool boolean(bool)");
  7133. static_assert(
  7134. is_detected_exact<bool, number_integer_function_t, SAX,
  7135. number_integer_t>::value,
  7136. "Missing/invalid function: bool number_integer(number_integer_t)");
  7137. static_assert(
  7138. is_detected_exact<bool, number_unsigned_function_t, SAX,
  7139. number_unsigned_t>::value,
  7140. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  7141. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  7142. number_float_t, string_t>::value,
  7143. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  7144. static_assert(
  7145. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  7146. "Missing/invalid function: bool string(string_t&)");
  7147. static_assert(
  7148. is_detected_exact<bool, binary_function_t, SAX, binary_t>::value,
  7149. "Missing/invalid function: bool binary(binary_t&)");
  7150. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  7151. "Missing/invalid function: bool start_object(std::size_t)");
  7152. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  7153. "Missing/invalid function: bool key(string_t&)");
  7154. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  7155. "Missing/invalid function: bool end_object()");
  7156. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  7157. "Missing/invalid function: bool start_array(std::size_t)");
  7158. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  7159. "Missing/invalid function: bool end_array()");
  7160. static_assert(
  7161. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  7162. "Missing/invalid function: bool parse_error(std::size_t, const "
  7163. "std::string&, const exception&)");
  7164. };
  7165. } // namespace detail
  7166. } // namespace nlohmann
  7167. // #include <nlohmann/detail/meta/type_traits.hpp>
  7168. // #include <nlohmann/detail/value_t.hpp>
  7169. namespace nlohmann
  7170. {
  7171. namespace detail
  7172. {
  7173. /// how to treat CBOR tags
  7174. enum class cbor_tag_handler_t
  7175. {
  7176. error, ///< throw a parse_error exception in case of a tag
  7177. ignore, ///< ignore tags
  7178. store ///< store tags as binary type
  7179. };
  7180. /*!
  7181. @brief determine system byte order
  7182. @return true if and only if system's byte order is little endian
  7183. @note from https://stackoverflow.com/a/1001328/266378
  7184. */
  7185. static inline bool little_endianness(int num = 1) noexcept
  7186. {
  7187. return *reinterpret_cast<char*>(&num) == 1;
  7188. }
  7189. ///////////////////
  7190. // binary reader //
  7191. ///////////////////
  7192. /*!
  7193. @brief deserialization of CBOR, MessagePack, and UBJSON values
  7194. */
  7195. template<typename BasicJsonType, typename InputAdapterType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  7196. class binary_reader
  7197. {
  7198. using number_integer_t = typename BasicJsonType::number_integer_t;
  7199. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7200. using number_float_t = typename BasicJsonType::number_float_t;
  7201. using string_t = typename BasicJsonType::string_t;
  7202. using binary_t = typename BasicJsonType::binary_t;
  7203. using json_sax_t = SAX;
  7204. using char_type = typename InputAdapterType::char_type;
  7205. using char_int_type = typename std::char_traits<char_type>::int_type;
  7206. public:
  7207. /*!
  7208. @brief create a binary reader
  7209. @param[in] adapter input adapter to read from
  7210. */
  7211. explicit binary_reader(InputAdapterType&& adapter) noexcept : ia(std::move(adapter))
  7212. {
  7213. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  7214. }
  7215. // make class move-only
  7216. binary_reader(const binary_reader&) = delete;
  7217. binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  7218. binary_reader& operator=(const binary_reader&) = delete;
  7219. binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  7220. ~binary_reader() = default;
  7221. /*!
  7222. @param[in] format the binary format to parse
  7223. @param[in] sax_ a SAX event processor
  7224. @param[in] strict whether to expect the input to be consumed completed
  7225. @param[in] tag_handler how to treat CBOR tags
  7226. @return whether parsing was successful
  7227. */
  7228. JSON_HEDLEY_NON_NULL(3)
  7229. bool sax_parse(const input_format_t format,
  7230. json_sax_t* sax_,
  7231. const bool strict = true,
  7232. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  7233. {
  7234. sax = sax_;
  7235. bool result = false;
  7236. switch (format)
  7237. {
  7238. case input_format_t::bson:
  7239. result = parse_bson_internal();
  7240. break;
  7241. case input_format_t::cbor:
  7242. result = parse_cbor_internal(true, tag_handler);
  7243. break;
  7244. case input_format_t::msgpack:
  7245. result = parse_msgpack_internal();
  7246. break;
  7247. case input_format_t::ubjson:
  7248. result = parse_ubjson_internal();
  7249. break;
  7250. case input_format_t::json: // LCOV_EXCL_LINE
  7251. default: // LCOV_EXCL_LINE
  7252. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  7253. }
  7254. // strict mode: next byte must be EOF
  7255. if (result && strict)
  7256. {
  7257. if (format == input_format_t::ubjson)
  7258. {
  7259. get_ignore_noop();
  7260. }
  7261. else
  7262. {
  7263. get();
  7264. }
  7265. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char_type>::eof()))
  7266. {
  7267. return sax->parse_error(chars_read, get_token_string(),
  7268. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"), BasicJsonType()));
  7269. }
  7270. }
  7271. return result;
  7272. }
  7273. private:
  7274. //////////
  7275. // BSON //
  7276. //////////
  7277. /*!
  7278. @brief Reads in a BSON-object and passes it to the SAX-parser.
  7279. @return whether a valid BSON-value was passed to the SAX parser
  7280. */
  7281. bool parse_bson_internal()
  7282. {
  7283. std::int32_t document_size{};
  7284. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  7285. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast<std::size_t>(-1))))
  7286. {
  7287. return false;
  7288. }
  7289. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false)))
  7290. {
  7291. return false;
  7292. }
  7293. return sax->end_object();
  7294. }
  7295. /*!
  7296. @brief Parses a C-style string from the BSON input.
  7297. @param[in,out] result A reference to the string variable where the read
  7298. string is to be stored.
  7299. @return `true` if the \x00-byte indicating the end of the string was
  7300. encountered before the EOF; false` indicates an unexpected EOF.
  7301. */
  7302. bool get_bson_cstr(string_t& result)
  7303. {
  7304. auto out = std::back_inserter(result);
  7305. while (true)
  7306. {
  7307. get();
  7308. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring")))
  7309. {
  7310. return false;
  7311. }
  7312. if (current == 0x00)
  7313. {
  7314. return true;
  7315. }
  7316. *out++ = static_cast<typename string_t::value_type>(current);
  7317. }
  7318. }
  7319. /*!
  7320. @brief Parses a zero-terminated string of length @a len from the BSON
  7321. input.
  7322. @param[in] len The length (including the zero-byte at the end) of the
  7323. string to be read.
  7324. @param[in,out] result A reference to the string variable where the read
  7325. string is to be stored.
  7326. @tparam NumberType The type of the length @a len
  7327. @pre len >= 1
  7328. @return `true` if the string was successfully parsed
  7329. */
  7330. template<typename NumberType>
  7331. bool get_bson_string(const NumberType len, string_t& result)
  7332. {
  7333. if (JSON_HEDLEY_UNLIKELY(len < 1))
  7334. {
  7335. auto last_token = get_token_string();
  7336. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"), BasicJsonType()));
  7337. }
  7338. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) && get() != std::char_traits<char_type>::eof();
  7339. }
  7340. /*!
  7341. @brief Parses a byte array input of length @a len from the BSON input.
  7342. @param[in] len The length of the byte array to be read.
  7343. @param[in,out] result A reference to the binary variable where the read
  7344. array is to be stored.
  7345. @tparam NumberType The type of the length @a len
  7346. @pre len >= 0
  7347. @return `true` if the byte array was successfully parsed
  7348. */
  7349. template<typename NumberType>
  7350. bool get_bson_binary(const NumberType len, binary_t& result)
  7351. {
  7352. if (JSON_HEDLEY_UNLIKELY(len < 0))
  7353. {
  7354. auto last_token = get_token_string();
  7355. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary"), BasicJsonType()));
  7356. }
  7357. // All BSON binary values have a subtype
  7358. std::uint8_t subtype{};
  7359. get_number<std::uint8_t>(input_format_t::bson, subtype);
  7360. result.set_subtype(subtype);
  7361. return get_binary(input_format_t::bson, len, result);
  7362. }
  7363. /*!
  7364. @brief Read a BSON document element of the given @a element_type.
  7365. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  7366. @param[in] element_type_parse_position The position in the input stream,
  7367. where the `element_type` was read.
  7368. @warning Not all BSON element types are supported yet. An unsupported
  7369. @a element_type will give rise to a parse_error.114:
  7370. Unsupported BSON record type 0x...
  7371. @return whether a valid BSON-object/array was passed to the SAX parser
  7372. */
  7373. bool parse_bson_element_internal(const char_int_type element_type,
  7374. const std::size_t element_type_parse_position)
  7375. {
  7376. switch (element_type)
  7377. {
  7378. case 0x01: // double
  7379. {
  7380. double number{};
  7381. return get_number<double, true>(input_format_t::bson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  7382. }
  7383. case 0x02: // string
  7384. {
  7385. std::int32_t len{};
  7386. string_t value;
  7387. return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value);
  7388. }
  7389. case 0x03: // object
  7390. {
  7391. return parse_bson_internal();
  7392. }
  7393. case 0x04: // array
  7394. {
  7395. return parse_bson_array();
  7396. }
  7397. case 0x05: // binary
  7398. {
  7399. std::int32_t len{};
  7400. binary_t value;
  7401. return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value);
  7402. }
  7403. case 0x08: // boolean
  7404. {
  7405. return sax->boolean(get() != 0);
  7406. }
  7407. case 0x0A: // null
  7408. {
  7409. return sax->null();
  7410. }
  7411. case 0x10: // int32
  7412. {
  7413. std::int32_t value{};
  7414. return get_number<std::int32_t, true>(input_format_t::bson, value) && sax->number_integer(value);
  7415. }
  7416. case 0x12: // int64
  7417. {
  7418. std::int64_t value{};
  7419. return get_number<std::int64_t, true>(input_format_t::bson, value) && sax->number_integer(value);
  7420. }
  7421. default: // anything else not supported (yet)
  7422. {
  7423. std::array<char, 3> cr{{}};
  7424. static_cast<void>((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  7425. return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data()), BasicJsonType()));
  7426. }
  7427. }
  7428. }
  7429. /*!
  7430. @brief Read a BSON element list (as specified in the BSON-spec)
  7431. The same binary layout is used for objects and arrays, hence it must be
  7432. indicated with the argument @a is_array which one is expected
  7433. (true --> array, false --> object).
  7434. @param[in] is_array Determines if the element list being read is to be
  7435. treated as an object (@a is_array == false), or as an
  7436. array (@a is_array == true).
  7437. @return whether a valid BSON-object/array was passed to the SAX parser
  7438. */
  7439. bool parse_bson_element_list(const bool is_array)
  7440. {
  7441. string_t key;
  7442. while (auto element_type = get())
  7443. {
  7444. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list")))
  7445. {
  7446. return false;
  7447. }
  7448. const std::size_t element_type_parse_position = chars_read;
  7449. if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key)))
  7450. {
  7451. return false;
  7452. }
  7453. if (!is_array && !sax->key(key))
  7454. {
  7455. return false;
  7456. }
  7457. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position)))
  7458. {
  7459. return false;
  7460. }
  7461. // get_bson_cstr only appends
  7462. key.clear();
  7463. }
  7464. return true;
  7465. }
  7466. /*!
  7467. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  7468. @return whether a valid BSON-array was passed to the SAX parser
  7469. */
  7470. bool parse_bson_array()
  7471. {
  7472. std::int32_t document_size{};
  7473. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  7474. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast<std::size_t>(-1))))
  7475. {
  7476. return false;
  7477. }
  7478. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true)))
  7479. {
  7480. return false;
  7481. }
  7482. return sax->end_array();
  7483. }
  7484. //////////
  7485. // CBOR //
  7486. //////////
  7487. /*!
  7488. @param[in] get_char whether a new character should be retrieved from the
  7489. input (true) or whether the last read character should
  7490. be considered instead (false)
  7491. @param[in] tag_handler how CBOR tags should be treated
  7492. @return whether a valid CBOR value was passed to the SAX parser
  7493. */
  7494. bool parse_cbor_internal(const bool get_char,
  7495. const cbor_tag_handler_t tag_handler)
  7496. {
  7497. switch (get_char ? get() : current)
  7498. {
  7499. // EOF
  7500. case std::char_traits<char_type>::eof():
  7501. return unexpect_eof(input_format_t::cbor, "value");
  7502. // Integer 0x00..0x17 (0..23)
  7503. case 0x00:
  7504. case 0x01:
  7505. case 0x02:
  7506. case 0x03:
  7507. case 0x04:
  7508. case 0x05:
  7509. case 0x06:
  7510. case 0x07:
  7511. case 0x08:
  7512. case 0x09:
  7513. case 0x0A:
  7514. case 0x0B:
  7515. case 0x0C:
  7516. case 0x0D:
  7517. case 0x0E:
  7518. case 0x0F:
  7519. case 0x10:
  7520. case 0x11:
  7521. case 0x12:
  7522. case 0x13:
  7523. case 0x14:
  7524. case 0x15:
  7525. case 0x16:
  7526. case 0x17:
  7527. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  7528. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  7529. {
  7530. std::uint8_t number{};
  7531. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7532. }
  7533. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  7534. {
  7535. std::uint16_t number{};
  7536. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7537. }
  7538. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  7539. {
  7540. std::uint32_t number{};
  7541. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7542. }
  7543. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  7544. {
  7545. std::uint64_t number{};
  7546. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7547. }
  7548. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  7549. case 0x20:
  7550. case 0x21:
  7551. case 0x22:
  7552. case 0x23:
  7553. case 0x24:
  7554. case 0x25:
  7555. case 0x26:
  7556. case 0x27:
  7557. case 0x28:
  7558. case 0x29:
  7559. case 0x2A:
  7560. case 0x2B:
  7561. case 0x2C:
  7562. case 0x2D:
  7563. case 0x2E:
  7564. case 0x2F:
  7565. case 0x30:
  7566. case 0x31:
  7567. case 0x32:
  7568. case 0x33:
  7569. case 0x34:
  7570. case 0x35:
  7571. case 0x36:
  7572. case 0x37:
  7573. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  7574. case 0x38: // Negative integer (one-byte uint8_t follows)
  7575. {
  7576. std::uint8_t number{};
  7577. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7578. }
  7579. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  7580. {
  7581. std::uint16_t number{};
  7582. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7583. }
  7584. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  7585. {
  7586. std::uint32_t number{};
  7587. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7588. }
  7589. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  7590. {
  7591. std::uint64_t number{};
  7592. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1)
  7593. - static_cast<number_integer_t>(number));
  7594. }
  7595. // Binary data (0x00..0x17 bytes follow)
  7596. case 0x40:
  7597. case 0x41:
  7598. case 0x42:
  7599. case 0x43:
  7600. case 0x44:
  7601. case 0x45:
  7602. case 0x46:
  7603. case 0x47:
  7604. case 0x48:
  7605. case 0x49:
  7606. case 0x4A:
  7607. case 0x4B:
  7608. case 0x4C:
  7609. case 0x4D:
  7610. case 0x4E:
  7611. case 0x4F:
  7612. case 0x50:
  7613. case 0x51:
  7614. case 0x52:
  7615. case 0x53:
  7616. case 0x54:
  7617. case 0x55:
  7618. case 0x56:
  7619. case 0x57:
  7620. case 0x58: // Binary data (one-byte uint8_t for n follows)
  7621. case 0x59: // Binary data (two-byte uint16_t for n follow)
  7622. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  7623. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  7624. case 0x5F: // Binary data (indefinite length)
  7625. {
  7626. binary_t b;
  7627. return get_cbor_binary(b) && sax->binary(b);
  7628. }
  7629. // UTF-8 string (0x00..0x17 bytes follow)
  7630. case 0x60:
  7631. case 0x61:
  7632. case 0x62:
  7633. case 0x63:
  7634. case 0x64:
  7635. case 0x65:
  7636. case 0x66:
  7637. case 0x67:
  7638. case 0x68:
  7639. case 0x69:
  7640. case 0x6A:
  7641. case 0x6B:
  7642. case 0x6C:
  7643. case 0x6D:
  7644. case 0x6E:
  7645. case 0x6F:
  7646. case 0x70:
  7647. case 0x71:
  7648. case 0x72:
  7649. case 0x73:
  7650. case 0x74:
  7651. case 0x75:
  7652. case 0x76:
  7653. case 0x77:
  7654. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  7655. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  7656. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  7657. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  7658. case 0x7F: // UTF-8 string (indefinite length)
  7659. {
  7660. string_t s;
  7661. return get_cbor_string(s) && sax->string(s);
  7662. }
  7663. // array (0x00..0x17 data items follow)
  7664. case 0x80:
  7665. case 0x81:
  7666. case 0x82:
  7667. case 0x83:
  7668. case 0x84:
  7669. case 0x85:
  7670. case 0x86:
  7671. case 0x87:
  7672. case 0x88:
  7673. case 0x89:
  7674. case 0x8A:
  7675. case 0x8B:
  7676. case 0x8C:
  7677. case 0x8D:
  7678. case 0x8E:
  7679. case 0x8F:
  7680. case 0x90:
  7681. case 0x91:
  7682. case 0x92:
  7683. case 0x93:
  7684. case 0x94:
  7685. case 0x95:
  7686. case 0x96:
  7687. case 0x97:
  7688. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler);
  7689. case 0x98: // array (one-byte uint8_t for n follows)
  7690. {
  7691. std::uint8_t len{};
  7692. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7693. }
  7694. case 0x99: // array (two-byte uint16_t for n follow)
  7695. {
  7696. std::uint16_t len{};
  7697. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7698. }
  7699. case 0x9A: // array (four-byte uint32_t for n follow)
  7700. {
  7701. std::uint32_t len{};
  7702. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7703. }
  7704. case 0x9B: // array (eight-byte uint64_t for n follow)
  7705. {
  7706. std::uint64_t len{};
  7707. return get_number(input_format_t::cbor, len) && get_cbor_array(detail::conditional_static_cast<std::size_t>(len), tag_handler);
  7708. }
  7709. case 0x9F: // array (indefinite length)
  7710. return get_cbor_array(static_cast<std::size_t>(-1), tag_handler);
  7711. // map (0x00..0x17 pairs of data items follow)
  7712. case 0xA0:
  7713. case 0xA1:
  7714. case 0xA2:
  7715. case 0xA3:
  7716. case 0xA4:
  7717. case 0xA5:
  7718. case 0xA6:
  7719. case 0xA7:
  7720. case 0xA8:
  7721. case 0xA9:
  7722. case 0xAA:
  7723. case 0xAB:
  7724. case 0xAC:
  7725. case 0xAD:
  7726. case 0xAE:
  7727. case 0xAF:
  7728. case 0xB0:
  7729. case 0xB1:
  7730. case 0xB2:
  7731. case 0xB3:
  7732. case 0xB4:
  7733. case 0xB5:
  7734. case 0xB6:
  7735. case 0xB7:
  7736. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler);
  7737. case 0xB8: // map (one-byte uint8_t for n follows)
  7738. {
  7739. std::uint8_t len{};
  7740. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7741. }
  7742. case 0xB9: // map (two-byte uint16_t for n follow)
  7743. {
  7744. std::uint16_t len{};
  7745. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7746. }
  7747. case 0xBA: // map (four-byte uint32_t for n follow)
  7748. {
  7749. std::uint32_t len{};
  7750. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7751. }
  7752. case 0xBB: // map (eight-byte uint64_t for n follow)
  7753. {
  7754. std::uint64_t len{};
  7755. return get_number(input_format_t::cbor, len) && get_cbor_object(detail::conditional_static_cast<std::size_t>(len), tag_handler);
  7756. }
  7757. case 0xBF: // map (indefinite length)
  7758. return get_cbor_object(static_cast<std::size_t>(-1), tag_handler);
  7759. case 0xC6: // tagged item
  7760. case 0xC7:
  7761. case 0xC8:
  7762. case 0xC9:
  7763. case 0xCA:
  7764. case 0xCB:
  7765. case 0xCC:
  7766. case 0xCD:
  7767. case 0xCE:
  7768. case 0xCF:
  7769. case 0xD0:
  7770. case 0xD1:
  7771. case 0xD2:
  7772. case 0xD3:
  7773. case 0xD4:
  7774. case 0xD8: // tagged item (1 bytes follow)
  7775. case 0xD9: // tagged item (2 bytes follow)
  7776. case 0xDA: // tagged item (4 bytes follow)
  7777. case 0xDB: // tagged item (8 bytes follow)
  7778. {
  7779. switch (tag_handler)
  7780. {
  7781. case cbor_tag_handler_t::error:
  7782. {
  7783. auto last_token = get_token_string();
  7784. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType()));
  7785. }
  7786. case cbor_tag_handler_t::ignore:
  7787. {
  7788. // ignore binary subtype
  7789. switch (current)
  7790. {
  7791. case 0xD8:
  7792. {
  7793. std::uint8_t subtype_to_ignore{};
  7794. get_number(input_format_t::cbor, subtype_to_ignore);
  7795. break;
  7796. }
  7797. case 0xD9:
  7798. {
  7799. std::uint16_t subtype_to_ignore{};
  7800. get_number(input_format_t::cbor, subtype_to_ignore);
  7801. break;
  7802. }
  7803. case 0xDA:
  7804. {
  7805. std::uint32_t subtype_to_ignore{};
  7806. get_number(input_format_t::cbor, subtype_to_ignore);
  7807. break;
  7808. }
  7809. case 0xDB:
  7810. {
  7811. std::uint64_t subtype_to_ignore{};
  7812. get_number(input_format_t::cbor, subtype_to_ignore);
  7813. break;
  7814. }
  7815. default:
  7816. break;
  7817. }
  7818. return parse_cbor_internal(true, tag_handler);
  7819. }
  7820. case cbor_tag_handler_t::store:
  7821. {
  7822. binary_t b;
  7823. // use binary subtype and store in binary container
  7824. switch (current)
  7825. {
  7826. case 0xD8:
  7827. {
  7828. std::uint8_t subtype{};
  7829. get_number(input_format_t::cbor, subtype);
  7830. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7831. break;
  7832. }
  7833. case 0xD9:
  7834. {
  7835. std::uint16_t subtype{};
  7836. get_number(input_format_t::cbor, subtype);
  7837. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7838. break;
  7839. }
  7840. case 0xDA:
  7841. {
  7842. std::uint32_t subtype{};
  7843. get_number(input_format_t::cbor, subtype);
  7844. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7845. break;
  7846. }
  7847. case 0xDB:
  7848. {
  7849. std::uint64_t subtype{};
  7850. get_number(input_format_t::cbor, subtype);
  7851. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7852. break;
  7853. }
  7854. default:
  7855. return parse_cbor_internal(true, tag_handler);
  7856. }
  7857. get();
  7858. return get_cbor_binary(b) && sax->binary(b);
  7859. }
  7860. default: // LCOV_EXCL_LINE
  7861. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  7862. return false; // LCOV_EXCL_LINE
  7863. }
  7864. }
  7865. case 0xF4: // false
  7866. return sax->boolean(false);
  7867. case 0xF5: // true
  7868. return sax->boolean(true);
  7869. case 0xF6: // null
  7870. return sax->null();
  7871. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  7872. {
  7873. const auto byte1_raw = get();
  7874. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
  7875. {
  7876. return false;
  7877. }
  7878. const auto byte2_raw = get();
  7879. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
  7880. {
  7881. return false;
  7882. }
  7883. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  7884. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  7885. // code from RFC 7049, Appendix D, Figure 3:
  7886. // As half-precision floating-point numbers were only added
  7887. // to IEEE 754 in 2008, today's programming platforms often
  7888. // still only have limited support for them. It is very
  7889. // easy to include at least decoding support for them even
  7890. // without such support. An example of a small decoder for
  7891. // half-precision floating-point numbers in the C language
  7892. // is shown in Fig. 3.
  7893. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  7894. const double val = [&half]
  7895. {
  7896. const int exp = (half >> 10u) & 0x1Fu;
  7897. const unsigned int mant = half & 0x3FFu;
  7898. JSON_ASSERT(0 <= exp&& exp <= 32);
  7899. JSON_ASSERT(mant <= 1024);
  7900. switch (exp)
  7901. {
  7902. case 0:
  7903. return std::ldexp(mant, -24);
  7904. case 31:
  7905. return (mant == 0)
  7906. ? std::numeric_limits<double>::infinity()
  7907. : std::numeric_limits<double>::quiet_NaN();
  7908. default:
  7909. return std::ldexp(mant + 1024, exp - 25);
  7910. }
  7911. }();
  7912. return sax->number_float((half & 0x8000u) != 0
  7913. ? static_cast<number_float_t>(-val)
  7914. : static_cast<number_float_t>(val), "");
  7915. }
  7916. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  7917. {
  7918. float number{};
  7919. return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
  7920. }
  7921. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  7922. {
  7923. double number{};
  7924. return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
  7925. }
  7926. default: // anything else (0xFF is handled inside the other types)
  7927. {
  7928. auto last_token = get_token_string();
  7929. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType()));
  7930. }
  7931. }
  7932. }
  7933. /*!
  7934. @brief reads a CBOR string
  7935. This function first reads starting bytes to determine the expected
  7936. string length and then copies this number of bytes into a string.
  7937. Additionally, CBOR's strings with indefinite lengths are supported.
  7938. @param[out] result created string
  7939. @return whether string creation completed
  7940. */
  7941. bool get_cbor_string(string_t& result)
  7942. {
  7943. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string")))
  7944. {
  7945. return false;
  7946. }
  7947. switch (current)
  7948. {
  7949. // UTF-8 string (0x00..0x17 bytes follow)
  7950. case 0x60:
  7951. case 0x61:
  7952. case 0x62:
  7953. case 0x63:
  7954. case 0x64:
  7955. case 0x65:
  7956. case 0x66:
  7957. case 0x67:
  7958. case 0x68:
  7959. case 0x69:
  7960. case 0x6A:
  7961. case 0x6B:
  7962. case 0x6C:
  7963. case 0x6D:
  7964. case 0x6E:
  7965. case 0x6F:
  7966. case 0x70:
  7967. case 0x71:
  7968. case 0x72:
  7969. case 0x73:
  7970. case 0x74:
  7971. case 0x75:
  7972. case 0x76:
  7973. case 0x77:
  7974. {
  7975. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  7976. }
  7977. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  7978. {
  7979. std::uint8_t len{};
  7980. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  7981. }
  7982. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  7983. {
  7984. std::uint16_t len{};
  7985. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  7986. }
  7987. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  7988. {
  7989. std::uint32_t len{};
  7990. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  7991. }
  7992. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  7993. {
  7994. std::uint64_t len{};
  7995. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  7996. }
  7997. case 0x7F: // UTF-8 string (indefinite length)
  7998. {
  7999. while (get() != 0xFF)
  8000. {
  8001. string_t chunk;
  8002. if (!get_cbor_string(chunk))
  8003. {
  8004. return false;
  8005. }
  8006. result.append(chunk);
  8007. }
  8008. return true;
  8009. }
  8010. default:
  8011. {
  8012. auto last_token = get_token_string();
  8013. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string"), BasicJsonType()));
  8014. }
  8015. }
  8016. }
  8017. /*!
  8018. @brief reads a CBOR byte array
  8019. This function first reads starting bytes to determine the expected
  8020. byte array length and then copies this number of bytes into the byte array.
  8021. Additionally, CBOR's byte arrays with indefinite lengths are supported.
  8022. @param[out] result created byte array
  8023. @return whether byte array creation completed
  8024. */
  8025. bool get_cbor_binary(binary_t& result)
  8026. {
  8027. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary")))
  8028. {
  8029. return false;
  8030. }
  8031. switch (current)
  8032. {
  8033. // Binary data (0x00..0x17 bytes follow)
  8034. case 0x40:
  8035. case 0x41:
  8036. case 0x42:
  8037. case 0x43:
  8038. case 0x44:
  8039. case 0x45:
  8040. case 0x46:
  8041. case 0x47:
  8042. case 0x48:
  8043. case 0x49:
  8044. case 0x4A:
  8045. case 0x4B:
  8046. case 0x4C:
  8047. case 0x4D:
  8048. case 0x4E:
  8049. case 0x4F:
  8050. case 0x50:
  8051. case 0x51:
  8052. case 0x52:
  8053. case 0x53:
  8054. case 0x54:
  8055. case 0x55:
  8056. case 0x56:
  8057. case 0x57:
  8058. {
  8059. return get_binary(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  8060. }
  8061. case 0x58: // Binary data (one-byte uint8_t for n follows)
  8062. {
  8063. std::uint8_t len{};
  8064. return get_number(input_format_t::cbor, len) &&
  8065. get_binary(input_format_t::cbor, len, result);
  8066. }
  8067. case 0x59: // Binary data (two-byte uint16_t for n follow)
  8068. {
  8069. std::uint16_t len{};
  8070. return get_number(input_format_t::cbor, len) &&
  8071. get_binary(input_format_t::cbor, len, result);
  8072. }
  8073. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  8074. {
  8075. std::uint32_t len{};
  8076. return get_number(input_format_t::cbor, len) &&
  8077. get_binary(input_format_t::cbor, len, result);
  8078. }
  8079. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  8080. {
  8081. std::uint64_t len{};
  8082. return get_number(input_format_t::cbor, len) &&
  8083. get_binary(input_format_t::cbor, len, result);
  8084. }
  8085. case 0x5F: // Binary data (indefinite length)
  8086. {
  8087. while (get() != 0xFF)
  8088. {
  8089. binary_t chunk;
  8090. if (!get_cbor_binary(chunk))
  8091. {
  8092. return false;
  8093. }
  8094. result.insert(result.end(), chunk.begin(), chunk.end());
  8095. }
  8096. return true;
  8097. }
  8098. default:
  8099. {
  8100. auto last_token = get_token_string();
  8101. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary"), BasicJsonType()));
  8102. }
  8103. }
  8104. }
  8105. /*!
  8106. @param[in] len the length of the array or static_cast<std::size_t>(-1) for an
  8107. array of indefinite size
  8108. @param[in] tag_handler how CBOR tags should be treated
  8109. @return whether array creation completed
  8110. */
  8111. bool get_cbor_array(const std::size_t len,
  8112. const cbor_tag_handler_t tag_handler)
  8113. {
  8114. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
  8115. {
  8116. return false;
  8117. }
  8118. if (len != static_cast<std::size_t>(-1))
  8119. {
  8120. for (std::size_t i = 0; i < len; ++i)
  8121. {
  8122. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  8123. {
  8124. return false;
  8125. }
  8126. }
  8127. }
  8128. else
  8129. {
  8130. while (get() != 0xFF)
  8131. {
  8132. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler)))
  8133. {
  8134. return false;
  8135. }
  8136. }
  8137. }
  8138. return sax->end_array();
  8139. }
  8140. /*!
  8141. @param[in] len the length of the object or static_cast<std::size_t>(-1) for an
  8142. object of indefinite size
  8143. @param[in] tag_handler how CBOR tags should be treated
  8144. @return whether object creation completed
  8145. */
  8146. bool get_cbor_object(const std::size_t len,
  8147. const cbor_tag_handler_t tag_handler)
  8148. {
  8149. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
  8150. {
  8151. return false;
  8152. }
  8153. if (len != 0)
  8154. {
  8155. string_t key;
  8156. if (len != static_cast<std::size_t>(-1))
  8157. {
  8158. for (std::size_t i = 0; i < len; ++i)
  8159. {
  8160. get();
  8161. if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
  8162. {
  8163. return false;
  8164. }
  8165. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  8166. {
  8167. return false;
  8168. }
  8169. key.clear();
  8170. }
  8171. }
  8172. else
  8173. {
  8174. while (get() != 0xFF)
  8175. {
  8176. if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
  8177. {
  8178. return false;
  8179. }
  8180. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  8181. {
  8182. return false;
  8183. }
  8184. key.clear();
  8185. }
  8186. }
  8187. }
  8188. return sax->end_object();
  8189. }
  8190. /////////////
  8191. // MsgPack //
  8192. /////////////
  8193. /*!
  8194. @return whether a valid MessagePack value was passed to the SAX parser
  8195. */
  8196. bool parse_msgpack_internal()
  8197. {
  8198. switch (get())
  8199. {
  8200. // EOF
  8201. case std::char_traits<char_type>::eof():
  8202. return unexpect_eof(input_format_t::msgpack, "value");
  8203. // positive fixint
  8204. case 0x00:
  8205. case 0x01:
  8206. case 0x02:
  8207. case 0x03:
  8208. case 0x04:
  8209. case 0x05:
  8210. case 0x06:
  8211. case 0x07:
  8212. case 0x08:
  8213. case 0x09:
  8214. case 0x0A:
  8215. case 0x0B:
  8216. case 0x0C:
  8217. case 0x0D:
  8218. case 0x0E:
  8219. case 0x0F:
  8220. case 0x10:
  8221. case 0x11:
  8222. case 0x12:
  8223. case 0x13:
  8224. case 0x14:
  8225. case 0x15:
  8226. case 0x16:
  8227. case 0x17:
  8228. case 0x18:
  8229. case 0x19:
  8230. case 0x1A:
  8231. case 0x1B:
  8232. case 0x1C:
  8233. case 0x1D:
  8234. case 0x1E:
  8235. case 0x1F:
  8236. case 0x20:
  8237. case 0x21:
  8238. case 0x22:
  8239. case 0x23:
  8240. case 0x24:
  8241. case 0x25:
  8242. case 0x26:
  8243. case 0x27:
  8244. case 0x28:
  8245. case 0x29:
  8246. case 0x2A:
  8247. case 0x2B:
  8248. case 0x2C:
  8249. case 0x2D:
  8250. case 0x2E:
  8251. case 0x2F:
  8252. case 0x30:
  8253. case 0x31:
  8254. case 0x32:
  8255. case 0x33:
  8256. case 0x34:
  8257. case 0x35:
  8258. case 0x36:
  8259. case 0x37:
  8260. case 0x38:
  8261. case 0x39:
  8262. case 0x3A:
  8263. case 0x3B:
  8264. case 0x3C:
  8265. case 0x3D:
  8266. case 0x3E:
  8267. case 0x3F:
  8268. case 0x40:
  8269. case 0x41:
  8270. case 0x42:
  8271. case 0x43:
  8272. case 0x44:
  8273. case 0x45:
  8274. case 0x46:
  8275. case 0x47:
  8276. case 0x48:
  8277. case 0x49:
  8278. case 0x4A:
  8279. case 0x4B:
  8280. case 0x4C:
  8281. case 0x4D:
  8282. case 0x4E:
  8283. case 0x4F:
  8284. case 0x50:
  8285. case 0x51:
  8286. case 0x52:
  8287. case 0x53:
  8288. case 0x54:
  8289. case 0x55:
  8290. case 0x56:
  8291. case 0x57:
  8292. case 0x58:
  8293. case 0x59:
  8294. case 0x5A:
  8295. case 0x5B:
  8296. case 0x5C:
  8297. case 0x5D:
  8298. case 0x5E:
  8299. case 0x5F:
  8300. case 0x60:
  8301. case 0x61:
  8302. case 0x62:
  8303. case 0x63:
  8304. case 0x64:
  8305. case 0x65:
  8306. case 0x66:
  8307. case 0x67:
  8308. case 0x68:
  8309. case 0x69:
  8310. case 0x6A:
  8311. case 0x6B:
  8312. case 0x6C:
  8313. case 0x6D:
  8314. case 0x6E:
  8315. case 0x6F:
  8316. case 0x70:
  8317. case 0x71:
  8318. case 0x72:
  8319. case 0x73:
  8320. case 0x74:
  8321. case 0x75:
  8322. case 0x76:
  8323. case 0x77:
  8324. case 0x78:
  8325. case 0x79:
  8326. case 0x7A:
  8327. case 0x7B:
  8328. case 0x7C:
  8329. case 0x7D:
  8330. case 0x7E:
  8331. case 0x7F:
  8332. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  8333. // fixmap
  8334. case 0x80:
  8335. case 0x81:
  8336. case 0x82:
  8337. case 0x83:
  8338. case 0x84:
  8339. case 0x85:
  8340. case 0x86:
  8341. case 0x87:
  8342. case 0x88:
  8343. case 0x89:
  8344. case 0x8A:
  8345. case 0x8B:
  8346. case 0x8C:
  8347. case 0x8D:
  8348. case 0x8E:
  8349. case 0x8F:
  8350. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  8351. // fixarray
  8352. case 0x90:
  8353. case 0x91:
  8354. case 0x92:
  8355. case 0x93:
  8356. case 0x94:
  8357. case 0x95:
  8358. case 0x96:
  8359. case 0x97:
  8360. case 0x98:
  8361. case 0x99:
  8362. case 0x9A:
  8363. case 0x9B:
  8364. case 0x9C:
  8365. case 0x9D:
  8366. case 0x9E:
  8367. case 0x9F:
  8368. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  8369. // fixstr
  8370. case 0xA0:
  8371. case 0xA1:
  8372. case 0xA2:
  8373. case 0xA3:
  8374. case 0xA4:
  8375. case 0xA5:
  8376. case 0xA6:
  8377. case 0xA7:
  8378. case 0xA8:
  8379. case 0xA9:
  8380. case 0xAA:
  8381. case 0xAB:
  8382. case 0xAC:
  8383. case 0xAD:
  8384. case 0xAE:
  8385. case 0xAF:
  8386. case 0xB0:
  8387. case 0xB1:
  8388. case 0xB2:
  8389. case 0xB3:
  8390. case 0xB4:
  8391. case 0xB5:
  8392. case 0xB6:
  8393. case 0xB7:
  8394. case 0xB8:
  8395. case 0xB9:
  8396. case 0xBA:
  8397. case 0xBB:
  8398. case 0xBC:
  8399. case 0xBD:
  8400. case 0xBE:
  8401. case 0xBF:
  8402. case 0xD9: // str 8
  8403. case 0xDA: // str 16
  8404. case 0xDB: // str 32
  8405. {
  8406. string_t s;
  8407. return get_msgpack_string(s) && sax->string(s);
  8408. }
  8409. case 0xC0: // nil
  8410. return sax->null();
  8411. case 0xC2: // false
  8412. return sax->boolean(false);
  8413. case 0xC3: // true
  8414. return sax->boolean(true);
  8415. case 0xC4: // bin 8
  8416. case 0xC5: // bin 16
  8417. case 0xC6: // bin 32
  8418. case 0xC7: // ext 8
  8419. case 0xC8: // ext 16
  8420. case 0xC9: // ext 32
  8421. case 0xD4: // fixext 1
  8422. case 0xD5: // fixext 2
  8423. case 0xD6: // fixext 4
  8424. case 0xD7: // fixext 8
  8425. case 0xD8: // fixext 16
  8426. {
  8427. binary_t b;
  8428. return get_msgpack_binary(b) && sax->binary(b);
  8429. }
  8430. case 0xCA: // float 32
  8431. {
  8432. float number{};
  8433. return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8434. }
  8435. case 0xCB: // float 64
  8436. {
  8437. double number{};
  8438. return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8439. }
  8440. case 0xCC: // uint 8
  8441. {
  8442. std::uint8_t number{};
  8443. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8444. }
  8445. case 0xCD: // uint 16
  8446. {
  8447. std::uint16_t number{};
  8448. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8449. }
  8450. case 0xCE: // uint 32
  8451. {
  8452. std::uint32_t number{};
  8453. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8454. }
  8455. case 0xCF: // uint 64
  8456. {
  8457. std::uint64_t number{};
  8458. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8459. }
  8460. case 0xD0: // int 8
  8461. {
  8462. std::int8_t number{};
  8463. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8464. }
  8465. case 0xD1: // int 16
  8466. {
  8467. std::int16_t number{};
  8468. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8469. }
  8470. case 0xD2: // int 32
  8471. {
  8472. std::int32_t number{};
  8473. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8474. }
  8475. case 0xD3: // int 64
  8476. {
  8477. std::int64_t number{};
  8478. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8479. }
  8480. case 0xDC: // array 16
  8481. {
  8482. std::uint16_t len{};
  8483. return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
  8484. }
  8485. case 0xDD: // array 32
  8486. {
  8487. std::uint32_t len{};
  8488. return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
  8489. }
  8490. case 0xDE: // map 16
  8491. {
  8492. std::uint16_t len{};
  8493. return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
  8494. }
  8495. case 0xDF: // map 32
  8496. {
  8497. std::uint32_t len{};
  8498. return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
  8499. }
  8500. // negative fixint
  8501. case 0xE0:
  8502. case 0xE1:
  8503. case 0xE2:
  8504. case 0xE3:
  8505. case 0xE4:
  8506. case 0xE5:
  8507. case 0xE6:
  8508. case 0xE7:
  8509. case 0xE8:
  8510. case 0xE9:
  8511. case 0xEA:
  8512. case 0xEB:
  8513. case 0xEC:
  8514. case 0xED:
  8515. case 0xEE:
  8516. case 0xEF:
  8517. case 0xF0:
  8518. case 0xF1:
  8519. case 0xF2:
  8520. case 0xF3:
  8521. case 0xF4:
  8522. case 0xF5:
  8523. case 0xF6:
  8524. case 0xF7:
  8525. case 0xF8:
  8526. case 0xF9:
  8527. case 0xFA:
  8528. case 0xFB:
  8529. case 0xFC:
  8530. case 0xFD:
  8531. case 0xFE:
  8532. case 0xFF:
  8533. return sax->number_integer(static_cast<std::int8_t>(current));
  8534. default: // anything else
  8535. {
  8536. auto last_token = get_token_string();
  8537. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value"), BasicJsonType()));
  8538. }
  8539. }
  8540. }
  8541. /*!
  8542. @brief reads a MessagePack string
  8543. This function first reads starting bytes to determine the expected
  8544. string length and then copies this number of bytes into a string.
  8545. @param[out] result created string
  8546. @return whether string creation completed
  8547. */
  8548. bool get_msgpack_string(string_t& result)
  8549. {
  8550. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string")))
  8551. {
  8552. return false;
  8553. }
  8554. switch (current)
  8555. {
  8556. // fixstr
  8557. case 0xA0:
  8558. case 0xA1:
  8559. case 0xA2:
  8560. case 0xA3:
  8561. case 0xA4:
  8562. case 0xA5:
  8563. case 0xA6:
  8564. case 0xA7:
  8565. case 0xA8:
  8566. case 0xA9:
  8567. case 0xAA:
  8568. case 0xAB:
  8569. case 0xAC:
  8570. case 0xAD:
  8571. case 0xAE:
  8572. case 0xAF:
  8573. case 0xB0:
  8574. case 0xB1:
  8575. case 0xB2:
  8576. case 0xB3:
  8577. case 0xB4:
  8578. case 0xB5:
  8579. case 0xB6:
  8580. case 0xB7:
  8581. case 0xB8:
  8582. case 0xB9:
  8583. case 0xBA:
  8584. case 0xBB:
  8585. case 0xBC:
  8586. case 0xBD:
  8587. case 0xBE:
  8588. case 0xBF:
  8589. {
  8590. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  8591. }
  8592. case 0xD9: // str 8
  8593. {
  8594. std::uint8_t len{};
  8595. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8596. }
  8597. case 0xDA: // str 16
  8598. {
  8599. std::uint16_t len{};
  8600. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8601. }
  8602. case 0xDB: // str 32
  8603. {
  8604. std::uint32_t len{};
  8605. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8606. }
  8607. default:
  8608. {
  8609. auto last_token = get_token_string();
  8610. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string"), BasicJsonType()));
  8611. }
  8612. }
  8613. }
  8614. /*!
  8615. @brief reads a MessagePack byte array
  8616. This function first reads starting bytes to determine the expected
  8617. byte array length and then copies this number of bytes into a byte array.
  8618. @param[out] result created byte array
  8619. @return whether byte array creation completed
  8620. */
  8621. bool get_msgpack_binary(binary_t& result)
  8622. {
  8623. // helper function to set the subtype
  8624. auto assign_and_return_true = [&result](std::int8_t subtype)
  8625. {
  8626. result.set_subtype(static_cast<std::uint8_t>(subtype));
  8627. return true;
  8628. };
  8629. switch (current)
  8630. {
  8631. case 0xC4: // bin 8
  8632. {
  8633. std::uint8_t len{};
  8634. return get_number(input_format_t::msgpack, len) &&
  8635. get_binary(input_format_t::msgpack, len, result);
  8636. }
  8637. case 0xC5: // bin 16
  8638. {
  8639. std::uint16_t len{};
  8640. return get_number(input_format_t::msgpack, len) &&
  8641. get_binary(input_format_t::msgpack, len, result);
  8642. }
  8643. case 0xC6: // bin 32
  8644. {
  8645. std::uint32_t len{};
  8646. return get_number(input_format_t::msgpack, len) &&
  8647. get_binary(input_format_t::msgpack, len, result);
  8648. }
  8649. case 0xC7: // ext 8
  8650. {
  8651. std::uint8_t len{};
  8652. std::int8_t subtype{};
  8653. return get_number(input_format_t::msgpack, len) &&
  8654. get_number(input_format_t::msgpack, subtype) &&
  8655. get_binary(input_format_t::msgpack, len, result) &&
  8656. assign_and_return_true(subtype);
  8657. }
  8658. case 0xC8: // ext 16
  8659. {
  8660. std::uint16_t len{};
  8661. std::int8_t subtype{};
  8662. return get_number(input_format_t::msgpack, len) &&
  8663. get_number(input_format_t::msgpack, subtype) &&
  8664. get_binary(input_format_t::msgpack, len, result) &&
  8665. assign_and_return_true(subtype);
  8666. }
  8667. case 0xC9: // ext 32
  8668. {
  8669. std::uint32_t len{};
  8670. std::int8_t subtype{};
  8671. return get_number(input_format_t::msgpack, len) &&
  8672. get_number(input_format_t::msgpack, subtype) &&
  8673. get_binary(input_format_t::msgpack, len, result) &&
  8674. assign_and_return_true(subtype);
  8675. }
  8676. case 0xD4: // fixext 1
  8677. {
  8678. std::int8_t subtype{};
  8679. return get_number(input_format_t::msgpack, subtype) &&
  8680. get_binary(input_format_t::msgpack, 1, result) &&
  8681. assign_and_return_true(subtype);
  8682. }
  8683. case 0xD5: // fixext 2
  8684. {
  8685. std::int8_t subtype{};
  8686. return get_number(input_format_t::msgpack, subtype) &&
  8687. get_binary(input_format_t::msgpack, 2, result) &&
  8688. assign_and_return_true(subtype);
  8689. }
  8690. case 0xD6: // fixext 4
  8691. {
  8692. std::int8_t subtype{};
  8693. return get_number(input_format_t::msgpack, subtype) &&
  8694. get_binary(input_format_t::msgpack, 4, result) &&
  8695. assign_and_return_true(subtype);
  8696. }
  8697. case 0xD7: // fixext 8
  8698. {
  8699. std::int8_t subtype{};
  8700. return get_number(input_format_t::msgpack, subtype) &&
  8701. get_binary(input_format_t::msgpack, 8, result) &&
  8702. assign_and_return_true(subtype);
  8703. }
  8704. case 0xD8: // fixext 16
  8705. {
  8706. std::int8_t subtype{};
  8707. return get_number(input_format_t::msgpack, subtype) &&
  8708. get_binary(input_format_t::msgpack, 16, result) &&
  8709. assign_and_return_true(subtype);
  8710. }
  8711. default: // LCOV_EXCL_LINE
  8712. return false; // LCOV_EXCL_LINE
  8713. }
  8714. }
  8715. /*!
  8716. @param[in] len the length of the array
  8717. @return whether array creation completed
  8718. */
  8719. bool get_msgpack_array(const std::size_t len)
  8720. {
  8721. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
  8722. {
  8723. return false;
  8724. }
  8725. for (std::size_t i = 0; i < len; ++i)
  8726. {
  8727. if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
  8728. {
  8729. return false;
  8730. }
  8731. }
  8732. return sax->end_array();
  8733. }
  8734. /*!
  8735. @param[in] len the length of the object
  8736. @return whether object creation completed
  8737. */
  8738. bool get_msgpack_object(const std::size_t len)
  8739. {
  8740. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
  8741. {
  8742. return false;
  8743. }
  8744. string_t key;
  8745. for (std::size_t i = 0; i < len; ++i)
  8746. {
  8747. get();
  8748. if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key)))
  8749. {
  8750. return false;
  8751. }
  8752. if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
  8753. {
  8754. return false;
  8755. }
  8756. key.clear();
  8757. }
  8758. return sax->end_object();
  8759. }
  8760. ////////////
  8761. // UBJSON //
  8762. ////////////
  8763. /*!
  8764. @param[in] get_char whether a new character should be retrieved from the
  8765. input (true, default) or whether the last read
  8766. character should be considered instead
  8767. @return whether a valid UBJSON value was passed to the SAX parser
  8768. */
  8769. bool parse_ubjson_internal(const bool get_char = true)
  8770. {
  8771. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  8772. }
  8773. /*!
  8774. @brief reads a UBJSON string
  8775. This function is either called after reading the 'S' byte explicitly
  8776. indicating a string, or in case of an object key where the 'S' byte can be
  8777. left out.
  8778. @param[out] result created string
  8779. @param[in] get_char whether a new character should be retrieved from the
  8780. input (true, default) or whether the last read
  8781. character should be considered instead
  8782. @return whether string creation completed
  8783. */
  8784. bool get_ubjson_string(string_t& result, const bool get_char = true)
  8785. {
  8786. if (get_char)
  8787. {
  8788. get(); // TODO(niels): may we ignore N here?
  8789. }
  8790. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
  8791. {
  8792. return false;
  8793. }
  8794. switch (current)
  8795. {
  8796. case 'U':
  8797. {
  8798. std::uint8_t len{};
  8799. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8800. }
  8801. case 'i':
  8802. {
  8803. std::int8_t len{};
  8804. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8805. }
  8806. case 'I':
  8807. {
  8808. std::int16_t len{};
  8809. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8810. }
  8811. case 'l':
  8812. {
  8813. std::int32_t len{};
  8814. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8815. }
  8816. case 'L':
  8817. {
  8818. std::int64_t len{};
  8819. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8820. }
  8821. default:
  8822. auto last_token = get_token_string();
  8823. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string"), BasicJsonType()));
  8824. }
  8825. }
  8826. /*!
  8827. @param[out] result determined size
  8828. @return whether size determination completed
  8829. */
  8830. bool get_ubjson_size_value(std::size_t& result)
  8831. {
  8832. switch (get_ignore_noop())
  8833. {
  8834. case 'U':
  8835. {
  8836. std::uint8_t number{};
  8837. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8838. {
  8839. return false;
  8840. }
  8841. result = static_cast<std::size_t>(number);
  8842. return true;
  8843. }
  8844. case 'i':
  8845. {
  8846. std::int8_t number{};
  8847. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8848. {
  8849. return false;
  8850. }
  8851. result = static_cast<std::size_t>(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char
  8852. return true;
  8853. }
  8854. case 'I':
  8855. {
  8856. std::int16_t number{};
  8857. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8858. {
  8859. return false;
  8860. }
  8861. result = static_cast<std::size_t>(number);
  8862. return true;
  8863. }
  8864. case 'l':
  8865. {
  8866. std::int32_t number{};
  8867. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8868. {
  8869. return false;
  8870. }
  8871. result = static_cast<std::size_t>(number);
  8872. return true;
  8873. }
  8874. case 'L':
  8875. {
  8876. std::int64_t number{};
  8877. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8878. {
  8879. return false;
  8880. }
  8881. result = static_cast<std::size_t>(number);
  8882. return true;
  8883. }
  8884. default:
  8885. {
  8886. auto last_token = get_token_string();
  8887. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size"), BasicJsonType()));
  8888. }
  8889. }
  8890. }
  8891. /*!
  8892. @brief determine the type and size for a container
  8893. In the optimized UBJSON format, a type and a size can be provided to allow
  8894. for a more compact representation.
  8895. @param[out] result pair of the size and the type
  8896. @return whether pair creation completed
  8897. */
  8898. bool get_ubjson_size_type(std::pair<std::size_t, char_int_type>& result)
  8899. {
  8900. result.first = string_t::npos; // size
  8901. result.second = 0; // type
  8902. get_ignore_noop();
  8903. if (current == '$')
  8904. {
  8905. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  8906. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type")))
  8907. {
  8908. return false;
  8909. }
  8910. get_ignore_noop();
  8911. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  8912. {
  8913. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
  8914. {
  8915. return false;
  8916. }
  8917. auto last_token = get_token_string();
  8918. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size"), BasicJsonType()));
  8919. }
  8920. return get_ubjson_size_value(result.first);
  8921. }
  8922. if (current == '#')
  8923. {
  8924. return get_ubjson_size_value(result.first);
  8925. }
  8926. return true;
  8927. }
  8928. /*!
  8929. @param prefix the previously read or set type prefix
  8930. @return whether value creation completed
  8931. */
  8932. bool get_ubjson_value(const char_int_type prefix)
  8933. {
  8934. switch (prefix)
  8935. {
  8936. case std::char_traits<char_type>::eof(): // EOF
  8937. return unexpect_eof(input_format_t::ubjson, "value");
  8938. case 'T': // true
  8939. return sax->boolean(true);
  8940. case 'F': // false
  8941. return sax->boolean(false);
  8942. case 'Z': // null
  8943. return sax->null();
  8944. case 'U':
  8945. {
  8946. std::uint8_t number{};
  8947. return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number);
  8948. }
  8949. case 'i':
  8950. {
  8951. std::int8_t number{};
  8952. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  8953. }
  8954. case 'I':
  8955. {
  8956. std::int16_t number{};
  8957. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  8958. }
  8959. case 'l':
  8960. {
  8961. std::int32_t number{};
  8962. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  8963. }
  8964. case 'L':
  8965. {
  8966. std::int64_t number{};
  8967. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  8968. }
  8969. case 'd':
  8970. {
  8971. float number{};
  8972. return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8973. }
  8974. case 'D':
  8975. {
  8976. double number{};
  8977. return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8978. }
  8979. case 'H':
  8980. {
  8981. return get_ubjson_high_precision_number();
  8982. }
  8983. case 'C': // char
  8984. {
  8985. get();
  8986. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char")))
  8987. {
  8988. return false;
  8989. }
  8990. if (JSON_HEDLEY_UNLIKELY(current > 127))
  8991. {
  8992. auto last_token = get_token_string();
  8993. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char"), BasicJsonType()));
  8994. }
  8995. string_t s(1, static_cast<typename string_t::value_type>(current));
  8996. return sax->string(s);
  8997. }
  8998. case 'S': // string
  8999. {
  9000. string_t s;
  9001. return get_ubjson_string(s) && sax->string(s);
  9002. }
  9003. case '[': // array
  9004. return get_ubjson_array();
  9005. case '{': // object
  9006. return get_ubjson_object();
  9007. default: // anything else
  9008. {
  9009. auto last_token = get_token_string();
  9010. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value"), BasicJsonType()));
  9011. }
  9012. }
  9013. }
  9014. /*!
  9015. @return whether array creation completed
  9016. */
  9017. bool get_ubjson_array()
  9018. {
  9019. std::pair<std::size_t, char_int_type> size_and_type;
  9020. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
  9021. {
  9022. return false;
  9023. }
  9024. if (size_and_type.first != string_t::npos)
  9025. {
  9026. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first)))
  9027. {
  9028. return false;
  9029. }
  9030. if (size_and_type.second != 0)
  9031. {
  9032. if (size_and_type.second != 'N')
  9033. {
  9034. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9035. {
  9036. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
  9037. {
  9038. return false;
  9039. }
  9040. }
  9041. }
  9042. }
  9043. else
  9044. {
  9045. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9046. {
  9047. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  9048. {
  9049. return false;
  9050. }
  9051. }
  9052. }
  9053. }
  9054. else
  9055. {
  9056. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast<std::size_t>(-1))))
  9057. {
  9058. return false;
  9059. }
  9060. while (current != ']')
  9061. {
  9062. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false)))
  9063. {
  9064. return false;
  9065. }
  9066. get_ignore_noop();
  9067. }
  9068. }
  9069. return sax->end_array();
  9070. }
  9071. /*!
  9072. @return whether object creation completed
  9073. */
  9074. bool get_ubjson_object()
  9075. {
  9076. std::pair<std::size_t, char_int_type> size_and_type;
  9077. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
  9078. {
  9079. return false;
  9080. }
  9081. string_t key;
  9082. if (size_and_type.first != string_t::npos)
  9083. {
  9084. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first)))
  9085. {
  9086. return false;
  9087. }
  9088. if (size_and_type.second != 0)
  9089. {
  9090. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9091. {
  9092. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
  9093. {
  9094. return false;
  9095. }
  9096. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
  9097. {
  9098. return false;
  9099. }
  9100. key.clear();
  9101. }
  9102. }
  9103. else
  9104. {
  9105. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9106. {
  9107. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
  9108. {
  9109. return false;
  9110. }
  9111. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  9112. {
  9113. return false;
  9114. }
  9115. key.clear();
  9116. }
  9117. }
  9118. }
  9119. else
  9120. {
  9121. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast<std::size_t>(-1))))
  9122. {
  9123. return false;
  9124. }
  9125. while (current != '}')
  9126. {
  9127. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key)))
  9128. {
  9129. return false;
  9130. }
  9131. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  9132. {
  9133. return false;
  9134. }
  9135. get_ignore_noop();
  9136. key.clear();
  9137. }
  9138. }
  9139. return sax->end_object();
  9140. }
  9141. // Note, no reader for UBJSON binary types is implemented because they do
  9142. // not exist
  9143. bool get_ubjson_high_precision_number()
  9144. {
  9145. // get size of following number string
  9146. std::size_t size{};
  9147. auto res = get_ubjson_size_value(size);
  9148. if (JSON_HEDLEY_UNLIKELY(!res))
  9149. {
  9150. return res;
  9151. }
  9152. // get number string
  9153. std::vector<char> number_vector;
  9154. for (std::size_t i = 0; i < size; ++i)
  9155. {
  9156. get();
  9157. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number")))
  9158. {
  9159. return false;
  9160. }
  9161. number_vector.push_back(static_cast<char>(current));
  9162. }
  9163. // parse number string
  9164. using ia_type = decltype(detail::input_adapter(number_vector));
  9165. auto number_lexer = detail::lexer<BasicJsonType, ia_type>(detail::input_adapter(number_vector), false);
  9166. const auto result_number = number_lexer.scan();
  9167. const auto number_string = number_lexer.get_token_string();
  9168. const auto result_remainder = number_lexer.scan();
  9169. using token_type = typename detail::lexer_base<BasicJsonType>::token_type;
  9170. if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input))
  9171. {
  9172. return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType()));
  9173. }
  9174. switch (result_number)
  9175. {
  9176. case token_type::value_integer:
  9177. return sax->number_integer(number_lexer.get_number_integer());
  9178. case token_type::value_unsigned:
  9179. return sax->number_unsigned(number_lexer.get_number_unsigned());
  9180. case token_type::value_float:
  9181. return sax->number_float(number_lexer.get_number_float(), std::move(number_string));
  9182. case token_type::uninitialized:
  9183. case token_type::literal_true:
  9184. case token_type::literal_false:
  9185. case token_type::literal_null:
  9186. case token_type::value_string:
  9187. case token_type::begin_array:
  9188. case token_type::begin_object:
  9189. case token_type::end_array:
  9190. case token_type::end_object:
  9191. case token_type::name_separator:
  9192. case token_type::value_separator:
  9193. case token_type::parse_error:
  9194. case token_type::end_of_input:
  9195. case token_type::literal_or_value:
  9196. default:
  9197. return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType()));
  9198. }
  9199. }
  9200. ///////////////////////
  9201. // Utility functions //
  9202. ///////////////////////
  9203. /*!
  9204. @brief get next character from the input
  9205. This function provides the interface to the used input adapter. It does
  9206. not throw in case the input reached EOF, but returns a -'ve valued
  9207. `std::char_traits<char_type>::eof()` in that case.
  9208. @return character read from the input
  9209. */
  9210. char_int_type get()
  9211. {
  9212. ++chars_read;
  9213. return current = ia.get_character();
  9214. }
  9215. /*!
  9216. @return character read from the input after ignoring all 'N' entries
  9217. */
  9218. char_int_type get_ignore_noop()
  9219. {
  9220. do
  9221. {
  9222. get();
  9223. }
  9224. while (current == 'N');
  9225. return current;
  9226. }
  9227. /*
  9228. @brief read a number from the input
  9229. @tparam NumberType the type of the number
  9230. @param[in] format the current format (for diagnostics)
  9231. @param[out] result number of type @a NumberType
  9232. @return whether conversion completed
  9233. @note This function needs to respect the system's endianness, because
  9234. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  9235. (big endian) and therefore need reordering on little endian systems.
  9236. */
  9237. template<typename NumberType, bool InputIsLittleEndian = false>
  9238. bool get_number(const input_format_t format, NumberType& result)
  9239. {
  9240. // step 1: read input into array with system's byte order
  9241. std::array<std::uint8_t, sizeof(NumberType)> vec{};
  9242. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  9243. {
  9244. get();
  9245. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number")))
  9246. {
  9247. return false;
  9248. }
  9249. // reverse byte order prior to conversion if necessary
  9250. if (is_little_endian != InputIsLittleEndian)
  9251. {
  9252. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  9253. }
  9254. else
  9255. {
  9256. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  9257. }
  9258. }
  9259. // step 2: convert array into number of type T and return
  9260. std::memcpy(&result, vec.data(), sizeof(NumberType));
  9261. return true;
  9262. }
  9263. /*!
  9264. @brief create a string by reading characters from the input
  9265. @tparam NumberType the type of the number
  9266. @param[in] format the current format (for diagnostics)
  9267. @param[in] len number of characters to read
  9268. @param[out] result string created by reading @a len bytes
  9269. @return whether string creation completed
  9270. @note We can not reserve @a len bytes for the result, because @a len
  9271. may be too large. Usually, @ref unexpect_eof() detects the end of
  9272. the input before we run out of string memory.
  9273. */
  9274. template<typename NumberType>
  9275. bool get_string(const input_format_t format,
  9276. const NumberType len,
  9277. string_t& result)
  9278. {
  9279. bool success = true;
  9280. for (NumberType i = 0; i < len; i++)
  9281. {
  9282. get();
  9283. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string")))
  9284. {
  9285. success = false;
  9286. break;
  9287. }
  9288. result.push_back(static_cast<typename string_t::value_type>(current));
  9289. }
  9290. return success;
  9291. }
  9292. /*!
  9293. @brief create a byte array by reading bytes from the input
  9294. @tparam NumberType the type of the number
  9295. @param[in] format the current format (for diagnostics)
  9296. @param[in] len number of bytes to read
  9297. @param[out] result byte array created by reading @a len bytes
  9298. @return whether byte array creation completed
  9299. @note We can not reserve @a len bytes for the result, because @a len
  9300. may be too large. Usually, @ref unexpect_eof() detects the end of
  9301. the input before we run out of memory.
  9302. */
  9303. template<typename NumberType>
  9304. bool get_binary(const input_format_t format,
  9305. const NumberType len,
  9306. binary_t& result)
  9307. {
  9308. bool success = true;
  9309. for (NumberType i = 0; i < len; i++)
  9310. {
  9311. get();
  9312. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary")))
  9313. {
  9314. success = false;
  9315. break;
  9316. }
  9317. result.push_back(static_cast<std::uint8_t>(current));
  9318. }
  9319. return success;
  9320. }
  9321. /*!
  9322. @param[in] format the current format (for diagnostics)
  9323. @param[in] context further context information (for diagnostics)
  9324. @return whether the last read character is not EOF
  9325. */
  9326. JSON_HEDLEY_NON_NULL(3)
  9327. bool unexpect_eof(const input_format_t format, const char* context) const
  9328. {
  9329. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char_type>::eof()))
  9330. {
  9331. return sax->parse_error(chars_read, "<end of file>",
  9332. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), BasicJsonType()));
  9333. }
  9334. return true;
  9335. }
  9336. /*!
  9337. @return a string representation of the last read byte
  9338. */
  9339. std::string get_token_string() const
  9340. {
  9341. std::array<char, 3> cr{{}};
  9342. static_cast<void>((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  9343. return std::string{cr.data()};
  9344. }
  9345. /*!
  9346. @param[in] format the current format
  9347. @param[in] detail a detailed error message
  9348. @param[in] context further context information
  9349. @return a message string to use in the parse_error exceptions
  9350. */
  9351. std::string exception_message(const input_format_t format,
  9352. const std::string& detail,
  9353. const std::string& context) const
  9354. {
  9355. std::string error_msg = "syntax error while parsing ";
  9356. switch (format)
  9357. {
  9358. case input_format_t::cbor:
  9359. error_msg += "CBOR";
  9360. break;
  9361. case input_format_t::msgpack:
  9362. error_msg += "MessagePack";
  9363. break;
  9364. case input_format_t::ubjson:
  9365. error_msg += "UBJSON";
  9366. break;
  9367. case input_format_t::bson:
  9368. error_msg += "BSON";
  9369. break;
  9370. case input_format_t::json: // LCOV_EXCL_LINE
  9371. default: // LCOV_EXCL_LINE
  9372. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  9373. }
  9374. return error_msg + " " + context + ": " + detail;
  9375. }
  9376. private:
  9377. /// input adapter
  9378. InputAdapterType ia;
  9379. /// the current character
  9380. char_int_type current = std::char_traits<char_type>::eof();
  9381. /// the number of characters read
  9382. std::size_t chars_read = 0;
  9383. /// whether we can assume little endianness
  9384. const bool is_little_endian = little_endianness();
  9385. /// the SAX parser
  9386. json_sax_t* sax = nullptr;
  9387. };
  9388. } // namespace detail
  9389. } // namespace nlohmann
  9390. // #include <nlohmann/detail/input/input_adapters.hpp>
  9391. // #include <nlohmann/detail/input/lexer.hpp>
  9392. // #include <nlohmann/detail/input/parser.hpp>
  9393. #include <cmath> // isfinite
  9394. #include <cstdint> // uint8_t
  9395. #include <functional> // function
  9396. #include <string> // string
  9397. #include <utility> // move
  9398. #include <vector> // vector
  9399. // #include <nlohmann/detail/exceptions.hpp>
  9400. // #include <nlohmann/detail/input/input_adapters.hpp>
  9401. // #include <nlohmann/detail/input/json_sax.hpp>
  9402. // #include <nlohmann/detail/input/lexer.hpp>
  9403. // #include <nlohmann/detail/macro_scope.hpp>
  9404. // #include <nlohmann/detail/meta/is_sax.hpp>
  9405. // #include <nlohmann/detail/value_t.hpp>
  9406. namespace nlohmann
  9407. {
  9408. namespace detail
  9409. {
  9410. ////////////
  9411. // parser //
  9412. ////////////
  9413. enum class parse_event_t : std::uint8_t
  9414. {
  9415. /// the parser read `{` and started to process a JSON object
  9416. object_start,
  9417. /// the parser read `}` and finished processing a JSON object
  9418. object_end,
  9419. /// the parser read `[` and started to process a JSON array
  9420. array_start,
  9421. /// the parser read `]` and finished processing a JSON array
  9422. array_end,
  9423. /// the parser read a key of a value in an object
  9424. key,
  9425. /// the parser finished reading a JSON value
  9426. value
  9427. };
  9428. template<typename BasicJsonType>
  9429. using parser_callback_t =
  9430. std::function<bool(int /*depth*/, parse_event_t /*event*/, BasicJsonType& /*parsed*/)>;
  9431. /*!
  9432. @brief syntax analysis
  9433. This class implements a recursive descent parser.
  9434. */
  9435. template<typename BasicJsonType, typename InputAdapterType>
  9436. class parser
  9437. {
  9438. using number_integer_t = typename BasicJsonType::number_integer_t;
  9439. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  9440. using number_float_t = typename BasicJsonType::number_float_t;
  9441. using string_t = typename BasicJsonType::string_t;
  9442. using lexer_t = lexer<BasicJsonType, InputAdapterType>;
  9443. using token_type = typename lexer_t::token_type;
  9444. public:
  9445. /// a parser reading from an input adapter
  9446. explicit parser(InputAdapterType&& adapter,
  9447. const parser_callback_t<BasicJsonType> cb = nullptr,
  9448. const bool allow_exceptions_ = true,
  9449. const bool skip_comments = false)
  9450. : callback(cb)
  9451. , m_lexer(std::move(adapter), skip_comments)
  9452. , allow_exceptions(allow_exceptions_)
  9453. {
  9454. // read first token
  9455. get_token();
  9456. }
  9457. /*!
  9458. @brief public parser interface
  9459. @param[in] strict whether to expect the last token to be EOF
  9460. @param[in,out] result parsed JSON value
  9461. @throw parse_error.101 in case of an unexpected token
  9462. @throw parse_error.102 if to_unicode fails or surrogate error
  9463. @throw parse_error.103 if to_unicode fails
  9464. */
  9465. void parse(const bool strict, BasicJsonType& result)
  9466. {
  9467. if (callback)
  9468. {
  9469. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  9470. sax_parse_internal(&sdp);
  9471. // in strict mode, input must be completely read
  9472. if (strict && (get_token() != token_type::end_of_input))
  9473. {
  9474. sdp.parse_error(m_lexer.get_position(),
  9475. m_lexer.get_token_string(),
  9476. parse_error::create(101, m_lexer.get_position(),
  9477. exception_message(token_type::end_of_input, "value"), BasicJsonType()));
  9478. }
  9479. // in case of an error, return discarded value
  9480. if (sdp.is_errored())
  9481. {
  9482. result = value_t::discarded;
  9483. return;
  9484. }
  9485. // set top-level value to null if it was discarded by the callback
  9486. // function
  9487. if (result.is_discarded())
  9488. {
  9489. result = nullptr;
  9490. }
  9491. }
  9492. else
  9493. {
  9494. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  9495. sax_parse_internal(&sdp);
  9496. // in strict mode, input must be completely read
  9497. if (strict && (get_token() != token_type::end_of_input))
  9498. {
  9499. sdp.parse_error(m_lexer.get_position(),
  9500. m_lexer.get_token_string(),
  9501. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType()));
  9502. }
  9503. // in case of an error, return discarded value
  9504. if (sdp.is_errored())
  9505. {
  9506. result = value_t::discarded;
  9507. return;
  9508. }
  9509. }
  9510. result.assert_invariant();
  9511. }
  9512. /*!
  9513. @brief public accept interface
  9514. @param[in] strict whether to expect the last token to be EOF
  9515. @return whether the input is a proper JSON text
  9516. */
  9517. bool accept(const bool strict = true)
  9518. {
  9519. json_sax_acceptor<BasicJsonType> sax_acceptor;
  9520. return sax_parse(&sax_acceptor, strict);
  9521. }
  9522. template<typename SAX>
  9523. JSON_HEDLEY_NON_NULL(2)
  9524. bool sax_parse(SAX* sax, const bool strict = true)
  9525. {
  9526. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  9527. const bool result = sax_parse_internal(sax);
  9528. // strict mode: next byte must be EOF
  9529. if (result && strict && (get_token() != token_type::end_of_input))
  9530. {
  9531. return sax->parse_error(m_lexer.get_position(),
  9532. m_lexer.get_token_string(),
  9533. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType()));
  9534. }
  9535. return result;
  9536. }
  9537. private:
  9538. template<typename SAX>
  9539. JSON_HEDLEY_NON_NULL(2)
  9540. bool sax_parse_internal(SAX* sax)
  9541. {
  9542. // stack to remember the hierarchy of structured values we are parsing
  9543. // true = array; false = object
  9544. std::vector<bool> states;
  9545. // value to avoid a goto (see comment where set to true)
  9546. bool skip_to_state_evaluation = false;
  9547. while (true)
  9548. {
  9549. if (!skip_to_state_evaluation)
  9550. {
  9551. // invariant: get_token() was called before each iteration
  9552. switch (last_token)
  9553. {
  9554. case token_type::begin_object:
  9555. {
  9556. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast<std::size_t>(-1))))
  9557. {
  9558. return false;
  9559. }
  9560. // closing } -> we are done
  9561. if (get_token() == token_type::end_object)
  9562. {
  9563. if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
  9564. {
  9565. return false;
  9566. }
  9567. break;
  9568. }
  9569. // parse key
  9570. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  9571. {
  9572. return sax->parse_error(m_lexer.get_position(),
  9573. m_lexer.get_token_string(),
  9574. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType()));
  9575. }
  9576. if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
  9577. {
  9578. return false;
  9579. }
  9580. // parse separator (:)
  9581. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  9582. {
  9583. return sax->parse_error(m_lexer.get_position(),
  9584. m_lexer.get_token_string(),
  9585. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType()));
  9586. }
  9587. // remember we are now inside an object
  9588. states.push_back(false);
  9589. // parse values
  9590. get_token();
  9591. continue;
  9592. }
  9593. case token_type::begin_array:
  9594. {
  9595. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast<std::size_t>(-1))))
  9596. {
  9597. return false;
  9598. }
  9599. // closing ] -> we are done
  9600. if (get_token() == token_type::end_array)
  9601. {
  9602. if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
  9603. {
  9604. return false;
  9605. }
  9606. break;
  9607. }
  9608. // remember we are now inside an array
  9609. states.push_back(true);
  9610. // parse values (no need to call get_token)
  9611. continue;
  9612. }
  9613. case token_type::value_float:
  9614. {
  9615. const auto res = m_lexer.get_number_float();
  9616. if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res)))
  9617. {
  9618. return sax->parse_error(m_lexer.get_position(),
  9619. m_lexer.get_token_string(),
  9620. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'", BasicJsonType()));
  9621. }
  9622. if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string())))
  9623. {
  9624. return false;
  9625. }
  9626. break;
  9627. }
  9628. case token_type::literal_false:
  9629. {
  9630. if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false)))
  9631. {
  9632. return false;
  9633. }
  9634. break;
  9635. }
  9636. case token_type::literal_null:
  9637. {
  9638. if (JSON_HEDLEY_UNLIKELY(!sax->null()))
  9639. {
  9640. return false;
  9641. }
  9642. break;
  9643. }
  9644. case token_type::literal_true:
  9645. {
  9646. if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true)))
  9647. {
  9648. return false;
  9649. }
  9650. break;
  9651. }
  9652. case token_type::value_integer:
  9653. {
  9654. if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer())))
  9655. {
  9656. return false;
  9657. }
  9658. break;
  9659. }
  9660. case token_type::value_string:
  9661. {
  9662. if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string())))
  9663. {
  9664. return false;
  9665. }
  9666. break;
  9667. }
  9668. case token_type::value_unsigned:
  9669. {
  9670. if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned())))
  9671. {
  9672. return false;
  9673. }
  9674. break;
  9675. }
  9676. case token_type::parse_error:
  9677. {
  9678. // using "uninitialized" to avoid "expected" message
  9679. return sax->parse_error(m_lexer.get_position(),
  9680. m_lexer.get_token_string(),
  9681. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), BasicJsonType()));
  9682. }
  9683. case token_type::uninitialized:
  9684. case token_type::end_array:
  9685. case token_type::end_object:
  9686. case token_type::name_separator:
  9687. case token_type::value_separator:
  9688. case token_type::end_of_input:
  9689. case token_type::literal_or_value:
  9690. default: // the last token was unexpected
  9691. {
  9692. return sax->parse_error(m_lexer.get_position(),
  9693. m_lexer.get_token_string(),
  9694. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), BasicJsonType()));
  9695. }
  9696. }
  9697. }
  9698. else
  9699. {
  9700. skip_to_state_evaluation = false;
  9701. }
  9702. // we reached this line after we successfully parsed a value
  9703. if (states.empty())
  9704. {
  9705. // empty stack: we reached the end of the hierarchy: done
  9706. return true;
  9707. }
  9708. if (states.back()) // array
  9709. {
  9710. // comma -> next value
  9711. if (get_token() == token_type::value_separator)
  9712. {
  9713. // parse a new value
  9714. get_token();
  9715. continue;
  9716. }
  9717. // closing ]
  9718. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  9719. {
  9720. if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
  9721. {
  9722. return false;
  9723. }
  9724. // We are done with this array. Before we can parse a
  9725. // new value, we need to evaluate the new state first.
  9726. // By setting skip_to_state_evaluation to false, we
  9727. // are effectively jumping to the beginning of this if.
  9728. JSON_ASSERT(!states.empty());
  9729. states.pop_back();
  9730. skip_to_state_evaluation = true;
  9731. continue;
  9732. }
  9733. return sax->parse_error(m_lexer.get_position(),
  9734. m_lexer.get_token_string(),
  9735. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), BasicJsonType()));
  9736. }
  9737. // states.back() is false -> object
  9738. // comma -> next value
  9739. if (get_token() == token_type::value_separator)
  9740. {
  9741. // parse key
  9742. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  9743. {
  9744. return sax->parse_error(m_lexer.get_position(),
  9745. m_lexer.get_token_string(),
  9746. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType()));
  9747. }
  9748. if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
  9749. {
  9750. return false;
  9751. }
  9752. // parse separator (:)
  9753. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  9754. {
  9755. return sax->parse_error(m_lexer.get_position(),
  9756. m_lexer.get_token_string(),
  9757. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType()));
  9758. }
  9759. // parse values
  9760. get_token();
  9761. continue;
  9762. }
  9763. // closing }
  9764. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  9765. {
  9766. if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
  9767. {
  9768. return false;
  9769. }
  9770. // We are done with this object. Before we can parse a
  9771. // new value, we need to evaluate the new state first.
  9772. // By setting skip_to_state_evaluation to false, we
  9773. // are effectively jumping to the beginning of this if.
  9774. JSON_ASSERT(!states.empty());
  9775. states.pop_back();
  9776. skip_to_state_evaluation = true;
  9777. continue;
  9778. }
  9779. return sax->parse_error(m_lexer.get_position(),
  9780. m_lexer.get_token_string(),
  9781. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), BasicJsonType()));
  9782. }
  9783. }
  9784. /// get next token from lexer
  9785. token_type get_token()
  9786. {
  9787. return last_token = m_lexer.scan();
  9788. }
  9789. std::string exception_message(const token_type expected, const std::string& context)
  9790. {
  9791. std::string error_msg = "syntax error ";
  9792. if (!context.empty())
  9793. {
  9794. error_msg += "while parsing " + context + " ";
  9795. }
  9796. error_msg += "- ";
  9797. if (last_token == token_type::parse_error)
  9798. {
  9799. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  9800. m_lexer.get_token_string() + "'";
  9801. }
  9802. else
  9803. {
  9804. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  9805. }
  9806. if (expected != token_type::uninitialized)
  9807. {
  9808. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  9809. }
  9810. return error_msg;
  9811. }
  9812. private:
  9813. /// callback function
  9814. const parser_callback_t<BasicJsonType> callback = nullptr;
  9815. /// the type of the last read token
  9816. token_type last_token = token_type::uninitialized;
  9817. /// the lexer
  9818. lexer_t m_lexer;
  9819. /// whether to throw exceptions in case of errors
  9820. const bool allow_exceptions = true;
  9821. };
  9822. } // namespace detail
  9823. } // namespace nlohmann
  9824. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  9825. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  9826. #include <cstddef> // ptrdiff_t
  9827. #include <limits> // numeric_limits
  9828. // #include <nlohmann/detail/macro_scope.hpp>
  9829. namespace nlohmann
  9830. {
  9831. namespace detail
  9832. {
  9833. /*
  9834. @brief an iterator for primitive JSON types
  9835. This class models an iterator for primitive JSON types (boolean, number,
  9836. string). It's only purpose is to allow the iterator/const_iterator classes
  9837. to "iterate" over primitive values. Internally, the iterator is modeled by
  9838. a `difference_type` variable. Value begin_value (`0`) models the begin,
  9839. end_value (`1`) models past the end.
  9840. */
  9841. class primitive_iterator_t
  9842. {
  9843. private:
  9844. using difference_type = std::ptrdiff_t;
  9845. static constexpr difference_type begin_value = 0;
  9846. static constexpr difference_type end_value = begin_value + 1;
  9847. JSON_PRIVATE_UNLESS_TESTED:
  9848. /// iterator as signed integer type
  9849. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  9850. public:
  9851. constexpr difference_type get_value() const noexcept
  9852. {
  9853. return m_it;
  9854. }
  9855. /// set iterator to a defined beginning
  9856. void set_begin() noexcept
  9857. {
  9858. m_it = begin_value;
  9859. }
  9860. /// set iterator to a defined past the end
  9861. void set_end() noexcept
  9862. {
  9863. m_it = end_value;
  9864. }
  9865. /// return whether the iterator can be dereferenced
  9866. constexpr bool is_begin() const noexcept
  9867. {
  9868. return m_it == begin_value;
  9869. }
  9870. /// return whether the iterator is at end
  9871. constexpr bool is_end() const noexcept
  9872. {
  9873. return m_it == end_value;
  9874. }
  9875. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  9876. {
  9877. return lhs.m_it == rhs.m_it;
  9878. }
  9879. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  9880. {
  9881. return lhs.m_it < rhs.m_it;
  9882. }
  9883. primitive_iterator_t operator+(difference_type n) noexcept
  9884. {
  9885. auto result = *this;
  9886. result += n;
  9887. return result;
  9888. }
  9889. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  9890. {
  9891. return lhs.m_it - rhs.m_it;
  9892. }
  9893. primitive_iterator_t& operator++() noexcept
  9894. {
  9895. ++m_it;
  9896. return *this;
  9897. }
  9898. primitive_iterator_t const operator++(int) noexcept // NOLINT(readability-const-return-type)
  9899. {
  9900. auto result = *this;
  9901. ++m_it;
  9902. return result;
  9903. }
  9904. primitive_iterator_t& operator--() noexcept
  9905. {
  9906. --m_it;
  9907. return *this;
  9908. }
  9909. primitive_iterator_t const operator--(int) noexcept // NOLINT(readability-const-return-type)
  9910. {
  9911. auto result = *this;
  9912. --m_it;
  9913. return result;
  9914. }
  9915. primitive_iterator_t& operator+=(difference_type n) noexcept
  9916. {
  9917. m_it += n;
  9918. return *this;
  9919. }
  9920. primitive_iterator_t& operator-=(difference_type n) noexcept
  9921. {
  9922. m_it -= n;
  9923. return *this;
  9924. }
  9925. };
  9926. } // namespace detail
  9927. } // namespace nlohmann
  9928. namespace nlohmann
  9929. {
  9930. namespace detail
  9931. {
  9932. /*!
  9933. @brief an iterator value
  9934. @note This structure could easily be a union, but MSVC currently does not allow
  9935. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  9936. */
  9937. template<typename BasicJsonType> struct internal_iterator
  9938. {
  9939. /// iterator for JSON objects
  9940. typename BasicJsonType::object_t::iterator object_iterator {};
  9941. /// iterator for JSON arrays
  9942. typename BasicJsonType::array_t::iterator array_iterator {};
  9943. /// generic iterator for all other types
  9944. primitive_iterator_t primitive_iterator {};
  9945. };
  9946. } // namespace detail
  9947. } // namespace nlohmann
  9948. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  9949. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  9950. #include <type_traits> // conditional, is_const, remove_const
  9951. // #include <nlohmann/detail/exceptions.hpp>
  9952. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  9953. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  9954. // #include <nlohmann/detail/macro_scope.hpp>
  9955. // #include <nlohmann/detail/meta/cpp_future.hpp>
  9956. // #include <nlohmann/detail/meta/type_traits.hpp>
  9957. // #include <nlohmann/detail/value_t.hpp>
  9958. namespace nlohmann
  9959. {
  9960. namespace detail
  9961. {
  9962. // forward declare, to be able to friend it later on
  9963. template<typename IteratorType> class iteration_proxy;
  9964. template<typename IteratorType> class iteration_proxy_value;
  9965. /*!
  9966. @brief a template for a bidirectional iterator for the @ref basic_json class
  9967. This class implements a both iterators (iterator and const_iterator) for the
  9968. @ref basic_json class.
  9969. @note An iterator is called *initialized* when a pointer to a JSON value has
  9970. been set (e.g., by a constructor or a copy assignment). If the iterator is
  9971. default-constructed, it is *uninitialized* and most methods are undefined.
  9972. **The library uses assertions to detect calls on uninitialized iterators.**
  9973. @requirement The class satisfies the following concept requirements:
  9974. -
  9975. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  9976. The iterator that can be moved can be moved in both directions (i.e.
  9977. incremented and decremented).
  9978. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  9979. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  9980. */
  9981. template<typename BasicJsonType>
  9982. class iter_impl // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)
  9983. {
  9984. /// the iterator with BasicJsonType of different const-ness
  9985. using other_iter_impl = iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  9986. /// allow basic_json to access private members
  9987. friend other_iter_impl;
  9988. friend BasicJsonType;
  9989. friend iteration_proxy<iter_impl>;
  9990. friend iteration_proxy_value<iter_impl>;
  9991. using object_t = typename BasicJsonType::object_t;
  9992. using array_t = typename BasicJsonType::array_t;
  9993. // make sure BasicJsonType is basic_json or const basic_json
  9994. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  9995. "iter_impl only accepts (const) basic_json");
  9996. public:
  9997. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  9998. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  9999. /// A user-defined iterator should provide publicly accessible typedefs named
  10000. /// iterator_category, value_type, difference_type, pointer, and reference.
  10001. /// Note that value_type is required to be non-const, even for constant iterators.
  10002. using iterator_category = std::bidirectional_iterator_tag;
  10003. /// the type of the values when the iterator is dereferenced
  10004. using value_type = typename BasicJsonType::value_type;
  10005. /// a type to represent differences between iterators
  10006. using difference_type = typename BasicJsonType::difference_type;
  10007. /// defines a pointer to the type iterated over (value_type)
  10008. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  10009. typename BasicJsonType::const_pointer,
  10010. typename BasicJsonType::pointer>::type;
  10011. /// defines a reference to the type iterated over (value_type)
  10012. using reference =
  10013. typename std::conditional<std::is_const<BasicJsonType>::value,
  10014. typename BasicJsonType::const_reference,
  10015. typename BasicJsonType::reference>::type;
  10016. iter_impl() = default;
  10017. ~iter_impl() = default;
  10018. iter_impl(iter_impl&&) noexcept = default;
  10019. iter_impl& operator=(iter_impl&&) noexcept = default;
  10020. /*!
  10021. @brief constructor for a given JSON instance
  10022. @param[in] object pointer to a JSON object for this iterator
  10023. @pre object != nullptr
  10024. @post The iterator is initialized; i.e. `m_object != nullptr`.
  10025. */
  10026. explicit iter_impl(pointer object) noexcept : m_object(object)
  10027. {
  10028. JSON_ASSERT(m_object != nullptr);
  10029. switch (m_object->m_type)
  10030. {
  10031. case value_t::object:
  10032. {
  10033. m_it.object_iterator = typename object_t::iterator();
  10034. break;
  10035. }
  10036. case value_t::array:
  10037. {
  10038. m_it.array_iterator = typename array_t::iterator();
  10039. break;
  10040. }
  10041. case value_t::null:
  10042. case value_t::string:
  10043. case value_t::boolean:
  10044. case value_t::number_integer:
  10045. case value_t::number_unsigned:
  10046. case value_t::number_float:
  10047. case value_t::binary:
  10048. case value_t::discarded:
  10049. default:
  10050. {
  10051. m_it.primitive_iterator = primitive_iterator_t();
  10052. break;
  10053. }
  10054. }
  10055. }
  10056. /*!
  10057. @note The conventional copy constructor and copy assignment are implicitly
  10058. defined. Combined with the following converting constructor and
  10059. assignment, they support: (1) copy from iterator to iterator, (2)
  10060. copy from const iterator to const iterator, and (3) conversion from
  10061. iterator to const iterator. However conversion from const iterator
  10062. to iterator is not defined.
  10063. */
  10064. /*!
  10065. @brief const copy constructor
  10066. @param[in] other const iterator to copy from
  10067. @note This copy constructor had to be defined explicitly to circumvent a bug
  10068. occurring on msvc v19.0 compiler (VS 2015) debug build. For more
  10069. information refer to: https://github.com/nlohmann/json/issues/1608
  10070. */
  10071. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  10072. : m_object(other.m_object), m_it(other.m_it)
  10073. {}
  10074. /*!
  10075. @brief converting assignment
  10076. @param[in] other const iterator to copy from
  10077. @return const/non-const iterator
  10078. @note It is not checked whether @a other is initialized.
  10079. */
  10080. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  10081. {
  10082. if (&other != this)
  10083. {
  10084. m_object = other.m_object;
  10085. m_it = other.m_it;
  10086. }
  10087. return *this;
  10088. }
  10089. /*!
  10090. @brief converting constructor
  10091. @param[in] other non-const iterator to copy from
  10092. @note It is not checked whether @a other is initialized.
  10093. */
  10094. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  10095. : m_object(other.m_object), m_it(other.m_it)
  10096. {}
  10097. /*!
  10098. @brief converting assignment
  10099. @param[in] other non-const iterator to copy from
  10100. @return const/non-const iterator
  10101. @note It is not checked whether @a other is initialized.
  10102. */
  10103. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept // NOLINT(cert-oop54-cpp)
  10104. {
  10105. m_object = other.m_object;
  10106. m_it = other.m_it;
  10107. return *this;
  10108. }
  10109. JSON_PRIVATE_UNLESS_TESTED:
  10110. /*!
  10111. @brief set the iterator to the first value
  10112. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10113. */
  10114. void set_begin() noexcept
  10115. {
  10116. JSON_ASSERT(m_object != nullptr);
  10117. switch (m_object->m_type)
  10118. {
  10119. case value_t::object:
  10120. {
  10121. m_it.object_iterator = m_object->m_value.object->begin();
  10122. break;
  10123. }
  10124. case value_t::array:
  10125. {
  10126. m_it.array_iterator = m_object->m_value.array->begin();
  10127. break;
  10128. }
  10129. case value_t::null:
  10130. {
  10131. // set to end so begin()==end() is true: null is empty
  10132. m_it.primitive_iterator.set_end();
  10133. break;
  10134. }
  10135. case value_t::string:
  10136. case value_t::boolean:
  10137. case value_t::number_integer:
  10138. case value_t::number_unsigned:
  10139. case value_t::number_float:
  10140. case value_t::binary:
  10141. case value_t::discarded:
  10142. default:
  10143. {
  10144. m_it.primitive_iterator.set_begin();
  10145. break;
  10146. }
  10147. }
  10148. }
  10149. /*!
  10150. @brief set the iterator past the last value
  10151. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10152. */
  10153. void set_end() noexcept
  10154. {
  10155. JSON_ASSERT(m_object != nullptr);
  10156. switch (m_object->m_type)
  10157. {
  10158. case value_t::object:
  10159. {
  10160. m_it.object_iterator = m_object->m_value.object->end();
  10161. break;
  10162. }
  10163. case value_t::array:
  10164. {
  10165. m_it.array_iterator = m_object->m_value.array->end();
  10166. break;
  10167. }
  10168. case value_t::null:
  10169. case value_t::string:
  10170. case value_t::boolean:
  10171. case value_t::number_integer:
  10172. case value_t::number_unsigned:
  10173. case value_t::number_float:
  10174. case value_t::binary:
  10175. case value_t::discarded:
  10176. default:
  10177. {
  10178. m_it.primitive_iterator.set_end();
  10179. break;
  10180. }
  10181. }
  10182. }
  10183. public:
  10184. /*!
  10185. @brief return a reference to the value pointed to by the iterator
  10186. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10187. */
  10188. reference operator*() const
  10189. {
  10190. JSON_ASSERT(m_object != nullptr);
  10191. switch (m_object->m_type)
  10192. {
  10193. case value_t::object:
  10194. {
  10195. JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
  10196. return m_it.object_iterator->second;
  10197. }
  10198. case value_t::array:
  10199. {
  10200. JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
  10201. return *m_it.array_iterator;
  10202. }
  10203. case value_t::null:
  10204. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10205. case value_t::string:
  10206. case value_t::boolean:
  10207. case value_t::number_integer:
  10208. case value_t::number_unsigned:
  10209. case value_t::number_float:
  10210. case value_t::binary:
  10211. case value_t::discarded:
  10212. default:
  10213. {
  10214. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  10215. {
  10216. return *m_object;
  10217. }
  10218. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10219. }
  10220. }
  10221. }
  10222. /*!
  10223. @brief dereference the iterator
  10224. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10225. */
  10226. pointer operator->() const
  10227. {
  10228. JSON_ASSERT(m_object != nullptr);
  10229. switch (m_object->m_type)
  10230. {
  10231. case value_t::object:
  10232. {
  10233. JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
  10234. return &(m_it.object_iterator->second);
  10235. }
  10236. case value_t::array:
  10237. {
  10238. JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
  10239. return &*m_it.array_iterator;
  10240. }
  10241. case value_t::null:
  10242. case value_t::string:
  10243. case value_t::boolean:
  10244. case value_t::number_integer:
  10245. case value_t::number_unsigned:
  10246. case value_t::number_float:
  10247. case value_t::binary:
  10248. case value_t::discarded:
  10249. default:
  10250. {
  10251. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  10252. {
  10253. return m_object;
  10254. }
  10255. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10256. }
  10257. }
  10258. }
  10259. /*!
  10260. @brief post-increment (it++)
  10261. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10262. */
  10263. iter_impl const operator++(int) // NOLINT(readability-const-return-type)
  10264. {
  10265. auto result = *this;
  10266. ++(*this);
  10267. return result;
  10268. }
  10269. /*!
  10270. @brief pre-increment (++it)
  10271. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10272. */
  10273. iter_impl& operator++()
  10274. {
  10275. JSON_ASSERT(m_object != nullptr);
  10276. switch (m_object->m_type)
  10277. {
  10278. case value_t::object:
  10279. {
  10280. std::advance(m_it.object_iterator, 1);
  10281. break;
  10282. }
  10283. case value_t::array:
  10284. {
  10285. std::advance(m_it.array_iterator, 1);
  10286. break;
  10287. }
  10288. case value_t::null:
  10289. case value_t::string:
  10290. case value_t::boolean:
  10291. case value_t::number_integer:
  10292. case value_t::number_unsigned:
  10293. case value_t::number_float:
  10294. case value_t::binary:
  10295. case value_t::discarded:
  10296. default:
  10297. {
  10298. ++m_it.primitive_iterator;
  10299. break;
  10300. }
  10301. }
  10302. return *this;
  10303. }
  10304. /*!
  10305. @brief post-decrement (it--)
  10306. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10307. */
  10308. iter_impl const operator--(int) // NOLINT(readability-const-return-type)
  10309. {
  10310. auto result = *this;
  10311. --(*this);
  10312. return result;
  10313. }
  10314. /*!
  10315. @brief pre-decrement (--it)
  10316. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10317. */
  10318. iter_impl& operator--()
  10319. {
  10320. JSON_ASSERT(m_object != nullptr);
  10321. switch (m_object->m_type)
  10322. {
  10323. case value_t::object:
  10324. {
  10325. std::advance(m_it.object_iterator, -1);
  10326. break;
  10327. }
  10328. case value_t::array:
  10329. {
  10330. std::advance(m_it.array_iterator, -1);
  10331. break;
  10332. }
  10333. case value_t::null:
  10334. case value_t::string:
  10335. case value_t::boolean:
  10336. case value_t::number_integer:
  10337. case value_t::number_unsigned:
  10338. case value_t::number_float:
  10339. case value_t::binary:
  10340. case value_t::discarded:
  10341. default:
  10342. {
  10343. --m_it.primitive_iterator;
  10344. break;
  10345. }
  10346. }
  10347. return *this;
  10348. }
  10349. /*!
  10350. @brief comparison: equal
  10351. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10352. */
  10353. 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 >
  10354. bool operator==(const IterImpl& other) const
  10355. {
  10356. // if objects are not the same, the comparison is undefined
  10357. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  10358. {
  10359. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object));
  10360. }
  10361. JSON_ASSERT(m_object != nullptr);
  10362. switch (m_object->m_type)
  10363. {
  10364. case value_t::object:
  10365. return (m_it.object_iterator == other.m_it.object_iterator);
  10366. case value_t::array:
  10367. return (m_it.array_iterator == other.m_it.array_iterator);
  10368. case value_t::null:
  10369. case value_t::string:
  10370. case value_t::boolean:
  10371. case value_t::number_integer:
  10372. case value_t::number_unsigned:
  10373. case value_t::number_float:
  10374. case value_t::binary:
  10375. case value_t::discarded:
  10376. default:
  10377. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  10378. }
  10379. }
  10380. /*!
  10381. @brief comparison: not equal
  10382. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10383. */
  10384. 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 >
  10385. bool operator!=(const IterImpl& other) const
  10386. {
  10387. return !operator==(other);
  10388. }
  10389. /*!
  10390. @brief comparison: smaller
  10391. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10392. */
  10393. bool operator<(const iter_impl& other) const
  10394. {
  10395. // if objects are not the same, the comparison is undefined
  10396. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  10397. {
  10398. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object));
  10399. }
  10400. JSON_ASSERT(m_object != nullptr);
  10401. switch (m_object->m_type)
  10402. {
  10403. case value_t::object:
  10404. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", *m_object));
  10405. case value_t::array:
  10406. return (m_it.array_iterator < other.m_it.array_iterator);
  10407. case value_t::null:
  10408. case value_t::string:
  10409. case value_t::boolean:
  10410. case value_t::number_integer:
  10411. case value_t::number_unsigned:
  10412. case value_t::number_float:
  10413. case value_t::binary:
  10414. case value_t::discarded:
  10415. default:
  10416. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  10417. }
  10418. }
  10419. /*!
  10420. @brief comparison: less than or equal
  10421. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10422. */
  10423. bool operator<=(const iter_impl& other) const
  10424. {
  10425. return !other.operator < (*this);
  10426. }
  10427. /*!
  10428. @brief comparison: greater than
  10429. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10430. */
  10431. bool operator>(const iter_impl& other) const
  10432. {
  10433. return !operator<=(other);
  10434. }
  10435. /*!
  10436. @brief comparison: greater than or equal
  10437. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10438. */
  10439. bool operator>=(const iter_impl& other) const
  10440. {
  10441. return !operator<(other);
  10442. }
  10443. /*!
  10444. @brief add to iterator
  10445. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10446. */
  10447. iter_impl& operator+=(difference_type i)
  10448. {
  10449. JSON_ASSERT(m_object != nullptr);
  10450. switch (m_object->m_type)
  10451. {
  10452. case value_t::object:
  10453. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object));
  10454. case value_t::array:
  10455. {
  10456. std::advance(m_it.array_iterator, i);
  10457. break;
  10458. }
  10459. case value_t::null:
  10460. case value_t::string:
  10461. case value_t::boolean:
  10462. case value_t::number_integer:
  10463. case value_t::number_unsigned:
  10464. case value_t::number_float:
  10465. case value_t::binary:
  10466. case value_t::discarded:
  10467. default:
  10468. {
  10469. m_it.primitive_iterator += i;
  10470. break;
  10471. }
  10472. }
  10473. return *this;
  10474. }
  10475. /*!
  10476. @brief subtract from iterator
  10477. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10478. */
  10479. iter_impl& operator-=(difference_type i)
  10480. {
  10481. return operator+=(-i);
  10482. }
  10483. /*!
  10484. @brief add to iterator
  10485. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10486. */
  10487. iter_impl operator+(difference_type i) const
  10488. {
  10489. auto result = *this;
  10490. result += i;
  10491. return result;
  10492. }
  10493. /*!
  10494. @brief addition of distance and iterator
  10495. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10496. */
  10497. friend iter_impl operator+(difference_type i, const iter_impl& it)
  10498. {
  10499. auto result = it;
  10500. result += i;
  10501. return result;
  10502. }
  10503. /*!
  10504. @brief subtract from iterator
  10505. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10506. */
  10507. iter_impl operator-(difference_type i) const
  10508. {
  10509. auto result = *this;
  10510. result -= i;
  10511. return result;
  10512. }
  10513. /*!
  10514. @brief return difference
  10515. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10516. */
  10517. difference_type operator-(const iter_impl& other) const
  10518. {
  10519. JSON_ASSERT(m_object != nullptr);
  10520. switch (m_object->m_type)
  10521. {
  10522. case value_t::object:
  10523. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object));
  10524. case value_t::array:
  10525. return m_it.array_iterator - other.m_it.array_iterator;
  10526. case value_t::null:
  10527. case value_t::string:
  10528. case value_t::boolean:
  10529. case value_t::number_integer:
  10530. case value_t::number_unsigned:
  10531. case value_t::number_float:
  10532. case value_t::binary:
  10533. case value_t::discarded:
  10534. default:
  10535. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  10536. }
  10537. }
  10538. /*!
  10539. @brief access to successor
  10540. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10541. */
  10542. reference operator[](difference_type n) const
  10543. {
  10544. JSON_ASSERT(m_object != nullptr);
  10545. switch (m_object->m_type)
  10546. {
  10547. case value_t::object:
  10548. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", *m_object));
  10549. case value_t::array:
  10550. return *std::next(m_it.array_iterator, n);
  10551. case value_t::null:
  10552. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10553. case value_t::string:
  10554. case value_t::boolean:
  10555. case value_t::number_integer:
  10556. case value_t::number_unsigned:
  10557. case value_t::number_float:
  10558. case value_t::binary:
  10559. case value_t::discarded:
  10560. default:
  10561. {
  10562. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  10563. {
  10564. return *m_object;
  10565. }
  10566. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10567. }
  10568. }
  10569. }
  10570. /*!
  10571. @brief return the key of an object iterator
  10572. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10573. */
  10574. const typename object_t::key_type& key() const
  10575. {
  10576. JSON_ASSERT(m_object != nullptr);
  10577. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  10578. {
  10579. return m_it.object_iterator->first;
  10580. }
  10581. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", *m_object));
  10582. }
  10583. /*!
  10584. @brief return the value of an iterator
  10585. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10586. */
  10587. reference value() const
  10588. {
  10589. return operator*();
  10590. }
  10591. JSON_PRIVATE_UNLESS_TESTED:
  10592. /// associated JSON instance
  10593. pointer m_object = nullptr;
  10594. /// the actual iterator of the associated instance
  10595. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  10596. };
  10597. } // namespace detail
  10598. } // namespace nlohmann
  10599. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  10600. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  10601. #include <cstddef> // ptrdiff_t
  10602. #include <iterator> // reverse_iterator
  10603. #include <utility> // declval
  10604. namespace nlohmann
  10605. {
  10606. namespace detail
  10607. {
  10608. //////////////////////
  10609. // reverse_iterator //
  10610. //////////////////////
  10611. /*!
  10612. @brief a template for a reverse iterator class
  10613. @tparam Base the base iterator type to reverse. Valid types are @ref
  10614. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  10615. create @ref const_reverse_iterator).
  10616. @requirement The class satisfies the following concept requirements:
  10617. -
  10618. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  10619. The iterator that can be moved can be moved in both directions (i.e.
  10620. incremented and decremented).
  10621. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  10622. It is possible to write to the pointed-to element (only if @a Base is
  10623. @ref iterator).
  10624. @since version 1.0.0
  10625. */
  10626. template<typename Base>
  10627. class json_reverse_iterator : public std::reverse_iterator<Base>
  10628. {
  10629. public:
  10630. using difference_type = std::ptrdiff_t;
  10631. /// shortcut to the reverse iterator adapter
  10632. using base_iterator = std::reverse_iterator<Base>;
  10633. /// the reference type for the pointed-to element
  10634. using reference = typename Base::reference;
  10635. /// create reverse iterator from iterator
  10636. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  10637. : base_iterator(it) {}
  10638. /// create reverse iterator from base class
  10639. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  10640. /// post-increment (it++)
  10641. json_reverse_iterator const operator++(int) // NOLINT(readability-const-return-type)
  10642. {
  10643. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  10644. }
  10645. /// pre-increment (++it)
  10646. json_reverse_iterator& operator++()
  10647. {
  10648. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  10649. }
  10650. /// post-decrement (it--)
  10651. json_reverse_iterator const operator--(int) // NOLINT(readability-const-return-type)
  10652. {
  10653. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  10654. }
  10655. /// pre-decrement (--it)
  10656. json_reverse_iterator& operator--()
  10657. {
  10658. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  10659. }
  10660. /// add to iterator
  10661. json_reverse_iterator& operator+=(difference_type i)
  10662. {
  10663. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  10664. }
  10665. /// add to iterator
  10666. json_reverse_iterator operator+(difference_type i) const
  10667. {
  10668. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  10669. }
  10670. /// subtract from iterator
  10671. json_reverse_iterator operator-(difference_type i) const
  10672. {
  10673. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  10674. }
  10675. /// return difference
  10676. difference_type operator-(const json_reverse_iterator& other) const
  10677. {
  10678. return base_iterator(*this) - base_iterator(other);
  10679. }
  10680. /// access to successor
  10681. reference operator[](difference_type n) const
  10682. {
  10683. return *(this->operator+(n));
  10684. }
  10685. /// return the key of an object iterator
  10686. auto key() const -> decltype(std::declval<Base>().key())
  10687. {
  10688. auto it = --this->base();
  10689. return it.key();
  10690. }
  10691. /// return the value of an iterator
  10692. reference value() const
  10693. {
  10694. auto it = --this->base();
  10695. return it.operator * ();
  10696. }
  10697. };
  10698. } // namespace detail
  10699. } // namespace nlohmann
  10700. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  10701. // #include <nlohmann/detail/json_pointer.hpp>
  10702. #include <algorithm> // all_of
  10703. #include <cctype> // isdigit
  10704. #include <limits> // max
  10705. #include <numeric> // accumulate
  10706. #include <string> // string
  10707. #include <utility> // move
  10708. #include <vector> // vector
  10709. // #include <nlohmann/detail/exceptions.hpp>
  10710. // #include <nlohmann/detail/macro_scope.hpp>
  10711. // #include <nlohmann/detail/string_escape.hpp>
  10712. // #include <nlohmann/detail/value_t.hpp>
  10713. namespace nlohmann
  10714. {
  10715. /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document
  10716. /// @sa https://json.nlohmann.me/api/json_pointer/
  10717. template<typename BasicJsonType>
  10718. class json_pointer
  10719. {
  10720. // allow basic_json to access private members
  10721. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  10722. friend class basic_json;
  10723. public:
  10724. /// @brief create JSON pointer
  10725. /// @sa https://json.nlohmann.me/api/json_pointer/json_pointer/
  10726. explicit json_pointer(const std::string& s = "")
  10727. : reference_tokens(split(s))
  10728. {}
  10729. /// @brief return a string representation of the JSON pointer
  10730. /// @sa https://json.nlohmann.me/api/json_pointer/to_string/
  10731. std::string to_string() const
  10732. {
  10733. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  10734. std::string{},
  10735. [](const std::string & a, const std::string & b)
  10736. {
  10737. return a + "/" + detail::escape(b);
  10738. });
  10739. }
  10740. /// @brief return a string representation of the JSON pointer
  10741. /// @sa https://json.nlohmann.me/api/json_pointer/operator_string/
  10742. operator std::string() const
  10743. {
  10744. return to_string();
  10745. }
  10746. /// @brief append another JSON pointer at the end of this JSON pointer
  10747. /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
  10748. json_pointer& operator/=(const json_pointer& ptr)
  10749. {
  10750. reference_tokens.insert(reference_tokens.end(),
  10751. ptr.reference_tokens.begin(),
  10752. ptr.reference_tokens.end());
  10753. return *this;
  10754. }
  10755. /// @brief append an unescaped reference token at the end of this JSON pointer
  10756. /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
  10757. json_pointer& operator/=(std::string token)
  10758. {
  10759. push_back(std::move(token));
  10760. return *this;
  10761. }
  10762. /// @brief append an array index at the end of this JSON pointer
  10763. /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
  10764. json_pointer& operator/=(std::size_t array_idx)
  10765. {
  10766. return *this /= std::to_string(array_idx);
  10767. }
  10768. /// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  10769. /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/
  10770. friend json_pointer operator/(const json_pointer& lhs,
  10771. const json_pointer& rhs)
  10772. {
  10773. return json_pointer(lhs) /= rhs;
  10774. }
  10775. /// @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  10776. /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/
  10777. friend json_pointer operator/(const json_pointer& lhs, std::string token) // NOLINT(performance-unnecessary-value-param)
  10778. {
  10779. return json_pointer(lhs) /= std::move(token);
  10780. }
  10781. /// @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  10782. /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/
  10783. friend json_pointer operator/(const json_pointer& lhs, std::size_t array_idx)
  10784. {
  10785. return json_pointer(lhs) /= array_idx;
  10786. }
  10787. /// @brief returns the parent of this JSON pointer
  10788. /// @sa https://json.nlohmann.me/api/json_pointer/parent_pointer/
  10789. json_pointer parent_pointer() const
  10790. {
  10791. if (empty())
  10792. {
  10793. return *this;
  10794. }
  10795. json_pointer res = *this;
  10796. res.pop_back();
  10797. return res;
  10798. }
  10799. /// @brief remove last reference token
  10800. /// @sa https://json.nlohmann.me/api/json_pointer/pop_back/
  10801. void pop_back()
  10802. {
  10803. if (JSON_HEDLEY_UNLIKELY(empty()))
  10804. {
  10805. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  10806. }
  10807. reference_tokens.pop_back();
  10808. }
  10809. /// @brief return last reference token
  10810. /// @sa https://json.nlohmann.me/api/json_pointer/back/
  10811. const std::string& back() const
  10812. {
  10813. if (JSON_HEDLEY_UNLIKELY(empty()))
  10814. {
  10815. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  10816. }
  10817. return reference_tokens.back();
  10818. }
  10819. /// @brief append an unescaped token at the end of the reference pointer
  10820. /// @sa https://json.nlohmann.me/api/json_pointer/push_back/
  10821. void push_back(const std::string& token)
  10822. {
  10823. reference_tokens.push_back(token);
  10824. }
  10825. /// @brief append an unescaped token at the end of the reference pointer
  10826. /// @sa https://json.nlohmann.me/api/json_pointer/push_back/
  10827. void push_back(std::string&& token)
  10828. {
  10829. reference_tokens.push_back(std::move(token));
  10830. }
  10831. /// @brief return whether pointer points to the root document
  10832. /// @sa https://json.nlohmann.me/api/json_pointer/empty/
  10833. bool empty() const noexcept
  10834. {
  10835. return reference_tokens.empty();
  10836. }
  10837. private:
  10838. /*!
  10839. @param[in] s reference token to be converted into an array index
  10840. @return integer representation of @a s
  10841. @throw parse_error.106 if an array index begins with '0'
  10842. @throw parse_error.109 if an array index begins not with a digit
  10843. @throw out_of_range.404 if string @a s could not be converted to an integer
  10844. @throw out_of_range.410 if an array index exceeds size_type
  10845. */
  10846. static typename BasicJsonType::size_type array_index(const std::string& s)
  10847. {
  10848. using size_type = typename BasicJsonType::size_type;
  10849. // error condition (cf. RFC 6901, Sect. 4)
  10850. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0'))
  10851. {
  10852. JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType()));
  10853. }
  10854. // error condition (cf. RFC 6901, Sect. 4)
  10855. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9')))
  10856. {
  10857. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType()));
  10858. }
  10859. std::size_t processed_chars = 0;
  10860. unsigned long long res = 0; // NOLINT(runtime/int)
  10861. JSON_TRY
  10862. {
  10863. res = std::stoull(s, &processed_chars);
  10864. }
  10865. JSON_CATCH(std::out_of_range&)
  10866. {
  10867. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType()));
  10868. }
  10869. // check if the string was completely read
  10870. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  10871. {
  10872. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType()));
  10873. }
  10874. // only triggered on special platforms (like 32bit), see also
  10875. // https://github.com/nlohmann/json/pull/2203
  10876. if (res >= static_cast<unsigned long long>((std::numeric_limits<size_type>::max)())) // NOLINT(runtime/int)
  10877. {
  10878. JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE
  10879. }
  10880. return static_cast<size_type>(res);
  10881. }
  10882. JSON_PRIVATE_UNLESS_TESTED:
  10883. json_pointer top() const
  10884. {
  10885. if (JSON_HEDLEY_UNLIKELY(empty()))
  10886. {
  10887. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  10888. }
  10889. json_pointer result = *this;
  10890. result.reference_tokens = {reference_tokens[0]};
  10891. return result;
  10892. }
  10893. private:
  10894. /*!
  10895. @brief create and return a reference to the pointed to value
  10896. @complexity Linear in the number of reference tokens.
  10897. @throw parse_error.109 if array index is not a number
  10898. @throw type_error.313 if value cannot be unflattened
  10899. */
  10900. BasicJsonType& get_and_create(BasicJsonType& j) const
  10901. {
  10902. auto* result = &j;
  10903. // in case no reference tokens exist, return a reference to the JSON value
  10904. // j which will be overwritten by a primitive value
  10905. for (const auto& reference_token : reference_tokens)
  10906. {
  10907. switch (result->type())
  10908. {
  10909. case detail::value_t::null:
  10910. {
  10911. if (reference_token == "0")
  10912. {
  10913. // start a new array if reference token is 0
  10914. result = &result->operator[](0);
  10915. }
  10916. else
  10917. {
  10918. // start a new object otherwise
  10919. result = &result->operator[](reference_token);
  10920. }
  10921. break;
  10922. }
  10923. case detail::value_t::object:
  10924. {
  10925. // create an entry in the object
  10926. result = &result->operator[](reference_token);
  10927. break;
  10928. }
  10929. case detail::value_t::array:
  10930. {
  10931. // create an entry in the array
  10932. result = &result->operator[](array_index(reference_token));
  10933. break;
  10934. }
  10935. /*
  10936. The following code is only reached if there exists a reference
  10937. token _and_ the current value is primitive. In this case, we have
  10938. an error situation, because primitive values may only occur as
  10939. single value; that is, with an empty list of reference tokens.
  10940. */
  10941. case detail::value_t::string:
  10942. case detail::value_t::boolean:
  10943. case detail::value_t::number_integer:
  10944. case detail::value_t::number_unsigned:
  10945. case detail::value_t::number_float:
  10946. case detail::value_t::binary:
  10947. case detail::value_t::discarded:
  10948. default:
  10949. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j));
  10950. }
  10951. }
  10952. return *result;
  10953. }
  10954. /*!
  10955. @brief return a reference to the pointed to value
  10956. @note This version does not throw if a value is not present, but tries to
  10957. create nested values instead. For instance, calling this function
  10958. with pointer `"/this/that"` on a null value is equivalent to calling
  10959. `operator[]("this").operator[]("that")` on that value, effectively
  10960. changing the null value to an object.
  10961. @param[in] ptr a JSON value
  10962. @return reference to the JSON value pointed to by the JSON pointer
  10963. @complexity Linear in the length of the JSON pointer.
  10964. @throw parse_error.106 if an array index begins with '0'
  10965. @throw parse_error.109 if an array index was not a number
  10966. @throw out_of_range.404 if the JSON pointer can not be resolved
  10967. */
  10968. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  10969. {
  10970. for (const auto& reference_token : reference_tokens)
  10971. {
  10972. // convert null values to arrays or objects before continuing
  10973. if (ptr->is_null())
  10974. {
  10975. // check if reference token is a number
  10976. const bool nums =
  10977. std::all_of(reference_token.begin(), reference_token.end(),
  10978. [](const unsigned char x)
  10979. {
  10980. return std::isdigit(x);
  10981. });
  10982. // change value to array for numbers or "-" or to object otherwise
  10983. *ptr = (nums || reference_token == "-")
  10984. ? detail::value_t::array
  10985. : detail::value_t::object;
  10986. }
  10987. switch (ptr->type())
  10988. {
  10989. case detail::value_t::object:
  10990. {
  10991. // use unchecked object access
  10992. ptr = &ptr->operator[](reference_token);
  10993. break;
  10994. }
  10995. case detail::value_t::array:
  10996. {
  10997. if (reference_token == "-")
  10998. {
  10999. // explicitly treat "-" as index beyond the end
  11000. ptr = &ptr->operator[](ptr->m_value.array->size());
  11001. }
  11002. else
  11003. {
  11004. // convert array index to number; unchecked access
  11005. ptr = &ptr->operator[](array_index(reference_token));
  11006. }
  11007. break;
  11008. }
  11009. case detail::value_t::null:
  11010. case detail::value_t::string:
  11011. case detail::value_t::boolean:
  11012. case detail::value_t::number_integer:
  11013. case detail::value_t::number_unsigned:
  11014. case detail::value_t::number_float:
  11015. case detail::value_t::binary:
  11016. case detail::value_t::discarded:
  11017. default:
  11018. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11019. }
  11020. }
  11021. return *ptr;
  11022. }
  11023. /*!
  11024. @throw parse_error.106 if an array index begins with '0'
  11025. @throw parse_error.109 if an array index was not a number
  11026. @throw out_of_range.402 if the array index '-' is used
  11027. @throw out_of_range.404 if the JSON pointer can not be resolved
  11028. */
  11029. BasicJsonType& get_checked(BasicJsonType* ptr) const
  11030. {
  11031. for (const auto& reference_token : reference_tokens)
  11032. {
  11033. switch (ptr->type())
  11034. {
  11035. case detail::value_t::object:
  11036. {
  11037. // note: at performs range check
  11038. ptr = &ptr->at(reference_token);
  11039. break;
  11040. }
  11041. case detail::value_t::array:
  11042. {
  11043. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11044. {
  11045. // "-" always fails the range check
  11046. JSON_THROW(detail::out_of_range::create(402,
  11047. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  11048. ") is out of range", *ptr));
  11049. }
  11050. // note: at performs range check
  11051. ptr = &ptr->at(array_index(reference_token));
  11052. break;
  11053. }
  11054. case detail::value_t::null:
  11055. case detail::value_t::string:
  11056. case detail::value_t::boolean:
  11057. case detail::value_t::number_integer:
  11058. case detail::value_t::number_unsigned:
  11059. case detail::value_t::number_float:
  11060. case detail::value_t::binary:
  11061. case detail::value_t::discarded:
  11062. default:
  11063. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11064. }
  11065. }
  11066. return *ptr;
  11067. }
  11068. /*!
  11069. @brief return a const reference to the pointed to value
  11070. @param[in] ptr a JSON value
  11071. @return const reference to the JSON value pointed to by the JSON
  11072. pointer
  11073. @throw parse_error.106 if an array index begins with '0'
  11074. @throw parse_error.109 if an array index was not a number
  11075. @throw out_of_range.402 if the array index '-' is used
  11076. @throw out_of_range.404 if the JSON pointer can not be resolved
  11077. */
  11078. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  11079. {
  11080. for (const auto& reference_token : reference_tokens)
  11081. {
  11082. switch (ptr->type())
  11083. {
  11084. case detail::value_t::object:
  11085. {
  11086. // use unchecked object access
  11087. ptr = &ptr->operator[](reference_token);
  11088. break;
  11089. }
  11090. case detail::value_t::array:
  11091. {
  11092. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11093. {
  11094. // "-" cannot be used for const access
  11095. JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr));
  11096. }
  11097. // use unchecked array access
  11098. ptr = &ptr->operator[](array_index(reference_token));
  11099. break;
  11100. }
  11101. case detail::value_t::null:
  11102. case detail::value_t::string:
  11103. case detail::value_t::boolean:
  11104. case detail::value_t::number_integer:
  11105. case detail::value_t::number_unsigned:
  11106. case detail::value_t::number_float:
  11107. case detail::value_t::binary:
  11108. case detail::value_t::discarded:
  11109. default:
  11110. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11111. }
  11112. }
  11113. return *ptr;
  11114. }
  11115. /*!
  11116. @throw parse_error.106 if an array index begins with '0'
  11117. @throw parse_error.109 if an array index was not a number
  11118. @throw out_of_range.402 if the array index '-' is used
  11119. @throw out_of_range.404 if the JSON pointer can not be resolved
  11120. */
  11121. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  11122. {
  11123. for (const auto& reference_token : reference_tokens)
  11124. {
  11125. switch (ptr->type())
  11126. {
  11127. case detail::value_t::object:
  11128. {
  11129. // note: at performs range check
  11130. ptr = &ptr->at(reference_token);
  11131. break;
  11132. }
  11133. case detail::value_t::array:
  11134. {
  11135. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11136. {
  11137. // "-" always fails the range check
  11138. JSON_THROW(detail::out_of_range::create(402,
  11139. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  11140. ") is out of range", *ptr));
  11141. }
  11142. // note: at performs range check
  11143. ptr = &ptr->at(array_index(reference_token));
  11144. break;
  11145. }
  11146. case detail::value_t::null:
  11147. case detail::value_t::string:
  11148. case detail::value_t::boolean:
  11149. case detail::value_t::number_integer:
  11150. case detail::value_t::number_unsigned:
  11151. case detail::value_t::number_float:
  11152. case detail::value_t::binary:
  11153. case detail::value_t::discarded:
  11154. default:
  11155. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11156. }
  11157. }
  11158. return *ptr;
  11159. }
  11160. /*!
  11161. @throw parse_error.106 if an array index begins with '0'
  11162. @throw parse_error.109 if an array index was not a number
  11163. */
  11164. bool contains(const BasicJsonType* ptr) const
  11165. {
  11166. for (const auto& reference_token : reference_tokens)
  11167. {
  11168. switch (ptr->type())
  11169. {
  11170. case detail::value_t::object:
  11171. {
  11172. if (!ptr->contains(reference_token))
  11173. {
  11174. // we did not find the key in the object
  11175. return false;
  11176. }
  11177. ptr = &ptr->operator[](reference_token);
  11178. break;
  11179. }
  11180. case detail::value_t::array:
  11181. {
  11182. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11183. {
  11184. // "-" always fails the range check
  11185. return false;
  11186. }
  11187. if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9")))
  11188. {
  11189. // invalid char
  11190. return false;
  11191. }
  11192. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1))
  11193. {
  11194. if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9')))
  11195. {
  11196. // first char should be between '1' and '9'
  11197. return false;
  11198. }
  11199. for (std::size_t i = 1; i < reference_token.size(); i++)
  11200. {
  11201. if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9')))
  11202. {
  11203. // other char should be between '0' and '9'
  11204. return false;
  11205. }
  11206. }
  11207. }
  11208. const auto idx = array_index(reference_token);
  11209. if (idx >= ptr->size())
  11210. {
  11211. // index out of range
  11212. return false;
  11213. }
  11214. ptr = &ptr->operator[](idx);
  11215. break;
  11216. }
  11217. case detail::value_t::null:
  11218. case detail::value_t::string:
  11219. case detail::value_t::boolean:
  11220. case detail::value_t::number_integer:
  11221. case detail::value_t::number_unsigned:
  11222. case detail::value_t::number_float:
  11223. case detail::value_t::binary:
  11224. case detail::value_t::discarded:
  11225. default:
  11226. {
  11227. // we do not expect primitive values if there is still a
  11228. // reference token to process
  11229. return false;
  11230. }
  11231. }
  11232. }
  11233. // no reference token left means we found a primitive value
  11234. return true;
  11235. }
  11236. /*!
  11237. @brief split the string input to reference tokens
  11238. @note This function is only called by the json_pointer constructor.
  11239. All exceptions below are documented there.
  11240. @throw parse_error.107 if the pointer is not empty or begins with '/'
  11241. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  11242. */
  11243. static std::vector<std::string> split(const std::string& reference_string)
  11244. {
  11245. std::vector<std::string> result;
  11246. // special case: empty reference string -> no reference tokens
  11247. if (reference_string.empty())
  11248. {
  11249. return result;
  11250. }
  11251. // check if nonempty reference string begins with slash
  11252. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  11253. {
  11254. JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType()));
  11255. }
  11256. // extract the reference tokens:
  11257. // - slash: position of the last read slash (or end of string)
  11258. // - start: position after the previous slash
  11259. for (
  11260. // search for the first slash after the first character
  11261. std::size_t slash = reference_string.find_first_of('/', 1),
  11262. // set the beginning of the first reference token
  11263. start = 1;
  11264. // we can stop if start == 0 (if slash == std::string::npos)
  11265. start != 0;
  11266. // set the beginning of the next reference token
  11267. // (will eventually be 0 if slash == std::string::npos)
  11268. start = (slash == std::string::npos) ? 0 : slash + 1,
  11269. // find next slash
  11270. slash = reference_string.find_first_of('/', start))
  11271. {
  11272. // use the text between the beginning of the reference token
  11273. // (start) and the last slash (slash).
  11274. auto reference_token = reference_string.substr(start, slash - start);
  11275. // check reference tokens are properly escaped
  11276. for (std::size_t pos = reference_token.find_first_of('~');
  11277. pos != std::string::npos;
  11278. pos = reference_token.find_first_of('~', pos + 1))
  11279. {
  11280. JSON_ASSERT(reference_token[pos] == '~');
  11281. // ~ must be followed by 0 or 1
  11282. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 ||
  11283. (reference_token[pos + 1] != '0' &&
  11284. reference_token[pos + 1] != '1')))
  11285. {
  11286. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType()));
  11287. }
  11288. }
  11289. // finally, store the reference token
  11290. detail::unescape(reference_token);
  11291. result.push_back(reference_token);
  11292. }
  11293. return result;
  11294. }
  11295. private:
  11296. /*!
  11297. @param[in] reference_string the reference string to the current value
  11298. @param[in] value the value to consider
  11299. @param[in,out] result the result object to insert values to
  11300. @note Empty objects or arrays are flattened to `null`.
  11301. */
  11302. static void flatten(const std::string& reference_string,
  11303. const BasicJsonType& value,
  11304. BasicJsonType& result)
  11305. {
  11306. switch (value.type())
  11307. {
  11308. case detail::value_t::array:
  11309. {
  11310. if (value.m_value.array->empty())
  11311. {
  11312. // flatten empty array as null
  11313. result[reference_string] = nullptr;
  11314. }
  11315. else
  11316. {
  11317. // iterate array and use index as reference string
  11318. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  11319. {
  11320. flatten(reference_string + "/" + std::to_string(i),
  11321. value.m_value.array->operator[](i), result);
  11322. }
  11323. }
  11324. break;
  11325. }
  11326. case detail::value_t::object:
  11327. {
  11328. if (value.m_value.object->empty())
  11329. {
  11330. // flatten empty object as null
  11331. result[reference_string] = nullptr;
  11332. }
  11333. else
  11334. {
  11335. // iterate object and use keys as reference string
  11336. for (const auto& element : *value.m_value.object)
  11337. {
  11338. flatten(reference_string + "/" + detail::escape(element.first), element.second, result);
  11339. }
  11340. }
  11341. break;
  11342. }
  11343. case detail::value_t::null:
  11344. case detail::value_t::string:
  11345. case detail::value_t::boolean:
  11346. case detail::value_t::number_integer:
  11347. case detail::value_t::number_unsigned:
  11348. case detail::value_t::number_float:
  11349. case detail::value_t::binary:
  11350. case detail::value_t::discarded:
  11351. default:
  11352. {
  11353. // add primitive value with its reference string
  11354. result[reference_string] = value;
  11355. break;
  11356. }
  11357. }
  11358. }
  11359. /*!
  11360. @param[in] value flattened JSON
  11361. @return unflattened JSON
  11362. @throw parse_error.109 if array index is not a number
  11363. @throw type_error.314 if value is not an object
  11364. @throw type_error.315 if object values are not primitive
  11365. @throw type_error.313 if value cannot be unflattened
  11366. */
  11367. static BasicJsonType
  11368. unflatten(const BasicJsonType& value)
  11369. {
  11370. if (JSON_HEDLEY_UNLIKELY(!value.is_object()))
  11371. {
  11372. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value));
  11373. }
  11374. BasicJsonType result;
  11375. // iterate the JSON object values
  11376. for (const auto& element : *value.m_value.object)
  11377. {
  11378. if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive()))
  11379. {
  11380. JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second));
  11381. }
  11382. // assign value to reference pointed to by JSON pointer; Note that if
  11383. // the JSON pointer is "" (i.e., points to the whole value), function
  11384. // get_and_create returns a reference to result itself. An assignment
  11385. // will then create a primitive value.
  11386. json_pointer(element.first).get_and_create(result) = element.second;
  11387. }
  11388. return result;
  11389. }
  11390. /*!
  11391. @brief compares two JSON pointers for equality
  11392. @param[in] lhs JSON pointer to compare
  11393. @param[in] rhs JSON pointer to compare
  11394. @return whether @a lhs is equal to @a rhs
  11395. @complexity Linear in the length of the JSON pointer
  11396. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11397. */
  11398. friend bool operator==(json_pointer const& lhs,
  11399. json_pointer const& rhs) noexcept
  11400. {
  11401. return lhs.reference_tokens == rhs.reference_tokens;
  11402. }
  11403. /*!
  11404. @brief compares two JSON pointers for inequality
  11405. @param[in] lhs JSON pointer to compare
  11406. @param[in] rhs JSON pointer to compare
  11407. @return whether @a lhs is not equal @a rhs
  11408. @complexity Linear in the length of the JSON pointer
  11409. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11410. */
  11411. friend bool operator!=(json_pointer const& lhs,
  11412. json_pointer const& rhs) noexcept
  11413. {
  11414. return !(lhs == rhs);
  11415. }
  11416. /// the reference tokens
  11417. std::vector<std::string> reference_tokens;
  11418. };
  11419. } // namespace nlohmann
  11420. // #include <nlohmann/detail/json_ref.hpp>
  11421. #include <initializer_list>
  11422. #include <utility>
  11423. // #include <nlohmann/detail/meta/type_traits.hpp>
  11424. namespace nlohmann
  11425. {
  11426. namespace detail
  11427. {
  11428. template<typename BasicJsonType>
  11429. class json_ref
  11430. {
  11431. public:
  11432. using value_type = BasicJsonType;
  11433. json_ref(value_type&& value)
  11434. : owned_value(std::move(value))
  11435. {}
  11436. json_ref(const value_type& value)
  11437. : value_ref(&value)
  11438. {}
  11439. json_ref(std::initializer_list<json_ref> init)
  11440. : owned_value(init)
  11441. {}
  11442. template <
  11443. class... Args,
  11444. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  11445. json_ref(Args && ... args)
  11446. : owned_value(std::forward<Args>(args)...)
  11447. {}
  11448. // class should be movable only
  11449. json_ref(json_ref&&) noexcept = default;
  11450. json_ref(const json_ref&) = delete;
  11451. json_ref& operator=(const json_ref&) = delete;
  11452. json_ref& operator=(json_ref&&) = delete;
  11453. ~json_ref() = default;
  11454. value_type moved_or_copied() const
  11455. {
  11456. if (value_ref == nullptr)
  11457. {
  11458. return std::move(owned_value);
  11459. }
  11460. return *value_ref;
  11461. }
  11462. value_type const& operator*() const
  11463. {
  11464. return value_ref ? *value_ref : owned_value;
  11465. }
  11466. value_type const* operator->() const
  11467. {
  11468. return &** this;
  11469. }
  11470. private:
  11471. mutable value_type owned_value = nullptr;
  11472. value_type const* value_ref = nullptr;
  11473. };
  11474. } // namespace detail
  11475. } // namespace nlohmann
  11476. // #include <nlohmann/detail/macro_scope.hpp>
  11477. // #include <nlohmann/detail/string_escape.hpp>
  11478. // #include <nlohmann/detail/meta/cpp_future.hpp>
  11479. // #include <nlohmann/detail/meta/type_traits.hpp>
  11480. // #include <nlohmann/detail/output/binary_writer.hpp>
  11481. #include <algorithm> // reverse
  11482. #include <array> // array
  11483. #include <cmath> // isnan, isinf
  11484. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  11485. #include <cstring> // memcpy
  11486. #include <limits> // numeric_limits
  11487. #include <string> // string
  11488. #include <utility> // move
  11489. // #include <nlohmann/detail/input/binary_reader.hpp>
  11490. // #include <nlohmann/detail/macro_scope.hpp>
  11491. // #include <nlohmann/detail/output/output_adapters.hpp>
  11492. #include <algorithm> // copy
  11493. #include <cstddef> // size_t
  11494. #include <iterator> // back_inserter
  11495. #include <memory> // shared_ptr, make_shared
  11496. #include <string> // basic_string
  11497. #include <vector> // vector
  11498. #ifndef JSON_NO_IO
  11499. #include <ios> // streamsize
  11500. #include <ostream> // basic_ostream
  11501. #endif // JSON_NO_IO
  11502. // #include <nlohmann/detail/macro_scope.hpp>
  11503. namespace nlohmann
  11504. {
  11505. namespace detail
  11506. {
  11507. /// abstract output adapter interface
  11508. template<typename CharType> struct output_adapter_protocol
  11509. {
  11510. virtual void write_character(CharType c) = 0;
  11511. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  11512. virtual ~output_adapter_protocol() = default;
  11513. output_adapter_protocol() = default;
  11514. output_adapter_protocol(const output_adapter_protocol&) = default;
  11515. output_adapter_protocol(output_adapter_protocol&&) noexcept = default;
  11516. output_adapter_protocol& operator=(const output_adapter_protocol&) = default;
  11517. output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default;
  11518. };
  11519. /// a type to simplify interfaces
  11520. template<typename CharType>
  11521. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  11522. /// output adapter for byte vectors
  11523. template<typename CharType, typename AllocatorType = std::allocator<CharType>>
  11524. class output_vector_adapter : public output_adapter_protocol<CharType>
  11525. {
  11526. public:
  11527. explicit output_vector_adapter(std::vector<CharType, AllocatorType>& vec) noexcept
  11528. : v(vec)
  11529. {}
  11530. void write_character(CharType c) override
  11531. {
  11532. v.push_back(c);
  11533. }
  11534. JSON_HEDLEY_NON_NULL(2)
  11535. void write_characters(const CharType* s, std::size_t length) override
  11536. {
  11537. std::copy(s, s + length, std::back_inserter(v));
  11538. }
  11539. private:
  11540. std::vector<CharType, AllocatorType>& v;
  11541. };
  11542. #ifndef JSON_NO_IO
  11543. /// output adapter for output streams
  11544. template<typename CharType>
  11545. class output_stream_adapter : public output_adapter_protocol<CharType>
  11546. {
  11547. public:
  11548. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  11549. : stream(s)
  11550. {}
  11551. void write_character(CharType c) override
  11552. {
  11553. stream.put(c);
  11554. }
  11555. JSON_HEDLEY_NON_NULL(2)
  11556. void write_characters(const CharType* s, std::size_t length) override
  11557. {
  11558. stream.write(s, static_cast<std::streamsize>(length));
  11559. }
  11560. private:
  11561. std::basic_ostream<CharType>& stream;
  11562. };
  11563. #endif // JSON_NO_IO
  11564. /// output adapter for basic_string
  11565. template<typename CharType, typename StringType = std::basic_string<CharType>>
  11566. class output_string_adapter : public output_adapter_protocol<CharType>
  11567. {
  11568. public:
  11569. explicit output_string_adapter(StringType& s) noexcept
  11570. : str(s)
  11571. {}
  11572. void write_character(CharType c) override
  11573. {
  11574. str.push_back(c);
  11575. }
  11576. JSON_HEDLEY_NON_NULL(2)
  11577. void write_characters(const CharType* s, std::size_t length) override
  11578. {
  11579. str.append(s, length);
  11580. }
  11581. private:
  11582. StringType& str;
  11583. };
  11584. template<typename CharType, typename StringType = std::basic_string<CharType>>
  11585. class output_adapter
  11586. {
  11587. public:
  11588. template<typename AllocatorType = std::allocator<CharType>>
  11589. output_adapter(std::vector<CharType, AllocatorType>& vec)
  11590. : oa(std::make_shared<output_vector_adapter<CharType, AllocatorType>>(vec)) {}
  11591. #ifndef JSON_NO_IO
  11592. output_adapter(std::basic_ostream<CharType>& s)
  11593. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  11594. #endif // JSON_NO_IO
  11595. output_adapter(StringType& s)
  11596. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  11597. operator output_adapter_t<CharType>()
  11598. {
  11599. return oa;
  11600. }
  11601. private:
  11602. output_adapter_t<CharType> oa = nullptr;
  11603. };
  11604. } // namespace detail
  11605. } // namespace nlohmann
  11606. namespace nlohmann
  11607. {
  11608. namespace detail
  11609. {
  11610. ///////////////////
  11611. // binary writer //
  11612. ///////////////////
  11613. /*!
  11614. @brief serialization to CBOR and MessagePack values
  11615. */
  11616. template<typename BasicJsonType, typename CharType>
  11617. class binary_writer
  11618. {
  11619. using string_t = typename BasicJsonType::string_t;
  11620. using binary_t = typename BasicJsonType::binary_t;
  11621. using number_float_t = typename BasicJsonType::number_float_t;
  11622. public:
  11623. /*!
  11624. @brief create a binary writer
  11625. @param[in] adapter output adapter to write to
  11626. */
  11627. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(std::move(adapter))
  11628. {
  11629. JSON_ASSERT(oa);
  11630. }
  11631. /*!
  11632. @param[in] j JSON value to serialize
  11633. @pre j.type() == value_t::object
  11634. */
  11635. void write_bson(const BasicJsonType& j)
  11636. {
  11637. switch (j.type())
  11638. {
  11639. case value_t::object:
  11640. {
  11641. write_bson_object(*j.m_value.object);
  11642. break;
  11643. }
  11644. case value_t::null:
  11645. case value_t::array:
  11646. case value_t::string:
  11647. case value_t::boolean:
  11648. case value_t::number_integer:
  11649. case value_t::number_unsigned:
  11650. case value_t::number_float:
  11651. case value_t::binary:
  11652. case value_t::discarded:
  11653. default:
  11654. {
  11655. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j));
  11656. }
  11657. }
  11658. }
  11659. /*!
  11660. @param[in] j JSON value to serialize
  11661. */
  11662. void write_cbor(const BasicJsonType& j)
  11663. {
  11664. switch (j.type())
  11665. {
  11666. case value_t::null:
  11667. {
  11668. oa->write_character(to_char_type(0xF6));
  11669. break;
  11670. }
  11671. case value_t::boolean:
  11672. {
  11673. oa->write_character(j.m_value.boolean
  11674. ? to_char_type(0xF5)
  11675. : to_char_type(0xF4));
  11676. break;
  11677. }
  11678. case value_t::number_integer:
  11679. {
  11680. if (j.m_value.number_integer >= 0)
  11681. {
  11682. // CBOR does not differentiate between positive signed
  11683. // integers and unsigned integers. Therefore, we used the
  11684. // code from the value_t::number_unsigned case here.
  11685. if (j.m_value.number_integer <= 0x17)
  11686. {
  11687. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11688. }
  11689. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  11690. {
  11691. oa->write_character(to_char_type(0x18));
  11692. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11693. }
  11694. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  11695. {
  11696. oa->write_character(to_char_type(0x19));
  11697. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  11698. }
  11699. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  11700. {
  11701. oa->write_character(to_char_type(0x1A));
  11702. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  11703. }
  11704. else
  11705. {
  11706. oa->write_character(to_char_type(0x1B));
  11707. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  11708. }
  11709. }
  11710. else
  11711. {
  11712. // The conversions below encode the sign in the first
  11713. // byte, and the value is converted to a positive number.
  11714. const auto positive_number = -1 - j.m_value.number_integer;
  11715. if (j.m_value.number_integer >= -24)
  11716. {
  11717. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  11718. }
  11719. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  11720. {
  11721. oa->write_character(to_char_type(0x38));
  11722. write_number(static_cast<std::uint8_t>(positive_number));
  11723. }
  11724. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  11725. {
  11726. oa->write_character(to_char_type(0x39));
  11727. write_number(static_cast<std::uint16_t>(positive_number));
  11728. }
  11729. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  11730. {
  11731. oa->write_character(to_char_type(0x3A));
  11732. write_number(static_cast<std::uint32_t>(positive_number));
  11733. }
  11734. else
  11735. {
  11736. oa->write_character(to_char_type(0x3B));
  11737. write_number(static_cast<std::uint64_t>(positive_number));
  11738. }
  11739. }
  11740. break;
  11741. }
  11742. case value_t::number_unsigned:
  11743. {
  11744. if (j.m_value.number_unsigned <= 0x17)
  11745. {
  11746. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  11747. }
  11748. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  11749. {
  11750. oa->write_character(to_char_type(0x18));
  11751. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  11752. }
  11753. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  11754. {
  11755. oa->write_character(to_char_type(0x19));
  11756. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  11757. }
  11758. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  11759. {
  11760. oa->write_character(to_char_type(0x1A));
  11761. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  11762. }
  11763. else
  11764. {
  11765. oa->write_character(to_char_type(0x1B));
  11766. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  11767. }
  11768. break;
  11769. }
  11770. case value_t::number_float:
  11771. {
  11772. if (std::isnan(j.m_value.number_float))
  11773. {
  11774. // NaN is 0xf97e00 in CBOR
  11775. oa->write_character(to_char_type(0xF9));
  11776. oa->write_character(to_char_type(0x7E));
  11777. oa->write_character(to_char_type(0x00));
  11778. }
  11779. else if (std::isinf(j.m_value.number_float))
  11780. {
  11781. // Infinity is 0xf97c00, -Infinity is 0xf9fc00
  11782. oa->write_character(to_char_type(0xf9));
  11783. oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC));
  11784. oa->write_character(to_char_type(0x00));
  11785. }
  11786. else
  11787. {
  11788. write_compact_float(j.m_value.number_float, detail::input_format_t::cbor);
  11789. }
  11790. break;
  11791. }
  11792. case value_t::string:
  11793. {
  11794. // step 1: write control byte and the string length
  11795. const auto N = j.m_value.string->size();
  11796. if (N <= 0x17)
  11797. {
  11798. write_number(static_cast<std::uint8_t>(0x60 + N));
  11799. }
  11800. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11801. {
  11802. oa->write_character(to_char_type(0x78));
  11803. write_number(static_cast<std::uint8_t>(N));
  11804. }
  11805. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11806. {
  11807. oa->write_character(to_char_type(0x79));
  11808. write_number(static_cast<std::uint16_t>(N));
  11809. }
  11810. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11811. {
  11812. oa->write_character(to_char_type(0x7A));
  11813. write_number(static_cast<std::uint32_t>(N));
  11814. }
  11815. // LCOV_EXCL_START
  11816. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  11817. {
  11818. oa->write_character(to_char_type(0x7B));
  11819. write_number(static_cast<std::uint64_t>(N));
  11820. }
  11821. // LCOV_EXCL_STOP
  11822. // step 2: write the string
  11823. oa->write_characters(
  11824. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  11825. j.m_value.string->size());
  11826. break;
  11827. }
  11828. case value_t::array:
  11829. {
  11830. // step 1: write control byte and the array size
  11831. const auto N = j.m_value.array->size();
  11832. if (N <= 0x17)
  11833. {
  11834. write_number(static_cast<std::uint8_t>(0x80 + N));
  11835. }
  11836. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11837. {
  11838. oa->write_character(to_char_type(0x98));
  11839. write_number(static_cast<std::uint8_t>(N));
  11840. }
  11841. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11842. {
  11843. oa->write_character(to_char_type(0x99));
  11844. write_number(static_cast<std::uint16_t>(N));
  11845. }
  11846. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11847. {
  11848. oa->write_character(to_char_type(0x9A));
  11849. write_number(static_cast<std::uint32_t>(N));
  11850. }
  11851. // LCOV_EXCL_START
  11852. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  11853. {
  11854. oa->write_character(to_char_type(0x9B));
  11855. write_number(static_cast<std::uint64_t>(N));
  11856. }
  11857. // LCOV_EXCL_STOP
  11858. // step 2: write each element
  11859. for (const auto& el : *j.m_value.array)
  11860. {
  11861. write_cbor(el);
  11862. }
  11863. break;
  11864. }
  11865. case value_t::binary:
  11866. {
  11867. if (j.m_value.binary->has_subtype())
  11868. {
  11869. if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint8_t>::max)())
  11870. {
  11871. write_number(static_cast<std::uint8_t>(0xd8));
  11872. write_number(static_cast<std::uint8_t>(j.m_value.binary->subtype()));
  11873. }
  11874. else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint16_t>::max)())
  11875. {
  11876. write_number(static_cast<std::uint8_t>(0xd9));
  11877. write_number(static_cast<std::uint16_t>(j.m_value.binary->subtype()));
  11878. }
  11879. else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint32_t>::max)())
  11880. {
  11881. write_number(static_cast<std::uint8_t>(0xda));
  11882. write_number(static_cast<std::uint32_t>(j.m_value.binary->subtype()));
  11883. }
  11884. else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint64_t>::max)())
  11885. {
  11886. write_number(static_cast<std::uint8_t>(0xdb));
  11887. write_number(static_cast<std::uint64_t>(j.m_value.binary->subtype()));
  11888. }
  11889. }
  11890. // step 1: write control byte and the binary array size
  11891. const auto N = j.m_value.binary->size();
  11892. if (N <= 0x17)
  11893. {
  11894. write_number(static_cast<std::uint8_t>(0x40 + N));
  11895. }
  11896. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11897. {
  11898. oa->write_character(to_char_type(0x58));
  11899. write_number(static_cast<std::uint8_t>(N));
  11900. }
  11901. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11902. {
  11903. oa->write_character(to_char_type(0x59));
  11904. write_number(static_cast<std::uint16_t>(N));
  11905. }
  11906. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11907. {
  11908. oa->write_character(to_char_type(0x5A));
  11909. write_number(static_cast<std::uint32_t>(N));
  11910. }
  11911. // LCOV_EXCL_START
  11912. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  11913. {
  11914. oa->write_character(to_char_type(0x5B));
  11915. write_number(static_cast<std::uint64_t>(N));
  11916. }
  11917. // LCOV_EXCL_STOP
  11918. // step 2: write each element
  11919. oa->write_characters(
  11920. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  11921. N);
  11922. break;
  11923. }
  11924. case value_t::object:
  11925. {
  11926. // step 1: write control byte and the object size
  11927. const auto N = j.m_value.object->size();
  11928. if (N <= 0x17)
  11929. {
  11930. write_number(static_cast<std::uint8_t>(0xA0 + N));
  11931. }
  11932. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11933. {
  11934. oa->write_character(to_char_type(0xB8));
  11935. write_number(static_cast<std::uint8_t>(N));
  11936. }
  11937. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11938. {
  11939. oa->write_character(to_char_type(0xB9));
  11940. write_number(static_cast<std::uint16_t>(N));
  11941. }
  11942. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11943. {
  11944. oa->write_character(to_char_type(0xBA));
  11945. write_number(static_cast<std::uint32_t>(N));
  11946. }
  11947. // LCOV_EXCL_START
  11948. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  11949. {
  11950. oa->write_character(to_char_type(0xBB));
  11951. write_number(static_cast<std::uint64_t>(N));
  11952. }
  11953. // LCOV_EXCL_STOP
  11954. // step 2: write each element
  11955. for (const auto& el : *j.m_value.object)
  11956. {
  11957. write_cbor(el.first);
  11958. write_cbor(el.second);
  11959. }
  11960. break;
  11961. }
  11962. case value_t::discarded:
  11963. default:
  11964. break;
  11965. }
  11966. }
  11967. /*!
  11968. @param[in] j JSON value to serialize
  11969. */
  11970. void write_msgpack(const BasicJsonType& j)
  11971. {
  11972. switch (j.type())
  11973. {
  11974. case value_t::null: // nil
  11975. {
  11976. oa->write_character(to_char_type(0xC0));
  11977. break;
  11978. }
  11979. case value_t::boolean: // true and false
  11980. {
  11981. oa->write_character(j.m_value.boolean
  11982. ? to_char_type(0xC3)
  11983. : to_char_type(0xC2));
  11984. break;
  11985. }
  11986. case value_t::number_integer:
  11987. {
  11988. if (j.m_value.number_integer >= 0)
  11989. {
  11990. // MessagePack does not differentiate between positive
  11991. // signed integers and unsigned integers. Therefore, we used
  11992. // the code from the value_t::number_unsigned case here.
  11993. if (j.m_value.number_unsigned < 128)
  11994. {
  11995. // positive fixnum
  11996. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11997. }
  11998. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  11999. {
  12000. // uint 8
  12001. oa->write_character(to_char_type(0xCC));
  12002. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12003. }
  12004. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  12005. {
  12006. // uint 16
  12007. oa->write_character(to_char_type(0xCD));
  12008. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  12009. }
  12010. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  12011. {
  12012. // uint 32
  12013. oa->write_character(to_char_type(0xCE));
  12014. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  12015. }
  12016. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  12017. {
  12018. // uint 64
  12019. oa->write_character(to_char_type(0xCF));
  12020. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  12021. }
  12022. }
  12023. else
  12024. {
  12025. if (j.m_value.number_integer >= -32)
  12026. {
  12027. // negative fixnum
  12028. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  12029. }
  12030. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() &&
  12031. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  12032. {
  12033. // int 8
  12034. oa->write_character(to_char_type(0xD0));
  12035. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  12036. }
  12037. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() &&
  12038. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  12039. {
  12040. // int 16
  12041. oa->write_character(to_char_type(0xD1));
  12042. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  12043. }
  12044. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() &&
  12045. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  12046. {
  12047. // int 32
  12048. oa->write_character(to_char_type(0xD2));
  12049. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  12050. }
  12051. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() &&
  12052. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  12053. {
  12054. // int 64
  12055. oa->write_character(to_char_type(0xD3));
  12056. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  12057. }
  12058. }
  12059. break;
  12060. }
  12061. case value_t::number_unsigned:
  12062. {
  12063. if (j.m_value.number_unsigned < 128)
  12064. {
  12065. // positive fixnum
  12066. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12067. }
  12068. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  12069. {
  12070. // uint 8
  12071. oa->write_character(to_char_type(0xCC));
  12072. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12073. }
  12074. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  12075. {
  12076. // uint 16
  12077. oa->write_character(to_char_type(0xCD));
  12078. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  12079. }
  12080. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  12081. {
  12082. // uint 32
  12083. oa->write_character(to_char_type(0xCE));
  12084. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  12085. }
  12086. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  12087. {
  12088. // uint 64
  12089. oa->write_character(to_char_type(0xCF));
  12090. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  12091. }
  12092. break;
  12093. }
  12094. case value_t::number_float:
  12095. {
  12096. write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack);
  12097. break;
  12098. }
  12099. case value_t::string:
  12100. {
  12101. // step 1: write control byte and the string length
  12102. const auto N = j.m_value.string->size();
  12103. if (N <= 31)
  12104. {
  12105. // fixstr
  12106. write_number(static_cast<std::uint8_t>(0xA0 | N));
  12107. }
  12108. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12109. {
  12110. // str 8
  12111. oa->write_character(to_char_type(0xD9));
  12112. write_number(static_cast<std::uint8_t>(N));
  12113. }
  12114. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12115. {
  12116. // str 16
  12117. oa->write_character(to_char_type(0xDA));
  12118. write_number(static_cast<std::uint16_t>(N));
  12119. }
  12120. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12121. {
  12122. // str 32
  12123. oa->write_character(to_char_type(0xDB));
  12124. write_number(static_cast<std::uint32_t>(N));
  12125. }
  12126. // step 2: write the string
  12127. oa->write_characters(
  12128. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  12129. j.m_value.string->size());
  12130. break;
  12131. }
  12132. case value_t::array:
  12133. {
  12134. // step 1: write control byte and the array size
  12135. const auto N = j.m_value.array->size();
  12136. if (N <= 15)
  12137. {
  12138. // fixarray
  12139. write_number(static_cast<std::uint8_t>(0x90 | N));
  12140. }
  12141. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12142. {
  12143. // array 16
  12144. oa->write_character(to_char_type(0xDC));
  12145. write_number(static_cast<std::uint16_t>(N));
  12146. }
  12147. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12148. {
  12149. // array 32
  12150. oa->write_character(to_char_type(0xDD));
  12151. write_number(static_cast<std::uint32_t>(N));
  12152. }
  12153. // step 2: write each element
  12154. for (const auto& el : *j.m_value.array)
  12155. {
  12156. write_msgpack(el);
  12157. }
  12158. break;
  12159. }
  12160. case value_t::binary:
  12161. {
  12162. // step 0: determine if the binary type has a set subtype to
  12163. // determine whether or not to use the ext or fixext types
  12164. const bool use_ext = j.m_value.binary->has_subtype();
  12165. // step 1: write control byte and the byte string length
  12166. const auto N = j.m_value.binary->size();
  12167. if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12168. {
  12169. std::uint8_t output_type{};
  12170. bool fixed = true;
  12171. if (use_ext)
  12172. {
  12173. switch (N)
  12174. {
  12175. case 1:
  12176. output_type = 0xD4; // fixext 1
  12177. break;
  12178. case 2:
  12179. output_type = 0xD5; // fixext 2
  12180. break;
  12181. case 4:
  12182. output_type = 0xD6; // fixext 4
  12183. break;
  12184. case 8:
  12185. output_type = 0xD7; // fixext 8
  12186. break;
  12187. case 16:
  12188. output_type = 0xD8; // fixext 16
  12189. break;
  12190. default:
  12191. output_type = 0xC7; // ext 8
  12192. fixed = false;
  12193. break;
  12194. }
  12195. }
  12196. else
  12197. {
  12198. output_type = 0xC4; // bin 8
  12199. fixed = false;
  12200. }
  12201. oa->write_character(to_char_type(output_type));
  12202. if (!fixed)
  12203. {
  12204. write_number(static_cast<std::uint8_t>(N));
  12205. }
  12206. }
  12207. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12208. {
  12209. std::uint8_t output_type = use_ext
  12210. ? 0xC8 // ext 16
  12211. : 0xC5; // bin 16
  12212. oa->write_character(to_char_type(output_type));
  12213. write_number(static_cast<std::uint16_t>(N));
  12214. }
  12215. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12216. {
  12217. std::uint8_t output_type = use_ext
  12218. ? 0xC9 // ext 32
  12219. : 0xC6; // bin 32
  12220. oa->write_character(to_char_type(output_type));
  12221. write_number(static_cast<std::uint32_t>(N));
  12222. }
  12223. // step 1.5: if this is an ext type, write the subtype
  12224. if (use_ext)
  12225. {
  12226. write_number(static_cast<std::int8_t>(j.m_value.binary->subtype()));
  12227. }
  12228. // step 2: write the byte string
  12229. oa->write_characters(
  12230. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  12231. N);
  12232. break;
  12233. }
  12234. case value_t::object:
  12235. {
  12236. // step 1: write control byte and the object size
  12237. const auto N = j.m_value.object->size();
  12238. if (N <= 15)
  12239. {
  12240. // fixmap
  12241. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  12242. }
  12243. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12244. {
  12245. // map 16
  12246. oa->write_character(to_char_type(0xDE));
  12247. write_number(static_cast<std::uint16_t>(N));
  12248. }
  12249. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12250. {
  12251. // map 32
  12252. oa->write_character(to_char_type(0xDF));
  12253. write_number(static_cast<std::uint32_t>(N));
  12254. }
  12255. // step 2: write each element
  12256. for (const auto& el : *j.m_value.object)
  12257. {
  12258. write_msgpack(el.first);
  12259. write_msgpack(el.second);
  12260. }
  12261. break;
  12262. }
  12263. case value_t::discarded:
  12264. default:
  12265. break;
  12266. }
  12267. }
  12268. /*!
  12269. @param[in] j JSON value to serialize
  12270. @param[in] use_count whether to use '#' prefixes (optimized format)
  12271. @param[in] use_type whether to use '$' prefixes (optimized format)
  12272. @param[in] add_prefix whether prefixes need to be used for this value
  12273. */
  12274. void write_ubjson(const BasicJsonType& j, const bool use_count,
  12275. const bool use_type, const bool add_prefix = true)
  12276. {
  12277. switch (j.type())
  12278. {
  12279. case value_t::null:
  12280. {
  12281. if (add_prefix)
  12282. {
  12283. oa->write_character(to_char_type('Z'));
  12284. }
  12285. break;
  12286. }
  12287. case value_t::boolean:
  12288. {
  12289. if (add_prefix)
  12290. {
  12291. oa->write_character(j.m_value.boolean
  12292. ? to_char_type('T')
  12293. : to_char_type('F'));
  12294. }
  12295. break;
  12296. }
  12297. case value_t::number_integer:
  12298. {
  12299. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  12300. break;
  12301. }
  12302. case value_t::number_unsigned:
  12303. {
  12304. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  12305. break;
  12306. }
  12307. case value_t::number_float:
  12308. {
  12309. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  12310. break;
  12311. }
  12312. case value_t::string:
  12313. {
  12314. if (add_prefix)
  12315. {
  12316. oa->write_character(to_char_type('S'));
  12317. }
  12318. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  12319. oa->write_characters(
  12320. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  12321. j.m_value.string->size());
  12322. break;
  12323. }
  12324. case value_t::array:
  12325. {
  12326. if (add_prefix)
  12327. {
  12328. oa->write_character(to_char_type('['));
  12329. }
  12330. bool prefix_required = true;
  12331. if (use_type && !j.m_value.array->empty())
  12332. {
  12333. JSON_ASSERT(use_count);
  12334. const CharType first_prefix = ubjson_prefix(j.front());
  12335. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  12336. [this, first_prefix](const BasicJsonType & v)
  12337. {
  12338. return ubjson_prefix(v) == first_prefix;
  12339. });
  12340. if (same_prefix)
  12341. {
  12342. prefix_required = false;
  12343. oa->write_character(to_char_type('$'));
  12344. oa->write_character(first_prefix);
  12345. }
  12346. }
  12347. if (use_count)
  12348. {
  12349. oa->write_character(to_char_type('#'));
  12350. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  12351. }
  12352. for (const auto& el : *j.m_value.array)
  12353. {
  12354. write_ubjson(el, use_count, use_type, prefix_required);
  12355. }
  12356. if (!use_count)
  12357. {
  12358. oa->write_character(to_char_type(']'));
  12359. }
  12360. break;
  12361. }
  12362. case value_t::binary:
  12363. {
  12364. if (add_prefix)
  12365. {
  12366. oa->write_character(to_char_type('['));
  12367. }
  12368. if (use_type && !j.m_value.binary->empty())
  12369. {
  12370. JSON_ASSERT(use_count);
  12371. oa->write_character(to_char_type('$'));
  12372. oa->write_character('U');
  12373. }
  12374. if (use_count)
  12375. {
  12376. oa->write_character(to_char_type('#'));
  12377. write_number_with_ubjson_prefix(j.m_value.binary->size(), true);
  12378. }
  12379. if (use_type)
  12380. {
  12381. oa->write_characters(
  12382. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  12383. j.m_value.binary->size());
  12384. }
  12385. else
  12386. {
  12387. for (size_t i = 0; i < j.m_value.binary->size(); ++i)
  12388. {
  12389. oa->write_character(to_char_type('U'));
  12390. oa->write_character(j.m_value.binary->data()[i]);
  12391. }
  12392. }
  12393. if (!use_count)
  12394. {
  12395. oa->write_character(to_char_type(']'));
  12396. }
  12397. break;
  12398. }
  12399. case value_t::object:
  12400. {
  12401. if (add_prefix)
  12402. {
  12403. oa->write_character(to_char_type('{'));
  12404. }
  12405. bool prefix_required = true;
  12406. if (use_type && !j.m_value.object->empty())
  12407. {
  12408. JSON_ASSERT(use_count);
  12409. const CharType first_prefix = ubjson_prefix(j.front());
  12410. const bool same_prefix = std::all_of(j.begin(), j.end(),
  12411. [this, first_prefix](const BasicJsonType & v)
  12412. {
  12413. return ubjson_prefix(v) == first_prefix;
  12414. });
  12415. if (same_prefix)
  12416. {
  12417. prefix_required = false;
  12418. oa->write_character(to_char_type('$'));
  12419. oa->write_character(first_prefix);
  12420. }
  12421. }
  12422. if (use_count)
  12423. {
  12424. oa->write_character(to_char_type('#'));
  12425. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  12426. }
  12427. for (const auto& el : *j.m_value.object)
  12428. {
  12429. write_number_with_ubjson_prefix(el.first.size(), true);
  12430. oa->write_characters(
  12431. reinterpret_cast<const CharType*>(el.first.c_str()),
  12432. el.first.size());
  12433. write_ubjson(el.second, use_count, use_type, prefix_required);
  12434. }
  12435. if (!use_count)
  12436. {
  12437. oa->write_character(to_char_type('}'));
  12438. }
  12439. break;
  12440. }
  12441. case value_t::discarded:
  12442. default:
  12443. break;
  12444. }
  12445. }
  12446. private:
  12447. //////////
  12448. // BSON //
  12449. //////////
  12450. /*!
  12451. @return The size of a BSON document entry header, including the id marker
  12452. and the entry name size (and its null-terminator).
  12453. */
  12454. static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j)
  12455. {
  12456. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  12457. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  12458. {
  12459. JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j));
  12460. static_cast<void>(j);
  12461. }
  12462. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  12463. }
  12464. /*!
  12465. @brief Writes the given @a element_type and @a name to the output adapter
  12466. */
  12467. void write_bson_entry_header(const string_t& name,
  12468. const std::uint8_t element_type)
  12469. {
  12470. oa->write_character(to_char_type(element_type)); // boolean
  12471. oa->write_characters(
  12472. reinterpret_cast<const CharType*>(name.c_str()),
  12473. name.size() + 1u);
  12474. }
  12475. /*!
  12476. @brief Writes a BSON element with key @a name and boolean value @a value
  12477. */
  12478. void write_bson_boolean(const string_t& name,
  12479. const bool value)
  12480. {
  12481. write_bson_entry_header(name, 0x08);
  12482. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  12483. }
  12484. /*!
  12485. @brief Writes a BSON element with key @a name and double value @a value
  12486. */
  12487. void write_bson_double(const string_t& name,
  12488. const double value)
  12489. {
  12490. write_bson_entry_header(name, 0x01);
  12491. write_number<double, true>(value);
  12492. }
  12493. /*!
  12494. @return The size of the BSON-encoded string in @a value
  12495. */
  12496. static std::size_t calc_bson_string_size(const string_t& value)
  12497. {
  12498. return sizeof(std::int32_t) + value.size() + 1ul;
  12499. }
  12500. /*!
  12501. @brief Writes a BSON element with key @a name and string value @a value
  12502. */
  12503. void write_bson_string(const string_t& name,
  12504. const string_t& value)
  12505. {
  12506. write_bson_entry_header(name, 0x02);
  12507. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  12508. oa->write_characters(
  12509. reinterpret_cast<const CharType*>(value.c_str()),
  12510. value.size() + 1);
  12511. }
  12512. /*!
  12513. @brief Writes a BSON element with key @a name and null value
  12514. */
  12515. void write_bson_null(const string_t& name)
  12516. {
  12517. write_bson_entry_header(name, 0x0A);
  12518. }
  12519. /*!
  12520. @return The size of the BSON-encoded integer @a value
  12521. */
  12522. static std::size_t calc_bson_integer_size(const std::int64_t value)
  12523. {
  12524. return (std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)()
  12525. ? sizeof(std::int32_t)
  12526. : sizeof(std::int64_t);
  12527. }
  12528. /*!
  12529. @brief Writes a BSON element with key @a name and integer @a value
  12530. */
  12531. void write_bson_integer(const string_t& name,
  12532. const std::int64_t value)
  12533. {
  12534. if ((std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)())
  12535. {
  12536. write_bson_entry_header(name, 0x10); // int32
  12537. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  12538. }
  12539. else
  12540. {
  12541. write_bson_entry_header(name, 0x12); // int64
  12542. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  12543. }
  12544. }
  12545. /*!
  12546. @return The size of the BSON-encoded unsigned integer in @a j
  12547. */
  12548. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  12549. {
  12550. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12551. ? sizeof(std::int32_t)
  12552. : sizeof(std::int64_t);
  12553. }
  12554. /*!
  12555. @brief Writes a BSON element with key @a name and unsigned @a value
  12556. */
  12557. void write_bson_unsigned(const string_t& name,
  12558. const BasicJsonType& j)
  12559. {
  12560. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12561. {
  12562. write_bson_entry_header(name, 0x10 /* int32 */);
  12563. write_number<std::int32_t, true>(static_cast<std::int32_t>(j.m_value.number_unsigned));
  12564. }
  12565. else if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  12566. {
  12567. write_bson_entry_header(name, 0x12 /* int64 */);
  12568. write_number<std::int64_t, true>(static_cast<std::int64_t>(j.m_value.number_unsigned));
  12569. }
  12570. else
  12571. {
  12572. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(j.m_value.number_unsigned) + " cannot be represented by BSON as it does not fit int64", j));
  12573. }
  12574. }
  12575. /*!
  12576. @brief Writes a BSON element with key @a name and object @a value
  12577. */
  12578. void write_bson_object_entry(const string_t& name,
  12579. const typename BasicJsonType::object_t& value)
  12580. {
  12581. write_bson_entry_header(name, 0x03); // object
  12582. write_bson_object(value);
  12583. }
  12584. /*!
  12585. @return The size of the BSON-encoded array @a value
  12586. */
  12587. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  12588. {
  12589. std::size_t array_index = 0ul;
  12590. const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), static_cast<std::size_t>(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el)
  12591. {
  12592. return result + calc_bson_element_size(std::to_string(array_index++), el);
  12593. });
  12594. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  12595. }
  12596. /*!
  12597. @return The size of the BSON-encoded binary array @a value
  12598. */
  12599. static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value)
  12600. {
  12601. return sizeof(std::int32_t) + value.size() + 1ul;
  12602. }
  12603. /*!
  12604. @brief Writes a BSON element with key @a name and array @a value
  12605. */
  12606. void write_bson_array(const string_t& name,
  12607. const typename BasicJsonType::array_t& value)
  12608. {
  12609. write_bson_entry_header(name, 0x04); // array
  12610. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  12611. std::size_t array_index = 0ul;
  12612. for (const auto& el : value)
  12613. {
  12614. write_bson_element(std::to_string(array_index++), el);
  12615. }
  12616. oa->write_character(to_char_type(0x00));
  12617. }
  12618. /*!
  12619. @brief Writes a BSON element with key @a name and binary value @a value
  12620. */
  12621. void write_bson_binary(const string_t& name,
  12622. const binary_t& value)
  12623. {
  12624. write_bson_entry_header(name, 0x05);
  12625. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size()));
  12626. write_number(value.has_subtype() ? static_cast<std::uint8_t>(value.subtype()) : static_cast<std::uint8_t>(0x00));
  12627. oa->write_characters(reinterpret_cast<const CharType*>(value.data()), value.size());
  12628. }
  12629. /*!
  12630. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  12631. @return The calculated size for the BSON document entry for @a j with the given @a name.
  12632. */
  12633. static std::size_t calc_bson_element_size(const string_t& name,
  12634. const BasicJsonType& j)
  12635. {
  12636. const auto header_size = calc_bson_entry_header_size(name, j);
  12637. switch (j.type())
  12638. {
  12639. case value_t::object:
  12640. return header_size + calc_bson_object_size(*j.m_value.object);
  12641. case value_t::array:
  12642. return header_size + calc_bson_array_size(*j.m_value.array);
  12643. case value_t::binary:
  12644. return header_size + calc_bson_binary_size(*j.m_value.binary);
  12645. case value_t::boolean:
  12646. return header_size + 1ul;
  12647. case value_t::number_float:
  12648. return header_size + 8ul;
  12649. case value_t::number_integer:
  12650. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  12651. case value_t::number_unsigned:
  12652. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  12653. case value_t::string:
  12654. return header_size + calc_bson_string_size(*j.m_value.string);
  12655. case value_t::null:
  12656. return header_size + 0ul;
  12657. // LCOV_EXCL_START
  12658. case value_t::discarded:
  12659. default:
  12660. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
  12661. return 0ul;
  12662. // LCOV_EXCL_STOP
  12663. }
  12664. }
  12665. /*!
  12666. @brief Serializes the JSON value @a j to BSON and associates it with the
  12667. key @a name.
  12668. @param name The name to associate with the JSON entity @a j within the
  12669. current BSON document
  12670. */
  12671. void write_bson_element(const string_t& name,
  12672. const BasicJsonType& j)
  12673. {
  12674. switch (j.type())
  12675. {
  12676. case value_t::object:
  12677. return write_bson_object_entry(name, *j.m_value.object);
  12678. case value_t::array:
  12679. return write_bson_array(name, *j.m_value.array);
  12680. case value_t::binary:
  12681. return write_bson_binary(name, *j.m_value.binary);
  12682. case value_t::boolean:
  12683. return write_bson_boolean(name, j.m_value.boolean);
  12684. case value_t::number_float:
  12685. return write_bson_double(name, j.m_value.number_float);
  12686. case value_t::number_integer:
  12687. return write_bson_integer(name, j.m_value.number_integer);
  12688. case value_t::number_unsigned:
  12689. return write_bson_unsigned(name, j);
  12690. case value_t::string:
  12691. return write_bson_string(name, *j.m_value.string);
  12692. case value_t::null:
  12693. return write_bson_null(name);
  12694. // LCOV_EXCL_START
  12695. case value_t::discarded:
  12696. default:
  12697. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
  12698. return;
  12699. // LCOV_EXCL_STOP
  12700. }
  12701. }
  12702. /*!
  12703. @brief Calculates the size of the BSON serialization of the given
  12704. JSON-object @a j.
  12705. @param[in] value JSON value to serialize
  12706. @pre value.type() == value_t::object
  12707. */
  12708. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  12709. {
  12710. std::size_t document_size = std::accumulate(value.begin(), value.end(), static_cast<std::size_t>(0),
  12711. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  12712. {
  12713. return result += calc_bson_element_size(el.first, el.second);
  12714. });
  12715. return sizeof(std::int32_t) + document_size + 1ul;
  12716. }
  12717. /*!
  12718. @param[in] value JSON value to serialize
  12719. @pre value.type() == value_t::object
  12720. */
  12721. void write_bson_object(const typename BasicJsonType::object_t& value)
  12722. {
  12723. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  12724. for (const auto& el : value)
  12725. {
  12726. write_bson_element(el.first, el.second);
  12727. }
  12728. oa->write_character(to_char_type(0x00));
  12729. }
  12730. //////////
  12731. // CBOR //
  12732. //////////
  12733. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  12734. {
  12735. return to_char_type(0xFA); // Single-Precision Float
  12736. }
  12737. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  12738. {
  12739. return to_char_type(0xFB); // Double-Precision Float
  12740. }
  12741. /////////////
  12742. // MsgPack //
  12743. /////////////
  12744. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  12745. {
  12746. return to_char_type(0xCA); // float 32
  12747. }
  12748. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  12749. {
  12750. return to_char_type(0xCB); // float 64
  12751. }
  12752. ////////////
  12753. // UBJSON //
  12754. ////////////
  12755. // UBJSON: write number (floating point)
  12756. template<typename NumberType, typename std::enable_if<
  12757. std::is_floating_point<NumberType>::value, int>::type = 0>
  12758. void write_number_with_ubjson_prefix(const NumberType n,
  12759. const bool add_prefix)
  12760. {
  12761. if (add_prefix)
  12762. {
  12763. oa->write_character(get_ubjson_float_prefix(n));
  12764. }
  12765. write_number(n);
  12766. }
  12767. // UBJSON: write number (unsigned integer)
  12768. template<typename NumberType, typename std::enable_if<
  12769. std::is_unsigned<NumberType>::value, int>::type = 0>
  12770. void write_number_with_ubjson_prefix(const NumberType n,
  12771. const bool add_prefix)
  12772. {
  12773. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  12774. {
  12775. if (add_prefix)
  12776. {
  12777. oa->write_character(to_char_type('i')); // int8
  12778. }
  12779. write_number(static_cast<std::uint8_t>(n));
  12780. }
  12781. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  12782. {
  12783. if (add_prefix)
  12784. {
  12785. oa->write_character(to_char_type('U')); // uint8
  12786. }
  12787. write_number(static_cast<std::uint8_t>(n));
  12788. }
  12789. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  12790. {
  12791. if (add_prefix)
  12792. {
  12793. oa->write_character(to_char_type('I')); // int16
  12794. }
  12795. write_number(static_cast<std::int16_t>(n));
  12796. }
  12797. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12798. {
  12799. if (add_prefix)
  12800. {
  12801. oa->write_character(to_char_type('l')); // int32
  12802. }
  12803. write_number(static_cast<std::int32_t>(n));
  12804. }
  12805. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  12806. {
  12807. if (add_prefix)
  12808. {
  12809. oa->write_character(to_char_type('L')); // int64
  12810. }
  12811. write_number(static_cast<std::int64_t>(n));
  12812. }
  12813. else
  12814. {
  12815. if (add_prefix)
  12816. {
  12817. oa->write_character(to_char_type('H')); // high-precision number
  12818. }
  12819. const auto number = BasicJsonType(n).dump();
  12820. write_number_with_ubjson_prefix(number.size(), true);
  12821. for (std::size_t i = 0; i < number.size(); ++i)
  12822. {
  12823. oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
  12824. }
  12825. }
  12826. }
  12827. // UBJSON: write number (signed integer)
  12828. template < typename NumberType, typename std::enable_if <
  12829. std::is_signed<NumberType>::value&&
  12830. !std::is_floating_point<NumberType>::value, int >::type = 0 >
  12831. void write_number_with_ubjson_prefix(const NumberType n,
  12832. const bool add_prefix)
  12833. {
  12834. if ((std::numeric_limits<std::int8_t>::min)() <= n && n <= (std::numeric_limits<std::int8_t>::max)())
  12835. {
  12836. if (add_prefix)
  12837. {
  12838. oa->write_character(to_char_type('i')); // int8
  12839. }
  12840. write_number(static_cast<std::int8_t>(n));
  12841. }
  12842. else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n && n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)()))
  12843. {
  12844. if (add_prefix)
  12845. {
  12846. oa->write_character(to_char_type('U')); // uint8
  12847. }
  12848. write_number(static_cast<std::uint8_t>(n));
  12849. }
  12850. else if ((std::numeric_limits<std::int16_t>::min)() <= n && n <= (std::numeric_limits<std::int16_t>::max)())
  12851. {
  12852. if (add_prefix)
  12853. {
  12854. oa->write_character(to_char_type('I')); // int16
  12855. }
  12856. write_number(static_cast<std::int16_t>(n));
  12857. }
  12858. else if ((std::numeric_limits<std::int32_t>::min)() <= n && n <= (std::numeric_limits<std::int32_t>::max)())
  12859. {
  12860. if (add_prefix)
  12861. {
  12862. oa->write_character(to_char_type('l')); // int32
  12863. }
  12864. write_number(static_cast<std::int32_t>(n));
  12865. }
  12866. else if ((std::numeric_limits<std::int64_t>::min)() <= n && n <= (std::numeric_limits<std::int64_t>::max)())
  12867. {
  12868. if (add_prefix)
  12869. {
  12870. oa->write_character(to_char_type('L')); // int64
  12871. }
  12872. write_number(static_cast<std::int64_t>(n));
  12873. }
  12874. // LCOV_EXCL_START
  12875. else
  12876. {
  12877. if (add_prefix)
  12878. {
  12879. oa->write_character(to_char_type('H')); // high-precision number
  12880. }
  12881. const auto number = BasicJsonType(n).dump();
  12882. write_number_with_ubjson_prefix(number.size(), true);
  12883. for (std::size_t i = 0; i < number.size(); ++i)
  12884. {
  12885. oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
  12886. }
  12887. }
  12888. // LCOV_EXCL_STOP
  12889. }
  12890. /*!
  12891. @brief determine the type prefix of container values
  12892. */
  12893. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  12894. {
  12895. switch (j.type())
  12896. {
  12897. case value_t::null:
  12898. return 'Z';
  12899. case value_t::boolean:
  12900. return j.m_value.boolean ? 'T' : 'F';
  12901. case value_t::number_integer:
  12902. {
  12903. if ((std::numeric_limits<std::int8_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  12904. {
  12905. return 'i';
  12906. }
  12907. if ((std::numeric_limits<std::uint8_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  12908. {
  12909. return 'U';
  12910. }
  12911. if ((std::numeric_limits<std::int16_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  12912. {
  12913. return 'I';
  12914. }
  12915. if ((std::numeric_limits<std::int32_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  12916. {
  12917. return 'l';
  12918. }
  12919. if ((std::numeric_limits<std::int64_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  12920. {
  12921. return 'L';
  12922. }
  12923. // anything else is treated as high-precision number
  12924. return 'H'; // LCOV_EXCL_LINE
  12925. }
  12926. case value_t::number_unsigned:
  12927. {
  12928. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  12929. {
  12930. return 'i';
  12931. }
  12932. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  12933. {
  12934. return 'U';
  12935. }
  12936. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  12937. {
  12938. return 'I';
  12939. }
  12940. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12941. {
  12942. return 'l';
  12943. }
  12944. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  12945. {
  12946. return 'L';
  12947. }
  12948. // anything else is treated as high-precision number
  12949. return 'H'; // LCOV_EXCL_LINE
  12950. }
  12951. case value_t::number_float:
  12952. return get_ubjson_float_prefix(j.m_value.number_float);
  12953. case value_t::string:
  12954. return 'S';
  12955. case value_t::array: // fallthrough
  12956. case value_t::binary:
  12957. return '[';
  12958. case value_t::object:
  12959. return '{';
  12960. case value_t::discarded:
  12961. default: // discarded values
  12962. return 'N';
  12963. }
  12964. }
  12965. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  12966. {
  12967. return 'd'; // float 32
  12968. }
  12969. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  12970. {
  12971. return 'D'; // float 64
  12972. }
  12973. ///////////////////////
  12974. // Utility functions //
  12975. ///////////////////////
  12976. /*
  12977. @brief write a number to output input
  12978. @param[in] n number of type @a NumberType
  12979. @tparam NumberType the type of the number
  12980. @tparam OutputIsLittleEndian Set to true if output data is
  12981. required to be little endian
  12982. @note This function needs to respect the system's endianness, because bytes
  12983. in CBOR, MessagePack, and UBJSON are stored in network order (big
  12984. endian) and therefore need reordering on little endian systems.
  12985. */
  12986. template<typename NumberType, bool OutputIsLittleEndian = false>
  12987. void write_number(const NumberType n)
  12988. {
  12989. // step 1: write number to array of length NumberType
  12990. std::array<CharType, sizeof(NumberType)> vec{};
  12991. std::memcpy(vec.data(), &n, sizeof(NumberType));
  12992. // step 2: write array to output (with possible reordering)
  12993. if (is_little_endian != OutputIsLittleEndian)
  12994. {
  12995. // reverse byte order prior to conversion if necessary
  12996. std::reverse(vec.begin(), vec.end());
  12997. }
  12998. oa->write_characters(vec.data(), sizeof(NumberType));
  12999. }
  13000. void write_compact_float(const number_float_t n, detail::input_format_t format)
  13001. {
  13002. #ifdef __GNUC__
  13003. #pragma GCC diagnostic push
  13004. #pragma GCC diagnostic ignored "-Wfloat-equal"
  13005. #endif
  13006. if (static_cast<double>(n) >= static_cast<double>(std::numeric_limits<float>::lowest()) &&
  13007. static_cast<double>(n) <= static_cast<double>((std::numeric_limits<float>::max)()) &&
  13008. static_cast<double>(static_cast<float>(n)) == static_cast<double>(n))
  13009. {
  13010. oa->write_character(format == detail::input_format_t::cbor
  13011. ? get_cbor_float_prefix(static_cast<float>(n))
  13012. : get_msgpack_float_prefix(static_cast<float>(n)));
  13013. write_number(static_cast<float>(n));
  13014. }
  13015. else
  13016. {
  13017. oa->write_character(format == detail::input_format_t::cbor
  13018. ? get_cbor_float_prefix(n)
  13019. : get_msgpack_float_prefix(n));
  13020. write_number(n);
  13021. }
  13022. #ifdef __GNUC__
  13023. #pragma GCC diagnostic pop
  13024. #endif
  13025. }
  13026. public:
  13027. // The following to_char_type functions are implement the conversion
  13028. // between uint8_t and CharType. In case CharType is not unsigned,
  13029. // such a conversion is required to allow values greater than 128.
  13030. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  13031. template < typename C = CharType,
  13032. enable_if_t < std::is_signed<C>::value && std::is_signed<char>::value > * = nullptr >
  13033. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  13034. {
  13035. return *reinterpret_cast<char*>(&x);
  13036. }
  13037. template < typename C = CharType,
  13038. enable_if_t < std::is_signed<C>::value && std::is_unsigned<char>::value > * = nullptr >
  13039. static CharType to_char_type(std::uint8_t x) noexcept
  13040. {
  13041. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  13042. static_assert(std::is_trivial<CharType>::value, "CharType must be trivial");
  13043. CharType result;
  13044. std::memcpy(&result, &x, sizeof(x));
  13045. return result;
  13046. }
  13047. template<typename C = CharType,
  13048. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  13049. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  13050. {
  13051. return x;
  13052. }
  13053. template < typename InputCharType, typename C = CharType,
  13054. enable_if_t <
  13055. std::is_signed<C>::value &&
  13056. std::is_signed<char>::value &&
  13057. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  13058. > * = nullptr >
  13059. static constexpr CharType to_char_type(InputCharType x) noexcept
  13060. {
  13061. return x;
  13062. }
  13063. private:
  13064. /// whether we can assume little endianness
  13065. const bool is_little_endian = little_endianness();
  13066. /// the output
  13067. output_adapter_t<CharType> oa = nullptr;
  13068. };
  13069. } // namespace detail
  13070. } // namespace nlohmann
  13071. // #include <nlohmann/detail/output/output_adapters.hpp>
  13072. // #include <nlohmann/detail/output/serializer.hpp>
  13073. #include <algorithm> // reverse, remove, fill, find, none_of
  13074. #include <array> // array
  13075. #include <clocale> // localeconv, lconv
  13076. #include <cmath> // labs, isfinite, isnan, signbit
  13077. #include <cstddef> // size_t, ptrdiff_t
  13078. #include <cstdint> // uint8_t
  13079. #include <cstdio> // snprintf
  13080. #include <limits> // numeric_limits
  13081. #include <string> // string, char_traits
  13082. #include <iomanip> // setfill, setw
  13083. #include <sstream> // stringstream
  13084. #include <type_traits> // is_same
  13085. #include <utility> // move
  13086. // #include <nlohmann/detail/conversions/to_chars.hpp>
  13087. #include <array> // array
  13088. #include <cmath> // signbit, isfinite
  13089. #include <cstdint> // intN_t, uintN_t
  13090. #include <cstring> // memcpy, memmove
  13091. #include <limits> // numeric_limits
  13092. #include <type_traits> // conditional
  13093. // #include <nlohmann/detail/macro_scope.hpp>
  13094. namespace nlohmann
  13095. {
  13096. namespace detail
  13097. {
  13098. /*!
  13099. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  13100. conversion.
  13101. This implementation is a slightly modified version of the reference
  13102. implementation which may be obtained from
  13103. http://florian.loitsch.com/publications (bench.tar.gz).
  13104. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  13105. For a detailed description of the algorithm see:
  13106. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  13107. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  13108. Language Design and Implementation, PLDI 2010
  13109. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  13110. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  13111. Design and Implementation, PLDI 1996
  13112. */
  13113. namespace dtoa_impl
  13114. {
  13115. template<typename Target, typename Source>
  13116. Target reinterpret_bits(const Source source)
  13117. {
  13118. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  13119. Target target;
  13120. std::memcpy(&target, &source, sizeof(Source));
  13121. return target;
  13122. }
  13123. struct diyfp // f * 2^e
  13124. {
  13125. static constexpr int kPrecision = 64; // = q
  13126. std::uint64_t f = 0;
  13127. int e = 0;
  13128. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  13129. /*!
  13130. @brief returns x - y
  13131. @pre x.e == y.e and x.f >= y.f
  13132. */
  13133. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  13134. {
  13135. JSON_ASSERT(x.e == y.e);
  13136. JSON_ASSERT(x.f >= y.f);
  13137. return {x.f - y.f, x.e};
  13138. }
  13139. /*!
  13140. @brief returns x * y
  13141. @note The result is rounded. (Only the upper q bits are returned.)
  13142. */
  13143. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  13144. {
  13145. static_assert(kPrecision == 64, "internal error");
  13146. // Computes:
  13147. // f = round((x.f * y.f) / 2^q)
  13148. // e = x.e + y.e + q
  13149. // Emulate the 64-bit * 64-bit multiplication:
  13150. //
  13151. // p = u * v
  13152. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  13153. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  13154. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  13155. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  13156. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  13157. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  13158. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  13159. //
  13160. // (Since Q might be larger than 2^32 - 1)
  13161. //
  13162. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  13163. //
  13164. // (Q_hi + H does not overflow a 64-bit int)
  13165. //
  13166. // = p_lo + 2^64 p_hi
  13167. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  13168. const std::uint64_t u_hi = x.f >> 32u;
  13169. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  13170. const std::uint64_t v_hi = y.f >> 32u;
  13171. const std::uint64_t p0 = u_lo * v_lo;
  13172. const std::uint64_t p1 = u_lo * v_hi;
  13173. const std::uint64_t p2 = u_hi * v_lo;
  13174. const std::uint64_t p3 = u_hi * v_hi;
  13175. const std::uint64_t p0_hi = p0 >> 32u;
  13176. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  13177. const std::uint64_t p1_hi = p1 >> 32u;
  13178. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  13179. const std::uint64_t p2_hi = p2 >> 32u;
  13180. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  13181. // The full product might now be computed as
  13182. //
  13183. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  13184. // p_lo = p0_lo + (Q << 32)
  13185. //
  13186. // But in this particular case here, the full p_lo is not required.
  13187. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  13188. // Q_hi + 1 does not overflow).
  13189. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  13190. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  13191. return {h, x.e + y.e + 64};
  13192. }
  13193. /*!
  13194. @brief normalize x such that the significand is >= 2^(q-1)
  13195. @pre x.f != 0
  13196. */
  13197. static diyfp normalize(diyfp x) noexcept
  13198. {
  13199. JSON_ASSERT(x.f != 0);
  13200. while ((x.f >> 63u) == 0)
  13201. {
  13202. x.f <<= 1u;
  13203. x.e--;
  13204. }
  13205. return x;
  13206. }
  13207. /*!
  13208. @brief normalize x such that the result has the exponent E
  13209. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  13210. */
  13211. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  13212. {
  13213. const int delta = x.e - target_exponent;
  13214. JSON_ASSERT(delta >= 0);
  13215. JSON_ASSERT(((x.f << delta) >> delta) == x.f);
  13216. return {x.f << delta, target_exponent};
  13217. }
  13218. };
  13219. struct boundaries
  13220. {
  13221. diyfp w;
  13222. diyfp minus;
  13223. diyfp plus;
  13224. };
  13225. /*!
  13226. Compute the (normalized) diyfp representing the input number 'value' and its
  13227. boundaries.
  13228. @pre value must be finite and positive
  13229. */
  13230. template<typename FloatType>
  13231. boundaries compute_boundaries(FloatType value)
  13232. {
  13233. JSON_ASSERT(std::isfinite(value));
  13234. JSON_ASSERT(value > 0);
  13235. // Convert the IEEE representation into a diyfp.
  13236. //
  13237. // If v is denormal:
  13238. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  13239. // If v is normalized:
  13240. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  13241. static_assert(std::numeric_limits<FloatType>::is_iec559,
  13242. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  13243. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  13244. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  13245. constexpr int kMinExp = 1 - kBias;
  13246. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  13247. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  13248. const auto bits = static_cast<std::uint64_t>(reinterpret_bits<bits_type>(value));
  13249. const std::uint64_t E = bits >> (kPrecision - 1);
  13250. const std::uint64_t F = bits & (kHiddenBit - 1);
  13251. const bool is_denormal = E == 0;
  13252. const diyfp v = is_denormal
  13253. ? diyfp(F, kMinExp)
  13254. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  13255. // Compute the boundaries m- and m+ of the floating-point value
  13256. // v = f * 2^e.
  13257. //
  13258. // Determine v- and v+, the floating-point predecessor and successor if v,
  13259. // respectively.
  13260. //
  13261. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  13262. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  13263. //
  13264. // v+ = v + 2^e
  13265. //
  13266. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  13267. // between m- and m+ round to v, regardless of how the input rounding
  13268. // algorithm breaks ties.
  13269. //
  13270. // ---+-------------+-------------+-------------+-------------+--- (A)
  13271. // v- m- v m+ v+
  13272. //
  13273. // -----------------+------+------+-------------+-------------+--- (B)
  13274. // v- m- v m+ v+
  13275. const bool lower_boundary_is_closer = F == 0 && E > 1;
  13276. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  13277. const diyfp m_minus = lower_boundary_is_closer
  13278. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  13279. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  13280. // Determine the normalized w+ = m+.
  13281. const diyfp w_plus = diyfp::normalize(m_plus);
  13282. // Determine w- = m- such that e_(w-) = e_(w+).
  13283. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  13284. return {diyfp::normalize(v), w_minus, w_plus};
  13285. }
  13286. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  13287. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  13288. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  13289. //
  13290. // alpha <= e = e_c + e_w + q <= gamma
  13291. //
  13292. // or
  13293. //
  13294. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  13295. // <= f_c * f_w * 2^gamma
  13296. //
  13297. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  13298. //
  13299. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  13300. //
  13301. // or
  13302. //
  13303. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  13304. //
  13305. // The choice of (alpha,gamma) determines the size of the table and the form of
  13306. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  13307. // in practice:
  13308. //
  13309. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  13310. // processed independently: An integral part p1, and a fractional part p2:
  13311. //
  13312. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  13313. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  13314. // = p1 + p2 * 2^e
  13315. //
  13316. // The conversion of p1 into decimal form requires a series of divisions and
  13317. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  13318. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  13319. // achieved by choosing
  13320. //
  13321. // -e >= 32 or e <= -32 := gamma
  13322. //
  13323. // In order to convert the fractional part
  13324. //
  13325. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  13326. //
  13327. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  13328. // d[-i] are extracted in order:
  13329. //
  13330. // (10 * p2) div 2^-e = d[-1]
  13331. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  13332. //
  13333. // The multiplication by 10 must not overflow. It is sufficient to choose
  13334. //
  13335. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  13336. //
  13337. // Since p2 = f mod 2^-e < 2^-e,
  13338. //
  13339. // -e <= 60 or e >= -60 := alpha
  13340. constexpr int kAlpha = -60;
  13341. constexpr int kGamma = -32;
  13342. struct cached_power // c = f * 2^e ~= 10^k
  13343. {
  13344. std::uint64_t f;
  13345. int e;
  13346. int k;
  13347. };
  13348. /*!
  13349. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  13350. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  13351. satisfies (Definition 3.2 from [1])
  13352. alpha <= e_c + e + q <= gamma.
  13353. */
  13354. inline cached_power get_cached_power_for_binary_exponent(int e)
  13355. {
  13356. // Now
  13357. //
  13358. // alpha <= e_c + e + q <= gamma (1)
  13359. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  13360. //
  13361. // and since the c's are normalized, 2^(q-1) <= f_c,
  13362. //
  13363. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  13364. // ==> 2^(alpha - e - 1) <= c
  13365. //
  13366. // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
  13367. //
  13368. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  13369. // = ceil( (alpha - e - 1) * log_10(2) )
  13370. //
  13371. // From the paper:
  13372. // "In theory the result of the procedure could be wrong since c is rounded,
  13373. // and the computation itself is approximated [...]. In practice, however,
  13374. // this simple function is sufficient."
  13375. //
  13376. // For IEEE double precision floating-point numbers converted into
  13377. // normalized diyfp's w = f * 2^e, with q = 64,
  13378. //
  13379. // e >= -1022 (min IEEE exponent)
  13380. // -52 (p - 1)
  13381. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  13382. // -11 (normalize the diyfp)
  13383. // = -1137
  13384. //
  13385. // and
  13386. //
  13387. // e <= +1023 (max IEEE exponent)
  13388. // -52 (p - 1)
  13389. // -11 (normalize the diyfp)
  13390. // = 960
  13391. //
  13392. // This binary exponent range [-1137,960] results in a decimal exponent
  13393. // range [-307,324]. One does not need to store a cached power for each
  13394. // k in this range. For each such k it suffices to find a cached power
  13395. // such that the exponent of the product lies in [alpha,gamma].
  13396. // This implies that the difference of the decimal exponents of adjacent
  13397. // table entries must be less than or equal to
  13398. //
  13399. // floor( (gamma - alpha) * log_10(2) ) = 8.
  13400. //
  13401. // (A smaller distance gamma-alpha would require a larger table.)
  13402. // NB:
  13403. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  13404. constexpr int kCachedPowersMinDecExp = -300;
  13405. constexpr int kCachedPowersDecStep = 8;
  13406. static constexpr std::array<cached_power, 79> kCachedPowers =
  13407. {
  13408. {
  13409. { 0xAB70FE17C79AC6CA, -1060, -300 },
  13410. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  13411. { 0xBE5691EF416BD60C, -1007, -284 },
  13412. { 0x8DD01FAD907FFC3C, -980, -276 },
  13413. { 0xD3515C2831559A83, -954, -268 },
  13414. { 0x9D71AC8FADA6C9B5, -927, -260 },
  13415. { 0xEA9C227723EE8BCB, -901, -252 },
  13416. { 0xAECC49914078536D, -874, -244 },
  13417. { 0x823C12795DB6CE57, -847, -236 },
  13418. { 0xC21094364DFB5637, -821, -228 },
  13419. { 0x9096EA6F3848984F, -794, -220 },
  13420. { 0xD77485CB25823AC7, -768, -212 },
  13421. { 0xA086CFCD97BF97F4, -741, -204 },
  13422. { 0xEF340A98172AACE5, -715, -196 },
  13423. { 0xB23867FB2A35B28E, -688, -188 },
  13424. { 0x84C8D4DFD2C63F3B, -661, -180 },
  13425. { 0xC5DD44271AD3CDBA, -635, -172 },
  13426. { 0x936B9FCEBB25C996, -608, -164 },
  13427. { 0xDBAC6C247D62A584, -582, -156 },
  13428. { 0xA3AB66580D5FDAF6, -555, -148 },
  13429. { 0xF3E2F893DEC3F126, -529, -140 },
  13430. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  13431. { 0x87625F056C7C4A8B, -475, -124 },
  13432. { 0xC9BCFF6034C13053, -449, -116 },
  13433. { 0x964E858C91BA2655, -422, -108 },
  13434. { 0xDFF9772470297EBD, -396, -100 },
  13435. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  13436. { 0xF8A95FCF88747D94, -343, -84 },
  13437. { 0xB94470938FA89BCF, -316, -76 },
  13438. { 0x8A08F0F8BF0F156B, -289, -68 },
  13439. { 0xCDB02555653131B6, -263, -60 },
  13440. { 0x993FE2C6D07B7FAC, -236, -52 },
  13441. { 0xE45C10C42A2B3B06, -210, -44 },
  13442. { 0xAA242499697392D3, -183, -36 },
  13443. { 0xFD87B5F28300CA0E, -157, -28 },
  13444. { 0xBCE5086492111AEB, -130, -20 },
  13445. { 0x8CBCCC096F5088CC, -103, -12 },
  13446. { 0xD1B71758E219652C, -77, -4 },
  13447. { 0x9C40000000000000, -50, 4 },
  13448. { 0xE8D4A51000000000, -24, 12 },
  13449. { 0xAD78EBC5AC620000, 3, 20 },
  13450. { 0x813F3978F8940984, 30, 28 },
  13451. { 0xC097CE7BC90715B3, 56, 36 },
  13452. { 0x8F7E32CE7BEA5C70, 83, 44 },
  13453. { 0xD5D238A4ABE98068, 109, 52 },
  13454. { 0x9F4F2726179A2245, 136, 60 },
  13455. { 0xED63A231D4C4FB27, 162, 68 },
  13456. { 0xB0DE65388CC8ADA8, 189, 76 },
  13457. { 0x83C7088E1AAB65DB, 216, 84 },
  13458. { 0xC45D1DF942711D9A, 242, 92 },
  13459. { 0x924D692CA61BE758, 269, 100 },
  13460. { 0xDA01EE641A708DEA, 295, 108 },
  13461. { 0xA26DA3999AEF774A, 322, 116 },
  13462. { 0xF209787BB47D6B85, 348, 124 },
  13463. { 0xB454E4A179DD1877, 375, 132 },
  13464. { 0x865B86925B9BC5C2, 402, 140 },
  13465. { 0xC83553C5C8965D3D, 428, 148 },
  13466. { 0x952AB45CFA97A0B3, 455, 156 },
  13467. { 0xDE469FBD99A05FE3, 481, 164 },
  13468. { 0xA59BC234DB398C25, 508, 172 },
  13469. { 0xF6C69A72A3989F5C, 534, 180 },
  13470. { 0xB7DCBF5354E9BECE, 561, 188 },
  13471. { 0x88FCF317F22241E2, 588, 196 },
  13472. { 0xCC20CE9BD35C78A5, 614, 204 },
  13473. { 0x98165AF37B2153DF, 641, 212 },
  13474. { 0xE2A0B5DC971F303A, 667, 220 },
  13475. { 0xA8D9D1535CE3B396, 694, 228 },
  13476. { 0xFB9B7CD9A4A7443C, 720, 236 },
  13477. { 0xBB764C4CA7A44410, 747, 244 },
  13478. { 0x8BAB8EEFB6409C1A, 774, 252 },
  13479. { 0xD01FEF10A657842C, 800, 260 },
  13480. { 0x9B10A4E5E9913129, 827, 268 },
  13481. { 0xE7109BFBA19C0C9D, 853, 276 },
  13482. { 0xAC2820D9623BF429, 880, 284 },
  13483. { 0x80444B5E7AA7CF85, 907, 292 },
  13484. { 0xBF21E44003ACDD2D, 933, 300 },
  13485. { 0x8E679C2F5E44FF8F, 960, 308 },
  13486. { 0xD433179D9C8CB841, 986, 316 },
  13487. { 0x9E19DB92B4E31BA9, 1013, 324 },
  13488. }
  13489. };
  13490. // This computation gives exactly the same results for k as
  13491. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  13492. // for |e| <= 1500, but doesn't require floating-point operations.
  13493. // NB: log_10(2) ~= 78913 / 2^18
  13494. JSON_ASSERT(e >= -1500);
  13495. JSON_ASSERT(e <= 1500);
  13496. const int f = kAlpha - e - 1;
  13497. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  13498. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  13499. JSON_ASSERT(index >= 0);
  13500. JSON_ASSERT(static_cast<std::size_t>(index) < kCachedPowers.size());
  13501. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  13502. JSON_ASSERT(kAlpha <= cached.e + e + 64);
  13503. JSON_ASSERT(kGamma >= cached.e + e + 64);
  13504. return cached;
  13505. }
  13506. /*!
  13507. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  13508. For n == 0, returns 1 and sets pow10 := 1.
  13509. */
  13510. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  13511. {
  13512. // LCOV_EXCL_START
  13513. if (n >= 1000000000)
  13514. {
  13515. pow10 = 1000000000;
  13516. return 10;
  13517. }
  13518. // LCOV_EXCL_STOP
  13519. if (n >= 100000000)
  13520. {
  13521. pow10 = 100000000;
  13522. return 9;
  13523. }
  13524. if (n >= 10000000)
  13525. {
  13526. pow10 = 10000000;
  13527. return 8;
  13528. }
  13529. if (n >= 1000000)
  13530. {
  13531. pow10 = 1000000;
  13532. return 7;
  13533. }
  13534. if (n >= 100000)
  13535. {
  13536. pow10 = 100000;
  13537. return 6;
  13538. }
  13539. if (n >= 10000)
  13540. {
  13541. pow10 = 10000;
  13542. return 5;
  13543. }
  13544. if (n >= 1000)
  13545. {
  13546. pow10 = 1000;
  13547. return 4;
  13548. }
  13549. if (n >= 100)
  13550. {
  13551. pow10 = 100;
  13552. return 3;
  13553. }
  13554. if (n >= 10)
  13555. {
  13556. pow10 = 10;
  13557. return 2;
  13558. }
  13559. pow10 = 1;
  13560. return 1;
  13561. }
  13562. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  13563. std::uint64_t rest, std::uint64_t ten_k)
  13564. {
  13565. JSON_ASSERT(len >= 1);
  13566. JSON_ASSERT(dist <= delta);
  13567. JSON_ASSERT(rest <= delta);
  13568. JSON_ASSERT(ten_k > 0);
  13569. // <--------------------------- delta ---->
  13570. // <---- dist --------->
  13571. // --------------[------------------+-------------------]--------------
  13572. // M- w M+
  13573. //
  13574. // ten_k
  13575. // <------>
  13576. // <---- rest ---->
  13577. // --------------[------------------+----+--------------]--------------
  13578. // w V
  13579. // = buf * 10^k
  13580. //
  13581. // ten_k represents a unit-in-the-last-place in the decimal representation
  13582. // stored in buf.
  13583. // Decrement buf by ten_k while this takes buf closer to w.
  13584. // The tests are written in this order to avoid overflow in unsigned
  13585. // integer arithmetic.
  13586. while (rest < dist
  13587. && delta - rest >= ten_k
  13588. && (rest + ten_k < dist || dist - rest > rest + ten_k - dist))
  13589. {
  13590. JSON_ASSERT(buf[len - 1] != '0');
  13591. buf[len - 1]--;
  13592. rest += ten_k;
  13593. }
  13594. }
  13595. /*!
  13596. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  13597. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  13598. */
  13599. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  13600. diyfp M_minus, diyfp w, diyfp M_plus)
  13601. {
  13602. static_assert(kAlpha >= -60, "internal error");
  13603. static_assert(kGamma <= -32, "internal error");
  13604. // Generates the digits (and the exponent) of a decimal floating-point
  13605. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  13606. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  13607. //
  13608. // <--------------------------- delta ---->
  13609. // <---- dist --------->
  13610. // --------------[------------------+-------------------]--------------
  13611. // M- w M+
  13612. //
  13613. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  13614. // V is in [M-,M+].
  13615. JSON_ASSERT(M_plus.e >= kAlpha);
  13616. JSON_ASSERT(M_plus.e <= kGamma);
  13617. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  13618. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  13619. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  13620. //
  13621. // M+ = f * 2^e
  13622. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  13623. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  13624. // = p1 + p2 * 2^e
  13625. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  13626. 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.)
  13627. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  13628. // 1)
  13629. //
  13630. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  13631. JSON_ASSERT(p1 > 0);
  13632. std::uint32_t pow10{};
  13633. const int k = find_largest_pow10(p1, pow10);
  13634. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  13635. //
  13636. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  13637. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  13638. //
  13639. // M+ = p1 + p2 * 2^e
  13640. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  13641. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  13642. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  13643. //
  13644. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  13645. //
  13646. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  13647. //
  13648. // but stop as soon as
  13649. //
  13650. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  13651. int n = k;
  13652. while (n > 0)
  13653. {
  13654. // Invariants:
  13655. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  13656. // pow10 = 10^(n-1) <= p1 < 10^n
  13657. //
  13658. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  13659. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  13660. //
  13661. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  13662. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  13663. //
  13664. JSON_ASSERT(d <= 9);
  13665. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  13666. //
  13667. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  13668. //
  13669. p1 = r;
  13670. n--;
  13671. //
  13672. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  13673. // pow10 = 10^n
  13674. //
  13675. // Now check if enough digits have been generated.
  13676. // Compute
  13677. //
  13678. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  13679. //
  13680. // Note:
  13681. // Since rest and delta share the same exponent e, it suffices to
  13682. // compare the significands.
  13683. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  13684. if (rest <= delta)
  13685. {
  13686. // V = buffer * 10^n, with M- <= V <= M+.
  13687. decimal_exponent += n;
  13688. // We may now just stop. But instead look if the buffer could be
  13689. // decremented to bring V closer to w.
  13690. //
  13691. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  13692. // The rounding procedure works with diyfp's with an implicit
  13693. // exponent of e.
  13694. //
  13695. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  13696. //
  13697. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  13698. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  13699. return;
  13700. }
  13701. pow10 /= 10;
  13702. //
  13703. // pow10 = 10^(n-1) <= p1 < 10^n
  13704. // Invariants restored.
  13705. }
  13706. // 2)
  13707. //
  13708. // The digits of the integral part have been generated:
  13709. //
  13710. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  13711. // = buffer + p2 * 2^e
  13712. //
  13713. // Now generate the digits of the fractional part p2 * 2^e.
  13714. //
  13715. // Note:
  13716. // No decimal point is generated: the exponent is adjusted instead.
  13717. //
  13718. // p2 actually represents the fraction
  13719. //
  13720. // p2 * 2^e
  13721. // = p2 / 2^-e
  13722. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  13723. //
  13724. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  13725. //
  13726. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  13727. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  13728. //
  13729. // using
  13730. //
  13731. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  13732. // = ( d) * 2^-e + ( r)
  13733. //
  13734. // or
  13735. // 10^m * p2 * 2^e = d + r * 2^e
  13736. //
  13737. // i.e.
  13738. //
  13739. // M+ = buffer + p2 * 2^e
  13740. // = buffer + 10^-m * (d + r * 2^e)
  13741. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  13742. //
  13743. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  13744. JSON_ASSERT(p2 > delta);
  13745. int m = 0;
  13746. for (;;)
  13747. {
  13748. // Invariant:
  13749. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  13750. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  13751. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  13752. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  13753. //
  13754. JSON_ASSERT(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  13755. p2 *= 10;
  13756. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  13757. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  13758. //
  13759. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  13760. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  13761. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  13762. //
  13763. JSON_ASSERT(d <= 9);
  13764. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  13765. //
  13766. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  13767. //
  13768. p2 = r;
  13769. m++;
  13770. //
  13771. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  13772. // Invariant restored.
  13773. // Check if enough digits have been generated.
  13774. //
  13775. // 10^-m * p2 * 2^e <= delta * 2^e
  13776. // p2 * 2^e <= 10^m * delta * 2^e
  13777. // p2 <= 10^m * delta
  13778. delta *= 10;
  13779. dist *= 10;
  13780. if (p2 <= delta)
  13781. {
  13782. break;
  13783. }
  13784. }
  13785. // V = buffer * 10^-m, with M- <= V <= M+.
  13786. decimal_exponent -= m;
  13787. // 1 ulp in the decimal representation is now 10^-m.
  13788. // Since delta and dist are now scaled by 10^m, we need to do the
  13789. // same with ulp in order to keep the units in sync.
  13790. //
  13791. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  13792. //
  13793. const std::uint64_t ten_m = one.f;
  13794. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  13795. // By construction this algorithm generates the shortest possible decimal
  13796. // number (Loitsch, Theorem 6.2) which rounds back to w.
  13797. // For an input number of precision p, at least
  13798. //
  13799. // N = 1 + ceil(p * log_10(2))
  13800. //
  13801. // decimal digits are sufficient to identify all binary floating-point
  13802. // numbers (Matula, "In-and-Out conversions").
  13803. // This implies that the algorithm does not produce more than N decimal
  13804. // digits.
  13805. //
  13806. // N = 17 for p = 53 (IEEE double precision)
  13807. // N = 9 for p = 24 (IEEE single precision)
  13808. }
  13809. /*!
  13810. v = buf * 10^decimal_exponent
  13811. len is the length of the buffer (number of decimal digits)
  13812. The buffer must be large enough, i.e. >= max_digits10.
  13813. */
  13814. JSON_HEDLEY_NON_NULL(1)
  13815. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  13816. diyfp m_minus, diyfp v, diyfp m_plus)
  13817. {
  13818. JSON_ASSERT(m_plus.e == m_minus.e);
  13819. JSON_ASSERT(m_plus.e == v.e);
  13820. // --------(-----------------------+-----------------------)-------- (A)
  13821. // m- v m+
  13822. //
  13823. // --------------------(-----------+-----------------------)-------- (B)
  13824. // m- v m+
  13825. //
  13826. // First scale v (and m- and m+) such that the exponent is in the range
  13827. // [alpha, gamma].
  13828. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  13829. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  13830. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  13831. const diyfp w = diyfp::mul(v, c_minus_k);
  13832. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  13833. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  13834. // ----(---+---)---------------(---+---)---------------(---+---)----
  13835. // w- w w+
  13836. // = c*m- = c*v = c*m+
  13837. //
  13838. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  13839. // w+ are now off by a small amount.
  13840. // In fact:
  13841. //
  13842. // w - v * 10^k < 1 ulp
  13843. //
  13844. // To account for this inaccuracy, add resp. subtract 1 ulp.
  13845. //
  13846. // --------+---[---------------(---+---)---------------]---+--------
  13847. // w- M- w M+ w+
  13848. //
  13849. // Now any number in [M-, M+] (bounds included) will round to w when input,
  13850. // regardless of how the input rounding algorithm breaks ties.
  13851. //
  13852. // And digit_gen generates the shortest possible such number in [M-, M+].
  13853. // Note that this does not mean that Grisu2 always generates the shortest
  13854. // possible number in the interval (m-, m+).
  13855. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  13856. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  13857. decimal_exponent = -cached.k; // = -(-k) = k
  13858. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  13859. }
  13860. /*!
  13861. v = buf * 10^decimal_exponent
  13862. len is the length of the buffer (number of decimal digits)
  13863. The buffer must be large enough, i.e. >= max_digits10.
  13864. */
  13865. template<typename FloatType>
  13866. JSON_HEDLEY_NON_NULL(1)
  13867. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  13868. {
  13869. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  13870. "internal error: not enough precision");
  13871. JSON_ASSERT(std::isfinite(value));
  13872. JSON_ASSERT(value > 0);
  13873. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  13874. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  13875. // decimal representations are not exactly "short".
  13876. //
  13877. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  13878. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  13879. // and since sprintf promotes floats to doubles, I think this is exactly what 'std::to_chars'
  13880. // does.
  13881. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  13882. // representation using the corresponding std::from_chars function recovers value exactly". That
  13883. // indicates that single precision floating-point numbers should be recovered using
  13884. // 'std::strtof'.
  13885. //
  13886. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  13887. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  13888. // value is off by 1 ulp.
  13889. #if 0
  13890. const boundaries w = compute_boundaries(static_cast<double>(value));
  13891. #else
  13892. const boundaries w = compute_boundaries(value);
  13893. #endif
  13894. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  13895. }
  13896. /*!
  13897. @brief appends a decimal representation of e to buf
  13898. @return a pointer to the element following the exponent.
  13899. @pre -1000 < e < 1000
  13900. */
  13901. JSON_HEDLEY_NON_NULL(1)
  13902. JSON_HEDLEY_RETURNS_NON_NULL
  13903. inline char* append_exponent(char* buf, int e)
  13904. {
  13905. JSON_ASSERT(e > -1000);
  13906. JSON_ASSERT(e < 1000);
  13907. if (e < 0)
  13908. {
  13909. e = -e;
  13910. *buf++ = '-';
  13911. }
  13912. else
  13913. {
  13914. *buf++ = '+';
  13915. }
  13916. auto k = static_cast<std::uint32_t>(e);
  13917. if (k < 10)
  13918. {
  13919. // Always print at least two digits in the exponent.
  13920. // This is for compatibility with printf("%g").
  13921. *buf++ = '0';
  13922. *buf++ = static_cast<char>('0' + k);
  13923. }
  13924. else if (k < 100)
  13925. {
  13926. *buf++ = static_cast<char>('0' + k / 10);
  13927. k %= 10;
  13928. *buf++ = static_cast<char>('0' + k);
  13929. }
  13930. else
  13931. {
  13932. *buf++ = static_cast<char>('0' + k / 100);
  13933. k %= 100;
  13934. *buf++ = static_cast<char>('0' + k / 10);
  13935. k %= 10;
  13936. *buf++ = static_cast<char>('0' + k);
  13937. }
  13938. return buf;
  13939. }
  13940. /*!
  13941. @brief prettify v = buf * 10^decimal_exponent
  13942. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  13943. notation. Otherwise it will be printed in exponential notation.
  13944. @pre min_exp < 0
  13945. @pre max_exp > 0
  13946. */
  13947. JSON_HEDLEY_NON_NULL(1)
  13948. JSON_HEDLEY_RETURNS_NON_NULL
  13949. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  13950. int min_exp, int max_exp)
  13951. {
  13952. JSON_ASSERT(min_exp < 0);
  13953. JSON_ASSERT(max_exp > 0);
  13954. const int k = len;
  13955. const int n = len + decimal_exponent;
  13956. // v = buf * 10^(n-k)
  13957. // k is the length of the buffer (number of decimal digits)
  13958. // n is the position of the decimal point relative to the start of the buffer.
  13959. if (k <= n && n <= max_exp)
  13960. {
  13961. // digits[000]
  13962. // len <= max_exp + 2
  13963. std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k));
  13964. // Make it look like a floating-point number (#362, #378)
  13965. buf[n + 0] = '.';
  13966. buf[n + 1] = '0';
  13967. return buf + (static_cast<size_t>(n) + 2);
  13968. }
  13969. if (0 < n && n <= max_exp)
  13970. {
  13971. // dig.its
  13972. // len <= max_digits10 + 1
  13973. JSON_ASSERT(k > n);
  13974. std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n));
  13975. buf[n] = '.';
  13976. return buf + (static_cast<size_t>(k) + 1U);
  13977. }
  13978. if (min_exp < n && n <= 0)
  13979. {
  13980. // 0.[000]digits
  13981. // len <= 2 + (-min_exp - 1) + max_digits10
  13982. std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k));
  13983. buf[0] = '0';
  13984. buf[1] = '.';
  13985. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  13986. return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k));
  13987. }
  13988. if (k == 1)
  13989. {
  13990. // dE+123
  13991. // len <= 1 + 5
  13992. buf += 1;
  13993. }
  13994. else
  13995. {
  13996. // d.igitsE+123
  13997. // len <= max_digits10 + 1 + 5
  13998. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1);
  13999. buf[1] = '.';
  14000. buf += 1 + static_cast<size_t>(k);
  14001. }
  14002. *buf++ = 'e';
  14003. return append_exponent(buf, n - 1);
  14004. }
  14005. } // namespace dtoa_impl
  14006. /*!
  14007. @brief generates a decimal representation of the floating-point number value in [first, last).
  14008. The format of the resulting decimal representation is similar to printf's %g
  14009. format. Returns an iterator pointing past-the-end of the decimal representation.
  14010. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  14011. @note The buffer must be large enough.
  14012. @note The result is NOT null-terminated.
  14013. */
  14014. template<typename FloatType>
  14015. JSON_HEDLEY_NON_NULL(1, 2)
  14016. JSON_HEDLEY_RETURNS_NON_NULL
  14017. char* to_chars(char* first, const char* last, FloatType value)
  14018. {
  14019. static_cast<void>(last); // maybe unused - fix warning
  14020. JSON_ASSERT(std::isfinite(value));
  14021. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  14022. if (std::signbit(value))
  14023. {
  14024. value = -value;
  14025. *first++ = '-';
  14026. }
  14027. #ifdef __GNUC__
  14028. #pragma GCC diagnostic push
  14029. #pragma GCC diagnostic ignored "-Wfloat-equal"
  14030. #endif
  14031. if (value == 0) // +-0
  14032. {
  14033. *first++ = '0';
  14034. // Make it look like a floating-point number (#362, #378)
  14035. *first++ = '.';
  14036. *first++ = '0';
  14037. return first;
  14038. }
  14039. #ifdef __GNUC__
  14040. #pragma GCC diagnostic pop
  14041. #endif
  14042. JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10);
  14043. // Compute v = buffer * 10^decimal_exponent.
  14044. // The decimal digits are stored in the buffer, which needs to be interpreted
  14045. // as an unsigned decimal integer.
  14046. // len is the length of the buffer, i.e. the number of decimal digits.
  14047. int len = 0;
  14048. int decimal_exponent = 0;
  14049. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  14050. JSON_ASSERT(len <= std::numeric_limits<FloatType>::max_digits10);
  14051. // Format the buffer like printf("%.*g", prec, value)
  14052. constexpr int kMinExp = -4;
  14053. // Use digits10 here to increase compatibility with version 2.
  14054. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  14055. JSON_ASSERT(last - first >= kMaxExp + 2);
  14056. JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  14057. JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  14058. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  14059. }
  14060. } // namespace detail
  14061. } // namespace nlohmann
  14062. // #include <nlohmann/detail/exceptions.hpp>
  14063. // #include <nlohmann/detail/macro_scope.hpp>
  14064. // #include <nlohmann/detail/meta/cpp_future.hpp>
  14065. // #include <nlohmann/detail/output/binary_writer.hpp>
  14066. // #include <nlohmann/detail/output/output_adapters.hpp>
  14067. // #include <nlohmann/detail/value_t.hpp>
  14068. namespace nlohmann
  14069. {
  14070. namespace detail
  14071. {
  14072. ///////////////////
  14073. // serialization //
  14074. ///////////////////
  14075. /// how to treat decoding errors
  14076. enum class error_handler_t
  14077. {
  14078. strict, ///< throw a type_error exception in case of invalid UTF-8
  14079. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  14080. ignore ///< ignore invalid UTF-8 sequences
  14081. };
  14082. template<typename BasicJsonType>
  14083. class serializer
  14084. {
  14085. using string_t = typename BasicJsonType::string_t;
  14086. using number_float_t = typename BasicJsonType::number_float_t;
  14087. using number_integer_t = typename BasicJsonType::number_integer_t;
  14088. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  14089. using binary_char_t = typename BasicJsonType::binary_t::value_type;
  14090. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  14091. static constexpr std::uint8_t UTF8_REJECT = 1;
  14092. public:
  14093. /*!
  14094. @param[in] s output stream to serialize to
  14095. @param[in] ichar indentation character to use
  14096. @param[in] error_handler_ how to react on decoding errors
  14097. */
  14098. serializer(output_adapter_t<char> s, const char ichar,
  14099. error_handler_t error_handler_ = error_handler_t::strict)
  14100. : o(std::move(s))
  14101. , loc(std::localeconv())
  14102. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->thousands_sep)))
  14103. , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->decimal_point)))
  14104. , indent_char(ichar)
  14105. , indent_string(512, indent_char)
  14106. , error_handler(error_handler_)
  14107. {}
  14108. // delete because of pointer members
  14109. serializer(const serializer&) = delete;
  14110. serializer& operator=(const serializer&) = delete;
  14111. serializer(serializer&&) = delete;
  14112. serializer& operator=(serializer&&) = delete;
  14113. ~serializer() = default;
  14114. /*!
  14115. @brief internal implementation of the serialization function
  14116. This function is called by the public member function dump and organizes
  14117. the serialization internally. The indentation level is propagated as
  14118. additional parameter. In case of arrays and objects, the function is
  14119. called recursively.
  14120. - strings and object keys are escaped using `escape_string()`
  14121. - integer numbers are converted implicitly via `operator<<`
  14122. - floating-point numbers are converted to a string using `"%g"` format
  14123. - binary values are serialized as objects containing the subtype and the
  14124. byte array
  14125. @param[in] val value to serialize
  14126. @param[in] pretty_print whether the output shall be pretty-printed
  14127. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  14128. in the output are escaped with `\uXXXX` sequences, and the result consists
  14129. of ASCII characters only.
  14130. @param[in] indent_step the indent level
  14131. @param[in] current_indent the current indent level (only used internally)
  14132. */
  14133. void dump(const BasicJsonType& val,
  14134. const bool pretty_print,
  14135. const bool ensure_ascii,
  14136. const unsigned int indent_step,
  14137. const unsigned int current_indent = 0)
  14138. {
  14139. switch (val.m_type)
  14140. {
  14141. case value_t::object:
  14142. {
  14143. if (val.m_value.object->empty())
  14144. {
  14145. o->write_characters("{}", 2);
  14146. return;
  14147. }
  14148. if (pretty_print)
  14149. {
  14150. o->write_characters("{\n", 2);
  14151. // variable to hold indentation for recursive calls
  14152. const auto new_indent = current_indent + indent_step;
  14153. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  14154. {
  14155. indent_string.resize(indent_string.size() * 2, ' ');
  14156. }
  14157. // first n-1 elements
  14158. auto i = val.m_value.object->cbegin();
  14159. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  14160. {
  14161. o->write_characters(indent_string.c_str(), new_indent);
  14162. o->write_character('\"');
  14163. dump_escaped(i->first, ensure_ascii);
  14164. o->write_characters("\": ", 3);
  14165. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  14166. o->write_characters(",\n", 2);
  14167. }
  14168. // last element
  14169. JSON_ASSERT(i != val.m_value.object->cend());
  14170. JSON_ASSERT(std::next(i) == val.m_value.object->cend());
  14171. o->write_characters(indent_string.c_str(), new_indent);
  14172. o->write_character('\"');
  14173. dump_escaped(i->first, ensure_ascii);
  14174. o->write_characters("\": ", 3);
  14175. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  14176. o->write_character('\n');
  14177. o->write_characters(indent_string.c_str(), current_indent);
  14178. o->write_character('}');
  14179. }
  14180. else
  14181. {
  14182. o->write_character('{');
  14183. // first n-1 elements
  14184. auto i = val.m_value.object->cbegin();
  14185. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  14186. {
  14187. o->write_character('\"');
  14188. dump_escaped(i->first, ensure_ascii);
  14189. o->write_characters("\":", 2);
  14190. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  14191. o->write_character(',');
  14192. }
  14193. // last element
  14194. JSON_ASSERT(i != val.m_value.object->cend());
  14195. JSON_ASSERT(std::next(i) == val.m_value.object->cend());
  14196. o->write_character('\"');
  14197. dump_escaped(i->first, ensure_ascii);
  14198. o->write_characters("\":", 2);
  14199. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  14200. o->write_character('}');
  14201. }
  14202. return;
  14203. }
  14204. case value_t::array:
  14205. {
  14206. if (val.m_value.array->empty())
  14207. {
  14208. o->write_characters("[]", 2);
  14209. return;
  14210. }
  14211. if (pretty_print)
  14212. {
  14213. o->write_characters("[\n", 2);
  14214. // variable to hold indentation for recursive calls
  14215. const auto new_indent = current_indent + indent_step;
  14216. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  14217. {
  14218. indent_string.resize(indent_string.size() * 2, ' ');
  14219. }
  14220. // first n-1 elements
  14221. for (auto i = val.m_value.array->cbegin();
  14222. i != val.m_value.array->cend() - 1; ++i)
  14223. {
  14224. o->write_characters(indent_string.c_str(), new_indent);
  14225. dump(*i, true, ensure_ascii, indent_step, new_indent);
  14226. o->write_characters(",\n", 2);
  14227. }
  14228. // last element
  14229. JSON_ASSERT(!val.m_value.array->empty());
  14230. o->write_characters(indent_string.c_str(), new_indent);
  14231. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  14232. o->write_character('\n');
  14233. o->write_characters(indent_string.c_str(), current_indent);
  14234. o->write_character(']');
  14235. }
  14236. else
  14237. {
  14238. o->write_character('[');
  14239. // first n-1 elements
  14240. for (auto i = val.m_value.array->cbegin();
  14241. i != val.m_value.array->cend() - 1; ++i)
  14242. {
  14243. dump(*i, false, ensure_ascii, indent_step, current_indent);
  14244. o->write_character(',');
  14245. }
  14246. // last element
  14247. JSON_ASSERT(!val.m_value.array->empty());
  14248. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  14249. o->write_character(']');
  14250. }
  14251. return;
  14252. }
  14253. case value_t::string:
  14254. {
  14255. o->write_character('\"');
  14256. dump_escaped(*val.m_value.string, ensure_ascii);
  14257. o->write_character('\"');
  14258. return;
  14259. }
  14260. case value_t::binary:
  14261. {
  14262. if (pretty_print)
  14263. {
  14264. o->write_characters("{\n", 2);
  14265. // variable to hold indentation for recursive calls
  14266. const auto new_indent = current_indent + indent_step;
  14267. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  14268. {
  14269. indent_string.resize(indent_string.size() * 2, ' ');
  14270. }
  14271. o->write_characters(indent_string.c_str(), new_indent);
  14272. o->write_characters("\"bytes\": [", 10);
  14273. if (!val.m_value.binary->empty())
  14274. {
  14275. for (auto i = val.m_value.binary->cbegin();
  14276. i != val.m_value.binary->cend() - 1; ++i)
  14277. {
  14278. dump_integer(*i);
  14279. o->write_characters(", ", 2);
  14280. }
  14281. dump_integer(val.m_value.binary->back());
  14282. }
  14283. o->write_characters("],\n", 3);
  14284. o->write_characters(indent_string.c_str(), new_indent);
  14285. o->write_characters("\"subtype\": ", 11);
  14286. if (val.m_value.binary->has_subtype())
  14287. {
  14288. dump_integer(val.m_value.binary->subtype());
  14289. }
  14290. else
  14291. {
  14292. o->write_characters("null", 4);
  14293. }
  14294. o->write_character('\n');
  14295. o->write_characters(indent_string.c_str(), current_indent);
  14296. o->write_character('}');
  14297. }
  14298. else
  14299. {
  14300. o->write_characters("{\"bytes\":[", 10);
  14301. if (!val.m_value.binary->empty())
  14302. {
  14303. for (auto i = val.m_value.binary->cbegin();
  14304. i != val.m_value.binary->cend() - 1; ++i)
  14305. {
  14306. dump_integer(*i);
  14307. o->write_character(',');
  14308. }
  14309. dump_integer(val.m_value.binary->back());
  14310. }
  14311. o->write_characters("],\"subtype\":", 12);
  14312. if (val.m_value.binary->has_subtype())
  14313. {
  14314. dump_integer(val.m_value.binary->subtype());
  14315. o->write_character('}');
  14316. }
  14317. else
  14318. {
  14319. o->write_characters("null}", 5);
  14320. }
  14321. }
  14322. return;
  14323. }
  14324. case value_t::boolean:
  14325. {
  14326. if (val.m_value.boolean)
  14327. {
  14328. o->write_characters("true", 4);
  14329. }
  14330. else
  14331. {
  14332. o->write_characters("false", 5);
  14333. }
  14334. return;
  14335. }
  14336. case value_t::number_integer:
  14337. {
  14338. dump_integer(val.m_value.number_integer);
  14339. return;
  14340. }
  14341. case value_t::number_unsigned:
  14342. {
  14343. dump_integer(val.m_value.number_unsigned);
  14344. return;
  14345. }
  14346. case value_t::number_float:
  14347. {
  14348. dump_float(val.m_value.number_float);
  14349. return;
  14350. }
  14351. case value_t::discarded:
  14352. {
  14353. o->write_characters("<discarded>", 11);
  14354. return;
  14355. }
  14356. case value_t::null:
  14357. {
  14358. o->write_characters("null", 4);
  14359. return;
  14360. }
  14361. default: // LCOV_EXCL_LINE
  14362. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14363. }
  14364. }
  14365. JSON_PRIVATE_UNLESS_TESTED:
  14366. /*!
  14367. @brief dump escaped string
  14368. Escape a string by replacing certain special characters by a sequence of an
  14369. escape character (backslash) and another character and other control
  14370. characters by a sequence of "\u" followed by a four-digit hex
  14371. representation. The escaped string is written to output stream @a o.
  14372. @param[in] s the string to escape
  14373. @param[in] ensure_ascii whether to escape non-ASCII characters with
  14374. \uXXXX sequences
  14375. @complexity Linear in the length of string @a s.
  14376. */
  14377. void dump_escaped(const string_t& s, const bool ensure_ascii)
  14378. {
  14379. std::uint32_t codepoint{};
  14380. std::uint8_t state = UTF8_ACCEPT;
  14381. std::size_t bytes = 0; // number of bytes written to string_buffer
  14382. // number of bytes written at the point of the last valid byte
  14383. std::size_t bytes_after_last_accept = 0;
  14384. std::size_t undumped_chars = 0;
  14385. for (std::size_t i = 0; i < s.size(); ++i)
  14386. {
  14387. const auto byte = static_cast<std::uint8_t>(s[i]);
  14388. switch (decode(state, codepoint, byte))
  14389. {
  14390. case UTF8_ACCEPT: // decode found a new code point
  14391. {
  14392. switch (codepoint)
  14393. {
  14394. case 0x08: // backspace
  14395. {
  14396. string_buffer[bytes++] = '\\';
  14397. string_buffer[bytes++] = 'b';
  14398. break;
  14399. }
  14400. case 0x09: // horizontal tab
  14401. {
  14402. string_buffer[bytes++] = '\\';
  14403. string_buffer[bytes++] = 't';
  14404. break;
  14405. }
  14406. case 0x0A: // newline
  14407. {
  14408. string_buffer[bytes++] = '\\';
  14409. string_buffer[bytes++] = 'n';
  14410. break;
  14411. }
  14412. case 0x0C: // formfeed
  14413. {
  14414. string_buffer[bytes++] = '\\';
  14415. string_buffer[bytes++] = 'f';
  14416. break;
  14417. }
  14418. case 0x0D: // carriage return
  14419. {
  14420. string_buffer[bytes++] = '\\';
  14421. string_buffer[bytes++] = 'r';
  14422. break;
  14423. }
  14424. case 0x22: // quotation mark
  14425. {
  14426. string_buffer[bytes++] = '\\';
  14427. string_buffer[bytes++] = '\"';
  14428. break;
  14429. }
  14430. case 0x5C: // reverse solidus
  14431. {
  14432. string_buffer[bytes++] = '\\';
  14433. string_buffer[bytes++] = '\\';
  14434. break;
  14435. }
  14436. default:
  14437. {
  14438. // escape control characters (0x00..0x1F) or, if
  14439. // ensure_ascii parameter is used, non-ASCII characters
  14440. if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F)))
  14441. {
  14442. if (codepoint <= 0xFFFF)
  14443. {
  14444. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14445. static_cast<void>((std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  14446. static_cast<std::uint16_t>(codepoint)));
  14447. bytes += 6;
  14448. }
  14449. else
  14450. {
  14451. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14452. static_cast<void>((std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  14453. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  14454. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu))));
  14455. bytes += 12;
  14456. }
  14457. }
  14458. else
  14459. {
  14460. // copy byte to buffer (all previous bytes
  14461. // been copied have in default case above)
  14462. string_buffer[bytes++] = s[i];
  14463. }
  14464. break;
  14465. }
  14466. }
  14467. // write buffer and reset index; there must be 13 bytes
  14468. // left, as this is the maximal number of bytes to be
  14469. // written ("\uxxxx\uxxxx\0") for one code point
  14470. if (string_buffer.size() - bytes < 13)
  14471. {
  14472. o->write_characters(string_buffer.data(), bytes);
  14473. bytes = 0;
  14474. }
  14475. // remember the byte position of this accept
  14476. bytes_after_last_accept = bytes;
  14477. undumped_chars = 0;
  14478. break;
  14479. }
  14480. case UTF8_REJECT: // decode found invalid UTF-8 byte
  14481. {
  14482. switch (error_handler)
  14483. {
  14484. case error_handler_t::strict:
  14485. {
  14486. std::stringstream ss;
  14487. ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (byte | 0);
  14488. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str(), BasicJsonType()));
  14489. }
  14490. case error_handler_t::ignore:
  14491. case error_handler_t::replace:
  14492. {
  14493. // in case we saw this character the first time, we
  14494. // would like to read it again, because the byte
  14495. // may be OK for itself, but just not OK for the
  14496. // previous sequence
  14497. if (undumped_chars > 0)
  14498. {
  14499. --i;
  14500. }
  14501. // reset length buffer to the last accepted index;
  14502. // thus removing/ignoring the invalid characters
  14503. bytes = bytes_after_last_accept;
  14504. if (error_handler == error_handler_t::replace)
  14505. {
  14506. // add a replacement character
  14507. if (ensure_ascii)
  14508. {
  14509. string_buffer[bytes++] = '\\';
  14510. string_buffer[bytes++] = 'u';
  14511. string_buffer[bytes++] = 'f';
  14512. string_buffer[bytes++] = 'f';
  14513. string_buffer[bytes++] = 'f';
  14514. string_buffer[bytes++] = 'd';
  14515. }
  14516. else
  14517. {
  14518. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  14519. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  14520. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  14521. }
  14522. // write buffer and reset index; there must be 13 bytes
  14523. // left, as this is the maximal number of bytes to be
  14524. // written ("\uxxxx\uxxxx\0") for one code point
  14525. if (string_buffer.size() - bytes < 13)
  14526. {
  14527. o->write_characters(string_buffer.data(), bytes);
  14528. bytes = 0;
  14529. }
  14530. bytes_after_last_accept = bytes;
  14531. }
  14532. undumped_chars = 0;
  14533. // continue processing the string
  14534. state = UTF8_ACCEPT;
  14535. break;
  14536. }
  14537. default: // LCOV_EXCL_LINE
  14538. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14539. }
  14540. break;
  14541. }
  14542. default: // decode found yet incomplete multi-byte code point
  14543. {
  14544. if (!ensure_ascii)
  14545. {
  14546. // code point will not be escaped - copy byte to buffer
  14547. string_buffer[bytes++] = s[i];
  14548. }
  14549. ++undumped_chars;
  14550. break;
  14551. }
  14552. }
  14553. }
  14554. // we finished processing the string
  14555. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  14556. {
  14557. // write buffer
  14558. if (bytes > 0)
  14559. {
  14560. o->write_characters(string_buffer.data(), bytes);
  14561. }
  14562. }
  14563. else
  14564. {
  14565. // we finish reading, but do not accept: string was incomplete
  14566. switch (error_handler)
  14567. {
  14568. case error_handler_t::strict:
  14569. {
  14570. std::stringstream ss;
  14571. ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (static_cast<std::uint8_t>(s.back()) | 0);
  14572. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str(), BasicJsonType()));
  14573. }
  14574. case error_handler_t::ignore:
  14575. {
  14576. // write all accepted bytes
  14577. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  14578. break;
  14579. }
  14580. case error_handler_t::replace:
  14581. {
  14582. // write all accepted bytes
  14583. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  14584. // add a replacement character
  14585. if (ensure_ascii)
  14586. {
  14587. o->write_characters("\\ufffd", 6);
  14588. }
  14589. else
  14590. {
  14591. o->write_characters("\xEF\xBF\xBD", 3);
  14592. }
  14593. break;
  14594. }
  14595. default: // LCOV_EXCL_LINE
  14596. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14597. }
  14598. }
  14599. }
  14600. private:
  14601. /*!
  14602. @brief count digits
  14603. Count the number of decimal (base 10) digits for an input unsigned integer.
  14604. @param[in] x unsigned integer number to count its digits
  14605. @return number of decimal digits
  14606. */
  14607. inline unsigned int count_digits(number_unsigned_t x) noexcept
  14608. {
  14609. unsigned int n_digits = 1;
  14610. for (;;)
  14611. {
  14612. if (x < 10)
  14613. {
  14614. return n_digits;
  14615. }
  14616. if (x < 100)
  14617. {
  14618. return n_digits + 1;
  14619. }
  14620. if (x < 1000)
  14621. {
  14622. return n_digits + 2;
  14623. }
  14624. if (x < 10000)
  14625. {
  14626. return n_digits + 3;
  14627. }
  14628. x = x / 10000u;
  14629. n_digits += 4;
  14630. }
  14631. }
  14632. // templates to avoid warnings about useless casts
  14633. template <typename NumberType, enable_if_t<std::is_signed<NumberType>::value, int> = 0>
  14634. bool is_negative_number(NumberType x)
  14635. {
  14636. return x < 0;
  14637. }
  14638. template < typename NumberType, enable_if_t <std::is_unsigned<NumberType>::value, int > = 0 >
  14639. bool is_negative_number(NumberType /*unused*/)
  14640. {
  14641. return false;
  14642. }
  14643. /*!
  14644. @brief dump an integer
  14645. Dump a given integer to output stream @a o. Works internally with
  14646. @a number_buffer.
  14647. @param[in] x integer number (signed or unsigned) to dump
  14648. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  14649. */
  14650. template < typename NumberType, detail::enable_if_t <
  14651. std::is_integral<NumberType>::value ||
  14652. std::is_same<NumberType, number_unsigned_t>::value ||
  14653. std::is_same<NumberType, number_integer_t>::value ||
  14654. std::is_same<NumberType, binary_char_t>::value,
  14655. int > = 0 >
  14656. void dump_integer(NumberType x)
  14657. {
  14658. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  14659. {
  14660. {
  14661. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  14662. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  14663. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  14664. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  14665. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  14666. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  14667. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  14668. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  14669. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  14670. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  14671. }
  14672. };
  14673. // special case for "0"
  14674. if (x == 0)
  14675. {
  14676. o->write_character('0');
  14677. return;
  14678. }
  14679. // use a pointer to fill the buffer
  14680. auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14681. number_unsigned_t abs_value;
  14682. unsigned int n_chars{};
  14683. if (is_negative_number(x))
  14684. {
  14685. *buffer_ptr = '-';
  14686. abs_value = remove_sign(static_cast<number_integer_t>(x));
  14687. // account one more byte for the minus sign
  14688. n_chars = 1 + count_digits(abs_value);
  14689. }
  14690. else
  14691. {
  14692. abs_value = static_cast<number_unsigned_t>(x);
  14693. n_chars = count_digits(abs_value);
  14694. }
  14695. // spare 1 byte for '\0'
  14696. JSON_ASSERT(n_chars < number_buffer.size() - 1);
  14697. // jump to the end to generate the string from backward,
  14698. // so we later avoid reversing the result
  14699. buffer_ptr += n_chars;
  14700. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  14701. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  14702. while (abs_value >= 100)
  14703. {
  14704. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  14705. abs_value /= 100;
  14706. *(--buffer_ptr) = digits_to_99[digits_index][1];
  14707. *(--buffer_ptr) = digits_to_99[digits_index][0];
  14708. }
  14709. if (abs_value >= 10)
  14710. {
  14711. const auto digits_index = static_cast<unsigned>(abs_value);
  14712. *(--buffer_ptr) = digits_to_99[digits_index][1];
  14713. *(--buffer_ptr) = digits_to_99[digits_index][0];
  14714. }
  14715. else
  14716. {
  14717. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  14718. }
  14719. o->write_characters(number_buffer.data(), n_chars);
  14720. }
  14721. /*!
  14722. @brief dump a floating-point number
  14723. Dump a given floating-point number to output stream @a o. Works internally
  14724. with @a number_buffer.
  14725. @param[in] x floating-point number to dump
  14726. */
  14727. void dump_float(number_float_t x)
  14728. {
  14729. // NaN / inf
  14730. if (!std::isfinite(x))
  14731. {
  14732. o->write_characters("null", 4);
  14733. return;
  14734. }
  14735. // If number_float_t is an IEEE-754 single or double precision number,
  14736. // use the Grisu2 algorithm to produce short numbers which are
  14737. // guaranteed to round-trip, using strtof and strtod, resp.
  14738. //
  14739. // NB: The test below works if <long double> == <double>.
  14740. static constexpr bool is_ieee_single_or_double
  14741. = (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) ||
  14742. (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);
  14743. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  14744. }
  14745. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  14746. {
  14747. auto* begin = number_buffer.data();
  14748. auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  14749. o->write_characters(begin, static_cast<size_t>(end - begin));
  14750. }
  14751. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  14752. {
  14753. // get number of digits for a float -> text -> float round-trip
  14754. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  14755. // the actual conversion
  14756. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14757. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  14758. // negative value indicates an error
  14759. JSON_ASSERT(len > 0);
  14760. // check if buffer was large enough
  14761. JSON_ASSERT(static_cast<std::size_t>(len) < number_buffer.size());
  14762. // erase thousands separator
  14763. if (thousands_sep != '\0')
  14764. {
  14765. // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081
  14766. const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep);
  14767. std::fill(end, number_buffer.end(), '\0');
  14768. JSON_ASSERT((end - number_buffer.begin()) <= len);
  14769. len = (end - number_buffer.begin());
  14770. }
  14771. // convert decimal point to '.'
  14772. if (decimal_point != '\0' && decimal_point != '.')
  14773. {
  14774. // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see https://github.com/nlohmann/json/issues/3081
  14775. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  14776. if (dec_pos != number_buffer.end())
  14777. {
  14778. *dec_pos = '.';
  14779. }
  14780. }
  14781. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  14782. // determine if we need to append ".0"
  14783. const bool value_is_int_like =
  14784. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  14785. [](char c)
  14786. {
  14787. return c == '.' || c == 'e';
  14788. });
  14789. if (value_is_int_like)
  14790. {
  14791. o->write_characters(".0", 2);
  14792. }
  14793. }
  14794. /*!
  14795. @brief check whether a string is UTF-8 encoded
  14796. The function checks each byte of a string whether it is UTF-8 encoded. The
  14797. result of the check is stored in the @a state parameter. The function must
  14798. be called initially with state 0 (accept). State 1 means the string must
  14799. be rejected, because the current byte is not allowed. If the string is
  14800. completely processed, but the state is non-zero, the string ended
  14801. prematurely; that is, the last byte indicated more bytes should have
  14802. followed.
  14803. @param[in,out] state the state of the decoding
  14804. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  14805. @param[in] byte next byte to decode
  14806. @return new state
  14807. @note The function has been edited: a std::array is used.
  14808. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  14809. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  14810. */
  14811. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  14812. {
  14813. static const std::array<std::uint8_t, 400> utf8d =
  14814. {
  14815. {
  14816. 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
  14817. 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
  14818. 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
  14819. 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
  14820. 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
  14821. 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
  14822. 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
  14823. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  14824. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  14825. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  14826. 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
  14827. 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
  14828. 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
  14829. 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
  14830. }
  14831. };
  14832. JSON_ASSERT(byte < utf8d.size());
  14833. const std::uint8_t type = utf8d[byte];
  14834. codep = (state != UTF8_ACCEPT)
  14835. ? (byte & 0x3fu) | (codep << 6u)
  14836. : (0xFFu >> type) & (byte);
  14837. std::size_t index = 256u + static_cast<size_t>(state) * 16u + static_cast<size_t>(type);
  14838. JSON_ASSERT(index < 400);
  14839. state = utf8d[index];
  14840. return state;
  14841. }
  14842. /*
  14843. * Overload to make the compiler happy while it is instantiating
  14844. * dump_integer for number_unsigned_t.
  14845. * Must never be called.
  14846. */
  14847. number_unsigned_t remove_sign(number_unsigned_t x)
  14848. {
  14849. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14850. return x; // LCOV_EXCL_LINE
  14851. }
  14852. /*
  14853. * Helper function for dump_integer
  14854. *
  14855. * This function takes a negative signed integer and returns its absolute
  14856. * value as unsigned integer. The plus/minus shuffling is necessary as we can
  14857. * not directly remove the sign of an arbitrary signed integer as the
  14858. * absolute values of INT_MIN and INT_MAX are usually not the same. See
  14859. * #1708 for details.
  14860. */
  14861. inline number_unsigned_t remove_sign(number_integer_t x) noexcept
  14862. {
  14863. JSON_ASSERT(x < 0 && x < (std::numeric_limits<number_integer_t>::max)()); // NOLINT(misc-redundant-expression)
  14864. return static_cast<number_unsigned_t>(-(x + 1)) + 1;
  14865. }
  14866. private:
  14867. /// the output of the serializer
  14868. output_adapter_t<char> o = nullptr;
  14869. /// a (hopefully) large enough character buffer
  14870. std::array<char, 64> number_buffer{{}};
  14871. /// the locale
  14872. const std::lconv* loc = nullptr;
  14873. /// the locale's thousand separator character
  14874. const char thousands_sep = '\0';
  14875. /// the locale's decimal point character
  14876. const char decimal_point = '\0';
  14877. /// string buffer
  14878. std::array<char, 512> string_buffer{{}};
  14879. /// the indentation character
  14880. const char indent_char;
  14881. /// the indentation string
  14882. string_t indent_string;
  14883. /// error_handler how to react on decoding errors
  14884. const error_handler_t error_handler;
  14885. };
  14886. } // namespace detail
  14887. } // namespace nlohmann
  14888. // #include <nlohmann/detail/value_t.hpp>
  14889. // #include <nlohmann/json_fwd.hpp>
  14890. // #include <nlohmann/ordered_map.hpp>
  14891. #include <functional> // less
  14892. #include <initializer_list> // initializer_list
  14893. #include <iterator> // input_iterator_tag, iterator_traits
  14894. #include <memory> // allocator
  14895. #include <stdexcept> // for out_of_range
  14896. #include <type_traits> // enable_if, is_convertible
  14897. #include <utility> // pair
  14898. #include <vector> // vector
  14899. // #include <nlohmann/detail/macro_scope.hpp>
  14900. namespace nlohmann
  14901. {
  14902. /// ordered_map: a minimal map-like container that preserves insertion order
  14903. /// for use within nlohmann::basic_json<ordered_map>
  14904. template <class Key, class T, class IgnoredLess = std::less<Key>,
  14905. class Allocator = std::allocator<std::pair<const Key, T>>>
  14906. struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>
  14907. {
  14908. using key_type = Key;
  14909. using mapped_type = T;
  14910. using Container = std::vector<std::pair<const Key, T>, Allocator>;
  14911. using iterator = typename Container::iterator;
  14912. using const_iterator = typename Container::const_iterator;
  14913. using size_type = typename Container::size_type;
  14914. using value_type = typename Container::value_type;
  14915. // Explicit constructors instead of `using Container::Container`
  14916. // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4)
  14917. ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {}
  14918. template <class It>
  14919. ordered_map(It first, It last, const Allocator& alloc = Allocator())
  14920. : Container{first, last, alloc} {}
  14921. ordered_map(std::initializer_list<T> init, const Allocator& alloc = Allocator() )
  14922. : Container{init, alloc} {}
  14923. std::pair<iterator, bool> emplace(const key_type& key, T&& t)
  14924. {
  14925. for (auto it = this->begin(); it != this->end(); ++it)
  14926. {
  14927. if (it->first == key)
  14928. {
  14929. return {it, false};
  14930. }
  14931. }
  14932. Container::emplace_back(key, t);
  14933. return {--this->end(), true};
  14934. }
  14935. T& operator[](const Key& key)
  14936. {
  14937. return emplace(key, T{}).first->second;
  14938. }
  14939. const T& operator[](const Key& key) const
  14940. {
  14941. return at(key);
  14942. }
  14943. T& at(const Key& key)
  14944. {
  14945. for (auto it = this->begin(); it != this->end(); ++it)
  14946. {
  14947. if (it->first == key)
  14948. {
  14949. return it->second;
  14950. }
  14951. }
  14952. JSON_THROW(std::out_of_range("key not found"));
  14953. }
  14954. const T& at(const Key& key) const
  14955. {
  14956. for (auto it = this->begin(); it != this->end(); ++it)
  14957. {
  14958. if (it->first == key)
  14959. {
  14960. return it->second;
  14961. }
  14962. }
  14963. JSON_THROW(std::out_of_range("key not found"));
  14964. }
  14965. size_type erase(const Key& key)
  14966. {
  14967. for (auto it = this->begin(); it != this->end(); ++it)
  14968. {
  14969. if (it->first == key)
  14970. {
  14971. // Since we cannot move const Keys, re-construct them in place
  14972. for (auto next = it; ++next != this->end(); ++it)
  14973. {
  14974. it->~value_type(); // Destroy but keep allocation
  14975. new (&*it) value_type{std::move(*next)};
  14976. }
  14977. Container::pop_back();
  14978. return 1;
  14979. }
  14980. }
  14981. return 0;
  14982. }
  14983. iterator erase(iterator pos)
  14984. {
  14985. return erase(pos, std::next(pos));
  14986. }
  14987. iterator erase(iterator first, iterator last)
  14988. {
  14989. const auto elements_affected = std::distance(first, last);
  14990. const auto offset = std::distance(Container::begin(), first);
  14991. // This is the start situation. We need to delete elements_affected
  14992. // elements (3 in this example: e, f, g), and need to return an
  14993. // iterator past the last deleted element (h in this example).
  14994. // Note that offset is the distance from the start of the vector
  14995. // to first. We will need this later.
  14996. // [ a, b, c, d, e, f, g, h, i, j ]
  14997. // ^ ^
  14998. // first last
  14999. // Since we cannot move const Keys, we re-construct them in place.
  15000. // We start at first and re-construct (viz. copy) the elements from
  15001. // the back of the vector. Example for first iteration:
  15002. // ,--------.
  15003. // v | destroy e and re-construct with h
  15004. // [ a, b, c, d, e, f, g, h, i, j ]
  15005. // ^ ^
  15006. // it it + elements_affected
  15007. for (auto it = first; std::next(it, elements_affected) != Container::end(); ++it)
  15008. {
  15009. it->~value_type(); // destroy but keep allocation
  15010. new (&*it) value_type{std::move(*std::next(it, elements_affected))}; // "move" next element to it
  15011. }
  15012. // [ a, b, c, d, h, i, j, h, i, j ]
  15013. // ^ ^
  15014. // first last
  15015. // remove the unneeded elements at the end of the vector
  15016. Container::resize(this->size() - static_cast<size_type>(elements_affected));
  15017. // [ a, b, c, d, h, i, j ]
  15018. // ^ ^
  15019. // first last
  15020. // first is now pointing past the last deleted element, but we cannot
  15021. // use this iterator, because it may have been invalidated by the
  15022. // resize call. Instead, we can return begin() + offset.
  15023. return Container::begin() + offset;
  15024. }
  15025. size_type count(const Key& key) const
  15026. {
  15027. for (auto it = this->begin(); it != this->end(); ++it)
  15028. {
  15029. if (it->first == key)
  15030. {
  15031. return 1;
  15032. }
  15033. }
  15034. return 0;
  15035. }
  15036. iterator find(const Key& key)
  15037. {
  15038. for (auto it = this->begin(); it != this->end(); ++it)
  15039. {
  15040. if (it->first == key)
  15041. {
  15042. return it;
  15043. }
  15044. }
  15045. return Container::end();
  15046. }
  15047. const_iterator find(const Key& key) const
  15048. {
  15049. for (auto it = this->begin(); it != this->end(); ++it)
  15050. {
  15051. if (it->first == key)
  15052. {
  15053. return it;
  15054. }
  15055. }
  15056. return Container::end();
  15057. }
  15058. std::pair<iterator, bool> insert( value_type&& value )
  15059. {
  15060. return emplace(value.first, std::move(value.second));
  15061. }
  15062. std::pair<iterator, bool> insert( const value_type& value )
  15063. {
  15064. for (auto it = this->begin(); it != this->end(); ++it)
  15065. {
  15066. if (it->first == value.first)
  15067. {
  15068. return {it, false};
  15069. }
  15070. }
  15071. Container::push_back(value);
  15072. return {--this->end(), true};
  15073. }
  15074. template<typename InputIt>
  15075. using require_input_iter = typename std::enable_if<std::is_convertible<typename std::iterator_traits<InputIt>::iterator_category,
  15076. std::input_iterator_tag>::value>::type;
  15077. template<typename InputIt, typename = require_input_iter<InputIt>>
  15078. void insert(InputIt first, InputIt last)
  15079. {
  15080. for (auto it = first; it != last; ++it)
  15081. {
  15082. insert(*it);
  15083. }
  15084. }
  15085. };
  15086. } // namespace nlohmann
  15087. #if defined(JSON_HAS_CPP_17)
  15088. #include <string_view>
  15089. #endif
  15090. /*!
  15091. @brief namespace for Niels Lohmann
  15092. @see https://github.com/nlohmann
  15093. @since version 1.0.0
  15094. */
  15095. namespace nlohmann
  15096. {
  15097. /*!
  15098. @brief a class to store JSON values
  15099. @internal
  15100. @invariant The member variables @a m_value and @a m_type have the following
  15101. relationship:
  15102. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  15103. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  15104. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  15105. The invariants are checked by member function assert_invariant().
  15106. @note ObjectType trick from https://stackoverflow.com/a/9860911
  15107. @endinternal
  15108. @since version 1.0.0
  15109. @nosubgrouping
  15110. */
  15111. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  15112. class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)
  15113. {
  15114. private:
  15115. template<detail::value_t> friend struct detail::external_constructor;
  15116. friend ::nlohmann::json_pointer<basic_json>;
  15117. template<typename BasicJsonType, typename InputType>
  15118. friend class ::nlohmann::detail::parser;
  15119. friend ::nlohmann::detail::serializer<basic_json>;
  15120. template<typename BasicJsonType>
  15121. friend class ::nlohmann::detail::iter_impl;
  15122. template<typename BasicJsonType, typename CharType>
  15123. friend class ::nlohmann::detail::binary_writer;
  15124. template<typename BasicJsonType, typename InputType, typename SAX>
  15125. friend class ::nlohmann::detail::binary_reader;
  15126. template<typename BasicJsonType>
  15127. friend class ::nlohmann::detail::json_sax_dom_parser;
  15128. template<typename BasicJsonType>
  15129. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  15130. friend class ::nlohmann::detail::exception;
  15131. /// workaround type for MSVC
  15132. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  15133. JSON_PRIVATE_UNLESS_TESTED:
  15134. // convenience aliases for types residing in namespace detail;
  15135. using lexer = ::nlohmann::detail::lexer_base<basic_json>;
  15136. template<typename InputAdapterType>
  15137. static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser(
  15138. InputAdapterType adapter,
  15139. detail::parser_callback_t<basic_json>cb = nullptr,
  15140. const bool allow_exceptions = true,
  15141. const bool ignore_comments = false
  15142. )
  15143. {
  15144. return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter),
  15145. std::move(cb), allow_exceptions, ignore_comments);
  15146. }
  15147. private:
  15148. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  15149. template<typename BasicJsonType>
  15150. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  15151. template<typename BasicJsonType>
  15152. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  15153. template<typename Iterator>
  15154. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  15155. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  15156. template<typename CharType>
  15157. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  15158. template<typename InputType>
  15159. using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
  15160. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  15161. JSON_PRIVATE_UNLESS_TESTED:
  15162. using serializer = ::nlohmann::detail::serializer<basic_json>;
  15163. public:
  15164. using value_t = detail::value_t;
  15165. /// JSON Pointer, see @ref nlohmann::json_pointer
  15166. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  15167. template<typename T, typename SFINAE>
  15168. using json_serializer = JSONSerializer<T, SFINAE>;
  15169. /// how to treat decoding errors
  15170. using error_handler_t = detail::error_handler_t;
  15171. /// how to treat CBOR tags
  15172. using cbor_tag_handler_t = detail::cbor_tag_handler_t;
  15173. /// helper type for initializer lists of basic_json values
  15174. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  15175. using input_format_t = detail::input_format_t;
  15176. /// SAX interface type, see @ref nlohmann::json_sax
  15177. using json_sax_t = json_sax<basic_json>;
  15178. ////////////////
  15179. // exceptions //
  15180. ////////////////
  15181. /// @name exceptions
  15182. /// Classes to implement user-defined exceptions.
  15183. /// @{
  15184. using exception = detail::exception;
  15185. using parse_error = detail::parse_error;
  15186. using invalid_iterator = detail::invalid_iterator;
  15187. using type_error = detail::type_error;
  15188. using out_of_range = detail::out_of_range;
  15189. using other_error = detail::other_error;
  15190. /// @}
  15191. /////////////////////
  15192. // container types //
  15193. /////////////////////
  15194. /// @name container types
  15195. /// The canonic container types to use @ref basic_json like any other STL
  15196. /// container.
  15197. /// @{
  15198. /// the type of elements in a basic_json container
  15199. using value_type = basic_json;
  15200. /// the type of an element reference
  15201. using reference = value_type&;
  15202. /// the type of an element const reference
  15203. using const_reference = const value_type&;
  15204. /// a type to represent differences between iterators
  15205. using difference_type = std::ptrdiff_t;
  15206. /// a type to represent container sizes
  15207. using size_type = std::size_t;
  15208. /// the allocator type
  15209. using allocator_type = AllocatorType<basic_json>;
  15210. /// the type of an element pointer
  15211. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  15212. /// the type of an element const pointer
  15213. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  15214. /// an iterator for a basic_json container
  15215. using iterator = iter_impl<basic_json>;
  15216. /// a const iterator for a basic_json container
  15217. using const_iterator = iter_impl<const basic_json>;
  15218. /// a reverse iterator for a basic_json container
  15219. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  15220. /// a const reverse iterator for a basic_json container
  15221. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  15222. /// @}
  15223. /// @brief returns the allocator associated with the container
  15224. /// @sa https://json.nlohmann.me/api/basic_json/get_allocator/
  15225. static allocator_type get_allocator()
  15226. {
  15227. return allocator_type();
  15228. }
  15229. /// @brief returns version information on the library
  15230. /// @sa https://json.nlohmann.me/api/basic_json/meta/
  15231. JSON_HEDLEY_WARN_UNUSED_RESULT
  15232. static basic_json meta()
  15233. {
  15234. basic_json result;
  15235. result["copyright"] = "(C) 2013-2022 Niels Lohmann";
  15236. result["name"] = "JSON for Modern C++";
  15237. result["url"] = "https://github.com/nlohmann/json";
  15238. result["version"]["string"] =
  15239. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  15240. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  15241. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  15242. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  15243. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  15244. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  15245. #ifdef _WIN32
  15246. result["platform"] = "win32";
  15247. #elif defined __linux__
  15248. result["platform"] = "linux";
  15249. #elif defined __APPLE__
  15250. result["platform"] = "apple";
  15251. #elif defined __unix__
  15252. result["platform"] = "unix";
  15253. #else
  15254. result["platform"] = "unknown";
  15255. #endif
  15256. #if defined(__ICC) || defined(__INTEL_COMPILER)
  15257. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  15258. #elif defined(__clang__)
  15259. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  15260. #elif defined(__GNUC__) || defined(__GNUG__)
  15261. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  15262. #elif defined(__HP_cc) || defined(__HP_aCC)
  15263. result["compiler"] = "hp"
  15264. #elif defined(__IBMCPP__)
  15265. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  15266. #elif defined(_MSC_VER)
  15267. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  15268. #elif defined(__PGI)
  15269. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  15270. #elif defined(__SUNPRO_CC)
  15271. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  15272. #else
  15273. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  15274. #endif
  15275. #ifdef __cplusplus
  15276. result["compiler"]["c++"] = std::to_string(__cplusplus);
  15277. #else
  15278. result["compiler"]["c++"] = "unknown";
  15279. #endif
  15280. return result;
  15281. }
  15282. ///////////////////////////
  15283. // JSON value data types //
  15284. ///////////////////////////
  15285. /// @name JSON value data types
  15286. /// The data types to store a JSON value. These types are derived from
  15287. /// the template arguments passed to class @ref basic_json.
  15288. /// @{
  15289. /// @brief object key comparator type
  15290. /// @sa https://json.nlohmann.me/api/basic_json/object_comparator_t/
  15291. #if defined(JSON_HAS_CPP_14)
  15292. // Use transparent comparator if possible, combined with perfect forwarding
  15293. // on find() and count() calls prevents unnecessary string construction.
  15294. using object_comparator_t = std::less<>;
  15295. #else
  15296. using object_comparator_t = std::less<StringType>;
  15297. #endif
  15298. /// @brief a type for an object
  15299. /// @sa https://json.nlohmann.me/api/basic_json/object_t/
  15300. using object_t = ObjectType<StringType,
  15301. basic_json,
  15302. object_comparator_t,
  15303. AllocatorType<std::pair<const StringType,
  15304. basic_json>>>;
  15305. /// @brief a type for an array
  15306. /// @sa https://json.nlohmann.me/api/basic_json/array_t/
  15307. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  15308. /// @brief a type for a string
  15309. /// @sa https://json.nlohmann.me/api/basic_json/string_t/
  15310. using string_t = StringType;
  15311. /// @brief a type for a boolean
  15312. /// @sa https://json.nlohmann.me/api/basic_json/boolean_t/
  15313. using boolean_t = BooleanType;
  15314. /// @brief a type for a number (integer)
  15315. /// @sa https://json.nlohmann.me/api/basic_json/number_integer_t/
  15316. using number_integer_t = NumberIntegerType;
  15317. /// @brief a type for a number (unsigned)
  15318. /// @sa https://json.nlohmann.me/api/basic_json/number_unsigned_t/
  15319. using number_unsigned_t = NumberUnsignedType;
  15320. /// @brief a type for a number (floating-point)
  15321. /// @sa https://json.nlohmann.me/api/basic_json/number_float_t/
  15322. using number_float_t = NumberFloatType;
  15323. /// @brief a type for a packed binary type
  15324. /// @sa https://json.nlohmann.me/api/basic_json/binary_t/
  15325. using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;
  15326. /// @}
  15327. private:
  15328. /// helper for exception-safe object creation
  15329. template<typename T, typename... Args>
  15330. JSON_HEDLEY_RETURNS_NON_NULL
  15331. static T* create(Args&& ... args)
  15332. {
  15333. AllocatorType<T> alloc;
  15334. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  15335. auto deleter = [&](T * obj)
  15336. {
  15337. AllocatorTraits::deallocate(alloc, obj, 1);
  15338. };
  15339. std::unique_ptr<T, decltype(deleter)> obj(AllocatorTraits::allocate(alloc, 1), deleter);
  15340. AllocatorTraits::construct(alloc, obj.get(), std::forward<Args>(args)...);
  15341. JSON_ASSERT(obj != nullptr);
  15342. return obj.release();
  15343. }
  15344. ////////////////////////
  15345. // JSON value storage //
  15346. ////////////////////////
  15347. JSON_PRIVATE_UNLESS_TESTED:
  15348. /*!
  15349. @brief a JSON value
  15350. The actual storage for a JSON value of the @ref basic_json class. This
  15351. union combines the different storage types for the JSON value types
  15352. defined in @ref value_t.
  15353. JSON type | value_t type | used type
  15354. --------- | --------------- | ------------------------
  15355. object | object | pointer to @ref object_t
  15356. array | array | pointer to @ref array_t
  15357. string | string | pointer to @ref string_t
  15358. boolean | boolean | @ref boolean_t
  15359. number | number_integer | @ref number_integer_t
  15360. number | number_unsigned | @ref number_unsigned_t
  15361. number | number_float | @ref number_float_t
  15362. binary | binary | pointer to @ref binary_t
  15363. null | null | *no value is stored*
  15364. @note Variable-length types (objects, arrays, and strings) are stored as
  15365. pointers. The size of the union should not exceed 64 bits if the default
  15366. value types are used.
  15367. @since version 1.0.0
  15368. */
  15369. union json_value
  15370. {
  15371. /// object (stored with pointer to save storage)
  15372. object_t* object;
  15373. /// array (stored with pointer to save storage)
  15374. array_t* array;
  15375. /// string (stored with pointer to save storage)
  15376. string_t* string;
  15377. /// binary (stored with pointer to save storage)
  15378. binary_t* binary;
  15379. /// boolean
  15380. boolean_t boolean;
  15381. /// number (integer)
  15382. number_integer_t number_integer;
  15383. /// number (unsigned integer)
  15384. number_unsigned_t number_unsigned;
  15385. /// number (floating-point)
  15386. number_float_t number_float;
  15387. /// default constructor (for null values)
  15388. json_value() = default;
  15389. /// constructor for booleans
  15390. json_value(boolean_t v) noexcept : boolean(v) {}
  15391. /// constructor for numbers (integer)
  15392. json_value(number_integer_t v) noexcept : number_integer(v) {}
  15393. /// constructor for numbers (unsigned)
  15394. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  15395. /// constructor for numbers (floating-point)
  15396. json_value(number_float_t v) noexcept : number_float(v) {}
  15397. /// constructor for empty values of a given type
  15398. json_value(value_t t)
  15399. {
  15400. switch (t)
  15401. {
  15402. case value_t::object:
  15403. {
  15404. object = create<object_t>();
  15405. break;
  15406. }
  15407. case value_t::array:
  15408. {
  15409. array = create<array_t>();
  15410. break;
  15411. }
  15412. case value_t::string:
  15413. {
  15414. string = create<string_t>("");
  15415. break;
  15416. }
  15417. case value_t::binary:
  15418. {
  15419. binary = create<binary_t>();
  15420. break;
  15421. }
  15422. case value_t::boolean:
  15423. {
  15424. boolean = static_cast<boolean_t>(false);
  15425. break;
  15426. }
  15427. case value_t::number_integer:
  15428. {
  15429. number_integer = static_cast<number_integer_t>(0);
  15430. break;
  15431. }
  15432. case value_t::number_unsigned:
  15433. {
  15434. number_unsigned = static_cast<number_unsigned_t>(0);
  15435. break;
  15436. }
  15437. case value_t::number_float:
  15438. {
  15439. number_float = static_cast<number_float_t>(0.0);
  15440. break;
  15441. }
  15442. case value_t::null:
  15443. {
  15444. object = nullptr; // silence warning, see #821
  15445. break;
  15446. }
  15447. case value_t::discarded:
  15448. default:
  15449. {
  15450. object = nullptr; // silence warning, see #821
  15451. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  15452. {
  15453. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.10.5", basic_json())); // LCOV_EXCL_LINE
  15454. }
  15455. break;
  15456. }
  15457. }
  15458. }
  15459. /// constructor for strings
  15460. json_value(const string_t& value) : string(create<string_t>(value)) {}
  15461. /// constructor for rvalue strings
  15462. json_value(string_t&& value) : string(create<string_t>(std::move(value))) {}
  15463. /// constructor for objects
  15464. json_value(const object_t& value) : object(create<object_t>(value)) {}
  15465. /// constructor for rvalue objects
  15466. json_value(object_t&& value) : object(create<object_t>(std::move(value))) {}
  15467. /// constructor for arrays
  15468. json_value(const array_t& value) : array(create<array_t>(value)) {}
  15469. /// constructor for rvalue arrays
  15470. json_value(array_t&& value) : array(create<array_t>(std::move(value))) {}
  15471. /// constructor for binary arrays
  15472. json_value(const typename binary_t::container_type& value) : binary(create<binary_t>(value)) {}
  15473. /// constructor for rvalue binary arrays
  15474. json_value(typename binary_t::container_type&& value) : binary(create<binary_t>(std::move(value))) {}
  15475. /// constructor for binary arrays (internal type)
  15476. json_value(const binary_t& value) : binary(create<binary_t>(value)) {}
  15477. /// constructor for rvalue binary arrays (internal type)
  15478. json_value(binary_t&& value) : binary(create<binary_t>(std::move(value))) {}
  15479. void destroy(value_t t)
  15480. {
  15481. if (t == value_t::array || t == value_t::object)
  15482. {
  15483. // flatten the current json_value to a heap-allocated stack
  15484. std::vector<basic_json> stack;
  15485. // move the top-level items to stack
  15486. if (t == value_t::array)
  15487. {
  15488. stack.reserve(array->size());
  15489. std::move(array->begin(), array->end(), std::back_inserter(stack));
  15490. }
  15491. else
  15492. {
  15493. stack.reserve(object->size());
  15494. for (auto&& it : *object)
  15495. {
  15496. stack.push_back(std::move(it.second));
  15497. }
  15498. }
  15499. while (!stack.empty())
  15500. {
  15501. // move the last item to local variable to be processed
  15502. basic_json current_item(std::move(stack.back()));
  15503. stack.pop_back();
  15504. // if current_item is array/object, move
  15505. // its children to the stack to be processed later
  15506. if (current_item.is_array())
  15507. {
  15508. std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack));
  15509. current_item.m_value.array->clear();
  15510. }
  15511. else if (current_item.is_object())
  15512. {
  15513. for (auto&& it : *current_item.m_value.object)
  15514. {
  15515. stack.push_back(std::move(it.second));
  15516. }
  15517. current_item.m_value.object->clear();
  15518. }
  15519. // it's now safe that current_item get destructed
  15520. // since it doesn't have any children
  15521. }
  15522. }
  15523. switch (t)
  15524. {
  15525. case value_t::object:
  15526. {
  15527. AllocatorType<object_t> alloc;
  15528. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  15529. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  15530. break;
  15531. }
  15532. case value_t::array:
  15533. {
  15534. AllocatorType<array_t> alloc;
  15535. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  15536. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  15537. break;
  15538. }
  15539. case value_t::string:
  15540. {
  15541. AllocatorType<string_t> alloc;
  15542. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  15543. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  15544. break;
  15545. }
  15546. case value_t::binary:
  15547. {
  15548. AllocatorType<binary_t> alloc;
  15549. std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
  15550. std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
  15551. break;
  15552. }
  15553. case value_t::null:
  15554. case value_t::boolean:
  15555. case value_t::number_integer:
  15556. case value_t::number_unsigned:
  15557. case value_t::number_float:
  15558. case value_t::discarded:
  15559. default:
  15560. {
  15561. break;
  15562. }
  15563. }
  15564. }
  15565. };
  15566. private:
  15567. /*!
  15568. @brief checks the class invariants
  15569. This function asserts the class invariants. It needs to be called at the
  15570. end of every constructor to make sure that created objects respect the
  15571. invariant. Furthermore, it has to be called each time the type of a JSON
  15572. value is changed, because the invariant expresses a relationship between
  15573. @a m_type and @a m_value.
  15574. Furthermore, the parent relation is checked for arrays and objects: If
  15575. @a check_parents true and the value is an array or object, then the
  15576. container's elements must have the current value as parent.
  15577. @param[in] check_parents whether the parent relation should be checked.
  15578. The value is true by default and should only be set to false
  15579. during destruction of objects when the invariant does not
  15580. need to hold.
  15581. */
  15582. void assert_invariant(bool check_parents = true) const noexcept
  15583. {
  15584. JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr);
  15585. JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr);
  15586. JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr);
  15587. JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr);
  15588. #if JSON_DIAGNOSTICS
  15589. JSON_TRY
  15590. {
  15591. // cppcheck-suppress assertWithSideEffect
  15592. JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j)
  15593. {
  15594. return j.m_parent == this;
  15595. }));
  15596. }
  15597. JSON_CATCH(...) {} // LCOV_EXCL_LINE
  15598. #endif
  15599. static_cast<void>(check_parents);
  15600. }
  15601. void set_parents()
  15602. {
  15603. #if JSON_DIAGNOSTICS
  15604. switch (m_type)
  15605. {
  15606. case value_t::array:
  15607. {
  15608. for (auto& element : *m_value.array)
  15609. {
  15610. element.m_parent = this;
  15611. }
  15612. break;
  15613. }
  15614. case value_t::object:
  15615. {
  15616. for (auto& element : *m_value.object)
  15617. {
  15618. element.second.m_parent = this;
  15619. }
  15620. break;
  15621. }
  15622. case value_t::null:
  15623. case value_t::string:
  15624. case value_t::boolean:
  15625. case value_t::number_integer:
  15626. case value_t::number_unsigned:
  15627. case value_t::number_float:
  15628. case value_t::binary:
  15629. case value_t::discarded:
  15630. default:
  15631. break;
  15632. }
  15633. #endif
  15634. }
  15635. iterator set_parents(iterator it, typename iterator::difference_type count_set_parents)
  15636. {
  15637. #if JSON_DIAGNOSTICS
  15638. for (typename iterator::difference_type i = 0; i < count_set_parents; ++i)
  15639. {
  15640. (it + i)->m_parent = this;
  15641. }
  15642. #else
  15643. static_cast<void>(count_set_parents);
  15644. #endif
  15645. return it;
  15646. }
  15647. reference set_parent(reference j, std::size_t old_capacity = static_cast<std::size_t>(-1))
  15648. {
  15649. #if JSON_DIAGNOSTICS
  15650. if (old_capacity != static_cast<std::size_t>(-1))
  15651. {
  15652. // see https://github.com/nlohmann/json/issues/2838
  15653. JSON_ASSERT(type() == value_t::array);
  15654. if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity))
  15655. {
  15656. // capacity has changed: update all parents
  15657. set_parents();
  15658. return j;
  15659. }
  15660. }
  15661. // ordered_json uses a vector internally, so pointers could have
  15662. // been invalidated; see https://github.com/nlohmann/json/issues/2962
  15663. #ifdef JSON_HEDLEY_MSVC_VERSION
  15664. #pragma warning(push )
  15665. #pragma warning(disable : 4127) // ignore warning to replace if with if constexpr
  15666. #endif
  15667. if (detail::is_ordered_map<object_t>::value)
  15668. {
  15669. set_parents();
  15670. return j;
  15671. }
  15672. #ifdef JSON_HEDLEY_MSVC_VERSION
  15673. #pragma warning( pop )
  15674. #endif
  15675. j.m_parent = this;
  15676. #else
  15677. static_cast<void>(j);
  15678. static_cast<void>(old_capacity);
  15679. #endif
  15680. return j;
  15681. }
  15682. public:
  15683. //////////////////////////
  15684. // JSON parser callback //
  15685. //////////////////////////
  15686. /// @brief parser event types
  15687. /// @sa https://json.nlohmann.me/api/basic_json/parse_event_t/
  15688. using parse_event_t = detail::parse_event_t;
  15689. /// @brief per-element parser callback type
  15690. /// @sa https://json.nlohmann.me/api/basic_json/parser_callback_t/
  15691. using parser_callback_t = detail::parser_callback_t<basic_json>;
  15692. //////////////////
  15693. // constructors //
  15694. //////////////////
  15695. /// @name constructors and destructors
  15696. /// Constructors of class @ref basic_json, copy/move constructor, copy
  15697. /// assignment, static functions creating objects, and the destructor.
  15698. /// @{
  15699. /// @brief create an empty value with a given type
  15700. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  15701. basic_json(const value_t v)
  15702. : m_type(v), m_value(v)
  15703. {
  15704. assert_invariant();
  15705. }
  15706. /// @brief create a null object
  15707. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  15708. basic_json(std::nullptr_t = nullptr) noexcept
  15709. : basic_json(value_t::null)
  15710. {
  15711. assert_invariant();
  15712. }
  15713. /// @brief create a JSON value from compatible types
  15714. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  15715. template < typename CompatibleType,
  15716. typename U = detail::uncvref_t<CompatibleType>,
  15717. detail::enable_if_t <
  15718. !detail::is_basic_json<U>::value && detail::is_compatible_type<basic_json_t, U>::value, int > = 0 >
  15719. basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape)
  15720. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  15721. std::forward<CompatibleType>(val))))
  15722. {
  15723. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  15724. set_parents();
  15725. assert_invariant();
  15726. }
  15727. /// @brief create a JSON value from an existing one
  15728. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  15729. template < typename BasicJsonType,
  15730. detail::enable_if_t <
  15731. detail::is_basic_json<BasicJsonType>::value&& !std::is_same<basic_json, BasicJsonType>::value, int > = 0 >
  15732. basic_json(const BasicJsonType& val)
  15733. {
  15734. using other_boolean_t = typename BasicJsonType::boolean_t;
  15735. using other_number_float_t = typename BasicJsonType::number_float_t;
  15736. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  15737. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  15738. using other_string_t = typename BasicJsonType::string_t;
  15739. using other_object_t = typename BasicJsonType::object_t;
  15740. using other_array_t = typename BasicJsonType::array_t;
  15741. using other_binary_t = typename BasicJsonType::binary_t;
  15742. switch (val.type())
  15743. {
  15744. case value_t::boolean:
  15745. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  15746. break;
  15747. case value_t::number_float:
  15748. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  15749. break;
  15750. case value_t::number_integer:
  15751. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  15752. break;
  15753. case value_t::number_unsigned:
  15754. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  15755. break;
  15756. case value_t::string:
  15757. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  15758. break;
  15759. case value_t::object:
  15760. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  15761. break;
  15762. case value_t::array:
  15763. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  15764. break;
  15765. case value_t::binary:
  15766. JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
  15767. break;
  15768. case value_t::null:
  15769. *this = nullptr;
  15770. break;
  15771. case value_t::discarded:
  15772. m_type = value_t::discarded;
  15773. break;
  15774. default: // LCOV_EXCL_LINE
  15775. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  15776. }
  15777. set_parents();
  15778. assert_invariant();
  15779. }
  15780. /// @brief create a container (array or object) from an initializer list
  15781. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  15782. basic_json(initializer_list_t init,
  15783. bool type_deduction = true,
  15784. value_t manual_type = value_t::array)
  15785. {
  15786. // check if each element is an array with two elements whose first
  15787. // element is a string
  15788. bool is_an_object = std::all_of(init.begin(), init.end(),
  15789. [](const detail::json_ref<basic_json>& element_ref)
  15790. {
  15791. return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string();
  15792. });
  15793. // adjust type if type deduction is not wanted
  15794. if (!type_deduction)
  15795. {
  15796. // if array is wanted, do not create an object though possible
  15797. if (manual_type == value_t::array)
  15798. {
  15799. is_an_object = false;
  15800. }
  15801. // if object is wanted but impossible, throw an exception
  15802. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object))
  15803. {
  15804. JSON_THROW(type_error::create(301, "cannot create object from initializer list", basic_json()));
  15805. }
  15806. }
  15807. if (is_an_object)
  15808. {
  15809. // the initializer list is a list of pairs -> create object
  15810. m_type = value_t::object;
  15811. m_value = value_t::object;
  15812. for (auto& element_ref : init)
  15813. {
  15814. auto element = element_ref.moved_or_copied();
  15815. m_value.object->emplace(
  15816. std::move(*((*element.m_value.array)[0].m_value.string)),
  15817. std::move((*element.m_value.array)[1]));
  15818. }
  15819. }
  15820. else
  15821. {
  15822. // the initializer list describes an array -> create array
  15823. m_type = value_t::array;
  15824. m_value.array = create<array_t>(init.begin(), init.end());
  15825. }
  15826. set_parents();
  15827. assert_invariant();
  15828. }
  15829. /// @brief explicitly create a binary array (without subtype)
  15830. /// @sa https://json.nlohmann.me/api/basic_json/binary/
  15831. JSON_HEDLEY_WARN_UNUSED_RESULT
  15832. static basic_json binary(const typename binary_t::container_type& init)
  15833. {
  15834. auto res = basic_json();
  15835. res.m_type = value_t::binary;
  15836. res.m_value = init;
  15837. return res;
  15838. }
  15839. /// @brief explicitly create a binary array (with subtype)
  15840. /// @sa https://json.nlohmann.me/api/basic_json/binary/
  15841. JSON_HEDLEY_WARN_UNUSED_RESULT
  15842. static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype)
  15843. {
  15844. auto res = basic_json();
  15845. res.m_type = value_t::binary;
  15846. res.m_value = binary_t(init, subtype);
  15847. return res;
  15848. }
  15849. /// @brief explicitly create a binary array
  15850. /// @sa https://json.nlohmann.me/api/basic_json/binary/
  15851. JSON_HEDLEY_WARN_UNUSED_RESULT
  15852. static basic_json binary(typename binary_t::container_type&& init)
  15853. {
  15854. auto res = basic_json();
  15855. res.m_type = value_t::binary;
  15856. res.m_value = std::move(init);
  15857. return res;
  15858. }
  15859. /// @brief explicitly create a binary array (with subtype)
  15860. /// @sa https://json.nlohmann.me/api/basic_json/binary/
  15861. JSON_HEDLEY_WARN_UNUSED_RESULT
  15862. static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype)
  15863. {
  15864. auto res = basic_json();
  15865. res.m_type = value_t::binary;
  15866. res.m_value = binary_t(std::move(init), subtype);
  15867. return res;
  15868. }
  15869. /// @brief explicitly create an array from an initializer list
  15870. /// @sa https://json.nlohmann.me/api/basic_json/array/
  15871. JSON_HEDLEY_WARN_UNUSED_RESULT
  15872. static basic_json array(initializer_list_t init = {})
  15873. {
  15874. return basic_json(init, false, value_t::array);
  15875. }
  15876. /// @brief explicitly create an object from an initializer list
  15877. /// @sa https://json.nlohmann.me/api/basic_json/object/
  15878. JSON_HEDLEY_WARN_UNUSED_RESULT
  15879. static basic_json object(initializer_list_t init = {})
  15880. {
  15881. return basic_json(init, false, value_t::object);
  15882. }
  15883. /// @brief construct an array with count copies of given value
  15884. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  15885. basic_json(size_type cnt, const basic_json& val)
  15886. : m_type(value_t::array)
  15887. {
  15888. m_value.array = create<array_t>(cnt, val);
  15889. set_parents();
  15890. assert_invariant();
  15891. }
  15892. /// @brief construct a JSON container given an iterator range
  15893. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  15894. template < class InputIT, typename std::enable_if <
  15895. std::is_same<InputIT, typename basic_json_t::iterator>::value ||
  15896. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int >::type = 0 >
  15897. basic_json(InputIT first, InputIT last)
  15898. {
  15899. JSON_ASSERT(first.m_object != nullptr);
  15900. JSON_ASSERT(last.m_object != nullptr);
  15901. // make sure iterator fits the current value
  15902. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  15903. {
  15904. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", basic_json()));
  15905. }
  15906. // copy type from first iterator
  15907. m_type = first.m_object->m_type;
  15908. // check if iterator range is complete for primitive values
  15909. switch (m_type)
  15910. {
  15911. case value_t::boolean:
  15912. case value_t::number_float:
  15913. case value_t::number_integer:
  15914. case value_t::number_unsigned:
  15915. case value_t::string:
  15916. {
  15917. if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin()
  15918. || !last.m_it.primitive_iterator.is_end()))
  15919. {
  15920. JSON_THROW(invalid_iterator::create(204, "iterators out of range", *first.m_object));
  15921. }
  15922. break;
  15923. }
  15924. case value_t::null:
  15925. case value_t::object:
  15926. case value_t::array:
  15927. case value_t::binary:
  15928. case value_t::discarded:
  15929. default:
  15930. break;
  15931. }
  15932. switch (m_type)
  15933. {
  15934. case value_t::number_integer:
  15935. {
  15936. m_value.number_integer = first.m_object->m_value.number_integer;
  15937. break;
  15938. }
  15939. case value_t::number_unsigned:
  15940. {
  15941. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  15942. break;
  15943. }
  15944. case value_t::number_float:
  15945. {
  15946. m_value.number_float = first.m_object->m_value.number_float;
  15947. break;
  15948. }
  15949. case value_t::boolean:
  15950. {
  15951. m_value.boolean = first.m_object->m_value.boolean;
  15952. break;
  15953. }
  15954. case value_t::string:
  15955. {
  15956. m_value = *first.m_object->m_value.string;
  15957. break;
  15958. }
  15959. case value_t::object:
  15960. {
  15961. m_value.object = create<object_t>(first.m_it.object_iterator,
  15962. last.m_it.object_iterator);
  15963. break;
  15964. }
  15965. case value_t::array:
  15966. {
  15967. m_value.array = create<array_t>(first.m_it.array_iterator,
  15968. last.m_it.array_iterator);
  15969. break;
  15970. }
  15971. case value_t::binary:
  15972. {
  15973. m_value = *first.m_object->m_value.binary;
  15974. break;
  15975. }
  15976. case value_t::null:
  15977. case value_t::discarded:
  15978. default:
  15979. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()), *first.m_object));
  15980. }
  15981. set_parents();
  15982. assert_invariant();
  15983. }
  15984. ///////////////////////////////////////
  15985. // other constructors and destructor //
  15986. ///////////////////////////////////////
  15987. template<typename JsonRef,
  15988. detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
  15989. std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
  15990. basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
  15991. /// @brief copy constructor
  15992. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  15993. basic_json(const basic_json& other)
  15994. : m_type(other.m_type)
  15995. {
  15996. // check of passed value is valid
  15997. other.assert_invariant();
  15998. switch (m_type)
  15999. {
  16000. case value_t::object:
  16001. {
  16002. m_value = *other.m_value.object;
  16003. break;
  16004. }
  16005. case value_t::array:
  16006. {
  16007. m_value = *other.m_value.array;
  16008. break;
  16009. }
  16010. case value_t::string:
  16011. {
  16012. m_value = *other.m_value.string;
  16013. break;
  16014. }
  16015. case value_t::boolean:
  16016. {
  16017. m_value = other.m_value.boolean;
  16018. break;
  16019. }
  16020. case value_t::number_integer:
  16021. {
  16022. m_value = other.m_value.number_integer;
  16023. break;
  16024. }
  16025. case value_t::number_unsigned:
  16026. {
  16027. m_value = other.m_value.number_unsigned;
  16028. break;
  16029. }
  16030. case value_t::number_float:
  16031. {
  16032. m_value = other.m_value.number_float;
  16033. break;
  16034. }
  16035. case value_t::binary:
  16036. {
  16037. m_value = *other.m_value.binary;
  16038. break;
  16039. }
  16040. case value_t::null:
  16041. case value_t::discarded:
  16042. default:
  16043. break;
  16044. }
  16045. set_parents();
  16046. assert_invariant();
  16047. }
  16048. /// @brief move constructor
  16049. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  16050. basic_json(basic_json&& other) noexcept
  16051. : m_type(std::move(other.m_type)),
  16052. m_value(std::move(other.m_value))
  16053. {
  16054. // check that passed value is valid
  16055. other.assert_invariant(false);
  16056. // invalidate payload
  16057. other.m_type = value_t::null;
  16058. other.m_value = {};
  16059. set_parents();
  16060. assert_invariant();
  16061. }
  16062. /// @brief copy assignment
  16063. /// @sa https://json.nlohmann.me/api/basic_json/operator=/
  16064. basic_json& operator=(basic_json other) noexcept (
  16065. std::is_nothrow_move_constructible<value_t>::value&&
  16066. std::is_nothrow_move_assignable<value_t>::value&&
  16067. std::is_nothrow_move_constructible<json_value>::value&&
  16068. std::is_nothrow_move_assignable<json_value>::value
  16069. )
  16070. {
  16071. // check that passed value is valid
  16072. other.assert_invariant();
  16073. using std::swap;
  16074. swap(m_type, other.m_type);
  16075. swap(m_value, other.m_value);
  16076. set_parents();
  16077. assert_invariant();
  16078. return *this;
  16079. }
  16080. /// @brief destructor
  16081. /// @sa https://json.nlohmann.me/api/basic_json/~basic_json/
  16082. ~basic_json() noexcept
  16083. {
  16084. assert_invariant(false);
  16085. m_value.destroy(m_type);
  16086. }
  16087. /// @}
  16088. public:
  16089. ///////////////////////
  16090. // object inspection //
  16091. ///////////////////////
  16092. /// @name object inspection
  16093. /// Functions to inspect the type of a JSON value.
  16094. /// @{
  16095. /// @brief serialization
  16096. /// @sa https://json.nlohmann.me/api/basic_json/dump/
  16097. string_t dump(const int indent = -1,
  16098. const char indent_char = ' ',
  16099. const bool ensure_ascii = false,
  16100. const error_handler_t error_handler = error_handler_t::strict) const
  16101. {
  16102. string_t result;
  16103. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  16104. if (indent >= 0)
  16105. {
  16106. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  16107. }
  16108. else
  16109. {
  16110. s.dump(*this, false, ensure_ascii, 0);
  16111. }
  16112. return result;
  16113. }
  16114. /// @brief return the type of the JSON value (explicit)
  16115. /// @sa https://json.nlohmann.me/api/basic_json/type/
  16116. constexpr value_t type() const noexcept
  16117. {
  16118. return m_type;
  16119. }
  16120. /// @brief return whether type is primitive
  16121. /// @sa https://json.nlohmann.me/api/basic_json/is_primitive/
  16122. constexpr bool is_primitive() const noexcept
  16123. {
  16124. return is_null() || is_string() || is_boolean() || is_number() || is_binary();
  16125. }
  16126. /// @brief return whether type is structured
  16127. /// @sa https://json.nlohmann.me/api/basic_json/is_structured/
  16128. constexpr bool is_structured() const noexcept
  16129. {
  16130. return is_array() || is_object();
  16131. }
  16132. /// @brief return whether value is null
  16133. /// @sa https://json.nlohmann.me/api/basic_json/is_null/
  16134. constexpr bool is_null() const noexcept
  16135. {
  16136. return m_type == value_t::null;
  16137. }
  16138. /// @brief return whether value is a boolean
  16139. /// @sa https://json.nlohmann.me/api/basic_json/is_boolean/
  16140. constexpr bool is_boolean() const noexcept
  16141. {
  16142. return m_type == value_t::boolean;
  16143. }
  16144. /// @brief return whether value is a number
  16145. /// @sa https://json.nlohmann.me/api/basic_json/is_number/
  16146. constexpr bool is_number() const noexcept
  16147. {
  16148. return is_number_integer() || is_number_float();
  16149. }
  16150. /// @brief return whether value is an integer number
  16151. /// @sa https://json.nlohmann.me/api/basic_json/is_number_integer/
  16152. constexpr bool is_number_integer() const noexcept
  16153. {
  16154. return m_type == value_t::number_integer || m_type == value_t::number_unsigned;
  16155. }
  16156. /// @brief return whether value is an unsigned integer number
  16157. /// @sa https://json.nlohmann.me/api/basic_json/is_number_unsigned/
  16158. constexpr bool is_number_unsigned() const noexcept
  16159. {
  16160. return m_type == value_t::number_unsigned;
  16161. }
  16162. /// @brief return whether value is a floating-point number
  16163. /// @sa https://json.nlohmann.me/api/basic_json/is_number_float/
  16164. constexpr bool is_number_float() const noexcept
  16165. {
  16166. return m_type == value_t::number_float;
  16167. }
  16168. /// @brief return whether value is an object
  16169. /// @sa https://json.nlohmann.me/api/basic_json/is_object/
  16170. constexpr bool is_object() const noexcept
  16171. {
  16172. return m_type == value_t::object;
  16173. }
  16174. /// @brief return whether value is an array
  16175. /// @sa https://json.nlohmann.me/api/basic_json/is_array/
  16176. constexpr bool is_array() const noexcept
  16177. {
  16178. return m_type == value_t::array;
  16179. }
  16180. /// @brief return whether value is a string
  16181. /// @sa https://json.nlohmann.me/api/basic_json/is_string/
  16182. constexpr bool is_string() const noexcept
  16183. {
  16184. return m_type == value_t::string;
  16185. }
  16186. /// @brief return whether value is a binary array
  16187. /// @sa https://json.nlohmann.me/api/basic_json/is_binary/
  16188. constexpr bool is_binary() const noexcept
  16189. {
  16190. return m_type == value_t::binary;
  16191. }
  16192. /// @brief return whether value is discarded
  16193. /// @sa https://json.nlohmann.me/api/basic_json/is_discarded/
  16194. constexpr bool is_discarded() const noexcept
  16195. {
  16196. return m_type == value_t::discarded;
  16197. }
  16198. /// @brief return the type of the JSON value (implicit)
  16199. /// @sa https://json.nlohmann.me/api/basic_json/operator_value_t/
  16200. constexpr operator value_t() const noexcept
  16201. {
  16202. return m_type;
  16203. }
  16204. /// @}
  16205. private:
  16206. //////////////////
  16207. // value access //
  16208. //////////////////
  16209. /// get a boolean (explicit)
  16210. boolean_t get_impl(boolean_t* /*unused*/) const
  16211. {
  16212. if (JSON_HEDLEY_LIKELY(is_boolean()))
  16213. {
  16214. return m_value.boolean;
  16215. }
  16216. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()), *this));
  16217. }
  16218. /// get a pointer to the value (object)
  16219. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  16220. {
  16221. return is_object() ? m_value.object : nullptr;
  16222. }
  16223. /// get a pointer to the value (object)
  16224. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  16225. {
  16226. return is_object() ? m_value.object : nullptr;
  16227. }
  16228. /// get a pointer to the value (array)
  16229. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  16230. {
  16231. return is_array() ? m_value.array : nullptr;
  16232. }
  16233. /// get a pointer to the value (array)
  16234. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  16235. {
  16236. return is_array() ? m_value.array : nullptr;
  16237. }
  16238. /// get a pointer to the value (string)
  16239. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  16240. {
  16241. return is_string() ? m_value.string : nullptr;
  16242. }
  16243. /// get a pointer to the value (string)
  16244. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  16245. {
  16246. return is_string() ? m_value.string : nullptr;
  16247. }
  16248. /// get a pointer to the value (boolean)
  16249. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  16250. {
  16251. return is_boolean() ? &m_value.boolean : nullptr;
  16252. }
  16253. /// get a pointer to the value (boolean)
  16254. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  16255. {
  16256. return is_boolean() ? &m_value.boolean : nullptr;
  16257. }
  16258. /// get a pointer to the value (integer number)
  16259. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  16260. {
  16261. return is_number_integer() ? &m_value.number_integer : nullptr;
  16262. }
  16263. /// get a pointer to the value (integer number)
  16264. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  16265. {
  16266. return is_number_integer() ? &m_value.number_integer : nullptr;
  16267. }
  16268. /// get a pointer to the value (unsigned number)
  16269. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  16270. {
  16271. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  16272. }
  16273. /// get a pointer to the value (unsigned number)
  16274. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  16275. {
  16276. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  16277. }
  16278. /// get a pointer to the value (floating-point number)
  16279. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  16280. {
  16281. return is_number_float() ? &m_value.number_float : nullptr;
  16282. }
  16283. /// get a pointer to the value (floating-point number)
  16284. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  16285. {
  16286. return is_number_float() ? &m_value.number_float : nullptr;
  16287. }
  16288. /// get a pointer to the value (binary)
  16289. binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
  16290. {
  16291. return is_binary() ? m_value.binary : nullptr;
  16292. }
  16293. /// get a pointer to the value (binary)
  16294. constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
  16295. {
  16296. return is_binary() ? m_value.binary : nullptr;
  16297. }
  16298. /*!
  16299. @brief helper function to implement get_ref()
  16300. This function helps to implement get_ref() without code duplication for
  16301. const and non-const overloads
  16302. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  16303. @throw type_error.303 if ReferenceType does not match underlying value
  16304. type of the current JSON
  16305. */
  16306. template<typename ReferenceType, typename ThisType>
  16307. static ReferenceType get_ref_impl(ThisType& obj)
  16308. {
  16309. // delegate the call to get_ptr<>()
  16310. auto* ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  16311. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  16312. {
  16313. return *ptr;
  16314. }
  16315. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()), obj));
  16316. }
  16317. public:
  16318. /// @name value access
  16319. /// Direct access to the stored value of a JSON value.
  16320. /// @{
  16321. /// @brief get a pointer value (implicit)
  16322. /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/
  16323. template<typename PointerType, typename std::enable_if<
  16324. std::is_pointer<PointerType>::value, int>::type = 0>
  16325. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  16326. {
  16327. // delegate the call to get_impl_ptr<>()
  16328. return get_impl_ptr(static_cast<PointerType>(nullptr));
  16329. }
  16330. /// @brief get a pointer value (implicit)
  16331. /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/
  16332. template < typename PointerType, typename std::enable_if <
  16333. std::is_pointer<PointerType>::value&&
  16334. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int >::type = 0 >
  16335. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  16336. {
  16337. // delegate the call to get_impl_ptr<>() const
  16338. return get_impl_ptr(static_cast<PointerType>(nullptr));
  16339. }
  16340. private:
  16341. /*!
  16342. @brief get a value (explicit)
  16343. Explicit type conversion between the JSON value and a compatible value
  16344. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  16345. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  16346. The value is converted by calling the @ref json_serializer<ValueType>
  16347. `from_json()` method.
  16348. The function is equivalent to executing
  16349. @code {.cpp}
  16350. ValueType ret;
  16351. JSONSerializer<ValueType>::from_json(*this, ret);
  16352. return ret;
  16353. @endcode
  16354. This overloads is chosen if:
  16355. - @a ValueType is not @ref basic_json,
  16356. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  16357. `void from_json(const basic_json&, ValueType&)`, and
  16358. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  16359. the form `ValueType from_json(const basic_json&)`
  16360. @tparam ValueType the returned value type
  16361. @return copy of the JSON value, converted to @a ValueType
  16362. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  16363. @liveexample{The example below shows several conversions from JSON values
  16364. to other types. There a few things to note: (1) Floating-point numbers can
  16365. be converted to integers\, (2) A JSON array can be converted to a standard
  16366. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16367. associative containers such as `std::unordered_map<std::string\,
  16368. json>`.,get__ValueType_const}
  16369. @since version 2.1.0
  16370. */
  16371. template < typename ValueType,
  16372. detail::enable_if_t <
  16373. detail::is_default_constructible<ValueType>::value&&
  16374. detail::has_from_json<basic_json_t, ValueType>::value,
  16375. int > = 0 >
  16376. ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept(
  16377. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  16378. {
  16379. auto ret = ValueType();
  16380. JSONSerializer<ValueType>::from_json(*this, ret);
  16381. return ret;
  16382. }
  16383. /*!
  16384. @brief get a value (explicit); special case
  16385. Explicit type conversion between the JSON value and a compatible value
  16386. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  16387. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  16388. The value is converted by calling the @ref json_serializer<ValueType>
  16389. `from_json()` method.
  16390. The function is equivalent to executing
  16391. @code {.cpp}
  16392. return JSONSerializer<ValueType>::from_json(*this);
  16393. @endcode
  16394. This overloads is chosen if:
  16395. - @a ValueType is not @ref basic_json and
  16396. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  16397. `ValueType from_json(const basic_json&)`
  16398. @note If @ref json_serializer<ValueType> has both overloads of
  16399. `from_json()`, this one is chosen.
  16400. @tparam ValueType the returned value type
  16401. @return copy of the JSON value, converted to @a ValueType
  16402. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  16403. @since version 2.1.0
  16404. */
  16405. template < typename ValueType,
  16406. detail::enable_if_t <
  16407. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  16408. int > = 0 >
  16409. ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept(
  16410. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  16411. {
  16412. return JSONSerializer<ValueType>::from_json(*this);
  16413. }
  16414. /*!
  16415. @brief get special-case overload
  16416. This overloads converts the current @ref basic_json in a different
  16417. @ref basic_json type
  16418. @tparam BasicJsonType == @ref basic_json
  16419. @return a copy of *this, converted into @a BasicJsonType
  16420. @complexity Depending on the implementation of the called `from_json()`
  16421. method.
  16422. @since version 3.2.0
  16423. */
  16424. template < typename BasicJsonType,
  16425. detail::enable_if_t <
  16426. detail::is_basic_json<BasicJsonType>::value,
  16427. int > = 0 >
  16428. BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const
  16429. {
  16430. return *this;
  16431. }
  16432. /*!
  16433. @brief get special-case overload
  16434. This overloads avoids a lot of template boilerplate, it can be seen as the
  16435. identity method
  16436. @tparam BasicJsonType == @ref basic_json
  16437. @return a copy of *this
  16438. @complexity Constant.
  16439. @since version 2.1.0
  16440. */
  16441. template<typename BasicJsonType,
  16442. detail::enable_if_t<
  16443. std::is_same<BasicJsonType, basic_json_t>::value,
  16444. int> = 0>
  16445. basic_json get_impl(detail::priority_tag<3> /*unused*/) const
  16446. {
  16447. return *this;
  16448. }
  16449. /*!
  16450. @brief get a pointer value (explicit)
  16451. @copydoc get()
  16452. */
  16453. template<typename PointerType,
  16454. detail::enable_if_t<
  16455. std::is_pointer<PointerType>::value,
  16456. int> = 0>
  16457. constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept
  16458. -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  16459. {
  16460. // delegate the call to get_ptr
  16461. return get_ptr<PointerType>();
  16462. }
  16463. public:
  16464. /*!
  16465. @brief get a (pointer) value (explicit)
  16466. Performs explicit type conversion between the JSON value and a compatible value if required.
  16467. - If the requested type is a pointer to the internally stored JSON value that pointer is returned.
  16468. No copies are made.
  16469. - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible
  16470. from the current @ref basic_json.
  16471. - Otherwise the value is converted by calling the @ref json_serializer<ValueType> `from_json()`
  16472. method.
  16473. @tparam ValueTypeCV the provided value type
  16474. @tparam ValueType the returned value type
  16475. @return copy of the JSON value, converted to @tparam ValueType if necessary
  16476. @throw what @ref json_serializer<ValueType> `from_json()` method throws if conversion is required
  16477. @since version 2.1.0
  16478. */
  16479. template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>>
  16480. #if defined(JSON_HAS_CPP_14)
  16481. constexpr
  16482. #endif
  16483. auto get() const noexcept(
  16484. noexcept(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {})))
  16485. -> decltype(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {}))
  16486. {
  16487. // we cannot static_assert on ValueTypeCV being non-const, because
  16488. // there is support for get<const basic_json_t>(), which is why we
  16489. // still need the uncvref
  16490. static_assert(!std::is_reference<ValueTypeCV>::value,
  16491. "get() cannot be used with reference types, you might want to use get_ref()");
  16492. return get_impl<ValueType>(detail::priority_tag<4> {});
  16493. }
  16494. /*!
  16495. @brief get a pointer value (explicit)
  16496. Explicit pointer access to the internally stored JSON value. No copies are
  16497. made.
  16498. @warning The pointer becomes invalid if the underlying JSON object
  16499. changes.
  16500. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  16501. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  16502. @ref number_unsigned_t, or @ref number_float_t.
  16503. @return pointer to the internally stored JSON value if the requested
  16504. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  16505. @complexity Constant.
  16506. @liveexample{The example below shows how pointers to internal values of a
  16507. JSON value can be requested. Note that no type conversions are made and a
  16508. `nullptr` is returned if the value and the requested pointer type does not
  16509. match.,get__PointerType}
  16510. @sa see @ref get_ptr() for explicit pointer-member access
  16511. @since version 1.0.0
  16512. */
  16513. template<typename PointerType, typename std::enable_if<
  16514. std::is_pointer<PointerType>::value, int>::type = 0>
  16515. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  16516. {
  16517. // delegate the call to get_ptr
  16518. return get_ptr<PointerType>();
  16519. }
  16520. /// @brief get a value (explicit)
  16521. /// @sa https://json.nlohmann.me/api/basic_json/get_to/
  16522. template < typename ValueType,
  16523. detail::enable_if_t <
  16524. !detail::is_basic_json<ValueType>::value&&
  16525. detail::has_from_json<basic_json_t, ValueType>::value,
  16526. int > = 0 >
  16527. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  16528. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  16529. {
  16530. JSONSerializer<ValueType>::from_json(*this, v);
  16531. return v;
  16532. }
  16533. // specialization to allow calling get_to with a basic_json value
  16534. // see https://github.com/nlohmann/json/issues/2175
  16535. template<typename ValueType,
  16536. detail::enable_if_t <
  16537. detail::is_basic_json<ValueType>::value,
  16538. int> = 0>
  16539. ValueType & get_to(ValueType& v) const
  16540. {
  16541. v = *this;
  16542. return v;
  16543. }
  16544. template <
  16545. typename T, std::size_t N,
  16546. typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  16547. detail::enable_if_t <
  16548. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  16549. Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  16550. noexcept(noexcept(JSONSerializer<Array>::from_json(
  16551. std::declval<const basic_json_t&>(), v)))
  16552. {
  16553. JSONSerializer<Array>::from_json(*this, v);
  16554. return v;
  16555. }
  16556. /// @brief get a reference value (implicit)
  16557. /// @sa https://json.nlohmann.me/api/basic_json/get_ref/
  16558. template<typename ReferenceType, typename std::enable_if<
  16559. std::is_reference<ReferenceType>::value, int>::type = 0>
  16560. ReferenceType get_ref()
  16561. {
  16562. // delegate call to get_ref_impl
  16563. return get_ref_impl<ReferenceType>(*this);
  16564. }
  16565. /// @brief get a reference value (implicit)
  16566. /// @sa https://json.nlohmann.me/api/basic_json/get_ref/
  16567. template < typename ReferenceType, typename std::enable_if <
  16568. std::is_reference<ReferenceType>::value&&
  16569. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int >::type = 0 >
  16570. ReferenceType get_ref() const
  16571. {
  16572. // delegate call to get_ref_impl
  16573. return get_ref_impl<ReferenceType>(*this);
  16574. }
  16575. /*!
  16576. @brief get a value (implicit)
  16577. Implicit type conversion between the JSON value and a compatible value.
  16578. The call is realized by calling @ref get() const.
  16579. @tparam ValueType non-pointer type compatible to the JSON value, for
  16580. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  16581. `std::vector` types for JSON arrays. The character type of @ref string_t
  16582. as well as an initializer list of this type is excluded to avoid
  16583. ambiguities as these types implicitly convert to `std::string`.
  16584. @return copy of the JSON value, converted to type @a ValueType
  16585. @throw type_error.302 in case passed type @a ValueType is incompatible
  16586. to the JSON value type (e.g., the JSON value is of type boolean, but a
  16587. string is requested); see example below
  16588. @complexity Linear in the size of the JSON value.
  16589. @liveexample{The example below shows several conversions from JSON values
  16590. to other types. There a few things to note: (1) Floating-point numbers can
  16591. be converted to integers\, (2) A JSON array can be converted to a standard
  16592. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16593. associative containers such as `std::unordered_map<std::string\,
  16594. json>`.,operator__ValueType}
  16595. @since version 1.0.0
  16596. */
  16597. template < typename ValueType, typename std::enable_if <
  16598. detail::conjunction <
  16599. detail::negation<std::is_pointer<ValueType>>,
  16600. detail::negation<std::is_same<ValueType, detail::json_ref<basic_json>>>,
  16601. detail::negation<std::is_same<ValueType, typename string_t::value_type>>,
  16602. detail::negation<detail::is_basic_json<ValueType>>,
  16603. detail::negation<std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>>,
  16604. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914))
  16605. detail::negation<std::is_same<ValueType, std::string_view>>,
  16606. #endif
  16607. detail::is_detected_lazy<detail::get_template_function, const basic_json_t&, ValueType>
  16608. >::value, int >::type = 0 >
  16609. JSON_EXPLICIT operator ValueType() const
  16610. {
  16611. // delegate the call to get<>() const
  16612. return get<ValueType>();
  16613. }
  16614. /// @brief get a binary value
  16615. /// @sa https://json.nlohmann.me/api/basic_json/get_binary/
  16616. binary_t& get_binary()
  16617. {
  16618. if (!is_binary())
  16619. {
  16620. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this));
  16621. }
  16622. return *get_ptr<binary_t*>();
  16623. }
  16624. /// @brief get a binary value
  16625. /// @sa https://json.nlohmann.me/api/basic_json/get_binary/
  16626. const binary_t& get_binary() const
  16627. {
  16628. if (!is_binary())
  16629. {
  16630. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this));
  16631. }
  16632. return *get_ptr<const binary_t*>();
  16633. }
  16634. /// @}
  16635. ////////////////////
  16636. // element access //
  16637. ////////////////////
  16638. /// @name element access
  16639. /// Access to the JSON value.
  16640. /// @{
  16641. /// @brief access specified array element with bounds checking
  16642. /// @sa https://json.nlohmann.me/api/basic_json/at/
  16643. reference at(size_type idx)
  16644. {
  16645. // at only works for arrays
  16646. if (JSON_HEDLEY_LIKELY(is_array()))
  16647. {
  16648. JSON_TRY
  16649. {
  16650. return set_parent(m_value.array->at(idx));
  16651. }
  16652. JSON_CATCH (std::out_of_range&)
  16653. {
  16654. // create better exception explanation
  16655. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
  16656. }
  16657. }
  16658. else
  16659. {
  16660. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  16661. }
  16662. }
  16663. /// @brief access specified array element with bounds checking
  16664. /// @sa https://json.nlohmann.me/api/basic_json/at/
  16665. const_reference at(size_type idx) const
  16666. {
  16667. // at only works for arrays
  16668. if (JSON_HEDLEY_LIKELY(is_array()))
  16669. {
  16670. JSON_TRY
  16671. {
  16672. return m_value.array->at(idx);
  16673. }
  16674. JSON_CATCH (std::out_of_range&)
  16675. {
  16676. // create better exception explanation
  16677. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
  16678. }
  16679. }
  16680. else
  16681. {
  16682. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  16683. }
  16684. }
  16685. /// @brief access specified object element with bounds checking
  16686. /// @sa https://json.nlohmann.me/api/basic_json/at/
  16687. reference at(const typename object_t::key_type& key)
  16688. {
  16689. // at only works for objects
  16690. if (JSON_HEDLEY_LIKELY(is_object()))
  16691. {
  16692. JSON_TRY
  16693. {
  16694. return set_parent(m_value.object->at(key));
  16695. }
  16696. JSON_CATCH (std::out_of_range&)
  16697. {
  16698. // create better exception explanation
  16699. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this));
  16700. }
  16701. }
  16702. else
  16703. {
  16704. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  16705. }
  16706. }
  16707. /// @brief access specified object element with bounds checking
  16708. /// @sa https://json.nlohmann.me/api/basic_json/at/
  16709. const_reference at(const typename object_t::key_type& key) const
  16710. {
  16711. // at only works for objects
  16712. if (JSON_HEDLEY_LIKELY(is_object()))
  16713. {
  16714. JSON_TRY
  16715. {
  16716. return m_value.object->at(key);
  16717. }
  16718. JSON_CATCH (std::out_of_range&)
  16719. {
  16720. // create better exception explanation
  16721. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this));
  16722. }
  16723. }
  16724. else
  16725. {
  16726. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  16727. }
  16728. }
  16729. /// @brief access specified array element
  16730. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  16731. reference operator[](size_type idx)
  16732. {
  16733. // implicitly convert null value to an empty array
  16734. if (is_null())
  16735. {
  16736. m_type = value_t::array;
  16737. m_value.array = create<array_t>();
  16738. assert_invariant();
  16739. }
  16740. // operator[] only works for arrays
  16741. if (JSON_HEDLEY_LIKELY(is_array()))
  16742. {
  16743. // fill up array with null values if given idx is outside range
  16744. if (idx >= m_value.array->size())
  16745. {
  16746. #if JSON_DIAGNOSTICS
  16747. // remember array size & capacity before resizing
  16748. const auto old_size = m_value.array->size();
  16749. const auto old_capacity = m_value.array->capacity();
  16750. #endif
  16751. m_value.array->resize(idx + 1);
  16752. #if JSON_DIAGNOSTICS
  16753. if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity))
  16754. {
  16755. // capacity has changed: update all parents
  16756. set_parents();
  16757. }
  16758. else
  16759. {
  16760. // set parent for values added above
  16761. set_parents(begin() + static_cast<typename iterator::difference_type>(old_size), static_cast<typename iterator::difference_type>(idx + 1 - old_size));
  16762. }
  16763. #endif
  16764. assert_invariant();
  16765. }
  16766. return m_value.array->operator[](idx);
  16767. }
  16768. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this));
  16769. }
  16770. /// @brief access specified array element
  16771. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  16772. const_reference operator[](size_type idx) const
  16773. {
  16774. // const operator[] only works for arrays
  16775. if (JSON_HEDLEY_LIKELY(is_array()))
  16776. {
  16777. return m_value.array->operator[](idx);
  16778. }
  16779. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this));
  16780. }
  16781. /// @brief access specified object element
  16782. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  16783. reference operator[](const typename object_t::key_type& key)
  16784. {
  16785. // implicitly convert null value to an empty object
  16786. if (is_null())
  16787. {
  16788. m_type = value_t::object;
  16789. m_value.object = create<object_t>();
  16790. assert_invariant();
  16791. }
  16792. // operator[] only works for objects
  16793. if (JSON_HEDLEY_LIKELY(is_object()))
  16794. {
  16795. return set_parent(m_value.object->operator[](key));
  16796. }
  16797. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  16798. }
  16799. /// @brief access specified object element
  16800. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  16801. const_reference operator[](const typename object_t::key_type& key) const
  16802. {
  16803. // const operator[] only works for objects
  16804. if (JSON_HEDLEY_LIKELY(is_object()))
  16805. {
  16806. JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
  16807. return m_value.object->find(key)->second;
  16808. }
  16809. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  16810. }
  16811. /// @brief access specified object element
  16812. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  16813. template<typename T>
  16814. JSON_HEDLEY_NON_NULL(2)
  16815. reference operator[](T* key)
  16816. {
  16817. // implicitly convert null to object
  16818. if (is_null())
  16819. {
  16820. m_type = value_t::object;
  16821. m_value = value_t::object;
  16822. assert_invariant();
  16823. }
  16824. // at only works for objects
  16825. if (JSON_HEDLEY_LIKELY(is_object()))
  16826. {
  16827. return set_parent(m_value.object->operator[](key));
  16828. }
  16829. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  16830. }
  16831. /// @brief access specified object element
  16832. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  16833. template<typename T>
  16834. JSON_HEDLEY_NON_NULL(2)
  16835. const_reference operator[](T* key) const
  16836. {
  16837. // at only works for objects
  16838. if (JSON_HEDLEY_LIKELY(is_object()))
  16839. {
  16840. JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
  16841. return m_value.object->find(key)->second;
  16842. }
  16843. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  16844. }
  16845. /// @brief access specified object element with default value
  16846. /// @sa https://json.nlohmann.me/api/basic_json/value/
  16847. /// using std::is_convertible in a std::enable_if will fail when using explicit conversions
  16848. template < class ValueType, typename std::enable_if <
  16849. detail::is_getable<basic_json_t, ValueType>::value
  16850. && !std::is_same<value_t, ValueType>::value, int >::type = 0 >
  16851. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  16852. {
  16853. // at only works for objects
  16854. if (JSON_HEDLEY_LIKELY(is_object()))
  16855. {
  16856. // if key is found, return value and given default value otherwise
  16857. const auto it = find(key);
  16858. if (it != end())
  16859. {
  16860. return it->template get<ValueType>();
  16861. }
  16862. return default_value;
  16863. }
  16864. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this));
  16865. }
  16866. /// @brief access specified object element with default value
  16867. /// @sa https://json.nlohmann.me/api/basic_json/value/
  16868. /// overload for a default value of type const char*
  16869. string_t value(const typename object_t::key_type& key, const char* default_value) const
  16870. {
  16871. return value(key, string_t(default_value));
  16872. }
  16873. /// @brief access specified object element via JSON Pointer with default value
  16874. /// @sa https://json.nlohmann.me/api/basic_json/value/
  16875. template<class ValueType, typename std::enable_if<
  16876. detail::is_getable<basic_json_t, ValueType>::value, int>::type = 0>
  16877. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  16878. {
  16879. // at only works for objects
  16880. if (JSON_HEDLEY_LIKELY(is_object()))
  16881. {
  16882. // if pointer resolves a value, return it or use default value
  16883. JSON_TRY
  16884. {
  16885. return ptr.get_checked(this).template get<ValueType>();
  16886. }
  16887. JSON_INTERNAL_CATCH (out_of_range&)
  16888. {
  16889. return default_value;
  16890. }
  16891. }
  16892. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this));
  16893. }
  16894. /// @brief access specified object element via JSON Pointer with default value
  16895. /// @sa https://json.nlohmann.me/api/basic_json/value/
  16896. /// overload for a default value of type const char*
  16897. JSON_HEDLEY_NON_NULL(3)
  16898. string_t value(const json_pointer& ptr, const char* default_value) const
  16899. {
  16900. return value(ptr, string_t(default_value));
  16901. }
  16902. /// @brief access the first element
  16903. /// @sa https://json.nlohmann.me/api/basic_json/front/
  16904. reference front()
  16905. {
  16906. return *begin();
  16907. }
  16908. /// @brief access the first element
  16909. /// @sa https://json.nlohmann.me/api/basic_json/front/
  16910. const_reference front() const
  16911. {
  16912. return *cbegin();
  16913. }
  16914. /// @brief access the last element
  16915. /// @sa https://json.nlohmann.me/api/basic_json/back/
  16916. reference back()
  16917. {
  16918. auto tmp = end();
  16919. --tmp;
  16920. return *tmp;
  16921. }
  16922. /// @brief access the last element
  16923. /// @sa https://json.nlohmann.me/api/basic_json/back/
  16924. const_reference back() const
  16925. {
  16926. auto tmp = cend();
  16927. --tmp;
  16928. return *tmp;
  16929. }
  16930. /// @brief remove element given an iterator
  16931. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  16932. template < class IteratorType, typename std::enable_if <
  16933. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  16934. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
  16935. = 0 >
  16936. IteratorType erase(IteratorType pos)
  16937. {
  16938. // make sure iterator fits the current value
  16939. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  16940. {
  16941. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  16942. }
  16943. IteratorType result = end();
  16944. switch (m_type)
  16945. {
  16946. case value_t::boolean:
  16947. case value_t::number_float:
  16948. case value_t::number_integer:
  16949. case value_t::number_unsigned:
  16950. case value_t::string:
  16951. case value_t::binary:
  16952. {
  16953. if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin()))
  16954. {
  16955. JSON_THROW(invalid_iterator::create(205, "iterator out of range", *this));
  16956. }
  16957. if (is_string())
  16958. {
  16959. AllocatorType<string_t> alloc;
  16960. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  16961. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  16962. m_value.string = nullptr;
  16963. }
  16964. else if (is_binary())
  16965. {
  16966. AllocatorType<binary_t> alloc;
  16967. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  16968. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  16969. m_value.binary = nullptr;
  16970. }
  16971. m_type = value_t::null;
  16972. assert_invariant();
  16973. break;
  16974. }
  16975. case value_t::object:
  16976. {
  16977. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  16978. break;
  16979. }
  16980. case value_t::array:
  16981. {
  16982. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  16983. break;
  16984. }
  16985. case value_t::null:
  16986. case value_t::discarded:
  16987. default:
  16988. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  16989. }
  16990. return result;
  16991. }
  16992. /// @brief remove elements given an iterator range
  16993. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  16994. template < class IteratorType, typename std::enable_if <
  16995. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  16996. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
  16997. = 0 >
  16998. IteratorType erase(IteratorType first, IteratorType last)
  16999. {
  17000. // make sure iterator fits the current value
  17001. if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object))
  17002. {
  17003. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", *this));
  17004. }
  17005. IteratorType result = end();
  17006. switch (m_type)
  17007. {
  17008. case value_t::boolean:
  17009. case value_t::number_float:
  17010. case value_t::number_integer:
  17011. case value_t::number_unsigned:
  17012. case value_t::string:
  17013. case value_t::binary:
  17014. {
  17015. if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin()
  17016. || !last.m_it.primitive_iterator.is_end()))
  17017. {
  17018. JSON_THROW(invalid_iterator::create(204, "iterators out of range", *this));
  17019. }
  17020. if (is_string())
  17021. {
  17022. AllocatorType<string_t> alloc;
  17023. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  17024. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  17025. m_value.string = nullptr;
  17026. }
  17027. else if (is_binary())
  17028. {
  17029. AllocatorType<binary_t> alloc;
  17030. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  17031. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  17032. m_value.binary = nullptr;
  17033. }
  17034. m_type = value_t::null;
  17035. assert_invariant();
  17036. break;
  17037. }
  17038. case value_t::object:
  17039. {
  17040. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  17041. last.m_it.object_iterator);
  17042. break;
  17043. }
  17044. case value_t::array:
  17045. {
  17046. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  17047. last.m_it.array_iterator);
  17048. break;
  17049. }
  17050. case value_t::null:
  17051. case value_t::discarded:
  17052. default:
  17053. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  17054. }
  17055. return result;
  17056. }
  17057. /// @brief remove element from a JSON object given a key
  17058. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  17059. size_type erase(const typename object_t::key_type& key)
  17060. {
  17061. // this erase only works for objects
  17062. if (JSON_HEDLEY_LIKELY(is_object()))
  17063. {
  17064. return m_value.object->erase(key);
  17065. }
  17066. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  17067. }
  17068. /// @brief remove element from a JSON array given an index
  17069. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  17070. void erase(const size_type idx)
  17071. {
  17072. // this erase only works for arrays
  17073. if (JSON_HEDLEY_LIKELY(is_array()))
  17074. {
  17075. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  17076. {
  17077. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
  17078. }
  17079. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  17080. }
  17081. else
  17082. {
  17083. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  17084. }
  17085. }
  17086. /// @}
  17087. ////////////
  17088. // lookup //
  17089. ////////////
  17090. /// @name lookup
  17091. /// @{
  17092. /// @brief find an element in a JSON object
  17093. /// @sa https://json.nlohmann.me/api/basic_json/find/
  17094. template<typename KeyT>
  17095. iterator find(KeyT&& key)
  17096. {
  17097. auto result = end();
  17098. if (is_object())
  17099. {
  17100. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  17101. }
  17102. return result;
  17103. }
  17104. /// @brief find an element in a JSON object
  17105. /// @sa https://json.nlohmann.me/api/basic_json/find/
  17106. template<typename KeyT>
  17107. const_iterator find(KeyT&& key) const
  17108. {
  17109. auto result = cend();
  17110. if (is_object())
  17111. {
  17112. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  17113. }
  17114. return result;
  17115. }
  17116. /// @brief returns the number of occurrences of a key in a JSON object
  17117. /// @sa https://json.nlohmann.me/api/basic_json/count/
  17118. template<typename KeyT>
  17119. size_type count(KeyT&& key) const
  17120. {
  17121. // return 0 for all nonobject types
  17122. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  17123. }
  17124. /// @brief check the existence of an element in a JSON object
  17125. /// @sa https://json.nlohmann.me/api/basic_json/contains/
  17126. template < typename KeyT, typename std::enable_if <
  17127. !std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int >::type = 0 >
  17128. bool contains(KeyT && key) const
  17129. {
  17130. return is_object() && m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  17131. }
  17132. /// @brief check the existence of an element in a JSON object given a JSON pointer
  17133. /// @sa https://json.nlohmann.me/api/basic_json/contains/
  17134. bool contains(const json_pointer& ptr) const
  17135. {
  17136. return ptr.contains(this);
  17137. }
  17138. /// @}
  17139. ///////////////
  17140. // iterators //
  17141. ///////////////
  17142. /// @name iterators
  17143. /// @{
  17144. /// @brief returns an iterator to the first element
  17145. /// @sa https://json.nlohmann.me/api/basic_json/begin/
  17146. iterator begin() noexcept
  17147. {
  17148. iterator result(this);
  17149. result.set_begin();
  17150. return result;
  17151. }
  17152. /// @brief returns an iterator to the first element
  17153. /// @sa https://json.nlohmann.me/api/basic_json/begin/
  17154. const_iterator begin() const noexcept
  17155. {
  17156. return cbegin();
  17157. }
  17158. /// @brief returns a const iterator to the first element
  17159. /// @sa https://json.nlohmann.me/api/basic_json/cbegin/
  17160. const_iterator cbegin() const noexcept
  17161. {
  17162. const_iterator result(this);
  17163. result.set_begin();
  17164. return result;
  17165. }
  17166. /// @brief returns an iterator to one past the last element
  17167. /// @sa https://json.nlohmann.me/api/basic_json/end/
  17168. iterator end() noexcept
  17169. {
  17170. iterator result(this);
  17171. result.set_end();
  17172. return result;
  17173. }
  17174. /// @brief returns an iterator to one past the last element
  17175. /// @sa https://json.nlohmann.me/api/basic_json/end/
  17176. const_iterator end() const noexcept
  17177. {
  17178. return cend();
  17179. }
  17180. /// @brief returns an iterator to one past the last element
  17181. /// @sa https://json.nlohmann.me/api/basic_json/cend/
  17182. const_iterator cend() const noexcept
  17183. {
  17184. const_iterator result(this);
  17185. result.set_end();
  17186. return result;
  17187. }
  17188. /// @brief returns an iterator to the reverse-beginning
  17189. /// @sa https://json.nlohmann.me/api/basic_json/rbegin/
  17190. reverse_iterator rbegin() noexcept
  17191. {
  17192. return reverse_iterator(end());
  17193. }
  17194. /// @brief returns an iterator to the reverse-beginning
  17195. /// @sa https://json.nlohmann.me/api/basic_json/rbegin/
  17196. const_reverse_iterator rbegin() const noexcept
  17197. {
  17198. return crbegin();
  17199. }
  17200. /// @brief returns an iterator to the reverse-end
  17201. /// @sa https://json.nlohmann.me/api/basic_json/rend/
  17202. reverse_iterator rend() noexcept
  17203. {
  17204. return reverse_iterator(begin());
  17205. }
  17206. /// @brief returns an iterator to the reverse-end
  17207. /// @sa https://json.nlohmann.me/api/basic_json/rend/
  17208. const_reverse_iterator rend() const noexcept
  17209. {
  17210. return crend();
  17211. }
  17212. /// @brief returns a const reverse iterator to the last element
  17213. /// @sa https://json.nlohmann.me/api/basic_json/crbegin/
  17214. const_reverse_iterator crbegin() const noexcept
  17215. {
  17216. return const_reverse_iterator(cend());
  17217. }
  17218. /// @brief returns a const reverse iterator to one before the first
  17219. /// @sa https://json.nlohmann.me/api/basic_json/crend/
  17220. const_reverse_iterator crend() const noexcept
  17221. {
  17222. return const_reverse_iterator(cbegin());
  17223. }
  17224. public:
  17225. /// @brief wrapper to access iterator member functions in range-based for
  17226. /// @sa https://json.nlohmann.me/api/basic_json/items/
  17227. /// @deprecated This function is deprecated since 3.1.0 and will be removed in
  17228. /// version 4.0.0 of the library. Please use @ref items() instead;
  17229. /// that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  17230. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  17231. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  17232. {
  17233. return ref.items();
  17234. }
  17235. /// @brief wrapper to access iterator member functions in range-based for
  17236. /// @sa https://json.nlohmann.me/api/basic_json/items/
  17237. /// @deprecated This function is deprecated since 3.1.0 and will be removed in
  17238. /// version 4.0.0 of the library. Please use @ref items() instead;
  17239. /// that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  17240. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  17241. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  17242. {
  17243. return ref.items();
  17244. }
  17245. /// @brief helper to access iterator member functions in range-based for
  17246. /// @sa https://json.nlohmann.me/api/basic_json/items/
  17247. iteration_proxy<iterator> items() noexcept
  17248. {
  17249. return iteration_proxy<iterator>(*this);
  17250. }
  17251. /// @brief helper to access iterator member functions in range-based for
  17252. /// @sa https://json.nlohmann.me/api/basic_json/items/
  17253. iteration_proxy<const_iterator> items() const noexcept
  17254. {
  17255. return iteration_proxy<const_iterator>(*this);
  17256. }
  17257. /// @}
  17258. //////////////
  17259. // capacity //
  17260. //////////////
  17261. /// @name capacity
  17262. /// @{
  17263. /// @brief checks whether the container is empty.
  17264. /// @sa https://json.nlohmann.me/api/basic_json/empty/
  17265. bool empty() const noexcept
  17266. {
  17267. switch (m_type)
  17268. {
  17269. case value_t::null:
  17270. {
  17271. // null values are empty
  17272. return true;
  17273. }
  17274. case value_t::array:
  17275. {
  17276. // delegate call to array_t::empty()
  17277. return m_value.array->empty();
  17278. }
  17279. case value_t::object:
  17280. {
  17281. // delegate call to object_t::empty()
  17282. return m_value.object->empty();
  17283. }
  17284. case value_t::string:
  17285. case value_t::boolean:
  17286. case value_t::number_integer:
  17287. case value_t::number_unsigned:
  17288. case value_t::number_float:
  17289. case value_t::binary:
  17290. case value_t::discarded:
  17291. default:
  17292. {
  17293. // all other types are nonempty
  17294. return false;
  17295. }
  17296. }
  17297. }
  17298. /// @brief returns the number of elements
  17299. /// @sa https://json.nlohmann.me/api/basic_json/size/
  17300. size_type size() const noexcept
  17301. {
  17302. switch (m_type)
  17303. {
  17304. case value_t::null:
  17305. {
  17306. // null values are empty
  17307. return 0;
  17308. }
  17309. case value_t::array:
  17310. {
  17311. // delegate call to array_t::size()
  17312. return m_value.array->size();
  17313. }
  17314. case value_t::object:
  17315. {
  17316. // delegate call to object_t::size()
  17317. return m_value.object->size();
  17318. }
  17319. case value_t::string:
  17320. case value_t::boolean:
  17321. case value_t::number_integer:
  17322. case value_t::number_unsigned:
  17323. case value_t::number_float:
  17324. case value_t::binary:
  17325. case value_t::discarded:
  17326. default:
  17327. {
  17328. // all other types have size 1
  17329. return 1;
  17330. }
  17331. }
  17332. }
  17333. /// @brief returns the maximum possible number of elements
  17334. /// @sa https://json.nlohmann.me/api/basic_json/max_size/
  17335. size_type max_size() const noexcept
  17336. {
  17337. switch (m_type)
  17338. {
  17339. case value_t::array:
  17340. {
  17341. // delegate call to array_t::max_size()
  17342. return m_value.array->max_size();
  17343. }
  17344. case value_t::object:
  17345. {
  17346. // delegate call to object_t::max_size()
  17347. return m_value.object->max_size();
  17348. }
  17349. case value_t::null:
  17350. case value_t::string:
  17351. case value_t::boolean:
  17352. case value_t::number_integer:
  17353. case value_t::number_unsigned:
  17354. case value_t::number_float:
  17355. case value_t::binary:
  17356. case value_t::discarded:
  17357. default:
  17358. {
  17359. // all other types have max_size() == size()
  17360. return size();
  17361. }
  17362. }
  17363. }
  17364. /// @}
  17365. ///////////////
  17366. // modifiers //
  17367. ///////////////
  17368. /// @name modifiers
  17369. /// @{
  17370. /// @brief clears the contents
  17371. /// @sa https://json.nlohmann.me/api/basic_json/clear/
  17372. void clear() noexcept
  17373. {
  17374. switch (m_type)
  17375. {
  17376. case value_t::number_integer:
  17377. {
  17378. m_value.number_integer = 0;
  17379. break;
  17380. }
  17381. case value_t::number_unsigned:
  17382. {
  17383. m_value.number_unsigned = 0;
  17384. break;
  17385. }
  17386. case value_t::number_float:
  17387. {
  17388. m_value.number_float = 0.0;
  17389. break;
  17390. }
  17391. case value_t::boolean:
  17392. {
  17393. m_value.boolean = false;
  17394. break;
  17395. }
  17396. case value_t::string:
  17397. {
  17398. m_value.string->clear();
  17399. break;
  17400. }
  17401. case value_t::binary:
  17402. {
  17403. m_value.binary->clear();
  17404. break;
  17405. }
  17406. case value_t::array:
  17407. {
  17408. m_value.array->clear();
  17409. break;
  17410. }
  17411. case value_t::object:
  17412. {
  17413. m_value.object->clear();
  17414. break;
  17415. }
  17416. case value_t::null:
  17417. case value_t::discarded:
  17418. default:
  17419. break;
  17420. }
  17421. }
  17422. /// @brief add an object to an array
  17423. /// @sa https://json.nlohmann.me/api/basic_json/push_back/
  17424. void push_back(basic_json&& val)
  17425. {
  17426. // push_back only works for null objects or arrays
  17427. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  17428. {
  17429. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
  17430. }
  17431. // transform null object into an array
  17432. if (is_null())
  17433. {
  17434. m_type = value_t::array;
  17435. m_value = value_t::array;
  17436. assert_invariant();
  17437. }
  17438. // add element to array (move semantics)
  17439. const auto old_capacity = m_value.array->capacity();
  17440. m_value.array->push_back(std::move(val));
  17441. set_parent(m_value.array->back(), old_capacity);
  17442. // if val is moved from, basic_json move constructor marks it null, so we do not call the destructor
  17443. }
  17444. /// @brief add an object to an array
  17445. /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
  17446. reference operator+=(basic_json&& val)
  17447. {
  17448. push_back(std::move(val));
  17449. return *this;
  17450. }
  17451. /// @brief add an object to an array
  17452. /// @sa https://json.nlohmann.me/api/basic_json/push_back/
  17453. void push_back(const basic_json& val)
  17454. {
  17455. // push_back only works for null objects or arrays
  17456. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  17457. {
  17458. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
  17459. }
  17460. // transform null object into an array
  17461. if (is_null())
  17462. {
  17463. m_type = value_t::array;
  17464. m_value = value_t::array;
  17465. assert_invariant();
  17466. }
  17467. // add element to array
  17468. const auto old_capacity = m_value.array->capacity();
  17469. m_value.array->push_back(val);
  17470. set_parent(m_value.array->back(), old_capacity);
  17471. }
  17472. /// @brief add an object to an array
  17473. /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
  17474. reference operator+=(const basic_json& val)
  17475. {
  17476. push_back(val);
  17477. return *this;
  17478. }
  17479. /// @brief add an object to an object
  17480. /// @sa https://json.nlohmann.me/api/basic_json/push_back/
  17481. void push_back(const typename object_t::value_type& val)
  17482. {
  17483. // push_back only works for null objects or objects
  17484. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  17485. {
  17486. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
  17487. }
  17488. // transform null object into an object
  17489. if (is_null())
  17490. {
  17491. m_type = value_t::object;
  17492. m_value = value_t::object;
  17493. assert_invariant();
  17494. }
  17495. // add element to object
  17496. auto res = m_value.object->insert(val);
  17497. set_parent(res.first->second);
  17498. }
  17499. /// @brief add an object to an object
  17500. /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
  17501. reference operator+=(const typename object_t::value_type& val)
  17502. {
  17503. push_back(val);
  17504. return *this;
  17505. }
  17506. /// @brief add an object to an object
  17507. /// @sa https://json.nlohmann.me/api/basic_json/push_back/
  17508. void push_back(initializer_list_t init)
  17509. {
  17510. if (is_object() && init.size() == 2 && (*init.begin())->is_string())
  17511. {
  17512. basic_json&& key = init.begin()->moved_or_copied();
  17513. push_back(typename object_t::value_type(
  17514. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  17515. }
  17516. else
  17517. {
  17518. push_back(basic_json(init));
  17519. }
  17520. }
  17521. /// @brief add an object to an object
  17522. /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
  17523. reference operator+=(initializer_list_t init)
  17524. {
  17525. push_back(init);
  17526. return *this;
  17527. }
  17528. /// @brief add an object to an array
  17529. /// @sa https://json.nlohmann.me/api/basic_json/emplace_back/
  17530. template<class... Args>
  17531. reference emplace_back(Args&& ... args)
  17532. {
  17533. // emplace_back only works for null objects or arrays
  17534. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  17535. {
  17536. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()), *this));
  17537. }
  17538. // transform null object into an array
  17539. if (is_null())
  17540. {
  17541. m_type = value_t::array;
  17542. m_value = value_t::array;
  17543. assert_invariant();
  17544. }
  17545. // add element to array (perfect forwarding)
  17546. const auto old_capacity = m_value.array->capacity();
  17547. m_value.array->emplace_back(std::forward<Args>(args)...);
  17548. return set_parent(m_value.array->back(), old_capacity);
  17549. }
  17550. /// @brief add an object to an object if key does not exist
  17551. /// @sa https://json.nlohmann.me/api/basic_json/emplace/
  17552. template<class... Args>
  17553. std::pair<iterator, bool> emplace(Args&& ... args)
  17554. {
  17555. // emplace only works for null objects or arrays
  17556. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  17557. {
  17558. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()), *this));
  17559. }
  17560. // transform null object into an object
  17561. if (is_null())
  17562. {
  17563. m_type = value_t::object;
  17564. m_value = value_t::object;
  17565. assert_invariant();
  17566. }
  17567. // add element to array (perfect forwarding)
  17568. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  17569. set_parent(res.first->second);
  17570. // create result iterator and set iterator to the result of emplace
  17571. auto it = begin();
  17572. it.m_it.object_iterator = res.first;
  17573. // return pair of iterator and boolean
  17574. return {it, res.second};
  17575. }
  17576. /// Helper for insertion of an iterator
  17577. /// @note: This uses std::distance to support GCC 4.8,
  17578. /// see https://github.com/nlohmann/json/pull/1257
  17579. template<typename... Args>
  17580. iterator insert_iterator(const_iterator pos, Args&& ... args)
  17581. {
  17582. iterator result(this);
  17583. JSON_ASSERT(m_value.array != nullptr);
  17584. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  17585. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  17586. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  17587. // This could have been written as:
  17588. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  17589. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  17590. set_parents();
  17591. return result;
  17592. }
  17593. /// @brief inserts element into array
  17594. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  17595. iterator insert(const_iterator pos, const basic_json& val)
  17596. {
  17597. // insert only works for arrays
  17598. if (JSON_HEDLEY_LIKELY(is_array()))
  17599. {
  17600. // check if iterator pos fits to this JSON value
  17601. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  17602. {
  17603. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  17604. }
  17605. // insert to array and return iterator
  17606. return insert_iterator(pos, val);
  17607. }
  17608. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  17609. }
  17610. /// @brief inserts element into array
  17611. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  17612. iterator insert(const_iterator pos, basic_json&& val)
  17613. {
  17614. return insert(pos, val);
  17615. }
  17616. /// @brief inserts copies of element into array
  17617. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  17618. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  17619. {
  17620. // insert only works for arrays
  17621. if (JSON_HEDLEY_LIKELY(is_array()))
  17622. {
  17623. // check if iterator pos fits to this JSON value
  17624. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  17625. {
  17626. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  17627. }
  17628. // insert to array and return iterator
  17629. return insert_iterator(pos, cnt, val);
  17630. }
  17631. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  17632. }
  17633. /// @brief inserts range of elements into array
  17634. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  17635. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  17636. {
  17637. // insert only works for arrays
  17638. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  17639. {
  17640. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  17641. }
  17642. // check if iterator pos fits to this JSON value
  17643. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  17644. {
  17645. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  17646. }
  17647. // check if range iterators belong to the same JSON object
  17648. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  17649. {
  17650. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
  17651. }
  17652. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  17653. {
  17654. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", *this));
  17655. }
  17656. // insert to array and return iterator
  17657. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  17658. }
  17659. /// @brief inserts elements from initializer list into array
  17660. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  17661. iterator insert(const_iterator pos, initializer_list_t ilist)
  17662. {
  17663. // insert only works for arrays
  17664. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  17665. {
  17666. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  17667. }
  17668. // check if iterator pos fits to this JSON value
  17669. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  17670. {
  17671. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  17672. }
  17673. // insert to array and return iterator
  17674. return insert_iterator(pos, ilist.begin(), ilist.end());
  17675. }
  17676. /// @brief inserts range of elements into object
  17677. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  17678. void insert(const_iterator first, const_iterator last)
  17679. {
  17680. // insert only works for objects
  17681. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  17682. {
  17683. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  17684. }
  17685. // check if range iterators belong to the same JSON object
  17686. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  17687. {
  17688. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
  17689. }
  17690. // passed iterators must belong to objects
  17691. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
  17692. {
  17693. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this));
  17694. }
  17695. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  17696. }
  17697. /// @brief updates a JSON object from another object, overwriting existing keys
  17698. /// @sa https://json.nlohmann.me/api/basic_json/update/
  17699. void update(const_reference j, bool merge_objects = false)
  17700. {
  17701. update(j.begin(), j.end(), merge_objects);
  17702. }
  17703. /// @brief updates a JSON object from another object, overwriting existing keys
  17704. /// @sa https://json.nlohmann.me/api/basic_json/update/
  17705. void update(const_iterator first, const_iterator last, bool merge_objects = false)
  17706. {
  17707. // implicitly convert null value to an empty object
  17708. if (is_null())
  17709. {
  17710. m_type = value_t::object;
  17711. m_value.object = create<object_t>();
  17712. assert_invariant();
  17713. }
  17714. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  17715. {
  17716. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this));
  17717. }
  17718. // check if range iterators belong to the same JSON object
  17719. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  17720. {
  17721. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
  17722. }
  17723. // passed iterators must belong to objects
  17724. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
  17725. {
  17726. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(first.m_object->type_name()), *first.m_object));
  17727. }
  17728. for (auto it = first; it != last; ++it)
  17729. {
  17730. if (merge_objects && it.value().is_object())
  17731. {
  17732. auto it2 = m_value.object->find(it.key());
  17733. if (it2 != m_value.object->end())
  17734. {
  17735. it2->second.update(it.value(), true);
  17736. continue;
  17737. }
  17738. }
  17739. m_value.object->operator[](it.key()) = it.value();
  17740. #if JSON_DIAGNOSTICS
  17741. m_value.object->operator[](it.key()).m_parent = this;
  17742. #endif
  17743. }
  17744. }
  17745. /// @brief exchanges the values
  17746. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  17747. void swap(reference other) noexcept (
  17748. std::is_nothrow_move_constructible<value_t>::value&&
  17749. std::is_nothrow_move_assignable<value_t>::value&&
  17750. std::is_nothrow_move_constructible<json_value>::value&&
  17751. std::is_nothrow_move_assignable<json_value>::value
  17752. )
  17753. {
  17754. std::swap(m_type, other.m_type);
  17755. std::swap(m_value, other.m_value);
  17756. set_parents();
  17757. other.set_parents();
  17758. assert_invariant();
  17759. }
  17760. /// @brief exchanges the values
  17761. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  17762. friend void swap(reference left, reference right) noexcept (
  17763. std::is_nothrow_move_constructible<value_t>::value&&
  17764. std::is_nothrow_move_assignable<value_t>::value&&
  17765. std::is_nothrow_move_constructible<json_value>::value&&
  17766. std::is_nothrow_move_assignable<json_value>::value
  17767. )
  17768. {
  17769. left.swap(right);
  17770. }
  17771. /// @brief exchanges the values
  17772. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  17773. void swap(array_t& other) // NOLINT(bugprone-exception-escape)
  17774. {
  17775. // swap only works for arrays
  17776. if (JSON_HEDLEY_LIKELY(is_array()))
  17777. {
  17778. std::swap(*(m_value.array), other);
  17779. }
  17780. else
  17781. {
  17782. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  17783. }
  17784. }
  17785. /// @brief exchanges the values
  17786. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  17787. void swap(object_t& other) // NOLINT(bugprone-exception-escape)
  17788. {
  17789. // swap only works for objects
  17790. if (JSON_HEDLEY_LIKELY(is_object()))
  17791. {
  17792. std::swap(*(m_value.object), other);
  17793. }
  17794. else
  17795. {
  17796. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  17797. }
  17798. }
  17799. /// @brief exchanges the values
  17800. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  17801. void swap(string_t& other) // NOLINT(bugprone-exception-escape)
  17802. {
  17803. // swap only works for strings
  17804. if (JSON_HEDLEY_LIKELY(is_string()))
  17805. {
  17806. std::swap(*(m_value.string), other);
  17807. }
  17808. else
  17809. {
  17810. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  17811. }
  17812. }
  17813. /// @brief exchanges the values
  17814. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  17815. void swap(binary_t& other) // NOLINT(bugprone-exception-escape)
  17816. {
  17817. // swap only works for strings
  17818. if (JSON_HEDLEY_LIKELY(is_binary()))
  17819. {
  17820. std::swap(*(m_value.binary), other);
  17821. }
  17822. else
  17823. {
  17824. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  17825. }
  17826. }
  17827. /// @brief exchanges the values
  17828. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  17829. void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape)
  17830. {
  17831. // swap only works for strings
  17832. if (JSON_HEDLEY_LIKELY(is_binary()))
  17833. {
  17834. std::swap(*(m_value.binary), other);
  17835. }
  17836. else
  17837. {
  17838. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  17839. }
  17840. }
  17841. /// @}
  17842. public:
  17843. //////////////////////////////////////////
  17844. // lexicographical comparison operators //
  17845. //////////////////////////////////////////
  17846. /// @name lexicographical comparison operators
  17847. /// @{
  17848. /// @brief comparison: equal
  17849. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  17850. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  17851. {
  17852. #ifdef __GNUC__
  17853. #pragma GCC diagnostic push
  17854. #pragma GCC diagnostic ignored "-Wfloat-equal"
  17855. #endif
  17856. const auto lhs_type = lhs.type();
  17857. const auto rhs_type = rhs.type();
  17858. if (lhs_type == rhs_type)
  17859. {
  17860. switch (lhs_type)
  17861. {
  17862. case value_t::array:
  17863. return *lhs.m_value.array == *rhs.m_value.array;
  17864. case value_t::object:
  17865. return *lhs.m_value.object == *rhs.m_value.object;
  17866. case value_t::null:
  17867. return true;
  17868. case value_t::string:
  17869. return *lhs.m_value.string == *rhs.m_value.string;
  17870. case value_t::boolean:
  17871. return lhs.m_value.boolean == rhs.m_value.boolean;
  17872. case value_t::number_integer:
  17873. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  17874. case value_t::number_unsigned:
  17875. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  17876. case value_t::number_float:
  17877. return lhs.m_value.number_float == rhs.m_value.number_float;
  17878. case value_t::binary:
  17879. return *lhs.m_value.binary == *rhs.m_value.binary;
  17880. case value_t::discarded:
  17881. default:
  17882. return false;
  17883. }
  17884. }
  17885. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
  17886. {
  17887. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  17888. }
  17889. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
  17890. {
  17891. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  17892. }
  17893. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
  17894. {
  17895. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  17896. }
  17897. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
  17898. {
  17899. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  17900. }
  17901. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
  17902. {
  17903. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  17904. }
  17905. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
  17906. {
  17907. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  17908. }
  17909. return false;
  17910. #ifdef __GNUC__
  17911. #pragma GCC diagnostic pop
  17912. #endif
  17913. }
  17914. /// @brief comparison: equal
  17915. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  17916. template<typename ScalarType, typename std::enable_if<
  17917. std::is_scalar<ScalarType>::value, int>::type = 0>
  17918. friend bool operator==(const_reference lhs, ScalarType rhs) noexcept
  17919. {
  17920. return lhs == basic_json(rhs);
  17921. }
  17922. /// @brief comparison: equal
  17923. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  17924. template<typename ScalarType, typename std::enable_if<
  17925. std::is_scalar<ScalarType>::value, int>::type = 0>
  17926. friend bool operator==(ScalarType lhs, const_reference rhs) noexcept
  17927. {
  17928. return basic_json(lhs) == rhs;
  17929. }
  17930. /// @brief comparison: not equal
  17931. /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
  17932. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  17933. {
  17934. return !(lhs == rhs);
  17935. }
  17936. /// @brief comparison: not equal
  17937. /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
  17938. template<typename ScalarType, typename std::enable_if<
  17939. std::is_scalar<ScalarType>::value, int>::type = 0>
  17940. friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept
  17941. {
  17942. return lhs != basic_json(rhs);
  17943. }
  17944. /// @brief comparison: not equal
  17945. /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
  17946. template<typename ScalarType, typename std::enable_if<
  17947. std::is_scalar<ScalarType>::value, int>::type = 0>
  17948. friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept
  17949. {
  17950. return basic_json(lhs) != rhs;
  17951. }
  17952. /// @brief comparison: less than
  17953. /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
  17954. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  17955. {
  17956. const auto lhs_type = lhs.type();
  17957. const auto rhs_type = rhs.type();
  17958. if (lhs_type == rhs_type)
  17959. {
  17960. switch (lhs_type)
  17961. {
  17962. case value_t::array:
  17963. // note parentheses are necessary, see
  17964. // https://github.com/nlohmann/json/issues/1530
  17965. return (*lhs.m_value.array) < (*rhs.m_value.array);
  17966. case value_t::object:
  17967. return (*lhs.m_value.object) < (*rhs.m_value.object);
  17968. case value_t::null:
  17969. return false;
  17970. case value_t::string:
  17971. return (*lhs.m_value.string) < (*rhs.m_value.string);
  17972. case value_t::boolean:
  17973. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  17974. case value_t::number_integer:
  17975. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  17976. case value_t::number_unsigned:
  17977. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  17978. case value_t::number_float:
  17979. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  17980. case value_t::binary:
  17981. return (*lhs.m_value.binary) < (*rhs.m_value.binary);
  17982. case value_t::discarded:
  17983. default:
  17984. return false;
  17985. }
  17986. }
  17987. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
  17988. {
  17989. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  17990. }
  17991. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
  17992. {
  17993. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  17994. }
  17995. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
  17996. {
  17997. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  17998. }
  17999. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
  18000. {
  18001. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  18002. }
  18003. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
  18004. {
  18005. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  18006. }
  18007. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
  18008. {
  18009. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  18010. }
  18011. // We only reach this line if we cannot compare values. In that case,
  18012. // we compare types. Note we have to call the operator explicitly,
  18013. // because MSVC has problems otherwise.
  18014. return operator<(lhs_type, rhs_type);
  18015. }
  18016. /// @brief comparison: less than
  18017. /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
  18018. template<typename ScalarType, typename std::enable_if<
  18019. std::is_scalar<ScalarType>::value, int>::type = 0>
  18020. friend bool operator<(const_reference lhs, ScalarType rhs) noexcept
  18021. {
  18022. return lhs < basic_json(rhs);
  18023. }
  18024. /// @brief comparison: less than
  18025. /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
  18026. template<typename ScalarType, typename std::enable_if<
  18027. std::is_scalar<ScalarType>::value, int>::type = 0>
  18028. friend bool operator<(ScalarType lhs, const_reference rhs) noexcept
  18029. {
  18030. return basic_json(lhs) < rhs;
  18031. }
  18032. /// @brief comparison: less than or equal
  18033. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  18034. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  18035. {
  18036. return !(rhs < lhs);
  18037. }
  18038. /// @brief comparison: less than or equal
  18039. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  18040. template<typename ScalarType, typename std::enable_if<
  18041. std::is_scalar<ScalarType>::value, int>::type = 0>
  18042. friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept
  18043. {
  18044. return lhs <= basic_json(rhs);
  18045. }
  18046. /// @brief comparison: less than or equal
  18047. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  18048. template<typename ScalarType, typename std::enable_if<
  18049. std::is_scalar<ScalarType>::value, int>::type = 0>
  18050. friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept
  18051. {
  18052. return basic_json(lhs) <= rhs;
  18053. }
  18054. /// @brief comparison: greater than
  18055. /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
  18056. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  18057. {
  18058. return !(lhs <= rhs);
  18059. }
  18060. /// @brief comparison: greater than
  18061. /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
  18062. template<typename ScalarType, typename std::enable_if<
  18063. std::is_scalar<ScalarType>::value, int>::type = 0>
  18064. friend bool operator>(const_reference lhs, ScalarType rhs) noexcept
  18065. {
  18066. return lhs > basic_json(rhs);
  18067. }
  18068. /// @brief comparison: greater than
  18069. /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
  18070. template<typename ScalarType, typename std::enable_if<
  18071. std::is_scalar<ScalarType>::value, int>::type = 0>
  18072. friend bool operator>(ScalarType lhs, const_reference rhs) noexcept
  18073. {
  18074. return basic_json(lhs) > rhs;
  18075. }
  18076. /// @brief comparison: greater than or equal
  18077. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  18078. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  18079. {
  18080. return !(lhs < rhs);
  18081. }
  18082. /// @brief comparison: greater than or equal
  18083. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  18084. template<typename ScalarType, typename std::enable_if<
  18085. std::is_scalar<ScalarType>::value, int>::type = 0>
  18086. friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept
  18087. {
  18088. return lhs >= basic_json(rhs);
  18089. }
  18090. /// @brief comparison: greater than or equal
  18091. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  18092. template<typename ScalarType, typename std::enable_if<
  18093. std::is_scalar<ScalarType>::value, int>::type = 0>
  18094. friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept
  18095. {
  18096. return basic_json(lhs) >= rhs;
  18097. }
  18098. /// @}
  18099. ///////////////////
  18100. // serialization //
  18101. ///////////////////
  18102. /// @name serialization
  18103. /// @{
  18104. #ifndef JSON_NO_IO
  18105. /// @brief serialize to stream
  18106. /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/
  18107. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  18108. {
  18109. // read width member and use it as indentation parameter if nonzero
  18110. const bool pretty_print = o.width() > 0;
  18111. const auto indentation = pretty_print ? o.width() : 0;
  18112. // reset width to 0 for subsequent calls to this stream
  18113. o.width(0);
  18114. // do the actual serialization
  18115. serializer s(detail::output_adapter<char>(o), o.fill());
  18116. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  18117. return o;
  18118. }
  18119. /// @brief serialize to stream
  18120. /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/
  18121. /// @deprecated This function is deprecated since 3.0.0 and will be removed in
  18122. /// version 4.0.0 of the library. Please use
  18123. /// operator<<(std::ostream&, const basic_json&) instead; that is,
  18124. /// replace calls like `j >> o;` with `o << j;`.
  18125. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&))
  18126. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  18127. {
  18128. return o << j;
  18129. }
  18130. #endif // JSON_NO_IO
  18131. /// @}
  18132. /////////////////////
  18133. // deserialization //
  18134. /////////////////////
  18135. /// @name deserialization
  18136. /// @{
  18137. /// @brief deserialize from a compatible input
  18138. /// @sa https://json.nlohmann.me/api/basic_json/parse/
  18139. template<typename InputType>
  18140. JSON_HEDLEY_WARN_UNUSED_RESULT
  18141. static basic_json parse(InputType&& i,
  18142. const parser_callback_t cb = nullptr,
  18143. const bool allow_exceptions = true,
  18144. const bool ignore_comments = false)
  18145. {
  18146. basic_json result;
  18147. parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions, ignore_comments).parse(true, result);
  18148. return result;
  18149. }
  18150. /// @brief deserialize from a pair of character iterators
  18151. /// @sa https://json.nlohmann.me/api/basic_json/parse/
  18152. template<typename IteratorType>
  18153. JSON_HEDLEY_WARN_UNUSED_RESULT
  18154. static basic_json parse(IteratorType first,
  18155. IteratorType last,
  18156. const parser_callback_t cb = nullptr,
  18157. const bool allow_exceptions = true,
  18158. const bool ignore_comments = false)
  18159. {
  18160. basic_json result;
  18161. parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result);
  18162. return result;
  18163. }
  18164. JSON_HEDLEY_WARN_UNUSED_RESULT
  18165. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len))
  18166. static basic_json parse(detail::span_input_adapter&& i,
  18167. const parser_callback_t cb = nullptr,
  18168. const bool allow_exceptions = true,
  18169. const bool ignore_comments = false)
  18170. {
  18171. basic_json result;
  18172. parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result);
  18173. return result;
  18174. }
  18175. /// @brief check if the input is valid JSON
  18176. /// @sa https://json.nlohmann.me/api/basic_json/accept/
  18177. template<typename InputType>
  18178. static bool accept(InputType&& i,
  18179. const bool ignore_comments = false)
  18180. {
  18181. return parser(detail::input_adapter(std::forward<InputType>(i)), nullptr, false, ignore_comments).accept(true);
  18182. }
  18183. /// @brief check if the input is valid JSON
  18184. /// @sa https://json.nlohmann.me/api/basic_json/accept/
  18185. template<typename IteratorType>
  18186. static bool accept(IteratorType first, IteratorType last,
  18187. const bool ignore_comments = false)
  18188. {
  18189. return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true);
  18190. }
  18191. JSON_HEDLEY_WARN_UNUSED_RESULT
  18192. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len))
  18193. static bool accept(detail::span_input_adapter&& i,
  18194. const bool ignore_comments = false)
  18195. {
  18196. return parser(i.get(), nullptr, false, ignore_comments).accept(true);
  18197. }
  18198. /// @brief generate SAX events
  18199. /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
  18200. template <typename InputType, typename SAX>
  18201. JSON_HEDLEY_NON_NULL(2)
  18202. static bool sax_parse(InputType&& i, SAX* sax,
  18203. input_format_t format = input_format_t::json,
  18204. const bool strict = true,
  18205. const bool ignore_comments = false)
  18206. {
  18207. auto ia = detail::input_adapter(std::forward<InputType>(i));
  18208. return format == input_format_t::json
  18209. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  18210. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  18211. }
  18212. /// @brief generate SAX events
  18213. /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
  18214. template<class IteratorType, class SAX>
  18215. JSON_HEDLEY_NON_NULL(3)
  18216. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax,
  18217. input_format_t format = input_format_t::json,
  18218. const bool strict = true,
  18219. const bool ignore_comments = false)
  18220. {
  18221. auto ia = detail::input_adapter(std::move(first), std::move(last));
  18222. return format == input_format_t::json
  18223. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  18224. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  18225. }
  18226. /// @brief generate SAX events
  18227. /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
  18228. /// @deprecated This function is deprecated since 3.8.0 and will be removed in
  18229. /// version 4.0.0 of the library. Please use
  18230. /// sax_parse(ptr, ptr + len) instead.
  18231. template <typename SAX>
  18232. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...))
  18233. JSON_HEDLEY_NON_NULL(2)
  18234. static bool sax_parse(detail::span_input_adapter&& i, SAX* sax,
  18235. input_format_t format = input_format_t::json,
  18236. const bool strict = true,
  18237. const bool ignore_comments = false)
  18238. {
  18239. auto ia = i.get();
  18240. return format == input_format_t::json
  18241. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  18242. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  18243. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  18244. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  18245. }
  18246. #ifndef JSON_NO_IO
  18247. /// @brief deserialize from stream
  18248. /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/
  18249. /// @deprecated This stream operator is deprecated since 3.0.0 and will be removed in
  18250. /// version 4.0.0 of the library. Please use
  18251. /// operator>>(std::istream&, basic_json&) instead; that is,
  18252. /// replace calls like `j << i;` with `i >> j;`.
  18253. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&))
  18254. friend std::istream& operator<<(basic_json& j, std::istream& i)
  18255. {
  18256. return operator>>(i, j);
  18257. }
  18258. /// @brief deserialize from stream
  18259. /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/
  18260. friend std::istream& operator>>(std::istream& i, basic_json& j)
  18261. {
  18262. parser(detail::input_adapter(i)).parse(false, j);
  18263. return i;
  18264. }
  18265. #endif // JSON_NO_IO
  18266. /// @}
  18267. ///////////////////////////
  18268. // convenience functions //
  18269. ///////////////////////////
  18270. /// @brief return the type as string
  18271. /// @sa https://json.nlohmann.me/api/basic_json/type_name/
  18272. JSON_HEDLEY_RETURNS_NON_NULL
  18273. const char* type_name() const noexcept
  18274. {
  18275. switch (m_type)
  18276. {
  18277. case value_t::null:
  18278. return "null";
  18279. case value_t::object:
  18280. return "object";
  18281. case value_t::array:
  18282. return "array";
  18283. case value_t::string:
  18284. return "string";
  18285. case value_t::boolean:
  18286. return "boolean";
  18287. case value_t::binary:
  18288. return "binary";
  18289. case value_t::discarded:
  18290. return "discarded";
  18291. case value_t::number_integer:
  18292. case value_t::number_unsigned:
  18293. case value_t::number_float:
  18294. default:
  18295. return "number";
  18296. }
  18297. }
  18298. JSON_PRIVATE_UNLESS_TESTED:
  18299. //////////////////////
  18300. // member variables //
  18301. //////////////////////
  18302. /// the type of the current element
  18303. value_t m_type = value_t::null;
  18304. /// the value of the current element
  18305. json_value m_value = {};
  18306. #if JSON_DIAGNOSTICS
  18307. /// a pointer to a parent value (for debugging purposes)
  18308. basic_json* m_parent = nullptr;
  18309. #endif
  18310. //////////////////////////////////////////
  18311. // binary serialization/deserialization //
  18312. //////////////////////////////////////////
  18313. /// @name binary serialization/deserialization support
  18314. /// @{
  18315. public:
  18316. /// @brief create a CBOR serialization of a given JSON value
  18317. /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
  18318. static std::vector<std::uint8_t> to_cbor(const basic_json& j)
  18319. {
  18320. std::vector<std::uint8_t> result;
  18321. to_cbor(j, result);
  18322. return result;
  18323. }
  18324. /// @brief create a CBOR serialization of a given JSON value
  18325. /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
  18326. static void to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  18327. {
  18328. binary_writer<std::uint8_t>(o).write_cbor(j);
  18329. }
  18330. /// @brief create a CBOR serialization of a given JSON value
  18331. /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
  18332. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  18333. {
  18334. binary_writer<char>(o).write_cbor(j);
  18335. }
  18336. /// @brief create a MessagePack serialization of a given JSON value
  18337. /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
  18338. static std::vector<std::uint8_t> to_msgpack(const basic_json& j)
  18339. {
  18340. std::vector<std::uint8_t> result;
  18341. to_msgpack(j, result);
  18342. return result;
  18343. }
  18344. /// @brief create a MessagePack serialization of a given JSON value
  18345. /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
  18346. static void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  18347. {
  18348. binary_writer<std::uint8_t>(o).write_msgpack(j);
  18349. }
  18350. /// @brief create a MessagePack serialization of a given JSON value
  18351. /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
  18352. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  18353. {
  18354. binary_writer<char>(o).write_msgpack(j);
  18355. }
  18356. /// @brief create a UBJSON serialization of a given JSON value
  18357. /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
  18358. static std::vector<std::uint8_t> to_ubjson(const basic_json& j,
  18359. const bool use_size = false,
  18360. const bool use_type = false)
  18361. {
  18362. std::vector<std::uint8_t> result;
  18363. to_ubjson(j, result, use_size, use_type);
  18364. return result;
  18365. }
  18366. /// @brief create a UBJSON serialization of a given JSON value
  18367. /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
  18368. static void to_ubjson(const basic_json& j, detail::output_adapter<std::uint8_t> o,
  18369. const bool use_size = false, const bool use_type = false)
  18370. {
  18371. binary_writer<std::uint8_t>(o).write_ubjson(j, use_size, use_type);
  18372. }
  18373. /// @brief create a UBJSON serialization of a given JSON value
  18374. /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
  18375. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  18376. const bool use_size = false, const bool use_type = false)
  18377. {
  18378. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  18379. }
  18380. /// @brief create a BSON serialization of a given JSON value
  18381. /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
  18382. static std::vector<std::uint8_t> to_bson(const basic_json& j)
  18383. {
  18384. std::vector<std::uint8_t> result;
  18385. to_bson(j, result);
  18386. return result;
  18387. }
  18388. /// @brief create a BSON serialization of a given JSON value
  18389. /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
  18390. static void to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  18391. {
  18392. binary_writer<std::uint8_t>(o).write_bson(j);
  18393. }
  18394. /// @brief create a BSON serialization of a given JSON value
  18395. /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
  18396. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  18397. {
  18398. binary_writer<char>(o).write_bson(j);
  18399. }
  18400. /// @brief create a JSON value from an input in CBOR format
  18401. /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/
  18402. template<typename InputType>
  18403. JSON_HEDLEY_WARN_UNUSED_RESULT
  18404. static basic_json from_cbor(InputType&& i,
  18405. const bool strict = true,
  18406. const bool allow_exceptions = true,
  18407. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  18408. {
  18409. basic_json result;
  18410. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18411. auto ia = detail::input_adapter(std::forward<InputType>(i));
  18412. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  18413. return res ? result : basic_json(value_t::discarded);
  18414. }
  18415. /// @brief create a JSON value from an input in CBOR format
  18416. /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/
  18417. template<typename IteratorType>
  18418. JSON_HEDLEY_WARN_UNUSED_RESULT
  18419. static basic_json from_cbor(IteratorType first, IteratorType last,
  18420. const bool strict = true,
  18421. const bool allow_exceptions = true,
  18422. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  18423. {
  18424. basic_json result;
  18425. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18426. auto ia = detail::input_adapter(std::move(first), std::move(last));
  18427. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  18428. return res ? result : basic_json(value_t::discarded);
  18429. }
  18430. template<typename T>
  18431. JSON_HEDLEY_WARN_UNUSED_RESULT
  18432. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  18433. static basic_json from_cbor(const T* ptr, std::size_t len,
  18434. const bool strict = true,
  18435. const bool allow_exceptions = true,
  18436. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  18437. {
  18438. return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler);
  18439. }
  18440. JSON_HEDLEY_WARN_UNUSED_RESULT
  18441. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  18442. static basic_json from_cbor(detail::span_input_adapter&& i,
  18443. const bool strict = true,
  18444. const bool allow_exceptions = true,
  18445. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  18446. {
  18447. basic_json result;
  18448. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18449. auto ia = i.get();
  18450. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  18451. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  18452. return res ? result : basic_json(value_t::discarded);
  18453. }
  18454. /// @brief create a JSON value from an input in MessagePack format
  18455. /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/
  18456. template<typename InputType>
  18457. JSON_HEDLEY_WARN_UNUSED_RESULT
  18458. static basic_json from_msgpack(InputType&& i,
  18459. const bool strict = true,
  18460. const bool allow_exceptions = true)
  18461. {
  18462. basic_json result;
  18463. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18464. auto ia = detail::input_adapter(std::forward<InputType>(i));
  18465. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  18466. return res ? result : basic_json(value_t::discarded);
  18467. }
  18468. /// @brief create a JSON value from an input in MessagePack format
  18469. /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/
  18470. template<typename IteratorType>
  18471. JSON_HEDLEY_WARN_UNUSED_RESULT
  18472. static basic_json from_msgpack(IteratorType first, IteratorType last,
  18473. const bool strict = true,
  18474. const bool allow_exceptions = true)
  18475. {
  18476. basic_json result;
  18477. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18478. auto ia = detail::input_adapter(std::move(first), std::move(last));
  18479. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  18480. return res ? result : basic_json(value_t::discarded);
  18481. }
  18482. template<typename T>
  18483. JSON_HEDLEY_WARN_UNUSED_RESULT
  18484. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  18485. static basic_json from_msgpack(const T* ptr, std::size_t len,
  18486. const bool strict = true,
  18487. const bool allow_exceptions = true)
  18488. {
  18489. return from_msgpack(ptr, ptr + len, strict, allow_exceptions);
  18490. }
  18491. JSON_HEDLEY_WARN_UNUSED_RESULT
  18492. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  18493. static basic_json from_msgpack(detail::span_input_adapter&& i,
  18494. const bool strict = true,
  18495. const bool allow_exceptions = true)
  18496. {
  18497. basic_json result;
  18498. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18499. auto ia = i.get();
  18500. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  18501. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  18502. return res ? result : basic_json(value_t::discarded);
  18503. }
  18504. /// @brief create a JSON value from an input in UBJSON format
  18505. /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/
  18506. template<typename InputType>
  18507. JSON_HEDLEY_WARN_UNUSED_RESULT
  18508. static basic_json from_ubjson(InputType&& i,
  18509. const bool strict = true,
  18510. const bool allow_exceptions = true)
  18511. {
  18512. basic_json result;
  18513. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18514. auto ia = detail::input_adapter(std::forward<InputType>(i));
  18515. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  18516. return res ? result : basic_json(value_t::discarded);
  18517. }
  18518. /// @brief create a JSON value from an input in UBJSON format
  18519. /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/
  18520. template<typename IteratorType>
  18521. JSON_HEDLEY_WARN_UNUSED_RESULT
  18522. static basic_json from_ubjson(IteratorType first, IteratorType last,
  18523. const bool strict = true,
  18524. const bool allow_exceptions = true)
  18525. {
  18526. basic_json result;
  18527. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18528. auto ia = detail::input_adapter(std::move(first), std::move(last));
  18529. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  18530. return res ? result : basic_json(value_t::discarded);
  18531. }
  18532. template<typename T>
  18533. JSON_HEDLEY_WARN_UNUSED_RESULT
  18534. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  18535. static basic_json from_ubjson(const T* ptr, std::size_t len,
  18536. const bool strict = true,
  18537. const bool allow_exceptions = true)
  18538. {
  18539. return from_ubjson(ptr, ptr + len, strict, allow_exceptions);
  18540. }
  18541. JSON_HEDLEY_WARN_UNUSED_RESULT
  18542. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  18543. static basic_json from_ubjson(detail::span_input_adapter&& i,
  18544. const bool strict = true,
  18545. const bool allow_exceptions = true)
  18546. {
  18547. basic_json result;
  18548. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18549. auto ia = i.get();
  18550. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  18551. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  18552. return res ? result : basic_json(value_t::discarded);
  18553. }
  18554. /// @brief create a JSON value from an input in BSON format
  18555. /// @sa https://json.nlohmann.me/api/basic_json/from_bson/
  18556. template<typename InputType>
  18557. JSON_HEDLEY_WARN_UNUSED_RESULT
  18558. static basic_json from_bson(InputType&& i,
  18559. const bool strict = true,
  18560. const bool allow_exceptions = true)
  18561. {
  18562. basic_json result;
  18563. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18564. auto ia = detail::input_adapter(std::forward<InputType>(i));
  18565. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  18566. return res ? result : basic_json(value_t::discarded);
  18567. }
  18568. /// @brief create a JSON value from an input in BSON format
  18569. /// @sa https://json.nlohmann.me/api/basic_json/from_bson/
  18570. template<typename IteratorType>
  18571. JSON_HEDLEY_WARN_UNUSED_RESULT
  18572. static basic_json from_bson(IteratorType first, IteratorType last,
  18573. const bool strict = true,
  18574. const bool allow_exceptions = true)
  18575. {
  18576. basic_json result;
  18577. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18578. auto ia = detail::input_adapter(std::move(first), std::move(last));
  18579. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  18580. return res ? result : basic_json(value_t::discarded);
  18581. }
  18582. template<typename T>
  18583. JSON_HEDLEY_WARN_UNUSED_RESULT
  18584. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  18585. static basic_json from_bson(const T* ptr, std::size_t len,
  18586. const bool strict = true,
  18587. const bool allow_exceptions = true)
  18588. {
  18589. return from_bson(ptr, ptr + len, strict, allow_exceptions);
  18590. }
  18591. JSON_HEDLEY_WARN_UNUSED_RESULT
  18592. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  18593. static basic_json from_bson(detail::span_input_adapter&& i,
  18594. const bool strict = true,
  18595. const bool allow_exceptions = true)
  18596. {
  18597. basic_json result;
  18598. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18599. auto ia = i.get();
  18600. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  18601. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  18602. return res ? result : basic_json(value_t::discarded);
  18603. }
  18604. /// @}
  18605. //////////////////////////
  18606. // JSON Pointer support //
  18607. //////////////////////////
  18608. /// @name JSON Pointer functions
  18609. /// @{
  18610. /// @brief access specified element via JSON Pointer
  18611. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  18612. reference operator[](const json_pointer& ptr)
  18613. {
  18614. return ptr.get_unchecked(this);
  18615. }
  18616. /// @brief access specified element via JSON Pointer
  18617. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  18618. const_reference operator[](const json_pointer& ptr) const
  18619. {
  18620. return ptr.get_unchecked(this);
  18621. }
  18622. /// @brief access specified element via JSON Pointer
  18623. /// @sa https://json.nlohmann.me/api/basic_json/at/
  18624. reference at(const json_pointer& ptr)
  18625. {
  18626. return ptr.get_checked(this);
  18627. }
  18628. /// @brief access specified element via JSON Pointer
  18629. /// @sa https://json.nlohmann.me/api/basic_json/at/
  18630. const_reference at(const json_pointer& ptr) const
  18631. {
  18632. return ptr.get_checked(this);
  18633. }
  18634. /// @brief return flattened JSON value
  18635. /// @sa https://json.nlohmann.me/api/basic_json/flatten/
  18636. basic_json flatten() const
  18637. {
  18638. basic_json result(value_t::object);
  18639. json_pointer::flatten("", *this, result);
  18640. return result;
  18641. }
  18642. /// @brief unflatten a previously flattened JSON value
  18643. /// @sa https://json.nlohmann.me/api/basic_json/unflatten/
  18644. basic_json unflatten() const
  18645. {
  18646. return json_pointer::unflatten(*this);
  18647. }
  18648. /// @}
  18649. //////////////////////////
  18650. // JSON Patch functions //
  18651. //////////////////////////
  18652. /// @name JSON Patch functions
  18653. /// @{
  18654. /// @brief applies a JSON patch
  18655. /// @sa https://json.nlohmann.me/api/basic_json/patch/
  18656. basic_json patch(const basic_json& json_patch) const
  18657. {
  18658. // make a working copy to apply the patch to
  18659. basic_json result = *this;
  18660. // the valid JSON Patch operations
  18661. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  18662. const auto get_op = [](const std::string & op)
  18663. {
  18664. if (op == "add")
  18665. {
  18666. return patch_operations::add;
  18667. }
  18668. if (op == "remove")
  18669. {
  18670. return patch_operations::remove;
  18671. }
  18672. if (op == "replace")
  18673. {
  18674. return patch_operations::replace;
  18675. }
  18676. if (op == "move")
  18677. {
  18678. return patch_operations::move;
  18679. }
  18680. if (op == "copy")
  18681. {
  18682. return patch_operations::copy;
  18683. }
  18684. if (op == "test")
  18685. {
  18686. return patch_operations::test;
  18687. }
  18688. return patch_operations::invalid;
  18689. };
  18690. // wrapper for "add" operation; add value at ptr
  18691. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  18692. {
  18693. // adding to the root of the target document means replacing it
  18694. if (ptr.empty())
  18695. {
  18696. result = val;
  18697. return;
  18698. }
  18699. // make sure the top element of the pointer exists
  18700. json_pointer top_pointer = ptr.top();
  18701. if (top_pointer != ptr)
  18702. {
  18703. result.at(top_pointer);
  18704. }
  18705. // get reference to parent of JSON pointer ptr
  18706. const auto last_path = ptr.back();
  18707. ptr.pop_back();
  18708. basic_json& parent = result[ptr];
  18709. switch (parent.m_type)
  18710. {
  18711. case value_t::null:
  18712. case value_t::object:
  18713. {
  18714. // use operator[] to add value
  18715. parent[last_path] = val;
  18716. break;
  18717. }
  18718. case value_t::array:
  18719. {
  18720. if (last_path == "-")
  18721. {
  18722. // special case: append to back
  18723. parent.push_back(val);
  18724. }
  18725. else
  18726. {
  18727. const auto idx = json_pointer::array_index(last_path);
  18728. if (JSON_HEDLEY_UNLIKELY(idx > parent.size()))
  18729. {
  18730. // avoid undefined behavior
  18731. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", parent));
  18732. }
  18733. // default case: insert add offset
  18734. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  18735. }
  18736. break;
  18737. }
  18738. // if there exists a parent it cannot be primitive
  18739. case value_t::string: // LCOV_EXCL_LINE
  18740. case value_t::boolean: // LCOV_EXCL_LINE
  18741. case value_t::number_integer: // LCOV_EXCL_LINE
  18742. case value_t::number_unsigned: // LCOV_EXCL_LINE
  18743. case value_t::number_float: // LCOV_EXCL_LINE
  18744. case value_t::binary: // LCOV_EXCL_LINE
  18745. case value_t::discarded: // LCOV_EXCL_LINE
  18746. default: // LCOV_EXCL_LINE
  18747. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  18748. }
  18749. };
  18750. // wrapper for "remove" operation; remove value at ptr
  18751. const auto operation_remove = [this, &result](json_pointer & ptr)
  18752. {
  18753. // get reference to parent of JSON pointer ptr
  18754. const auto last_path = ptr.back();
  18755. ptr.pop_back();
  18756. basic_json& parent = result.at(ptr);
  18757. // remove child
  18758. if (parent.is_object())
  18759. {
  18760. // perform range check
  18761. auto it = parent.find(last_path);
  18762. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  18763. {
  18764. parent.erase(it);
  18765. }
  18766. else
  18767. {
  18768. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found", *this));
  18769. }
  18770. }
  18771. else if (parent.is_array())
  18772. {
  18773. // note erase performs range check
  18774. parent.erase(json_pointer::array_index(last_path));
  18775. }
  18776. };
  18777. // type check: top level value must be an array
  18778. if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array()))
  18779. {
  18780. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", json_patch));
  18781. }
  18782. // iterate and apply the operations
  18783. for (const auto& val : json_patch)
  18784. {
  18785. // wrapper to get a value for an operation
  18786. const auto get_value = [&val](const std::string & op,
  18787. const std::string & member,
  18788. bool string_type) -> basic_json &
  18789. {
  18790. // find value
  18791. auto it = val.m_value.object->find(member);
  18792. // context-sensitive error message
  18793. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  18794. // check if desired value is present
  18795. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  18796. {
  18797. // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
  18798. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'", val));
  18799. }
  18800. // check if result is of type string
  18801. if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string()))
  18802. {
  18803. // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
  18804. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'", val));
  18805. }
  18806. // no error: return value
  18807. return it->second;
  18808. };
  18809. // type check: every element of the array must be an object
  18810. if (JSON_HEDLEY_UNLIKELY(!val.is_object()))
  18811. {
  18812. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", val));
  18813. }
  18814. // collect mandatory members
  18815. const auto op = get_value("op", "op", true).template get<std::string>();
  18816. const auto path = get_value(op, "path", true).template get<std::string>();
  18817. json_pointer ptr(path);
  18818. switch (get_op(op))
  18819. {
  18820. case patch_operations::add:
  18821. {
  18822. operation_add(ptr, get_value("add", "value", false));
  18823. break;
  18824. }
  18825. case patch_operations::remove:
  18826. {
  18827. operation_remove(ptr);
  18828. break;
  18829. }
  18830. case patch_operations::replace:
  18831. {
  18832. // the "path" location must exist - use at()
  18833. result.at(ptr) = get_value("replace", "value", false);
  18834. break;
  18835. }
  18836. case patch_operations::move:
  18837. {
  18838. const auto from_path = get_value("move", "from", true).template get<std::string>();
  18839. json_pointer from_ptr(from_path);
  18840. // the "from" location must exist - use at()
  18841. basic_json v = result.at(from_ptr);
  18842. // The move operation is functionally identical to a
  18843. // "remove" operation on the "from" location, followed
  18844. // immediately by an "add" operation at the target
  18845. // location with the value that was just removed.
  18846. operation_remove(from_ptr);
  18847. operation_add(ptr, v);
  18848. break;
  18849. }
  18850. case patch_operations::copy:
  18851. {
  18852. const auto from_path = get_value("copy", "from", true).template get<std::string>();
  18853. const json_pointer from_ptr(from_path);
  18854. // the "from" location must exist - use at()
  18855. basic_json v = result.at(from_ptr);
  18856. // The copy is functionally identical to an "add"
  18857. // operation at the target location using the value
  18858. // specified in the "from" member.
  18859. operation_add(ptr, v);
  18860. break;
  18861. }
  18862. case patch_operations::test:
  18863. {
  18864. bool success = false;
  18865. JSON_TRY
  18866. {
  18867. // check if "value" matches the one at "path"
  18868. // the "path" location must exist - use at()
  18869. success = (result.at(ptr) == get_value("test", "value", false));
  18870. }
  18871. JSON_INTERNAL_CATCH (out_of_range&)
  18872. {
  18873. // ignore out of range errors: success remains false
  18874. }
  18875. // throw an exception if test fails
  18876. if (JSON_HEDLEY_UNLIKELY(!success))
  18877. {
  18878. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump(), val));
  18879. }
  18880. break;
  18881. }
  18882. case patch_operations::invalid:
  18883. default:
  18884. {
  18885. // op must be "add", "remove", "replace", "move", "copy", or
  18886. // "test"
  18887. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid", val));
  18888. }
  18889. }
  18890. }
  18891. return result;
  18892. }
  18893. /// @brief creates a diff as a JSON patch
  18894. /// @sa https://json.nlohmann.me/api/basic_json/diff/
  18895. JSON_HEDLEY_WARN_UNUSED_RESULT
  18896. static basic_json diff(const basic_json& source, const basic_json& target,
  18897. const std::string& path = "")
  18898. {
  18899. // the patch
  18900. basic_json result(value_t::array);
  18901. // if the values are the same, return empty patch
  18902. if (source == target)
  18903. {
  18904. return result;
  18905. }
  18906. if (source.type() != target.type())
  18907. {
  18908. // different types: replace value
  18909. result.push_back(
  18910. {
  18911. {"op", "replace"}, {"path", path}, {"value", target}
  18912. });
  18913. return result;
  18914. }
  18915. switch (source.type())
  18916. {
  18917. case value_t::array:
  18918. {
  18919. // first pass: traverse common elements
  18920. std::size_t i = 0;
  18921. while (i < source.size() && i < target.size())
  18922. {
  18923. // recursive call to compare array values at index i
  18924. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  18925. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  18926. ++i;
  18927. }
  18928. // We now reached the end of at least one array
  18929. // in a second pass, traverse the remaining elements
  18930. // remove my remaining elements
  18931. const auto end_index = static_cast<difference_type>(result.size());
  18932. while (i < source.size())
  18933. {
  18934. // add operations in reverse order to avoid invalid
  18935. // indices
  18936. result.insert(result.begin() + end_index, object(
  18937. {
  18938. {"op", "remove"},
  18939. {"path", path + "/" + std::to_string(i)}
  18940. }));
  18941. ++i;
  18942. }
  18943. // add other remaining elements
  18944. while (i < target.size())
  18945. {
  18946. result.push_back(
  18947. {
  18948. {"op", "add"},
  18949. {"path", path + "/-"},
  18950. {"value", target[i]}
  18951. });
  18952. ++i;
  18953. }
  18954. break;
  18955. }
  18956. case value_t::object:
  18957. {
  18958. // first pass: traverse this object's elements
  18959. for (auto it = source.cbegin(); it != source.cend(); ++it)
  18960. {
  18961. // escape the key name to be used in a JSON patch
  18962. const auto path_key = path + "/" + detail::escape(it.key());
  18963. if (target.find(it.key()) != target.end())
  18964. {
  18965. // recursive call to compare object values at key it
  18966. auto temp_diff = diff(it.value(), target[it.key()], path_key);
  18967. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  18968. }
  18969. else
  18970. {
  18971. // found a key that is not in o -> remove it
  18972. result.push_back(object(
  18973. {
  18974. {"op", "remove"}, {"path", path_key}
  18975. }));
  18976. }
  18977. }
  18978. // second pass: traverse other object's elements
  18979. for (auto it = target.cbegin(); it != target.cend(); ++it)
  18980. {
  18981. if (source.find(it.key()) == source.end())
  18982. {
  18983. // found a key that is not in this -> add it
  18984. const auto path_key = path + "/" + detail::escape(it.key());
  18985. result.push_back(
  18986. {
  18987. {"op", "add"}, {"path", path_key},
  18988. {"value", it.value()}
  18989. });
  18990. }
  18991. }
  18992. break;
  18993. }
  18994. case value_t::null:
  18995. case value_t::string:
  18996. case value_t::boolean:
  18997. case value_t::number_integer:
  18998. case value_t::number_unsigned:
  18999. case value_t::number_float:
  19000. case value_t::binary:
  19001. case value_t::discarded:
  19002. default:
  19003. {
  19004. // both primitive type: replace value
  19005. result.push_back(
  19006. {
  19007. {"op", "replace"}, {"path", path}, {"value", target}
  19008. });
  19009. break;
  19010. }
  19011. }
  19012. return result;
  19013. }
  19014. /// @}
  19015. ////////////////////////////////
  19016. // JSON Merge Patch functions //
  19017. ////////////////////////////////
  19018. /// @name JSON Merge Patch functions
  19019. /// @{
  19020. /// @brief applies a JSON Merge Patch
  19021. /// @sa https://json.nlohmann.me/api/basic_json/merge_patch/
  19022. void merge_patch(const basic_json& apply_patch)
  19023. {
  19024. if (apply_patch.is_object())
  19025. {
  19026. if (!is_object())
  19027. {
  19028. *this = object();
  19029. }
  19030. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  19031. {
  19032. if (it.value().is_null())
  19033. {
  19034. erase(it.key());
  19035. }
  19036. else
  19037. {
  19038. operator[](it.key()).merge_patch(it.value());
  19039. }
  19040. }
  19041. }
  19042. else
  19043. {
  19044. *this = apply_patch;
  19045. }
  19046. }
  19047. /// @}
  19048. };
  19049. /// @brief user-defined to_string function for JSON values
  19050. /// @sa https://json.nlohmann.me/api/basic_json/to_string/
  19051. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  19052. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  19053. {
  19054. return j.dump();
  19055. }
  19056. } // namespace nlohmann
  19057. ///////////////////////
  19058. // nonmember support //
  19059. ///////////////////////
  19060. namespace std // NOLINT(cert-dcl58-cpp)
  19061. {
  19062. /// @brief hash value for JSON objects
  19063. /// @sa https://json.nlohmann.me/api/basic_json/std_hash/
  19064. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  19065. struct hash<nlohmann::NLOHMANN_BASIC_JSON_TPL>
  19066. {
  19067. std::size_t operator()(const nlohmann::NLOHMANN_BASIC_JSON_TPL& j) const
  19068. {
  19069. return nlohmann::detail::hash(j);
  19070. }
  19071. };
  19072. // specialization for std::less<value_t>
  19073. template<>
  19074. struct less< ::nlohmann::detail::value_t> // do not remove the space after '<', see https://github.com/nlohmann/json/pull/679
  19075. {
  19076. /*!
  19077. @brief compare two value_t enum values
  19078. @since version 3.0.0
  19079. */
  19080. bool operator()(nlohmann::detail::value_t lhs,
  19081. nlohmann::detail::value_t rhs) const noexcept
  19082. {
  19083. return nlohmann::detail::operator<(lhs, rhs);
  19084. }
  19085. };
  19086. // C++20 prohibit function specialization in the std namespace.
  19087. #ifndef JSON_HAS_CPP_20
  19088. /// @brief exchanges the values of two JSON objects
  19089. /// @sa https://json.nlohmann.me/api/basic_json/std_swap/
  19090. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  19091. inline void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL& j1, nlohmann::NLOHMANN_BASIC_JSON_TPL& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name)
  19092. is_nothrow_move_constructible<nlohmann::NLOHMANN_BASIC_JSON_TPL>::value&& // NOLINT(misc-redundant-expression)
  19093. is_nothrow_move_assignable<nlohmann::NLOHMANN_BASIC_JSON_TPL>::value)
  19094. {
  19095. j1.swap(j2);
  19096. }
  19097. #endif
  19098. } // namespace std
  19099. /// @brief user-defined string literal for JSON values
  19100. /// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json/
  19101. JSON_HEDLEY_NON_NULL(1)
  19102. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  19103. {
  19104. return nlohmann::json::parse(s, s + n);
  19105. }
  19106. /// @brief user-defined string literal for JSON pointer
  19107. /// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json_pointer/
  19108. JSON_HEDLEY_NON_NULL(1)
  19109. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  19110. {
  19111. return nlohmann::json::json_pointer(std::string(s, n));
  19112. }
  19113. // #include <nlohmann/detail/macro_unscope.hpp>
  19114. // restore clang diagnostic settings
  19115. #if defined(__clang__)
  19116. #pragma clang diagnostic pop
  19117. #endif
  19118. // clean up
  19119. #undef JSON_ASSERT
  19120. #undef JSON_INTERNAL_CATCH
  19121. #undef JSON_CATCH
  19122. #undef JSON_THROW
  19123. #undef JSON_TRY
  19124. #undef JSON_PRIVATE_UNLESS_TESTED
  19125. #undef JSON_HAS_CPP_11
  19126. #undef JSON_HAS_CPP_14
  19127. #undef JSON_HAS_CPP_17
  19128. #undef JSON_HAS_CPP_20
  19129. #undef JSON_HAS_FILESYSTEM
  19130. #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
  19131. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  19132. #undef NLOHMANN_BASIC_JSON_TPL
  19133. #undef JSON_EXPLICIT
  19134. #undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL
  19135. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  19136. #undef JSON_HEDLEY_ALWAYS_INLINE
  19137. #undef JSON_HEDLEY_ARM_VERSION
  19138. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  19139. #undef JSON_HEDLEY_ARRAY_PARAM
  19140. #undef JSON_HEDLEY_ASSUME
  19141. #undef JSON_HEDLEY_BEGIN_C_DECLS
  19142. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  19143. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  19144. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  19145. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  19146. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  19147. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  19148. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  19149. #undef JSON_HEDLEY_COMPCERT_VERSION
  19150. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  19151. #undef JSON_HEDLEY_CONCAT
  19152. #undef JSON_HEDLEY_CONCAT3
  19153. #undef JSON_HEDLEY_CONCAT3_EX
  19154. #undef JSON_HEDLEY_CONCAT_EX
  19155. #undef JSON_HEDLEY_CONST
  19156. #undef JSON_HEDLEY_CONSTEXPR
  19157. #undef JSON_HEDLEY_CONST_CAST
  19158. #undef JSON_HEDLEY_CPP_CAST
  19159. #undef JSON_HEDLEY_CRAY_VERSION
  19160. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  19161. #undef JSON_HEDLEY_C_DECL
  19162. #undef JSON_HEDLEY_DEPRECATED
  19163. #undef JSON_HEDLEY_DEPRECATED_FOR
  19164. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  19165. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  19166. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  19167. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  19168. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  19169. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
  19170. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  19171. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  19172. #undef JSON_HEDLEY_DMC_VERSION
  19173. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  19174. #undef JSON_HEDLEY_EMPTY_BASES
  19175. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  19176. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  19177. #undef JSON_HEDLEY_END_C_DECLS
  19178. #undef JSON_HEDLEY_FLAGS
  19179. #undef JSON_HEDLEY_FLAGS_CAST
  19180. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  19181. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  19182. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  19183. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  19184. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  19185. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  19186. #undef JSON_HEDLEY_GCC_HAS_WARNING
  19187. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  19188. #undef JSON_HEDLEY_GCC_VERSION
  19189. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  19190. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  19191. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  19192. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  19193. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  19194. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  19195. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  19196. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  19197. #undef JSON_HEDLEY_GNUC_VERSION
  19198. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  19199. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  19200. #undef JSON_HEDLEY_HAS_BUILTIN
  19201. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  19202. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  19203. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  19204. #undef JSON_HEDLEY_HAS_EXTENSION
  19205. #undef JSON_HEDLEY_HAS_FEATURE
  19206. #undef JSON_HEDLEY_HAS_WARNING
  19207. #undef JSON_HEDLEY_IAR_VERSION
  19208. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  19209. #undef JSON_HEDLEY_IBM_VERSION
  19210. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  19211. #undef JSON_HEDLEY_IMPORT
  19212. #undef JSON_HEDLEY_INLINE
  19213. #undef JSON_HEDLEY_INTEL_CL_VERSION
  19214. #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK
  19215. #undef JSON_HEDLEY_INTEL_VERSION
  19216. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  19217. #undef JSON_HEDLEY_IS_CONSTANT
  19218. #undef JSON_HEDLEY_IS_CONSTEXPR_
  19219. #undef JSON_HEDLEY_LIKELY
  19220. #undef JSON_HEDLEY_MALLOC
  19221. #undef JSON_HEDLEY_MCST_LCC_VERSION
  19222. #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK
  19223. #undef JSON_HEDLEY_MESSAGE
  19224. #undef JSON_HEDLEY_MSVC_VERSION
  19225. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  19226. #undef JSON_HEDLEY_NEVER_INLINE
  19227. #undef JSON_HEDLEY_NON_NULL
  19228. #undef JSON_HEDLEY_NO_ESCAPE
  19229. #undef JSON_HEDLEY_NO_RETURN
  19230. #undef JSON_HEDLEY_NO_THROW
  19231. #undef JSON_HEDLEY_NULL
  19232. #undef JSON_HEDLEY_PELLES_VERSION
  19233. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  19234. #undef JSON_HEDLEY_PGI_VERSION
  19235. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  19236. #undef JSON_HEDLEY_PREDICT
  19237. #undef JSON_HEDLEY_PRINTF_FORMAT
  19238. #undef JSON_HEDLEY_PRIVATE
  19239. #undef JSON_HEDLEY_PUBLIC
  19240. #undef JSON_HEDLEY_PURE
  19241. #undef JSON_HEDLEY_REINTERPRET_CAST
  19242. #undef JSON_HEDLEY_REQUIRE
  19243. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  19244. #undef JSON_HEDLEY_REQUIRE_MSG
  19245. #undef JSON_HEDLEY_RESTRICT
  19246. #undef JSON_HEDLEY_RETURNS_NON_NULL
  19247. #undef JSON_HEDLEY_SENTINEL
  19248. #undef JSON_HEDLEY_STATIC_ASSERT
  19249. #undef JSON_HEDLEY_STATIC_CAST
  19250. #undef JSON_HEDLEY_STRINGIFY
  19251. #undef JSON_HEDLEY_STRINGIFY_EX
  19252. #undef JSON_HEDLEY_SUNPRO_VERSION
  19253. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  19254. #undef JSON_HEDLEY_TINYC_VERSION
  19255. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  19256. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  19257. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  19258. #undef JSON_HEDLEY_TI_CL2000_VERSION
  19259. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  19260. #undef JSON_HEDLEY_TI_CL430_VERSION
  19261. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  19262. #undef JSON_HEDLEY_TI_CL6X_VERSION
  19263. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  19264. #undef JSON_HEDLEY_TI_CL7X_VERSION
  19265. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  19266. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  19267. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  19268. #undef JSON_HEDLEY_TI_VERSION
  19269. #undef JSON_HEDLEY_TI_VERSION_CHECK
  19270. #undef JSON_HEDLEY_UNAVAILABLE
  19271. #undef JSON_HEDLEY_UNLIKELY
  19272. #undef JSON_HEDLEY_UNPREDICTABLE
  19273. #undef JSON_HEDLEY_UNREACHABLE
  19274. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  19275. #undef JSON_HEDLEY_VERSION
  19276. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  19277. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  19278. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  19279. #undef JSON_HEDLEY_VERSION_ENCODE
  19280. #undef JSON_HEDLEY_WARNING
  19281. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  19282. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  19283. #undef JSON_HEDLEY_FALL_THROUGH
  19284. #endif // INCLUDE_NLOHMANN_JSON_HPP_