🛠️🐜 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.

26647 lines
956 KiB

  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.10.2
  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-2019 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. #ifndef INCLUDE_NLOHMANN_JSON_HPP_
  26. #define INCLUDE_NLOHMANN_JSON_HPP_
  27. #define NLOHMANN_JSON_VERSION_MAJOR 3
  28. #define NLOHMANN_JSON_VERSION_MINOR 10
  29. #define NLOHMANN_JSON_VERSION_PATCH 2
  30. #include <algorithm> // all_of, find, for_each
  31. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  32. #include <functional> // hash, less
  33. #include <initializer_list> // initializer_list
  34. #ifndef JSON_NO_IO
  35. #include <iosfwd> // istream, ostream
  36. #endif // JSON_NO_IO
  37. #include <iterator> // random_access_iterator_tag
  38. #include <memory> // unique_ptr
  39. #include <numeric> // accumulate
  40. #include <string> // string, stoi, to_string
  41. #include <utility> // declval, forward, move, pair, swap
  42. #include <vector> // vector
  43. // #include <nlohmann/adl_serializer.hpp>
  44. #include <type_traits>
  45. #include <utility>
  46. // #include <nlohmann/detail/conversions/from_json.hpp>
  47. #include <algorithm> // transform
  48. #include <array> // array
  49. #include <forward_list> // forward_list
  50. #include <iterator> // inserter, front_inserter, end
  51. #include <map> // map
  52. #include <string> // string
  53. #include <tuple> // tuple, make_tuple
  54. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  55. #include <unordered_map> // unordered_map
  56. #include <utility> // pair, declval
  57. #include <valarray> // valarray
  58. // #include <nlohmann/detail/exceptions.hpp>
  59. #include <exception> // exception
  60. #include <stdexcept> // runtime_error
  61. #include <string> // to_string
  62. #include <vector> // vector
  63. // #include <nlohmann/detail/value_t.hpp>
  64. #include <array> // array
  65. #include <cstddef> // size_t
  66. #include <cstdint> // uint8_t
  67. #include <string> // string
  68. namespace nlohmann
  69. {
  70. namespace detail
  71. {
  72. ///////////////////////////
  73. // JSON type enumeration //
  74. ///////////////////////////
  75. /*!
  76. @brief the JSON type enumeration
  77. This enumeration collects the different JSON types. It is internally used to
  78. distinguish the stored values, and the functions @ref basic_json::is_null(),
  79. @ref basic_json::is_object(), @ref basic_json::is_array(),
  80. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  81. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  82. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  83. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  84. @ref basic_json::is_structured() rely on it.
  85. @note There are three enumeration entries (number_integer, number_unsigned, and
  86. number_float), because the library distinguishes these three types for numbers:
  87. @ref basic_json::number_unsigned_t is used for unsigned integers,
  88. @ref basic_json::number_integer_t is used for signed integers, and
  89. @ref basic_json::number_float_t is used for floating-point numbers or to
  90. approximate integers which do not fit in the limits of their respective type.
  91. @sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  92. value with the default value for a given type
  93. @since version 1.0.0
  94. */
  95. enum class value_t : std::uint8_t
  96. {
  97. null, ///< null value
  98. object, ///< object (unordered set of name/value pairs)
  99. array, ///< array (ordered collection of values)
  100. string, ///< string value
  101. boolean, ///< boolean value
  102. number_integer, ///< number value (signed integer)
  103. number_unsigned, ///< number value (unsigned integer)
  104. number_float, ///< number value (floating-point)
  105. binary, ///< binary array (ordered collection of bytes)
  106. discarded ///< discarded by the parser callback function
  107. };
  108. /*!
  109. @brief comparison operator for JSON types
  110. Returns an ordering that is similar to Python:
  111. - order: null < boolean < number < object < array < string < binary
  112. - furthermore, each type is not smaller than itself
  113. - discarded values are not comparable
  114. - binary is represented as a b"" string in python and directly comparable to a
  115. string; however, making a binary array directly comparable with a string would
  116. be surprising behavior in a JSON file.
  117. @since version 1.0.0
  118. */
  119. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  120. {
  121. static constexpr std::array<std::uint8_t, 9> order = {{
  122. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  123. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */,
  124. 6 /* binary */
  125. }
  126. };
  127. const auto l_index = static_cast<std::size_t>(lhs);
  128. const auto r_index = static_cast<std::size_t>(rhs);
  129. return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index];
  130. }
  131. } // namespace detail
  132. } // namespace nlohmann
  133. // #include <nlohmann/detail/string_escape.hpp>
  134. #include <string>
  135. // #include <nlohmann/detail/macro_scope.hpp>
  136. #include <utility> // pair
  137. // #include <nlohmann/thirdparty/hedley/hedley.hpp>
  138. /* Hedley - https://nemequ.github.io/hedley
  139. * Created by Evan Nemerson <evan@nemerson.com>
  140. *
  141. * To the extent possible under law, the author(s) have dedicated all
  142. * copyright and related and neighboring rights to this software to
  143. * the public domain worldwide. This software is distributed without
  144. * any warranty.
  145. *
  146. * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
  147. * SPDX-License-Identifier: CC0-1.0
  148. */
  149. #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15)
  150. #if defined(JSON_HEDLEY_VERSION)
  151. #undef JSON_HEDLEY_VERSION
  152. #endif
  153. #define JSON_HEDLEY_VERSION 15
  154. #if defined(JSON_HEDLEY_STRINGIFY_EX)
  155. #undef JSON_HEDLEY_STRINGIFY_EX
  156. #endif
  157. #define JSON_HEDLEY_STRINGIFY_EX(x) #x
  158. #if defined(JSON_HEDLEY_STRINGIFY)
  159. #undef JSON_HEDLEY_STRINGIFY
  160. #endif
  161. #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
  162. #if defined(JSON_HEDLEY_CONCAT_EX)
  163. #undef JSON_HEDLEY_CONCAT_EX
  164. #endif
  165. #define JSON_HEDLEY_CONCAT_EX(a,b) a##b
  166. #if defined(JSON_HEDLEY_CONCAT)
  167. #undef JSON_HEDLEY_CONCAT
  168. #endif
  169. #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b)
  170. #if defined(JSON_HEDLEY_CONCAT3_EX)
  171. #undef JSON_HEDLEY_CONCAT3_EX
  172. #endif
  173. #define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c
  174. #if defined(JSON_HEDLEY_CONCAT3)
  175. #undef JSON_HEDLEY_CONCAT3
  176. #endif
  177. #define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c)
  178. #if defined(JSON_HEDLEY_VERSION_ENCODE)
  179. #undef JSON_HEDLEY_VERSION_ENCODE
  180. #endif
  181. #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
  182. #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
  183. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  184. #endif
  185. #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
  186. #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
  187. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  188. #endif
  189. #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
  190. #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
  191. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  192. #endif
  193. #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
  194. #if defined(JSON_HEDLEY_GNUC_VERSION)
  195. #undef JSON_HEDLEY_GNUC_VERSION
  196. #endif
  197. #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
  198. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
  199. #elif defined(__GNUC__)
  200. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
  201. #endif
  202. #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
  203. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  204. #endif
  205. #if defined(JSON_HEDLEY_GNUC_VERSION)
  206. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  207. #else
  208. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
  209. #endif
  210. #if defined(JSON_HEDLEY_MSVC_VERSION)
  211. #undef JSON_HEDLEY_MSVC_VERSION
  212. #endif
  213. #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL)
  214. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
  215. #elif defined(_MSC_FULL_VER) && !defined(__ICL)
  216. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
  217. #elif defined(_MSC_VER) && !defined(__ICL)
  218. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
  219. #endif
  220. #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
  221. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  222. #endif
  223. #if !defined(JSON_HEDLEY_MSVC_VERSION)
  224. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
  225. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  226. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
  227. #elif defined(_MSC_VER) && (_MSC_VER >= 1200)
  228. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
  229. #else
  230. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
  231. #endif
  232. #if defined(JSON_HEDLEY_INTEL_VERSION)
  233. #undef JSON_HEDLEY_INTEL_VERSION
  234. #endif
  235. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL)
  236. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
  237. #elif defined(__INTEL_COMPILER) && !defined(__ICL)
  238. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
  239. #endif
  240. #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
  241. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  242. #endif
  243. #if defined(JSON_HEDLEY_INTEL_VERSION)
  244. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  245. #else
  246. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
  247. #endif
  248. #if defined(JSON_HEDLEY_INTEL_CL_VERSION)
  249. #undef JSON_HEDLEY_INTEL_CL_VERSION
  250. #endif
  251. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL)
  252. #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0)
  253. #endif
  254. #if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK)
  255. #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK
  256. #endif
  257. #if defined(JSON_HEDLEY_INTEL_CL_VERSION)
  258. #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  259. #else
  260. #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0)
  261. #endif
  262. #if defined(JSON_HEDLEY_PGI_VERSION)
  263. #undef JSON_HEDLEY_PGI_VERSION
  264. #endif
  265. #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
  266. #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
  267. #endif
  268. #if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
  269. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  270. #endif
  271. #if defined(JSON_HEDLEY_PGI_VERSION)
  272. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  273. #else
  274. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
  275. #endif
  276. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  277. #undef JSON_HEDLEY_SUNPRO_VERSION
  278. #endif
  279. #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
  280. #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)
  281. #elif defined(__SUNPRO_C)
  282. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
  283. #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
  284. #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)
  285. #elif defined(__SUNPRO_CC)
  286. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
  287. #endif
  288. #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
  289. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  290. #endif
  291. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  292. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  293. #else
  294. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
  295. #endif
  296. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  297. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  298. #endif
  299. #if defined(__EMSCRIPTEN__)
  300. #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
  301. #endif
  302. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
  303. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  304. #endif
  305. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  306. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  307. #else
  308. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
  309. #endif
  310. #if defined(JSON_HEDLEY_ARM_VERSION)
  311. #undef JSON_HEDLEY_ARM_VERSION
  312. #endif
  313. #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
  314. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
  315. #elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
  316. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
  317. #endif
  318. #if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
  319. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  320. #endif
  321. #if defined(JSON_HEDLEY_ARM_VERSION)
  322. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  323. #else
  324. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
  325. #endif
  326. #if defined(JSON_HEDLEY_IBM_VERSION)
  327. #undef JSON_HEDLEY_IBM_VERSION
  328. #endif
  329. #if defined(__ibmxl__)
  330. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
  331. #elif defined(__xlC__) && defined(__xlC_ver__)
  332. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
  333. #elif defined(__xlC__)
  334. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
  335. #endif
  336. #if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
  337. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  338. #endif
  339. #if defined(JSON_HEDLEY_IBM_VERSION)
  340. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  341. #else
  342. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
  343. #endif
  344. #if defined(JSON_HEDLEY_TI_VERSION)
  345. #undef JSON_HEDLEY_TI_VERSION
  346. #endif
  347. #if \
  348. defined(__TI_COMPILER_VERSION__) && \
  349. ( \
  350. defined(__TMS470__) || defined(__TI_ARM__) || \
  351. defined(__MSP430__) || \
  352. defined(__TMS320C2000__) \
  353. )
  354. #if (__TI_COMPILER_VERSION__ >= 16000000)
  355. #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  356. #endif
  357. #endif
  358. #if defined(JSON_HEDLEY_TI_VERSION_CHECK)
  359. #undef JSON_HEDLEY_TI_VERSION_CHECK
  360. #endif
  361. #if defined(JSON_HEDLEY_TI_VERSION)
  362. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  363. #else
  364. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
  365. #endif
  366. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  367. #undef JSON_HEDLEY_TI_CL2000_VERSION
  368. #endif
  369. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__)
  370. #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  371. #endif
  372. #if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK)
  373. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  374. #endif
  375. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  376. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  377. #else
  378. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0)
  379. #endif
  380. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  381. #undef JSON_HEDLEY_TI_CL430_VERSION
  382. #endif
  383. #if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__)
  384. #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  385. #endif
  386. #if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK)
  387. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  388. #endif
  389. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  390. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  391. #else
  392. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0)
  393. #endif
  394. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  395. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  396. #endif
  397. #if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__))
  398. #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  399. #endif
  400. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK)
  401. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  402. #endif
  403. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  404. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  405. #else
  406. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0)
  407. #endif
  408. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  409. #undef JSON_HEDLEY_TI_CL6X_VERSION
  410. #endif
  411. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__)
  412. #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  413. #endif
  414. #if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK)
  415. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  416. #endif
  417. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  418. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  419. #else
  420. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0)
  421. #endif
  422. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  423. #undef JSON_HEDLEY_TI_CL7X_VERSION
  424. #endif
  425. #if defined(__TI_COMPILER_VERSION__) && defined(__C7000__)
  426. #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  427. #endif
  428. #if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK)
  429. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  430. #endif
  431. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  432. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  433. #else
  434. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0)
  435. #endif
  436. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  437. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  438. #endif
  439. #if defined(__TI_COMPILER_VERSION__) && defined(__PRU__)
  440. #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  441. #endif
  442. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK)
  443. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  444. #endif
  445. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  446. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  447. #else
  448. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0)
  449. #endif
  450. #if defined(JSON_HEDLEY_CRAY_VERSION)
  451. #undef JSON_HEDLEY_CRAY_VERSION
  452. #endif
  453. #if defined(_CRAYC)
  454. #if defined(_RELEASE_PATCHLEVEL)
  455. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
  456. #else
  457. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
  458. #endif
  459. #endif
  460. #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
  461. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  462. #endif
  463. #if defined(JSON_HEDLEY_CRAY_VERSION)
  464. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  465. #else
  466. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
  467. #endif
  468. #if defined(JSON_HEDLEY_IAR_VERSION)
  469. #undef JSON_HEDLEY_IAR_VERSION
  470. #endif
  471. #if defined(__IAR_SYSTEMS_ICC__)
  472. #if __VER__ > 1000
  473. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
  474. #else
  475. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0)
  476. #endif
  477. #endif
  478. #if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
  479. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  480. #endif
  481. #if defined(JSON_HEDLEY_IAR_VERSION)
  482. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  483. #else
  484. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
  485. #endif
  486. #if defined(JSON_HEDLEY_TINYC_VERSION)
  487. #undef JSON_HEDLEY_TINYC_VERSION
  488. #endif
  489. #if defined(__TINYC__)
  490. #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
  491. #endif
  492. #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
  493. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  494. #endif
  495. #if defined(JSON_HEDLEY_TINYC_VERSION)
  496. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  497. #else
  498. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
  499. #endif
  500. #if defined(JSON_HEDLEY_DMC_VERSION)
  501. #undef JSON_HEDLEY_DMC_VERSION
  502. #endif
  503. #if defined(__DMC__)
  504. #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
  505. #endif
  506. #if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
  507. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  508. #endif
  509. #if defined(JSON_HEDLEY_DMC_VERSION)
  510. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  511. #else
  512. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
  513. #endif
  514. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  515. #undef JSON_HEDLEY_COMPCERT_VERSION
  516. #endif
  517. #if defined(__COMPCERT_VERSION__)
  518. #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
  519. #endif
  520. #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
  521. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  522. #endif
  523. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  524. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  525. #else
  526. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
  527. #endif
  528. #if defined(JSON_HEDLEY_PELLES_VERSION)
  529. #undef JSON_HEDLEY_PELLES_VERSION
  530. #endif
  531. #if defined(__POCC__)
  532. #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
  533. #endif
  534. #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
  535. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  536. #endif
  537. #if defined(JSON_HEDLEY_PELLES_VERSION)
  538. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  539. #else
  540. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
  541. #endif
  542. #if defined(JSON_HEDLEY_MCST_LCC_VERSION)
  543. #undef JSON_HEDLEY_MCST_LCC_VERSION
  544. #endif
  545. #if defined(__LCC__) && defined(__LCC_MINOR__)
  546. #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__)
  547. #endif
  548. #if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK)
  549. #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK
  550. #endif
  551. #if defined(JSON_HEDLEY_MCST_LCC_VERSION)
  552. #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  553. #else
  554. #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0)
  555. #endif
  556. #if defined(JSON_HEDLEY_GCC_VERSION)
  557. #undef JSON_HEDLEY_GCC_VERSION
  558. #endif
  559. #if \
  560. defined(JSON_HEDLEY_GNUC_VERSION) && \
  561. !defined(__clang__) && \
  562. !defined(JSON_HEDLEY_INTEL_VERSION) && \
  563. !defined(JSON_HEDLEY_PGI_VERSION) && \
  564. !defined(JSON_HEDLEY_ARM_VERSION) && \
  565. !defined(JSON_HEDLEY_CRAY_VERSION) && \
  566. !defined(JSON_HEDLEY_TI_VERSION) && \
  567. !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \
  568. !defined(JSON_HEDLEY_TI_CL430_VERSION) && \
  569. !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \
  570. !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \
  571. !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \
  572. !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \
  573. !defined(__COMPCERT__) && \
  574. !defined(JSON_HEDLEY_MCST_LCC_VERSION)
  575. #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
  576. #endif
  577. #if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
  578. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  579. #endif
  580. #if defined(JSON_HEDLEY_GCC_VERSION)
  581. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  582. #else
  583. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
  584. #endif
  585. #if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
  586. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  587. #endif
  588. #if \
  589. defined(__has_attribute) && \
  590. ( \
  591. (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \
  592. )
  593. # define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
  594. #else
  595. # define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
  596. #endif
  597. #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
  598. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  599. #endif
  600. #if defined(__has_attribute)
  601. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  602. #else
  603. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  604. #endif
  605. #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
  606. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  607. #endif
  608. #if defined(__has_attribute)
  609. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  610. #else
  611. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  612. #endif
  613. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
  614. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  615. #endif
  616. #if \
  617. defined(__has_cpp_attribute) && \
  618. defined(__cplusplus) && \
  619. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0))
  620. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
  621. #else
  622. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
  623. #endif
  624. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS)
  625. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  626. #endif
  627. #if !defined(__cplusplus) || !defined(__has_cpp_attribute)
  628. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  629. #elif \
  630. !defined(JSON_HEDLEY_PGI_VERSION) && \
  631. !defined(JSON_HEDLEY_IAR_VERSION) && \
  632. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
  633. (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0))
  634. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute)
  635. #else
  636. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  637. #endif
  638. #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
  639. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  640. #endif
  641. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  642. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  643. #else
  644. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  645. #endif
  646. #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
  647. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  648. #endif
  649. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  650. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  651. #else
  652. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  653. #endif
  654. #if defined(JSON_HEDLEY_HAS_BUILTIN)
  655. #undef JSON_HEDLEY_HAS_BUILTIN
  656. #endif
  657. #if defined(__has_builtin)
  658. #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
  659. #else
  660. #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
  661. #endif
  662. #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
  663. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  664. #endif
  665. #if defined(__has_builtin)
  666. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  667. #else
  668. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  669. #endif
  670. #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
  671. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  672. #endif
  673. #if defined(__has_builtin)
  674. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  675. #else
  676. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  677. #endif
  678. #if defined(JSON_HEDLEY_HAS_FEATURE)
  679. #undef JSON_HEDLEY_HAS_FEATURE
  680. #endif
  681. #if defined(__has_feature)
  682. #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
  683. #else
  684. #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
  685. #endif
  686. #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
  687. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  688. #endif
  689. #if defined(__has_feature)
  690. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  691. #else
  692. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  693. #endif
  694. #if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
  695. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  696. #endif
  697. #if defined(__has_feature)
  698. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  699. #else
  700. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  701. #endif
  702. #if defined(JSON_HEDLEY_HAS_EXTENSION)
  703. #undef JSON_HEDLEY_HAS_EXTENSION
  704. #endif
  705. #if defined(__has_extension)
  706. #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
  707. #else
  708. #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
  709. #endif
  710. #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
  711. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  712. #endif
  713. #if defined(__has_extension)
  714. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  715. #else
  716. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  717. #endif
  718. #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
  719. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  720. #endif
  721. #if defined(__has_extension)
  722. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  723. #else
  724. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  725. #endif
  726. #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
  727. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  728. #endif
  729. #if defined(__has_declspec_attribute)
  730. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
  731. #else
  732. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
  733. #endif
  734. #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
  735. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  736. #endif
  737. #if defined(__has_declspec_attribute)
  738. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  739. #else
  740. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  741. #endif
  742. #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
  743. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  744. #endif
  745. #if defined(__has_declspec_attribute)
  746. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  747. #else
  748. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  749. #endif
  750. #if defined(JSON_HEDLEY_HAS_WARNING)
  751. #undef JSON_HEDLEY_HAS_WARNING
  752. #endif
  753. #if defined(__has_warning)
  754. #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
  755. #else
  756. #define JSON_HEDLEY_HAS_WARNING(warning) (0)
  757. #endif
  758. #if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
  759. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  760. #endif
  761. #if defined(__has_warning)
  762. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  763. #else
  764. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  765. #endif
  766. #if defined(JSON_HEDLEY_GCC_HAS_WARNING)
  767. #undef JSON_HEDLEY_GCC_HAS_WARNING
  768. #endif
  769. #if defined(__has_warning)
  770. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  771. #else
  772. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  773. #endif
  774. #if \
  775. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  776. defined(__clang__) || \
  777. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  778. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  779. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  780. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  781. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  782. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  783. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  784. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  785. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  786. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \
  787. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  788. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  789. JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
  790. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
  791. JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
  792. (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
  793. #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
  794. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  795. #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
  796. #else
  797. #define JSON_HEDLEY_PRAGMA(value)
  798. #endif
  799. #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
  800. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  801. #endif
  802. #if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
  803. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  804. #endif
  805. #if defined(__clang__)
  806. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
  807. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
  808. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  809. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  810. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  811. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  812. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
  813. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
  814. #elif \
  815. JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \
  816. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  817. #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
  818. #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
  819. #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
  820. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
  821. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
  822. #elif \
  823. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  824. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  825. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \
  826. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  827. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  828. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  829. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
  830. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
  831. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  832. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  833. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  834. #else
  835. #define JSON_HEDLEY_DIAGNOSTIC_PUSH
  836. #define JSON_HEDLEY_DIAGNOSTIC_POP
  837. #endif
  838. /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for
  839. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  840. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  841. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  842. #endif
  843. #if defined(__cplusplus)
  844. # if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat")
  845. # if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions")
  846. # if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions")
  847. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  848. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  849. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  850. _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
  851. _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \
  852. xpr \
  853. JSON_HEDLEY_DIAGNOSTIC_POP
  854. # else
  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. xpr \
  860. JSON_HEDLEY_DIAGNOSTIC_POP
  861. # endif
  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. xpr \
  867. JSON_HEDLEY_DIAGNOSTIC_POP
  868. # endif
  869. # endif
  870. #endif
  871. #if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  872. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x
  873. #endif
  874. #if defined(JSON_HEDLEY_CONST_CAST)
  875. #undef JSON_HEDLEY_CONST_CAST
  876. #endif
  877. #if defined(__cplusplus)
  878. # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
  879. #elif \
  880. JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
  881. JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
  882. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  883. # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
  884. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  885. JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
  886. ((T) (expr)); \
  887. JSON_HEDLEY_DIAGNOSTIC_POP \
  888. }))
  889. #else
  890. # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
  891. #endif
  892. #if defined(JSON_HEDLEY_REINTERPRET_CAST)
  893. #undef JSON_HEDLEY_REINTERPRET_CAST
  894. #endif
  895. #if defined(__cplusplus)
  896. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
  897. #else
  898. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr))
  899. #endif
  900. #if defined(JSON_HEDLEY_STATIC_CAST)
  901. #undef JSON_HEDLEY_STATIC_CAST
  902. #endif
  903. #if defined(__cplusplus)
  904. #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
  905. #else
  906. #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
  907. #endif
  908. #if defined(JSON_HEDLEY_CPP_CAST)
  909. #undef JSON_HEDLEY_CPP_CAST
  910. #endif
  911. #if defined(__cplusplus)
  912. # if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast")
  913. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  914. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  915. _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \
  916. ((T) (expr)) \
  917. JSON_HEDLEY_DIAGNOSTIC_POP
  918. # elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0)
  919. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  920. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  921. _Pragma("diag_suppress=Pe137") \
  922. JSON_HEDLEY_DIAGNOSTIC_POP
  923. # else
  924. # define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr))
  925. # endif
  926. #else
  927. # define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
  928. #endif
  929. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
  930. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  931. #endif
  932. #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
  933. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
  934. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  935. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
  936. #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  937. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786))
  938. #elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0)
  939. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445")
  940. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  941. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  942. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  943. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  944. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  945. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
  946. #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  947. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  948. #elif \
  949. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  950. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  951. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  952. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  953. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  954. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  955. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  956. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  957. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  958. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  959. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  960. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
  961. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
  962. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
  963. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
  964. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
  965. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  966. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
  967. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  968. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
  969. #else
  970. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  971. #endif
  972. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
  973. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  974. #endif
  975. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  976. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
  977. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  978. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
  979. #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  980. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161))
  981. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  982. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
  983. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  984. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
  985. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  986. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
  987. #elif \
  988. JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \
  989. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  990. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  991. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0)
  992. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  993. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0)
  994. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  995. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  996. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
  997. #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  998. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161")
  999. #else
  1000. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  1001. #endif
  1002. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES)
  1003. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  1004. #endif
  1005. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes")
  1006. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"")
  1007. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  1008. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  1009. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0)
  1010. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)")
  1011. #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1012. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292))
  1013. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0)
  1014. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030))
  1015. #elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0)
  1016. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098")
  1017. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1018. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
  1019. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)
  1020. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)")
  1021. #elif \
  1022. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  1023. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  1024. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0)
  1025. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173")
  1026. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1027. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097")
  1028. #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1029. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
  1030. #else
  1031. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  1032. #endif
  1033. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
  1034. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  1035. #endif
  1036. #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
  1037. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
  1038. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1039. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
  1040. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
  1041. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
  1042. #else
  1043. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  1044. #endif
  1045. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION)
  1046. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
  1047. #endif
  1048. #if JSON_HEDLEY_HAS_WARNING("-Wunused-function")
  1049. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"")
  1050. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0)
  1051. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"")
  1052. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0)
  1053. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505))
  1054. #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1055. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142")
  1056. #else
  1057. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
  1058. #endif
  1059. #if defined(JSON_HEDLEY_DEPRECATED)
  1060. #undef JSON_HEDLEY_DEPRECATED
  1061. #endif
  1062. #if defined(JSON_HEDLEY_DEPRECATED_FOR)
  1063. #undef JSON_HEDLEY_DEPRECATED_FOR
  1064. #endif
  1065. #if \
  1066. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1067. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1068. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
  1069. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
  1070. #elif \
  1071. (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1072. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  1073. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1074. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  1075. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
  1076. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1077. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  1078. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \
  1079. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  1080. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1081. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \
  1082. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1083. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
  1084. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
  1085. #elif defined(__cplusplus) && (__cplusplus >= 201402L)
  1086. #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]])
  1087. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]])
  1088. #elif \
  1089. JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
  1090. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1091. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1092. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1093. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1094. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1095. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1096. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1097. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1098. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1099. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1100. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1101. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1102. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1103. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \
  1104. JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
  1105. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
  1106. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
  1107. #elif \
  1108. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1109. JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \
  1110. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1111. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated)
  1112. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
  1113. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1114. #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
  1115. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
  1116. #else
  1117. #define JSON_HEDLEY_DEPRECATED(since)
  1118. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
  1119. #endif
  1120. #if defined(JSON_HEDLEY_UNAVAILABLE)
  1121. #undef JSON_HEDLEY_UNAVAILABLE
  1122. #endif
  1123. #if \
  1124. JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
  1125. JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
  1126. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1127. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1128. #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
  1129. #else
  1130. #define JSON_HEDLEY_UNAVAILABLE(available_since)
  1131. #endif
  1132. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
  1133. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  1134. #endif
  1135. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG)
  1136. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  1137. #endif
  1138. #if \
  1139. JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
  1140. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1141. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1142. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1143. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1144. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1145. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1146. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1147. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1148. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1149. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1150. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1151. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1152. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1153. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1154. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1155. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1156. #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
  1157. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__))
  1158. #elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L)
  1159. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1160. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]])
  1161. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard)
  1162. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1163. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1164. #elif defined(_Check_return_) /* SAL */
  1165. #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
  1166. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_
  1167. #else
  1168. #define JSON_HEDLEY_WARN_UNUSED_RESULT
  1169. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg)
  1170. #endif
  1171. #if defined(JSON_HEDLEY_SENTINEL)
  1172. #undef JSON_HEDLEY_SENTINEL
  1173. #endif
  1174. #if \
  1175. JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
  1176. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1177. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1178. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1179. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1180. #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
  1181. #else
  1182. #define JSON_HEDLEY_SENTINEL(position)
  1183. #endif
  1184. #if defined(JSON_HEDLEY_NO_RETURN)
  1185. #undef JSON_HEDLEY_NO_RETURN
  1186. #endif
  1187. #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1188. #define JSON_HEDLEY_NO_RETURN __noreturn
  1189. #elif \
  1190. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1191. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1192. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1193. #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
  1194. #define JSON_HEDLEY_NO_RETURN _Noreturn
  1195. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  1196. #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]])
  1197. #elif \
  1198. JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
  1199. JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
  1200. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1201. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1202. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1203. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1204. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1205. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1206. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1207. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1208. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1209. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1210. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1211. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1212. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1213. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1214. JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
  1215. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1216. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1217. #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return")
  1218. #elif \
  1219. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1220. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1221. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1222. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1223. #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
  1224. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1225. #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
  1226. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1227. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1228. #else
  1229. #define JSON_HEDLEY_NO_RETURN
  1230. #endif
  1231. #if defined(JSON_HEDLEY_NO_ESCAPE)
  1232. #undef JSON_HEDLEY_NO_ESCAPE
  1233. #endif
  1234. #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape)
  1235. #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__))
  1236. #else
  1237. #define JSON_HEDLEY_NO_ESCAPE
  1238. #endif
  1239. #if defined(JSON_HEDLEY_UNREACHABLE)
  1240. #undef JSON_HEDLEY_UNREACHABLE
  1241. #endif
  1242. #if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  1243. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  1244. #endif
  1245. #if defined(JSON_HEDLEY_ASSUME)
  1246. #undef JSON_HEDLEY_ASSUME
  1247. #endif
  1248. #if \
  1249. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1250. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1251. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1252. #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
  1253. #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
  1254. #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
  1255. #elif \
  1256. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1257. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1258. #if defined(__cplusplus)
  1259. #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
  1260. #else
  1261. #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
  1262. #endif
  1263. #endif
  1264. #if \
  1265. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
  1266. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  1267. JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \
  1268. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1269. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \
  1270. JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \
  1271. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1272. #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
  1273. #elif defined(JSON_HEDLEY_ASSUME)
  1274. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1275. #endif
  1276. #if !defined(JSON_HEDLEY_ASSUME)
  1277. #if defined(JSON_HEDLEY_UNREACHABLE)
  1278. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1)))
  1279. #else
  1280. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr)
  1281. #endif
  1282. #endif
  1283. #if defined(JSON_HEDLEY_UNREACHABLE)
  1284. #if \
  1285. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1286. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1287. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value))
  1288. #else
  1289. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
  1290. #endif
  1291. #else
  1292. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value)
  1293. #endif
  1294. #if !defined(JSON_HEDLEY_UNREACHABLE)
  1295. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1296. #endif
  1297. JSON_HEDLEY_DIAGNOSTIC_PUSH
  1298. #if JSON_HEDLEY_HAS_WARNING("-Wpedantic")
  1299. #pragma clang diagnostic ignored "-Wpedantic"
  1300. #endif
  1301. #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus)
  1302. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  1303. #endif
  1304. #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0)
  1305. #if defined(__clang__)
  1306. #pragma clang diagnostic ignored "-Wvariadic-macros"
  1307. #elif defined(JSON_HEDLEY_GCC_VERSION)
  1308. #pragma GCC diagnostic ignored "-Wvariadic-macros"
  1309. #endif
  1310. #endif
  1311. #if defined(JSON_HEDLEY_NON_NULL)
  1312. #undef JSON_HEDLEY_NON_NULL
  1313. #endif
  1314. #if \
  1315. JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
  1316. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1317. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1318. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1319. #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
  1320. #else
  1321. #define JSON_HEDLEY_NON_NULL(...)
  1322. #endif
  1323. JSON_HEDLEY_DIAGNOSTIC_POP
  1324. #if defined(JSON_HEDLEY_PRINTF_FORMAT)
  1325. #undef JSON_HEDLEY_PRINTF_FORMAT
  1326. #endif
  1327. #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
  1328. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
  1329. #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
  1330. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
  1331. #elif \
  1332. JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
  1333. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1334. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1335. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  1336. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1337. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1338. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1339. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1340. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1341. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1342. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1343. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1344. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1345. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1346. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1347. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1348. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1349. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
  1350. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
  1351. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
  1352. #else
  1353. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
  1354. #endif
  1355. #if defined(JSON_HEDLEY_CONSTEXPR)
  1356. #undef JSON_HEDLEY_CONSTEXPR
  1357. #endif
  1358. #if defined(__cplusplus)
  1359. #if __cplusplus >= 201103L
  1360. #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr)
  1361. #endif
  1362. #endif
  1363. #if !defined(JSON_HEDLEY_CONSTEXPR)
  1364. #define JSON_HEDLEY_CONSTEXPR
  1365. #endif
  1366. #if defined(JSON_HEDLEY_PREDICT)
  1367. #undef JSON_HEDLEY_PREDICT
  1368. #endif
  1369. #if defined(JSON_HEDLEY_LIKELY)
  1370. #undef JSON_HEDLEY_LIKELY
  1371. #endif
  1372. #if defined(JSON_HEDLEY_UNLIKELY)
  1373. #undef JSON_HEDLEY_UNLIKELY
  1374. #endif
  1375. #if defined(JSON_HEDLEY_UNPREDICTABLE)
  1376. #undef JSON_HEDLEY_UNPREDICTABLE
  1377. #endif
  1378. #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
  1379. #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr))
  1380. #endif
  1381. #if \
  1382. (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \
  1383. JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \
  1384. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1385. # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability))
  1386. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability))
  1387. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability))
  1388. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 )
  1389. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 )
  1390. #elif \
  1391. (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \
  1392. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  1393. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1394. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1395. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1396. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1397. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1398. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  1399. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1400. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  1401. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1402. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1403. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1404. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \
  1405. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1406. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1407. # define JSON_HEDLEY_PREDICT(expr, expected, probability) \
  1408. (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)))
  1409. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
  1410. (__extension__ ({ \
  1411. double hedley_probability_ = (probability); \
  1412. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
  1413. }))
  1414. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
  1415. (__extension__ ({ \
  1416. double hedley_probability_ = (probability); \
  1417. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
  1418. }))
  1419. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  1420. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  1421. #else
  1422. # define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))
  1423. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
  1424. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
  1425. # define JSON_HEDLEY_LIKELY(expr) (!!(expr))
  1426. # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
  1427. #endif
  1428. #if !defined(JSON_HEDLEY_UNPREDICTABLE)
  1429. #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
  1430. #endif
  1431. #if defined(JSON_HEDLEY_MALLOC)
  1432. #undef JSON_HEDLEY_MALLOC
  1433. #endif
  1434. #if \
  1435. JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
  1436. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1437. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1438. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1439. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1440. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1441. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1442. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1443. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1444. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1445. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1446. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1447. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1448. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1449. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1450. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1451. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1452. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1453. #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
  1454. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1455. #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory")
  1456. #elif \
  1457. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1458. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1459. #define JSON_HEDLEY_MALLOC __declspec(restrict)
  1460. #else
  1461. #define JSON_HEDLEY_MALLOC
  1462. #endif
  1463. #if defined(JSON_HEDLEY_PURE)
  1464. #undef JSON_HEDLEY_PURE
  1465. #endif
  1466. #if \
  1467. JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
  1468. JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
  1469. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1470. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1471. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1472. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1473. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1474. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1475. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1476. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1477. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1478. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1479. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1480. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1481. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1482. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1483. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1484. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1485. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1486. # define JSON_HEDLEY_PURE __attribute__((__pure__))
  1487. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1488. # define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data")
  1489. #elif defined(__cplusplus) && \
  1490. ( \
  1491. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  1492. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \
  1493. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \
  1494. )
  1495. # define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
  1496. #else
  1497. # define JSON_HEDLEY_PURE
  1498. #endif
  1499. #if defined(JSON_HEDLEY_CONST)
  1500. #undef JSON_HEDLEY_CONST
  1501. #endif
  1502. #if \
  1503. JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
  1504. JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
  1505. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1506. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1507. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1508. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1509. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1510. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1511. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1512. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1513. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1514. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1515. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1516. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1517. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1518. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1519. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1520. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1521. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1522. #define JSON_HEDLEY_CONST __attribute__((__const__))
  1523. #elif \
  1524. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1525. #define JSON_HEDLEY_CONST _Pragma("no_side_effect")
  1526. #else
  1527. #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
  1528. #endif
  1529. #if defined(JSON_HEDLEY_RESTRICT)
  1530. #undef JSON_HEDLEY_RESTRICT
  1531. #endif
  1532. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
  1533. #define JSON_HEDLEY_RESTRICT restrict
  1534. #elif \
  1535. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1536. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1537. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1538. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \
  1539. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1540. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1541. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1542. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1543. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \
  1544. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  1545. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1546. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
  1547. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  1548. defined(__clang__) || \
  1549. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1550. #define JSON_HEDLEY_RESTRICT __restrict
  1551. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
  1552. #define JSON_HEDLEY_RESTRICT _Restrict
  1553. #else
  1554. #define JSON_HEDLEY_RESTRICT
  1555. #endif
  1556. #if defined(JSON_HEDLEY_INLINE)
  1557. #undef JSON_HEDLEY_INLINE
  1558. #endif
  1559. #if \
  1560. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  1561. (defined(__cplusplus) && (__cplusplus >= 199711L))
  1562. #define JSON_HEDLEY_INLINE inline
  1563. #elif \
  1564. defined(JSON_HEDLEY_GCC_VERSION) || \
  1565. JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
  1566. #define JSON_HEDLEY_INLINE __inline__
  1567. #elif \
  1568. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1569. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \
  1570. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1571. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \
  1572. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1573. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1574. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  1575. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1576. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1577. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1578. #define JSON_HEDLEY_INLINE __inline
  1579. #else
  1580. #define JSON_HEDLEY_INLINE
  1581. #endif
  1582. #if defined(JSON_HEDLEY_ALWAYS_INLINE)
  1583. #undef JSON_HEDLEY_ALWAYS_INLINE
  1584. #endif
  1585. #if \
  1586. JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
  1587. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1588. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1589. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1590. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1591. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1592. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1593. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1594. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1595. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1596. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1597. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1598. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1599. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1600. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1601. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1602. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1603. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \
  1604. JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
  1605. # define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
  1606. #elif \
  1607. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1608. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1609. # define JSON_HEDLEY_ALWAYS_INLINE __forceinline
  1610. #elif defined(__cplusplus) && \
  1611. ( \
  1612. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1613. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1614. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1615. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1616. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1617. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \
  1618. )
  1619. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
  1620. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1621. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
  1622. #else
  1623. # define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
  1624. #endif
  1625. #if defined(JSON_HEDLEY_NEVER_INLINE)
  1626. #undef JSON_HEDLEY_NEVER_INLINE
  1627. #endif
  1628. #if \
  1629. JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
  1630. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1631. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1632. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1633. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1634. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1635. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1636. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1637. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1638. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1639. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1640. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1641. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1642. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1643. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1644. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1645. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1646. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \
  1647. JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
  1648. #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
  1649. #elif \
  1650. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1651. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1652. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1653. #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
  1654. #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
  1655. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1656. #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
  1657. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1658. #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
  1659. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1660. #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
  1661. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1662. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1663. #else
  1664. #define JSON_HEDLEY_NEVER_INLINE
  1665. #endif
  1666. #if defined(JSON_HEDLEY_PRIVATE)
  1667. #undef JSON_HEDLEY_PRIVATE
  1668. #endif
  1669. #if defined(JSON_HEDLEY_PUBLIC)
  1670. #undef JSON_HEDLEY_PUBLIC
  1671. #endif
  1672. #if defined(JSON_HEDLEY_IMPORT)
  1673. #undef JSON_HEDLEY_IMPORT
  1674. #endif
  1675. #if defined(_WIN32) || defined(__CYGWIN__)
  1676. # define JSON_HEDLEY_PRIVATE
  1677. # define JSON_HEDLEY_PUBLIC __declspec(dllexport)
  1678. # define JSON_HEDLEY_IMPORT __declspec(dllimport)
  1679. #else
  1680. # if \
  1681. JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
  1682. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1683. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1684. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1685. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1686. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1687. ( \
  1688. defined(__TI_EABI__) && \
  1689. ( \
  1690. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1691. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \
  1692. ) \
  1693. ) || \
  1694. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1695. # define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
  1696. # define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default")))
  1697. # else
  1698. # define JSON_HEDLEY_PRIVATE
  1699. # define JSON_HEDLEY_PUBLIC
  1700. # endif
  1701. # define JSON_HEDLEY_IMPORT extern
  1702. #endif
  1703. #if defined(JSON_HEDLEY_NO_THROW)
  1704. #undef JSON_HEDLEY_NO_THROW
  1705. #endif
  1706. #if \
  1707. JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
  1708. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1709. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1710. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1711. #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
  1712. #elif \
  1713. JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
  1714. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \
  1715. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1716. #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
  1717. #else
  1718. #define JSON_HEDLEY_NO_THROW
  1719. #endif
  1720. #if defined(JSON_HEDLEY_FALL_THROUGH)
  1721. #undef JSON_HEDLEY_FALL_THROUGH
  1722. #endif
  1723. #if \
  1724. JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \
  1725. JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \
  1726. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1727. #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
  1728. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough)
  1729. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]])
  1730. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough)
  1731. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]])
  1732. #elif defined(__fallthrough) /* SAL */
  1733. #define JSON_HEDLEY_FALL_THROUGH __fallthrough
  1734. #else
  1735. #define JSON_HEDLEY_FALL_THROUGH
  1736. #endif
  1737. #if defined(JSON_HEDLEY_RETURNS_NON_NULL)
  1738. #undef JSON_HEDLEY_RETURNS_NON_NULL
  1739. #endif
  1740. #if \
  1741. JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
  1742. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1743. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1744. #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
  1745. #elif defined(_Ret_notnull_) /* SAL */
  1746. #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
  1747. #else
  1748. #define JSON_HEDLEY_RETURNS_NON_NULL
  1749. #endif
  1750. #if defined(JSON_HEDLEY_ARRAY_PARAM)
  1751. #undef JSON_HEDLEY_ARRAY_PARAM
  1752. #endif
  1753. #if \
  1754. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
  1755. !defined(__STDC_NO_VLA__) && \
  1756. !defined(__cplusplus) && \
  1757. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1758. !defined(JSON_HEDLEY_TINYC_VERSION)
  1759. #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
  1760. #else
  1761. #define JSON_HEDLEY_ARRAY_PARAM(name)
  1762. #endif
  1763. #if defined(JSON_HEDLEY_IS_CONSTANT)
  1764. #undef JSON_HEDLEY_IS_CONSTANT
  1765. #endif
  1766. #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
  1767. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  1768. #endif
  1769. /* JSON_HEDLEY_IS_CONSTEXPR_ is for
  1770. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  1771. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1772. #undef JSON_HEDLEY_IS_CONSTEXPR_
  1773. #endif
  1774. #if \
  1775. JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
  1776. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1777. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1778. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
  1779. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1780. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1781. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1782. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \
  1783. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1784. JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
  1785. #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
  1786. #endif
  1787. #if !defined(__cplusplus)
  1788. # if \
  1789. JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
  1790. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1791. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1792. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1793. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1794. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1795. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
  1796. #if defined(__INTPTR_TYPE__)
  1797. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
  1798. #else
  1799. #include <stdint.h>
  1800. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
  1801. #endif
  1802. # elif \
  1803. ( \
  1804. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \
  1805. !defined(JSON_HEDLEY_SUNPRO_VERSION) && \
  1806. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1807. !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1808. (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1809. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1810. JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
  1811. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1812. JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
  1813. #if defined(__INTPTR_TYPE__)
  1814. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
  1815. #else
  1816. #include <stdint.h>
  1817. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
  1818. #endif
  1819. # elif \
  1820. defined(JSON_HEDLEY_GCC_VERSION) || \
  1821. defined(JSON_HEDLEY_INTEL_VERSION) || \
  1822. defined(JSON_HEDLEY_TINYC_VERSION) || \
  1823. defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \
  1824. JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \
  1825. defined(JSON_HEDLEY_TI_CL2000_VERSION) || \
  1826. defined(JSON_HEDLEY_TI_CL6X_VERSION) || \
  1827. defined(JSON_HEDLEY_TI_CL7X_VERSION) || \
  1828. defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \
  1829. defined(__clang__)
  1830. # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \
  1831. sizeof(void) != \
  1832. sizeof(*( \
  1833. 1 ? \
  1834. ((void*) ((expr) * 0L) ) : \
  1835. ((struct { char v[sizeof(void) * 2]; } *) 1) \
  1836. ) \
  1837. ) \
  1838. )
  1839. # endif
  1840. #endif
  1841. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1842. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1843. #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr)
  1844. #endif
  1845. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1))
  1846. #else
  1847. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1848. #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
  1849. #endif
  1850. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
  1851. #endif
  1852. #if defined(JSON_HEDLEY_BEGIN_C_DECLS)
  1853. #undef JSON_HEDLEY_BEGIN_C_DECLS
  1854. #endif
  1855. #if defined(JSON_HEDLEY_END_C_DECLS)
  1856. #undef JSON_HEDLEY_END_C_DECLS
  1857. #endif
  1858. #if defined(JSON_HEDLEY_C_DECL)
  1859. #undef JSON_HEDLEY_C_DECL
  1860. #endif
  1861. #if defined(__cplusplus)
  1862. #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
  1863. #define JSON_HEDLEY_END_C_DECLS }
  1864. #define JSON_HEDLEY_C_DECL extern "C"
  1865. #else
  1866. #define JSON_HEDLEY_BEGIN_C_DECLS
  1867. #define JSON_HEDLEY_END_C_DECLS
  1868. #define JSON_HEDLEY_C_DECL
  1869. #endif
  1870. #if defined(JSON_HEDLEY_STATIC_ASSERT)
  1871. #undef JSON_HEDLEY_STATIC_ASSERT
  1872. #endif
  1873. #if \
  1874. !defined(__cplusplus) && ( \
  1875. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
  1876. (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \
  1877. JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
  1878. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1879. defined(_Static_assert) \
  1880. )
  1881. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
  1882. #elif \
  1883. (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
  1884. JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \
  1885. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1886. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message))
  1887. #else
  1888. # define JSON_HEDLEY_STATIC_ASSERT(expr, message)
  1889. #endif
  1890. #if defined(JSON_HEDLEY_NULL)
  1891. #undef JSON_HEDLEY_NULL
  1892. #endif
  1893. #if defined(__cplusplus)
  1894. #if __cplusplus >= 201103L
  1895. #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr)
  1896. #elif defined(NULL)
  1897. #define JSON_HEDLEY_NULL NULL
  1898. #else
  1899. #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0)
  1900. #endif
  1901. #elif defined(NULL)
  1902. #define JSON_HEDLEY_NULL NULL
  1903. #else
  1904. #define JSON_HEDLEY_NULL ((void*) 0)
  1905. #endif
  1906. #if defined(JSON_HEDLEY_MESSAGE)
  1907. #undef JSON_HEDLEY_MESSAGE
  1908. #endif
  1909. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1910. # define JSON_HEDLEY_MESSAGE(msg) \
  1911. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1912. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1913. JSON_HEDLEY_PRAGMA(message msg) \
  1914. JSON_HEDLEY_DIAGNOSTIC_POP
  1915. #elif \
  1916. JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
  1917. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1918. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
  1919. #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
  1920. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
  1921. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1922. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1923. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
  1924. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1925. #else
  1926. # define JSON_HEDLEY_MESSAGE(msg)
  1927. #endif
  1928. #if defined(JSON_HEDLEY_WARNING)
  1929. #undef JSON_HEDLEY_WARNING
  1930. #endif
  1931. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1932. # define JSON_HEDLEY_WARNING(msg) \
  1933. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1934. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1935. JSON_HEDLEY_PRAGMA(clang warning msg) \
  1936. JSON_HEDLEY_DIAGNOSTIC_POP
  1937. #elif \
  1938. JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
  1939. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  1940. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1941. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
  1942. #elif \
  1943. JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \
  1944. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  1945. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1946. #else
  1947. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
  1948. #endif
  1949. #if defined(JSON_HEDLEY_REQUIRE)
  1950. #undef JSON_HEDLEY_REQUIRE
  1951. #endif
  1952. #if defined(JSON_HEDLEY_REQUIRE_MSG)
  1953. #undef JSON_HEDLEY_REQUIRE_MSG
  1954. #endif
  1955. #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
  1956. # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
  1957. # define JSON_HEDLEY_REQUIRE(expr) \
  1958. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1959. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1960. __attribute__((diagnose_if(!(expr), #expr, "error"))) \
  1961. JSON_HEDLEY_DIAGNOSTIC_POP
  1962. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \
  1963. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1964. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1965. __attribute__((diagnose_if(!(expr), msg, "error"))) \
  1966. JSON_HEDLEY_DIAGNOSTIC_POP
  1967. # else
  1968. # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error")))
  1969. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error")))
  1970. # endif
  1971. #else
  1972. # define JSON_HEDLEY_REQUIRE(expr)
  1973. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg)
  1974. #endif
  1975. #if defined(JSON_HEDLEY_FLAGS)
  1976. #undef JSON_HEDLEY_FLAGS
  1977. #endif
  1978. #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion"))
  1979. #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
  1980. #else
  1981. #define JSON_HEDLEY_FLAGS
  1982. #endif
  1983. #if defined(JSON_HEDLEY_FLAGS_CAST)
  1984. #undef JSON_HEDLEY_FLAGS_CAST
  1985. #endif
  1986. #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
  1987. # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
  1988. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1989. _Pragma("warning(disable:188)") \
  1990. ((T) (expr)); \
  1991. JSON_HEDLEY_DIAGNOSTIC_POP \
  1992. }))
  1993. #else
  1994. # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
  1995. #endif
  1996. #if defined(JSON_HEDLEY_EMPTY_BASES)
  1997. #undef JSON_HEDLEY_EMPTY_BASES
  1998. #endif
  1999. #if \
  2000. (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \
  2001. JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
  2002. #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases)
  2003. #else
  2004. #define JSON_HEDLEY_EMPTY_BASES
  2005. #endif
  2006. /* Remaining macros are deprecated. */
  2007. #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
  2008. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  2009. #endif
  2010. #if defined(__clang__)
  2011. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
  2012. #else
  2013. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  2014. #endif
  2015. #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
  2016. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  2017. #endif
  2018. #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  2019. #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
  2020. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  2021. #endif
  2022. #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
  2023. #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
  2024. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  2025. #endif
  2026. #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
  2027. #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
  2028. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  2029. #endif
  2030. #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
  2031. #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
  2032. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  2033. #endif
  2034. #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
  2035. #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
  2036. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  2037. #endif
  2038. #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
  2039. #if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
  2040. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  2041. #endif
  2042. #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
  2043. #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
  2044. // This file contains all internal macro definitions
  2045. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  2046. // exclude unsupported compilers
  2047. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  2048. #if defined(__clang__)
  2049. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  2050. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  2051. #endif
  2052. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  2053. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  2054. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  2055. #endif
  2056. #endif
  2057. #endif
  2058. // C++ language standard detection
  2059. // if the user manually specified the used c++ version this is skipped
  2060. #if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11)
  2061. #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L)
  2062. #define JSON_HAS_CPP_20
  2063. #define JSON_HAS_CPP_17
  2064. #define JSON_HAS_CPP_14
  2065. #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  2066. #define JSON_HAS_CPP_17
  2067. #define JSON_HAS_CPP_14
  2068. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  2069. #define JSON_HAS_CPP_14
  2070. #endif
  2071. // the cpp 11 flag is always specified because it is the minimal required version
  2072. #define JSON_HAS_CPP_11
  2073. #endif
  2074. // disable documentation warnings on clang
  2075. #if defined(__clang__)
  2076. #pragma clang diagnostic push
  2077. #pragma clang diagnostic ignored "-Wdocumentation"
  2078. #pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
  2079. #endif
  2080. // allow to disable exceptions
  2081. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  2082. #define JSON_THROW(exception) throw exception
  2083. #define JSON_TRY try
  2084. #define JSON_CATCH(exception) catch(exception)
  2085. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  2086. #else
  2087. #include <cstdlib>
  2088. #define JSON_THROW(exception) std::abort()
  2089. #define JSON_TRY if(true)
  2090. #define JSON_CATCH(exception) if(false)
  2091. #define JSON_INTERNAL_CATCH(exception) if(false)
  2092. #endif
  2093. // override exception macros
  2094. #if defined(JSON_THROW_USER)
  2095. #undef JSON_THROW
  2096. #define JSON_THROW JSON_THROW_USER
  2097. #endif
  2098. #if defined(JSON_TRY_USER)
  2099. #undef JSON_TRY
  2100. #define JSON_TRY JSON_TRY_USER
  2101. #endif
  2102. #if defined(JSON_CATCH_USER)
  2103. #undef JSON_CATCH
  2104. #define JSON_CATCH JSON_CATCH_USER
  2105. #undef JSON_INTERNAL_CATCH
  2106. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  2107. #endif
  2108. #if defined(JSON_INTERNAL_CATCH_USER)
  2109. #undef JSON_INTERNAL_CATCH
  2110. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  2111. #endif
  2112. // allow to override assert
  2113. #if !defined(JSON_ASSERT)
  2114. #include <cassert> // assert
  2115. #define JSON_ASSERT(x) assert(x)
  2116. #endif
  2117. // allow to access some private functions (needed by the test suite)
  2118. #if defined(JSON_TESTS_PRIVATE)
  2119. #define JSON_PRIVATE_UNLESS_TESTED public
  2120. #else
  2121. #define JSON_PRIVATE_UNLESS_TESTED private
  2122. #endif
  2123. /*!
  2124. @brief macro to briefly define a mapping between an enum and JSON
  2125. @def NLOHMANN_JSON_SERIALIZE_ENUM
  2126. @since version 3.4.0
  2127. */
  2128. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  2129. template<typename BasicJsonType> \
  2130. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  2131. { \
  2132. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  2133. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  2134. auto it = std::find_if(std::begin(m), std::end(m), \
  2135. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  2136. { \
  2137. return ej_pair.first == e; \
  2138. }); \
  2139. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  2140. } \
  2141. template<typename BasicJsonType> \
  2142. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  2143. { \
  2144. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  2145. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  2146. auto it = std::find_if(std::begin(m), std::end(m), \
  2147. [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  2148. { \
  2149. return ej_pair.second == j; \
  2150. }); \
  2151. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  2152. }
  2153. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  2154. // may be removed in the future once the class is split.
  2155. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  2156. template<template<typename, typename, typename...> class ObjectType, \
  2157. template<typename, typename...> class ArrayType, \
  2158. class StringType, class BooleanType, class NumberIntegerType, \
  2159. class NumberUnsignedType, class NumberFloatType, \
  2160. template<typename> class AllocatorType, \
  2161. template<typename, typename = void> class JSONSerializer, \
  2162. class BinaryType>
  2163. #define NLOHMANN_BASIC_JSON_TPL \
  2164. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  2165. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  2166. AllocatorType, JSONSerializer, BinaryType>
  2167. // Macros to simplify conversion from/to types
  2168. #define NLOHMANN_JSON_EXPAND( x ) x
  2169. #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
  2170. #define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \
  2171. NLOHMANN_JSON_PASTE64, \
  2172. NLOHMANN_JSON_PASTE63, \
  2173. NLOHMANN_JSON_PASTE62, \
  2174. NLOHMANN_JSON_PASTE61, \
  2175. NLOHMANN_JSON_PASTE60, \
  2176. NLOHMANN_JSON_PASTE59, \
  2177. NLOHMANN_JSON_PASTE58, \
  2178. NLOHMANN_JSON_PASTE57, \
  2179. NLOHMANN_JSON_PASTE56, \
  2180. NLOHMANN_JSON_PASTE55, \
  2181. NLOHMANN_JSON_PASTE54, \
  2182. NLOHMANN_JSON_PASTE53, \
  2183. NLOHMANN_JSON_PASTE52, \
  2184. NLOHMANN_JSON_PASTE51, \
  2185. NLOHMANN_JSON_PASTE50, \
  2186. NLOHMANN_JSON_PASTE49, \
  2187. NLOHMANN_JSON_PASTE48, \
  2188. NLOHMANN_JSON_PASTE47, \
  2189. NLOHMANN_JSON_PASTE46, \
  2190. NLOHMANN_JSON_PASTE45, \
  2191. NLOHMANN_JSON_PASTE44, \
  2192. NLOHMANN_JSON_PASTE43, \
  2193. NLOHMANN_JSON_PASTE42, \
  2194. NLOHMANN_JSON_PASTE41, \
  2195. NLOHMANN_JSON_PASTE40, \
  2196. NLOHMANN_JSON_PASTE39, \
  2197. NLOHMANN_JSON_PASTE38, \
  2198. NLOHMANN_JSON_PASTE37, \
  2199. NLOHMANN_JSON_PASTE36, \
  2200. NLOHMANN_JSON_PASTE35, \
  2201. NLOHMANN_JSON_PASTE34, \
  2202. NLOHMANN_JSON_PASTE33, \
  2203. NLOHMANN_JSON_PASTE32, \
  2204. NLOHMANN_JSON_PASTE31, \
  2205. NLOHMANN_JSON_PASTE30, \
  2206. NLOHMANN_JSON_PASTE29, \
  2207. NLOHMANN_JSON_PASTE28, \
  2208. NLOHMANN_JSON_PASTE27, \
  2209. NLOHMANN_JSON_PASTE26, \
  2210. NLOHMANN_JSON_PASTE25, \
  2211. NLOHMANN_JSON_PASTE24, \
  2212. NLOHMANN_JSON_PASTE23, \
  2213. NLOHMANN_JSON_PASTE22, \
  2214. NLOHMANN_JSON_PASTE21, \
  2215. NLOHMANN_JSON_PASTE20, \
  2216. NLOHMANN_JSON_PASTE19, \
  2217. NLOHMANN_JSON_PASTE18, \
  2218. NLOHMANN_JSON_PASTE17, \
  2219. NLOHMANN_JSON_PASTE16, \
  2220. NLOHMANN_JSON_PASTE15, \
  2221. NLOHMANN_JSON_PASTE14, \
  2222. NLOHMANN_JSON_PASTE13, \
  2223. NLOHMANN_JSON_PASTE12, \
  2224. NLOHMANN_JSON_PASTE11, \
  2225. NLOHMANN_JSON_PASTE10, \
  2226. NLOHMANN_JSON_PASTE9, \
  2227. NLOHMANN_JSON_PASTE8, \
  2228. NLOHMANN_JSON_PASTE7, \
  2229. NLOHMANN_JSON_PASTE6, \
  2230. NLOHMANN_JSON_PASTE5, \
  2231. NLOHMANN_JSON_PASTE4, \
  2232. NLOHMANN_JSON_PASTE3, \
  2233. NLOHMANN_JSON_PASTE2, \
  2234. NLOHMANN_JSON_PASTE1)(__VA_ARGS__))
  2235. #define NLOHMANN_JSON_PASTE2(func, v1) func(v1)
  2236. #define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2)
  2237. #define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3)
  2238. #define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4)
  2239. #define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5)
  2240. #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)
  2241. #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)
  2242. #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)
  2243. #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)
  2244. #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)
  2245. #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)
  2246. #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)
  2247. #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)
  2248. #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)
  2249. #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)
  2250. #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)
  2251. #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)
  2252. #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)
  2253. #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)
  2254. #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)
  2255. #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)
  2256. #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)
  2257. #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)
  2258. #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)
  2259. #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)
  2260. #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)
  2261. #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)
  2262. #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)
  2263. #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)
  2264. #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)
  2265. #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)
  2266. #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)
  2267. #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)
  2268. #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)
  2269. #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)
  2270. #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)
  2271. #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)
  2272. #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)
  2273. #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)
  2274. #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)
  2275. #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)
  2276. #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)
  2277. #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)
  2278. #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)
  2279. #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)
  2280. #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)
  2281. #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)
  2282. #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)
  2283. #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)
  2284. #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)
  2285. #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)
  2286. #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)
  2287. #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)
  2288. #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)
  2289. #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)
  2290. #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)
  2291. #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)
  2292. #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)
  2293. #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)
  2294. #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)
  2295. #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)
  2296. #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)
  2297. #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)
  2298. #define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1;
  2299. #define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1);
  2300. /*!
  2301. @brief macro
  2302. @def NLOHMANN_DEFINE_TYPE_INTRUSIVE
  2303. @since version 3.9.0
  2304. */
  2305. #define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \
  2306. 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__)) } \
  2307. 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__)) }
  2308. /*!
  2309. @brief macro
  2310. @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE
  2311. @since version 3.9.0
  2312. */
  2313. #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \
  2314. 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__)) } \
  2315. 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__)) }
  2316. #ifndef JSON_USE_IMPLICIT_CONVERSIONS
  2317. #define JSON_USE_IMPLICIT_CONVERSIONS 1
  2318. #endif
  2319. #if JSON_USE_IMPLICIT_CONVERSIONS
  2320. #define JSON_EXPLICIT
  2321. #else
  2322. #define JSON_EXPLICIT explicit
  2323. #endif
  2324. #ifndef JSON_DIAGNOSTICS
  2325. #define JSON_DIAGNOSTICS 0
  2326. #endif
  2327. namespace nlohmann
  2328. {
  2329. namespace detail
  2330. {
  2331. /*!
  2332. @brief replace all occurrences of a substring by another string
  2333. @param[in,out] s the string to manipulate; changed so that all
  2334. occurrences of @a f are replaced with @a t
  2335. @param[in] f the substring to replace with @a t
  2336. @param[in] t the string to replace @a f
  2337. @pre The search string @a f must not be empty. **This precondition is
  2338. enforced with an assertion.**
  2339. @since version 2.0.0
  2340. */
  2341. inline void replace_substring(std::string& s, const std::string& f,
  2342. const std::string& t)
  2343. {
  2344. JSON_ASSERT(!f.empty());
  2345. for (auto pos = s.find(f); // find first occurrence of f
  2346. pos != std::string::npos; // make sure f was found
  2347. s.replace(pos, f.size(), t), // replace with t, and
  2348. pos = s.find(f, pos + t.size())) // find next occurrence of f
  2349. {}
  2350. }
  2351. /*!
  2352. * @brief string escaping as described in RFC 6901 (Sect. 4)
  2353. * @param[in] s string to escape
  2354. * @return escaped string
  2355. *
  2356. * Note the order of escaping "~" to "~0" and "/" to "~1" is important.
  2357. */
  2358. inline std::string escape(std::string s)
  2359. {
  2360. replace_substring(s, "~", "~0");
  2361. replace_substring(s, "/", "~1");
  2362. return s;
  2363. }
  2364. /*!
  2365. * @brief string unescaping as described in RFC 6901 (Sect. 4)
  2366. * @param[in] s string to unescape
  2367. * @return unescaped string
  2368. *
  2369. * Note the order of escaping "~1" to "/" and "~0" to "~" is important.
  2370. */
  2371. static void unescape(std::string& s)
  2372. {
  2373. replace_substring(s, "~1", "/");
  2374. replace_substring(s, "~0", "~");
  2375. }
  2376. } // namespace detail
  2377. } // namespace nlohmann
  2378. // #include <nlohmann/detail/input/position_t.hpp>
  2379. #include <cstddef> // size_t
  2380. namespace nlohmann
  2381. {
  2382. namespace detail
  2383. {
  2384. /// struct to capture the start position of the current token
  2385. struct position_t
  2386. {
  2387. /// the total number of characters read
  2388. std::size_t chars_read_total = 0;
  2389. /// the number of characters read in the current line
  2390. std::size_t chars_read_current_line = 0;
  2391. /// the number of lines read
  2392. std::size_t lines_read = 0;
  2393. /// conversion to size_t to preserve SAX interface
  2394. constexpr operator size_t() const
  2395. {
  2396. return chars_read_total;
  2397. }
  2398. };
  2399. } // namespace detail
  2400. } // namespace nlohmann
  2401. // #include <nlohmann/detail/macro_scope.hpp>
  2402. namespace nlohmann
  2403. {
  2404. namespace detail
  2405. {
  2406. ////////////////
  2407. // exceptions //
  2408. ////////////////
  2409. /*!
  2410. @brief general exception of the @ref basic_json class
  2411. This class is an extension of `std::exception` objects with a member @a id for
  2412. exception ids. It is used as the base class for all exceptions thrown by the
  2413. @ref basic_json class. This class can hence be used as "wildcard" to catch
  2414. exceptions.
  2415. Subclasses:
  2416. - @ref parse_error for exceptions indicating a parse error
  2417. - @ref invalid_iterator for exceptions indicating errors with iterators
  2418. - @ref type_error for exceptions indicating executing a member function with
  2419. a wrong type
  2420. - @ref out_of_range for exceptions indicating access out of the defined range
  2421. - @ref other_error for exceptions indicating other library errors
  2422. @internal
  2423. @note To have nothrow-copy-constructible exceptions, we internally use
  2424. `std::runtime_error` which can cope with arbitrary-length error messages.
  2425. Intermediate strings are built with static functions and then passed to
  2426. the actual constructor.
  2427. @endinternal
  2428. @liveexample{The following code shows how arbitrary library exceptions can be
  2429. caught.,exception}
  2430. @since version 3.0.0
  2431. */
  2432. class exception : public std::exception
  2433. {
  2434. public:
  2435. /// returns the explanatory string
  2436. const char* what() const noexcept override
  2437. {
  2438. return m.what();
  2439. }
  2440. /// the id of the exception
  2441. const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes)
  2442. protected:
  2443. JSON_HEDLEY_NON_NULL(3)
  2444. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  2445. static std::string name(const std::string& ename, int id_)
  2446. {
  2447. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  2448. }
  2449. template<typename BasicJsonType>
  2450. static std::string diagnostics(const BasicJsonType& leaf_element)
  2451. {
  2452. #if JSON_DIAGNOSTICS
  2453. std::vector<std::string> tokens;
  2454. for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent)
  2455. {
  2456. switch (current->m_parent->type())
  2457. {
  2458. case value_t::array:
  2459. {
  2460. for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i)
  2461. {
  2462. if (&current->m_parent->m_value.array->operator[](i) == current)
  2463. {
  2464. tokens.emplace_back(std::to_string(i));
  2465. break;
  2466. }
  2467. }
  2468. break;
  2469. }
  2470. case value_t::object:
  2471. {
  2472. for (const auto& element : *current->m_parent->m_value.object)
  2473. {
  2474. if (&element.second == current)
  2475. {
  2476. tokens.emplace_back(element.first.c_str());
  2477. break;
  2478. }
  2479. }
  2480. break;
  2481. }
  2482. case value_t::null: // LCOV_EXCL_LINE
  2483. case value_t::string: // LCOV_EXCL_LINE
  2484. case value_t::boolean: // LCOV_EXCL_LINE
  2485. case value_t::number_integer: // LCOV_EXCL_LINE
  2486. case value_t::number_unsigned: // LCOV_EXCL_LINE
  2487. case value_t::number_float: // LCOV_EXCL_LINE
  2488. case value_t::binary: // LCOV_EXCL_LINE
  2489. case value_t::discarded: // LCOV_EXCL_LINE
  2490. default: // LCOV_EXCL_LINE
  2491. break; // LCOV_EXCL_LINE
  2492. }
  2493. }
  2494. if (tokens.empty())
  2495. {
  2496. return "";
  2497. }
  2498. return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{},
  2499. [](const std::string & a, const std::string & b)
  2500. {
  2501. return a + "/" + detail::escape(b);
  2502. }) + ") ";
  2503. #else
  2504. static_cast<void>(leaf_element);
  2505. return "";
  2506. #endif
  2507. }
  2508. private:
  2509. /// an exception object as storage for error messages
  2510. std::runtime_error m;
  2511. };
  2512. /*!
  2513. @brief exception indicating a parse error
  2514. This exception is thrown by the library when a parse error occurs. Parse errors
  2515. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  2516. as when using JSON Patch.
  2517. Member @a byte holds the byte index of the last read character in the input
  2518. file.
  2519. Exceptions have ids 1xx.
  2520. name / id | example message | description
  2521. ------------------------------ | --------------- | -------------------------
  2522. json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position.
  2523. json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
  2524. json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
  2525. json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects.
  2526. json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors.
  2527. json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`.
  2528. json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character.
  2529. json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences.
  2530. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  2531. json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
  2532. json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.
  2533. json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read.
  2534. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  2535. json.exception.parse_error.115 | parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A | A UBJSON high-precision number could not be parsed.
  2536. @note For an input with n bytes, 1 is the index of the first character and n+1
  2537. is the index of the terminating null byte or the end of file. This also
  2538. holds true when reading a byte vector (CBOR or MessagePack).
  2539. @liveexample{The following code shows how a `parse_error` exception can be
  2540. caught.,parse_error}
  2541. @sa - @ref exception for the base class of the library exceptions
  2542. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2543. @sa - @ref type_error for exceptions indicating executing a member function with
  2544. a wrong type
  2545. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2546. @sa - @ref other_error for exceptions indicating other library errors
  2547. @since version 3.0.0
  2548. */
  2549. class parse_error : public exception
  2550. {
  2551. public:
  2552. /*!
  2553. @brief create a parse error exception
  2554. @param[in] id_ the id of the exception
  2555. @param[in] pos the position where the error occurred (or with
  2556. chars_read_total=0 if the position cannot be
  2557. determined)
  2558. @param[in] what_arg the explanatory string
  2559. @return parse_error object
  2560. */
  2561. template<typename BasicJsonType>
  2562. static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context)
  2563. {
  2564. std::string w = exception::name("parse_error", id_) + "parse error" +
  2565. position_string(pos) + ": " + exception::diagnostics(context) + what_arg;
  2566. return parse_error(id_, pos.chars_read_total, w.c_str());
  2567. }
  2568. template<typename BasicJsonType>
  2569. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context)
  2570. {
  2571. std::string w = exception::name("parse_error", id_) + "parse error" +
  2572. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  2573. ": " + exception::diagnostics(context) + what_arg;
  2574. return parse_error(id_, byte_, w.c_str());
  2575. }
  2576. /*!
  2577. @brief byte index of the parse error
  2578. The byte index of the last read character in the input file.
  2579. @note For an input with n bytes, 1 is the index of the first character and
  2580. n+1 is the index of the terminating null byte or the end of file.
  2581. This also holds true when reading a byte vector (CBOR or MessagePack).
  2582. */
  2583. const std::size_t byte;
  2584. private:
  2585. parse_error(int id_, std::size_t byte_, const char* what_arg)
  2586. : exception(id_, what_arg), byte(byte_) {}
  2587. static std::string position_string(const position_t& pos)
  2588. {
  2589. return " at line " + std::to_string(pos.lines_read + 1) +
  2590. ", column " + std::to_string(pos.chars_read_current_line);
  2591. }
  2592. };
  2593. /*!
  2594. @brief exception indicating errors with iterators
  2595. This exception is thrown if iterators passed to a library function do not match
  2596. the expected semantics.
  2597. Exceptions have ids 2xx.
  2598. name / id | example message | description
  2599. ----------------------------------- | --------------- | -------------------------
  2600. json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
  2601. json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
  2602. json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
  2603. json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid.
  2604. json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.
  2605. json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.
  2606. json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
  2607. json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
  2608. json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
  2609. json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
  2610. json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to.
  2611. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  2612. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  2613. json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin().
  2614. @liveexample{The following code shows how an `invalid_iterator` exception can be
  2615. caught.,invalid_iterator}
  2616. @sa - @ref exception for the base class of the library exceptions
  2617. @sa - @ref parse_error for exceptions indicating a parse error
  2618. @sa - @ref type_error for exceptions indicating executing a member function with
  2619. a wrong type
  2620. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2621. @sa - @ref other_error for exceptions indicating other library errors
  2622. @since version 3.0.0
  2623. */
  2624. class invalid_iterator : public exception
  2625. {
  2626. public:
  2627. template<typename BasicJsonType>
  2628. static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context)
  2629. {
  2630. std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg;
  2631. return invalid_iterator(id_, w.c_str());
  2632. }
  2633. private:
  2634. JSON_HEDLEY_NON_NULL(3)
  2635. invalid_iterator(int id_, const char* what_arg)
  2636. : exception(id_, what_arg) {}
  2637. };
  2638. /*!
  2639. @brief exception indicating executing a member function with a wrong type
  2640. This exception is thrown in case of a type error; that is, a library function is
  2641. executed on a JSON value whose type does not match the expected semantics.
  2642. Exceptions have ids 3xx.
  2643. name / id | example message | description
  2644. ----------------------------- | --------------- | -------------------------
  2645. json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
  2646. json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
  2647. json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &.
  2648. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  2649. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  2650. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  2651. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  2652. json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types.
  2653. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  2654. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  2655. json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types.
  2656. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  2657. json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined.
  2658. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  2659. json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive.
  2660. json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. |
  2661. json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) |
  2662. @liveexample{The following code shows how a `type_error` exception can be
  2663. caught.,type_error}
  2664. @sa - @ref exception for the base class of the library exceptions
  2665. @sa - @ref parse_error for exceptions indicating a parse error
  2666. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2667. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2668. @sa - @ref other_error for exceptions indicating other library errors
  2669. @since version 3.0.0
  2670. */
  2671. class type_error : public exception
  2672. {
  2673. public:
  2674. template<typename BasicJsonType>
  2675. static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context)
  2676. {
  2677. std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg;
  2678. return type_error(id_, w.c_str());
  2679. }
  2680. private:
  2681. JSON_HEDLEY_NON_NULL(3)
  2682. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2683. };
  2684. /*!
  2685. @brief exception indicating access out of the defined range
  2686. This exception is thrown in case a library function is called on an input
  2687. parameter that exceeds the expected range, for instance in case of array
  2688. indices or nonexisting object keys.
  2689. Exceptions have ids 4xx.
  2690. name / id | example message | description
  2691. ------------------------------- | --------------- | -------------------------
  2692. json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1.
  2693. json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
  2694. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  2695. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  2696. json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
  2697. json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF.
  2698. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. (until version 3.8.0) |
  2699. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  2700. json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string |
  2701. @liveexample{The following code shows how an `out_of_range` exception can be
  2702. caught.,out_of_range}
  2703. @sa - @ref exception for the base class of the library exceptions
  2704. @sa - @ref parse_error for exceptions indicating a parse error
  2705. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2706. @sa - @ref type_error for exceptions indicating executing a member function with
  2707. a wrong type
  2708. @sa - @ref other_error for exceptions indicating other library errors
  2709. @since version 3.0.0
  2710. */
  2711. class out_of_range : public exception
  2712. {
  2713. public:
  2714. template<typename BasicJsonType>
  2715. static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context)
  2716. {
  2717. std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg;
  2718. return out_of_range(id_, w.c_str());
  2719. }
  2720. private:
  2721. JSON_HEDLEY_NON_NULL(3)
  2722. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2723. };
  2724. /*!
  2725. @brief exception indicating other library errors
  2726. This exception is thrown in case of errors that cannot be classified with the
  2727. other exception types.
  2728. Exceptions have ids 5xx.
  2729. name / id | example message | description
  2730. ------------------------------ | --------------- | -------------------------
  2731. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  2732. @sa - @ref exception for the base class of the library exceptions
  2733. @sa - @ref parse_error for exceptions indicating a parse error
  2734. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2735. @sa - @ref type_error for exceptions indicating executing a member function with
  2736. a wrong type
  2737. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2738. @liveexample{The following code shows how an `other_error` exception can be
  2739. caught.,other_error}
  2740. @since version 3.0.0
  2741. */
  2742. class other_error : public exception
  2743. {
  2744. public:
  2745. template<typename BasicJsonType>
  2746. static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context)
  2747. {
  2748. std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg;
  2749. return other_error(id_, w.c_str());
  2750. }
  2751. private:
  2752. JSON_HEDLEY_NON_NULL(3)
  2753. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2754. };
  2755. } // namespace detail
  2756. } // namespace nlohmann
  2757. // #include <nlohmann/detail/macro_scope.hpp>
  2758. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2759. #include <cstddef> // size_t
  2760. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  2761. #include <utility> // index_sequence, make_index_sequence, index_sequence_for
  2762. // #include <nlohmann/detail/macro_scope.hpp>
  2763. namespace nlohmann
  2764. {
  2765. namespace detail
  2766. {
  2767. template<typename T>
  2768. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  2769. #ifdef JSON_HAS_CPP_14
  2770. // the following utilities are natively available in C++14
  2771. using std::enable_if_t;
  2772. using std::index_sequence;
  2773. using std::make_index_sequence;
  2774. using std::index_sequence_for;
  2775. #else
  2776. // alias templates to reduce boilerplate
  2777. template<bool B, typename T = void>
  2778. using enable_if_t = typename std::enable_if<B, T>::type;
  2779. // The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h
  2780. // which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0.
  2781. //// START OF CODE FROM GOOGLE ABSEIL
  2782. // integer_sequence
  2783. //
  2784. // Class template representing a compile-time integer sequence. An instantiation
  2785. // of `integer_sequence<T, Ints...>` has a sequence of integers encoded in its
  2786. // type through its template arguments (which is a common need when
  2787. // working with C++11 variadic templates). `absl::integer_sequence` is designed
  2788. // to be a drop-in replacement for C++14's `std::integer_sequence`.
  2789. //
  2790. // Example:
  2791. //
  2792. // template< class T, T... Ints >
  2793. // void user_function(integer_sequence<T, Ints...>);
  2794. //
  2795. // int main()
  2796. // {
  2797. // // user_function's `T` will be deduced to `int` and `Ints...`
  2798. // // will be deduced to `0, 1, 2, 3, 4`.
  2799. // user_function(make_integer_sequence<int, 5>());
  2800. // }
  2801. template <typename T, T... Ints>
  2802. struct integer_sequence
  2803. {
  2804. using value_type = T;
  2805. static constexpr std::size_t size() noexcept
  2806. {
  2807. return sizeof...(Ints);
  2808. }
  2809. };
  2810. // index_sequence
  2811. //
  2812. // A helper template for an `integer_sequence` of `size_t`,
  2813. // `absl::index_sequence` is designed to be a drop-in replacement for C++14's
  2814. // `std::index_sequence`.
  2815. template <size_t... Ints>
  2816. using index_sequence = integer_sequence<size_t, Ints...>;
  2817. namespace utility_internal
  2818. {
  2819. template <typename Seq, size_t SeqSize, size_t Rem>
  2820. struct Extend;
  2821. // Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency.
  2822. template <typename T, T... Ints, size_t SeqSize>
  2823. struct Extend<integer_sequence<T, Ints...>, SeqSize, 0>
  2824. {
  2825. using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >;
  2826. };
  2827. template <typename T, T... Ints, size_t SeqSize>
  2828. struct Extend<integer_sequence<T, Ints...>, SeqSize, 1>
  2829. {
  2830. using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >;
  2831. };
  2832. // Recursion helper for 'make_integer_sequence<T, N>'.
  2833. // 'Gen<T, N>::type' is an alias for 'integer_sequence<T, 0, 1, ... N-1>'.
  2834. template <typename T, size_t N>
  2835. struct Gen
  2836. {
  2837. using type =
  2838. typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type;
  2839. };
  2840. template <typename T>
  2841. struct Gen<T, 0>
  2842. {
  2843. using type = integer_sequence<T>;
  2844. };
  2845. } // namespace utility_internal
  2846. // Compile-time sequences of integers
  2847. // make_integer_sequence
  2848. //
  2849. // This template alias is equivalent to
  2850. // `integer_sequence<int, 0, 1, ..., N-1>`, and is designed to be a drop-in
  2851. // replacement for C++14's `std::make_integer_sequence`.
  2852. template <typename T, T N>
  2853. using make_integer_sequence = typename utility_internal::Gen<T, N>::type;
  2854. // make_index_sequence
  2855. //
  2856. // This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`,
  2857. // and is designed to be a drop-in replacement for C++14's
  2858. // `std::make_index_sequence`.
  2859. template <size_t N>
  2860. using make_index_sequence = make_integer_sequence<size_t, N>;
  2861. // index_sequence_for
  2862. //
  2863. // Converts a typename pack into an index sequence of the same length, and
  2864. // is designed to be a drop-in replacement for C++14's
  2865. // `std::index_sequence_for()`
  2866. template <typename... Ts>
  2867. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  2868. //// END OF CODE FROM GOOGLE ABSEIL
  2869. #endif
  2870. // dispatch utility (taken from ranges-v3)
  2871. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  2872. template<> struct priority_tag<0> {};
  2873. // taken from ranges-v3
  2874. template<typename T>
  2875. struct static_const
  2876. {
  2877. static constexpr T value{};
  2878. };
  2879. template<typename T>
  2880. constexpr T static_const<T>::value;
  2881. } // namespace detail
  2882. } // namespace nlohmann
  2883. // #include <nlohmann/detail/meta/identity_tag.hpp>
  2884. namespace nlohmann
  2885. {
  2886. namespace detail
  2887. {
  2888. // dispatching helper struct
  2889. template <class T> struct identity_tag {};
  2890. } // namespace detail
  2891. } // namespace nlohmann
  2892. // #include <nlohmann/detail/meta/type_traits.hpp>
  2893. #include <limits> // numeric_limits
  2894. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  2895. #include <utility> // declval
  2896. #include <tuple> // tuple
  2897. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  2898. #include <iterator> // random_access_iterator_tag
  2899. // #include <nlohmann/detail/meta/void_t.hpp>
  2900. namespace nlohmann
  2901. {
  2902. namespace detail
  2903. {
  2904. template<typename ...Ts> struct make_void
  2905. {
  2906. using type = void;
  2907. };
  2908. template<typename ...Ts> using void_t = typename make_void<Ts...>::type;
  2909. } // namespace detail
  2910. } // namespace nlohmann
  2911. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2912. namespace nlohmann
  2913. {
  2914. namespace detail
  2915. {
  2916. template<typename It, typename = void>
  2917. struct iterator_types {};
  2918. template<typename It>
  2919. struct iterator_types <
  2920. It,
  2921. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  2922. typename It::reference, typename It::iterator_category >>
  2923. {
  2924. using difference_type = typename It::difference_type;
  2925. using value_type = typename It::value_type;
  2926. using pointer = typename It::pointer;
  2927. using reference = typename It::reference;
  2928. using iterator_category = typename It::iterator_category;
  2929. };
  2930. // This is required as some compilers implement std::iterator_traits in a way that
  2931. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  2932. template<typename T, typename = void>
  2933. struct iterator_traits
  2934. {
  2935. };
  2936. template<typename T>
  2937. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  2938. : iterator_types<T>
  2939. {
  2940. };
  2941. template<typename T>
  2942. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  2943. {
  2944. using iterator_category = std::random_access_iterator_tag;
  2945. using value_type = T;
  2946. using difference_type = ptrdiff_t;
  2947. using pointer = T*;
  2948. using reference = T&;
  2949. };
  2950. } // namespace detail
  2951. } // namespace nlohmann
  2952. // #include <nlohmann/detail/macro_scope.hpp>
  2953. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2954. // #include <nlohmann/detail/meta/detected.hpp>
  2955. #include <type_traits>
  2956. // #include <nlohmann/detail/meta/void_t.hpp>
  2957. // https://en.cppreference.com/w/cpp/experimental/is_detected
  2958. namespace nlohmann
  2959. {
  2960. namespace detail
  2961. {
  2962. struct nonesuch
  2963. {
  2964. nonesuch() = delete;
  2965. ~nonesuch() = delete;
  2966. nonesuch(nonesuch const&) = delete;
  2967. nonesuch(nonesuch const&&) = delete;
  2968. void operator=(nonesuch const&) = delete;
  2969. void operator=(nonesuch&&) = delete;
  2970. };
  2971. template<class Default,
  2972. class AlwaysVoid,
  2973. template<class...> class Op,
  2974. class... Args>
  2975. struct detector
  2976. {
  2977. using value_t = std::false_type;
  2978. using type = Default;
  2979. };
  2980. template<class Default, template<class...> class Op, class... Args>
  2981. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  2982. {
  2983. using value_t = std::true_type;
  2984. using type = Op<Args...>;
  2985. };
  2986. template<template<class...> class Op, class... Args>
  2987. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  2988. template<template<class...> class Op, class... Args>
  2989. struct is_detected_lazy : is_detected<Op, Args...> { };
  2990. template<template<class...> class Op, class... Args>
  2991. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  2992. template<class Default, template<class...> class Op, class... Args>
  2993. using detected_or = detector<Default, void, Op, Args...>;
  2994. template<class Default, template<class...> class Op, class... Args>
  2995. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  2996. template<class Expected, template<class...> class Op, class... Args>
  2997. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  2998. template<class To, template<class...> class Op, class... Args>
  2999. using is_detected_convertible =
  3000. std::is_convertible<detected_t<Op, Args...>, To>;
  3001. } // namespace detail
  3002. } // namespace nlohmann
  3003. // #include <nlohmann/json_fwd.hpp>
  3004. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  3005. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  3006. #include <cstdint> // int64_t, uint64_t
  3007. #include <map> // map
  3008. #include <memory> // allocator
  3009. #include <string> // string
  3010. #include <vector> // vector
  3011. /*!
  3012. @brief namespace for Niels Lohmann
  3013. @see https://github.com/nlohmann
  3014. @since version 1.0.0
  3015. */
  3016. namespace nlohmann
  3017. {
  3018. /*!
  3019. @brief default JSONSerializer template argument
  3020. This serializer ignores the template arguments and uses ADL
  3021. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  3022. for serialization.
  3023. */
  3024. template<typename T = void, typename SFINAE = void>
  3025. struct adl_serializer;
  3026. template<template<typename U, typename V, typename... Args> class ObjectType =
  3027. std::map,
  3028. template<typename U, typename... Args> class ArrayType = std::vector,
  3029. class StringType = std::string, class BooleanType = bool,
  3030. class NumberIntegerType = std::int64_t,
  3031. class NumberUnsignedType = std::uint64_t,
  3032. class NumberFloatType = double,
  3033. template<typename U> class AllocatorType = std::allocator,
  3034. template<typename T, typename SFINAE = void> class JSONSerializer =
  3035. adl_serializer,
  3036. class BinaryType = std::vector<std::uint8_t>>
  3037. class basic_json;
  3038. /*!
  3039. @brief JSON Pointer
  3040. A JSON pointer defines a string syntax for identifying a specific value
  3041. within a JSON document. It can be used with functions `at` and
  3042. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  3043. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  3044. @since version 2.0.0
  3045. */
  3046. template<typename BasicJsonType>
  3047. class json_pointer;
  3048. /*!
  3049. @brief default JSON class
  3050. This type is the default specialization of the @ref basic_json class which
  3051. uses the standard template types.
  3052. @since version 1.0.0
  3053. */
  3054. using json = basic_json<>;
  3055. template<class Key, class T, class IgnoredLess, class Allocator>
  3056. struct ordered_map;
  3057. /*!
  3058. @brief ordered JSON class
  3059. This type preserves the insertion order of object keys.
  3060. @since version 3.9.0
  3061. */
  3062. using ordered_json = basic_json<nlohmann::ordered_map>;
  3063. } // namespace nlohmann
  3064. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  3065. namespace nlohmann
  3066. {
  3067. /*!
  3068. @brief detail namespace with internal helper functions
  3069. This namespace collects functions that should not be exposed,
  3070. implementations of some @ref basic_json methods, and meta-programming helpers.
  3071. @since version 2.1.0
  3072. */
  3073. namespace detail
  3074. {
  3075. /////////////
  3076. // helpers //
  3077. /////////////
  3078. // Note to maintainers:
  3079. //
  3080. // Every trait in this file expects a non CV-qualified type.
  3081. // The only exceptions are in the 'aliases for detected' section
  3082. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  3083. //
  3084. // In this case, T has to be properly CV-qualified to constraint the function arguments
  3085. // (e.g. to_json(BasicJsonType&, const T&))
  3086. template<typename> struct is_basic_json : std::false_type {};
  3087. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  3088. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  3089. //////////////////////
  3090. // json_ref helpers //
  3091. //////////////////////
  3092. template<typename>
  3093. class json_ref;
  3094. template<typename>
  3095. struct is_json_ref : std::false_type {};
  3096. template<typename T>
  3097. struct is_json_ref<json_ref<T>> : std::true_type {};
  3098. //////////////////////////
  3099. // aliases for detected //
  3100. //////////////////////////
  3101. template<typename T>
  3102. using mapped_type_t = typename T::mapped_type;
  3103. template<typename T>
  3104. using key_type_t = typename T::key_type;
  3105. template<typename T>
  3106. using value_type_t = typename T::value_type;
  3107. template<typename T>
  3108. using difference_type_t = typename T::difference_type;
  3109. template<typename T>
  3110. using pointer_t = typename T::pointer;
  3111. template<typename T>
  3112. using reference_t = typename T::reference;
  3113. template<typename T>
  3114. using iterator_category_t = typename T::iterator_category;
  3115. template<typename T>
  3116. using iterator_t = typename T::iterator;
  3117. template<typename T, typename... Args>
  3118. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  3119. template<typename T, typename... Args>
  3120. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  3121. template<typename T, typename U>
  3122. using get_template_function = decltype(std::declval<T>().template get<U>());
  3123. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  3124. template<typename BasicJsonType, typename T, typename = void>
  3125. struct has_from_json : std::false_type {};
  3126. // trait checking if j.get<T> is valid
  3127. // use this trait instead of std::is_constructible or std::is_convertible,
  3128. // both rely on, or make use of implicit conversions, and thus fail when T
  3129. // has several constructors/operator= (see https://github.com/nlohmann/json/issues/958)
  3130. template <typename BasicJsonType, typename T>
  3131. struct is_getable
  3132. {
  3133. static constexpr bool value = is_detected<get_template_function, const BasicJsonType&, T>::value;
  3134. };
  3135. template<typename BasicJsonType, typename T>
  3136. struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  3137. {
  3138. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  3139. static constexpr bool value =
  3140. is_detected_exact<void, from_json_function, serializer,
  3141. const BasicJsonType&, T&>::value;
  3142. };
  3143. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  3144. // this overload is used for non-default-constructible user-defined-types
  3145. template<typename BasicJsonType, typename T, typename = void>
  3146. struct has_non_default_from_json : std::false_type {};
  3147. template<typename BasicJsonType, typename T>
  3148. struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  3149. {
  3150. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  3151. static constexpr bool value =
  3152. is_detected_exact<T, from_json_function, serializer,
  3153. const BasicJsonType&>::value;
  3154. };
  3155. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  3156. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  3157. template<typename BasicJsonType, typename T, typename = void>
  3158. struct has_to_json : std::false_type {};
  3159. template<typename BasicJsonType, typename T>
  3160. struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  3161. {
  3162. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  3163. static constexpr bool value =
  3164. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  3165. T>::value;
  3166. };
  3167. ///////////////////
  3168. // is_ functions //
  3169. ///////////////////
  3170. // https://en.cppreference.com/w/cpp/types/conjunction
  3171. template<class...> struct conjunction : std::true_type { };
  3172. template<class B1> struct conjunction<B1> : B1 { };
  3173. template<class B1, class... Bn>
  3174. struct conjunction<B1, Bn...>
  3175. : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  3176. // https://en.cppreference.com/w/cpp/types/negation
  3177. template<class B> struct negation : std::integral_constant < bool, !B::value > { };
  3178. // Reimplementation of is_constructible and is_default_constructible, due to them being broken for
  3179. // std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367).
  3180. // This causes compile errors in e.g. clang 3.5 or gcc 4.9.
  3181. template <typename T>
  3182. struct is_default_constructible : std::is_default_constructible<T> {};
  3183. template <typename T1, typename T2>
  3184. struct is_default_constructible<std::pair<T1, T2>>
  3185. : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {};
  3186. template <typename T1, typename T2>
  3187. struct is_default_constructible<const std::pair<T1, T2>>
  3188. : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {};
  3189. template <typename... Ts>
  3190. struct is_default_constructible<std::tuple<Ts...>>
  3191. : conjunction<is_default_constructible<Ts>...> {};
  3192. template <typename... Ts>
  3193. struct is_default_constructible<const std::tuple<Ts...>>
  3194. : conjunction<is_default_constructible<Ts>...> {};
  3195. template <typename T, typename... Args>
  3196. struct is_constructible : std::is_constructible<T, Args...> {};
  3197. template <typename T1, typename T2>
  3198. struct is_constructible<std::pair<T1, T2>> : is_default_constructible<std::pair<T1, T2>> {};
  3199. template <typename T1, typename T2>
  3200. struct is_constructible<const std::pair<T1, T2>> : is_default_constructible<const std::pair<T1, T2>> {};
  3201. template <typename... Ts>
  3202. struct is_constructible<std::tuple<Ts...>> : is_default_constructible<std::tuple<Ts...>> {};
  3203. template <typename... Ts>
  3204. struct is_constructible<const std::tuple<Ts...>> : is_default_constructible<const std::tuple<Ts...>> {};
  3205. template<typename T, typename = void>
  3206. struct is_iterator_traits : std::false_type {};
  3207. template<typename T>
  3208. struct is_iterator_traits<iterator_traits<T>>
  3209. {
  3210. private:
  3211. using traits = iterator_traits<T>;
  3212. public:
  3213. static constexpr auto value =
  3214. is_detected<value_type_t, traits>::value &&
  3215. is_detected<difference_type_t, traits>::value &&
  3216. is_detected<pointer_t, traits>::value &&
  3217. is_detected<iterator_category_t, traits>::value &&
  3218. is_detected<reference_t, traits>::value;
  3219. };
  3220. // The following implementation of is_complete_type is taken from
  3221. // https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/
  3222. // and is written by Xiang Fan who agreed to using it in this library.
  3223. template<typename T, typename = void>
  3224. struct is_complete_type : std::false_type {};
  3225. template<typename T>
  3226. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  3227. template<typename BasicJsonType, typename CompatibleObjectType,
  3228. typename = void>
  3229. struct is_compatible_object_type_impl : std::false_type {};
  3230. template<typename BasicJsonType, typename CompatibleObjectType>
  3231. struct is_compatible_object_type_impl <
  3232. BasicJsonType, CompatibleObjectType,
  3233. enable_if_t < is_detected<mapped_type_t, CompatibleObjectType>::value&&
  3234. is_detected<key_type_t, CompatibleObjectType>::value >>
  3235. {
  3236. using object_t = typename BasicJsonType::object_t;
  3237. // macOS's is_constructible does not play well with nonesuch...
  3238. static constexpr bool value =
  3239. is_constructible<typename object_t::key_type,
  3240. typename CompatibleObjectType::key_type>::value &&
  3241. is_constructible<typename object_t::mapped_type,
  3242. typename CompatibleObjectType::mapped_type>::value;
  3243. };
  3244. template<typename BasicJsonType, typename CompatibleObjectType>
  3245. struct is_compatible_object_type
  3246. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  3247. template<typename BasicJsonType, typename ConstructibleObjectType,
  3248. typename = void>
  3249. struct is_constructible_object_type_impl : std::false_type {};
  3250. template<typename BasicJsonType, typename ConstructibleObjectType>
  3251. struct is_constructible_object_type_impl <
  3252. BasicJsonType, ConstructibleObjectType,
  3253. enable_if_t < is_detected<mapped_type_t, ConstructibleObjectType>::value&&
  3254. is_detected<key_type_t, ConstructibleObjectType>::value >>
  3255. {
  3256. using object_t = typename BasicJsonType::object_t;
  3257. static constexpr bool value =
  3258. (is_default_constructible<ConstructibleObjectType>::value &&
  3259. (std::is_move_assignable<ConstructibleObjectType>::value ||
  3260. std::is_copy_assignable<ConstructibleObjectType>::value) &&
  3261. (is_constructible<typename ConstructibleObjectType::key_type,
  3262. typename object_t::key_type>::value &&
  3263. std::is_same <
  3264. typename object_t::mapped_type,
  3265. typename ConstructibleObjectType::mapped_type >::value)) ||
  3266. (has_from_json<BasicJsonType,
  3267. typename ConstructibleObjectType::mapped_type>::value ||
  3268. has_non_default_from_json <
  3269. BasicJsonType,
  3270. typename ConstructibleObjectType::mapped_type >::value);
  3271. };
  3272. template<typename BasicJsonType, typename ConstructibleObjectType>
  3273. struct is_constructible_object_type
  3274. : is_constructible_object_type_impl<BasicJsonType,
  3275. ConstructibleObjectType> {};
  3276. template<typename BasicJsonType, typename CompatibleStringType,
  3277. typename = void>
  3278. struct is_compatible_string_type_impl : std::false_type {};
  3279. template<typename BasicJsonType, typename CompatibleStringType>
  3280. struct is_compatible_string_type_impl <
  3281. BasicJsonType, CompatibleStringType,
  3282. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  3283. value_type_t, CompatibleStringType>::value >>
  3284. {
  3285. static constexpr auto value =
  3286. is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  3287. };
  3288. template<typename BasicJsonType, typename ConstructibleStringType>
  3289. struct is_compatible_string_type
  3290. : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  3291. template<typename BasicJsonType, typename ConstructibleStringType,
  3292. typename = void>
  3293. struct is_constructible_string_type_impl : std::false_type {};
  3294. template<typename BasicJsonType, typename ConstructibleStringType>
  3295. struct is_constructible_string_type_impl <
  3296. BasicJsonType, ConstructibleStringType,
  3297. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  3298. value_type_t, ConstructibleStringType>::value >>
  3299. {
  3300. static constexpr auto value =
  3301. is_constructible<ConstructibleStringType,
  3302. typename BasicJsonType::string_t>::value;
  3303. };
  3304. template<typename BasicJsonType, typename ConstructibleStringType>
  3305. struct is_constructible_string_type
  3306. : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  3307. template<typename BasicJsonType, typename CompatibleArrayType, typename = void>
  3308. struct is_compatible_array_type_impl : std::false_type {};
  3309. template<typename BasicJsonType, typename CompatibleArrayType>
  3310. struct is_compatible_array_type_impl <
  3311. BasicJsonType, CompatibleArrayType,
  3312. enable_if_t < is_detected<value_type_t, CompatibleArrayType>::value&&
  3313. is_detected<iterator_t, CompatibleArrayType>::value&&
  3314. // This is needed because json_reverse_iterator has a ::iterator type...
  3315. // Therefore it is detected as a CompatibleArrayType.
  3316. // The real fix would be to have an Iterable concept.
  3317. !is_iterator_traits <
  3318. iterator_traits<CompatibleArrayType >>::value >>
  3319. {
  3320. static constexpr bool value =
  3321. is_constructible<BasicJsonType,
  3322. typename CompatibleArrayType::value_type>::value;
  3323. };
  3324. template<typename BasicJsonType, typename CompatibleArrayType>
  3325. struct is_compatible_array_type
  3326. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  3327. template<typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  3328. struct is_constructible_array_type_impl : std::false_type {};
  3329. template<typename BasicJsonType, typename ConstructibleArrayType>
  3330. struct is_constructible_array_type_impl <
  3331. BasicJsonType, ConstructibleArrayType,
  3332. enable_if_t<std::is_same<ConstructibleArrayType,
  3333. typename BasicJsonType::value_type>::value >>
  3334. : std::true_type {};
  3335. template<typename BasicJsonType, typename ConstructibleArrayType>
  3336. struct is_constructible_array_type_impl <
  3337. BasicJsonType, ConstructibleArrayType,
  3338. enable_if_t < !std::is_same<ConstructibleArrayType,
  3339. typename BasicJsonType::value_type>::value&&
  3340. is_default_constructible<ConstructibleArrayType>::value&&
  3341. (std::is_move_assignable<ConstructibleArrayType>::value ||
  3342. std::is_copy_assignable<ConstructibleArrayType>::value)&&
  3343. is_detected<value_type_t, ConstructibleArrayType>::value&&
  3344. is_detected<iterator_t, ConstructibleArrayType>::value&&
  3345. is_complete_type <
  3346. detected_t<value_type_t, ConstructibleArrayType >>::value >>
  3347. {
  3348. static constexpr bool value =
  3349. // This is needed because json_reverse_iterator has a ::iterator type,
  3350. // furthermore, std::back_insert_iterator (and other iterators) have a
  3351. // base class `iterator`... Therefore it is detected as a
  3352. // ConstructibleArrayType. The real fix would be to have an Iterable
  3353. // concept.
  3354. !is_iterator_traits<iterator_traits<ConstructibleArrayType>>::value &&
  3355. (std::is_same<typename ConstructibleArrayType::value_type,
  3356. typename BasicJsonType::array_t::value_type>::value ||
  3357. has_from_json<BasicJsonType,
  3358. typename ConstructibleArrayType::value_type>::value ||
  3359. has_non_default_from_json <
  3360. BasicJsonType, typename ConstructibleArrayType::value_type >::value);
  3361. };
  3362. template<typename BasicJsonType, typename ConstructibleArrayType>
  3363. struct is_constructible_array_type
  3364. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  3365. template<typename RealIntegerType, typename CompatibleNumberIntegerType,
  3366. typename = void>
  3367. struct is_compatible_integer_type_impl : std::false_type {};
  3368. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  3369. struct is_compatible_integer_type_impl <
  3370. RealIntegerType, CompatibleNumberIntegerType,
  3371. enable_if_t < std::is_integral<RealIntegerType>::value&&
  3372. std::is_integral<CompatibleNumberIntegerType>::value&&
  3373. !std::is_same<bool, CompatibleNumberIntegerType>::value >>
  3374. {
  3375. // is there an assert somewhere on overflows?
  3376. using RealLimits = std::numeric_limits<RealIntegerType>;
  3377. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  3378. static constexpr auto value =
  3379. is_constructible<RealIntegerType,
  3380. CompatibleNumberIntegerType>::value &&
  3381. CompatibleLimits::is_integer &&
  3382. RealLimits::is_signed == CompatibleLimits::is_signed;
  3383. };
  3384. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  3385. struct is_compatible_integer_type
  3386. : is_compatible_integer_type_impl<RealIntegerType,
  3387. CompatibleNumberIntegerType> {};
  3388. template<typename BasicJsonType, typename CompatibleType, typename = void>
  3389. struct is_compatible_type_impl: std::false_type {};
  3390. template<typename BasicJsonType, typename CompatibleType>
  3391. struct is_compatible_type_impl <
  3392. BasicJsonType, CompatibleType,
  3393. enable_if_t<is_complete_type<CompatibleType>::value >>
  3394. {
  3395. static constexpr bool value =
  3396. has_to_json<BasicJsonType, CompatibleType>::value;
  3397. };
  3398. template<typename BasicJsonType, typename CompatibleType>
  3399. struct is_compatible_type
  3400. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  3401. template<typename T1, typename T2>
  3402. struct is_constructible_tuple : std::false_type {};
  3403. template<typename T1, typename... Args>
  3404. struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<is_constructible<T1, Args>...> {};
  3405. // a naive helper to check if a type is an ordered_map (exploits the fact that
  3406. // ordered_map inherits capacity() from std::vector)
  3407. template <typename T>
  3408. struct is_ordered_map
  3409. {
  3410. using one = char;
  3411. struct two
  3412. {
  3413. char x[2]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  3414. };
  3415. template <typename C> static one test( decltype(&C::capacity) ) ;
  3416. template <typename C> static two test(...);
  3417. enum { value = sizeof(test<T>(nullptr)) == sizeof(char) }; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  3418. };
  3419. // to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324)
  3420. template < typename T, typename U, enable_if_t < !std::is_same<T, U>::value, int > = 0 >
  3421. T conditional_static_cast(U value)
  3422. {
  3423. return static_cast<T>(value);
  3424. }
  3425. template<typename T, typename U, enable_if_t<std::is_same<T, U>::value, int> = 0>
  3426. T conditional_static_cast(U value)
  3427. {
  3428. return value;
  3429. }
  3430. } // namespace detail
  3431. } // namespace nlohmann
  3432. // #include <nlohmann/detail/value_t.hpp>
  3433. namespace nlohmann
  3434. {
  3435. namespace detail
  3436. {
  3437. template<typename BasicJsonType>
  3438. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  3439. {
  3440. if (JSON_HEDLEY_UNLIKELY(!j.is_null()))
  3441. {
  3442. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j));
  3443. }
  3444. n = nullptr;
  3445. }
  3446. // overloads for basic_json template parameters
  3447. template < typename BasicJsonType, typename ArithmeticType,
  3448. enable_if_t < std::is_arithmetic<ArithmeticType>::value&&
  3449. !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3450. int > = 0 >
  3451. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  3452. {
  3453. switch (static_cast<value_t>(j))
  3454. {
  3455. case value_t::number_unsigned:
  3456. {
  3457. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3458. break;
  3459. }
  3460. case value_t::number_integer:
  3461. {
  3462. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3463. break;
  3464. }
  3465. case value_t::number_float:
  3466. {
  3467. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3468. break;
  3469. }
  3470. case value_t::null:
  3471. case value_t::object:
  3472. case value_t::array:
  3473. case value_t::string:
  3474. case value_t::boolean:
  3475. case value_t::binary:
  3476. case value_t::discarded:
  3477. default:
  3478. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j));
  3479. }
  3480. }
  3481. template<typename BasicJsonType>
  3482. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  3483. {
  3484. if (JSON_HEDLEY_UNLIKELY(!j.is_boolean()))
  3485. {
  3486. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j));
  3487. }
  3488. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  3489. }
  3490. template<typename BasicJsonType>
  3491. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  3492. {
  3493. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3494. {
  3495. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
  3496. }
  3497. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3498. }
  3499. template <
  3500. typename BasicJsonType, typename ConstructibleStringType,
  3501. enable_if_t <
  3502. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value&&
  3503. !std::is_same<typename BasicJsonType::string_t,
  3504. ConstructibleStringType>::value,
  3505. int > = 0 >
  3506. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  3507. {
  3508. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  3509. {
  3510. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
  3511. }
  3512. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  3513. }
  3514. template<typename BasicJsonType>
  3515. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  3516. {
  3517. get_arithmetic_value(j, val);
  3518. }
  3519. template<typename BasicJsonType>
  3520. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  3521. {
  3522. get_arithmetic_value(j, val);
  3523. }
  3524. template<typename BasicJsonType>
  3525. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  3526. {
  3527. get_arithmetic_value(j, val);
  3528. }
  3529. template<typename BasicJsonType, typename EnumType,
  3530. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3531. void from_json(const BasicJsonType& j, EnumType& e)
  3532. {
  3533. typename std::underlying_type<EnumType>::type val;
  3534. get_arithmetic_value(j, val);
  3535. e = static_cast<EnumType>(val);
  3536. }
  3537. // forward_list doesn't have an insert method
  3538. template<typename BasicJsonType, typename T, typename Allocator,
  3539. enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
  3540. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  3541. {
  3542. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3543. {
  3544. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3545. }
  3546. l.clear();
  3547. std::transform(j.rbegin(), j.rend(),
  3548. std::front_inserter(l), [](const BasicJsonType & i)
  3549. {
  3550. return i.template get<T>();
  3551. });
  3552. }
  3553. // valarray doesn't have an insert method
  3554. template<typename BasicJsonType, typename T,
  3555. enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
  3556. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  3557. {
  3558. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3559. {
  3560. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3561. }
  3562. l.resize(j.size());
  3563. std::transform(j.begin(), j.end(), std::begin(l),
  3564. [](const BasicJsonType & elem)
  3565. {
  3566. return elem.template get<T>();
  3567. });
  3568. }
  3569. template<typename BasicJsonType, typename T, std::size_t N>
  3570. auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  3571. -> decltype(j.template get<T>(), void())
  3572. {
  3573. for (std::size_t i = 0; i < N; ++i)
  3574. {
  3575. arr[i] = j.at(i).template get<T>();
  3576. }
  3577. }
  3578. template<typename BasicJsonType>
  3579. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  3580. {
  3581. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  3582. }
  3583. template<typename BasicJsonType, typename T, std::size_t N>
  3584. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  3585. priority_tag<2> /*unused*/)
  3586. -> decltype(j.template get<T>(), void())
  3587. {
  3588. for (std::size_t i = 0; i < N; ++i)
  3589. {
  3590. arr[i] = j.at(i).template get<T>();
  3591. }
  3592. }
  3593. template<typename BasicJsonType, typename ConstructibleArrayType,
  3594. enable_if_t<
  3595. std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
  3596. int> = 0>
  3597. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  3598. -> decltype(
  3599. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  3600. j.template get<typename ConstructibleArrayType::value_type>(),
  3601. void())
  3602. {
  3603. using std::end;
  3604. ConstructibleArrayType ret;
  3605. ret.reserve(j.size());
  3606. std::transform(j.begin(), j.end(),
  3607. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  3608. {
  3609. // get<BasicJsonType>() returns *this, this won't call a from_json
  3610. // method when value_type is BasicJsonType
  3611. return i.template get<typename ConstructibleArrayType::value_type>();
  3612. });
  3613. arr = std::move(ret);
  3614. }
  3615. template<typename BasicJsonType, typename ConstructibleArrayType,
  3616. enable_if_t<
  3617. std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
  3618. int> = 0>
  3619. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  3620. priority_tag<0> /*unused*/)
  3621. {
  3622. using std::end;
  3623. ConstructibleArrayType ret;
  3624. std::transform(
  3625. j.begin(), j.end(), std::inserter(ret, end(ret)),
  3626. [](const BasicJsonType & i)
  3627. {
  3628. // get<BasicJsonType>() returns *this, this won't call a from_json
  3629. // method when value_type is BasicJsonType
  3630. return i.template get<typename ConstructibleArrayType::value_type>();
  3631. });
  3632. arr = std::move(ret);
  3633. }
  3634. template < typename BasicJsonType, typename ConstructibleArrayType,
  3635. enable_if_t <
  3636. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value&&
  3637. !is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value&&
  3638. !is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value&&
  3639. !std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value&&
  3640. !is_basic_json<ConstructibleArrayType>::value,
  3641. int > = 0 >
  3642. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  3643. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  3644. j.template get<typename ConstructibleArrayType::value_type>(),
  3645. void())
  3646. {
  3647. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3648. {
  3649. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3650. }
  3651. from_json_array_impl(j, arr, priority_tag<3> {});
  3652. }
  3653. template < typename BasicJsonType, typename T, std::size_t... Idx >
  3654. std::array<T, sizeof...(Idx)> from_json_inplace_array_impl(BasicJsonType&& j,
  3655. identity_tag<std::array<T, sizeof...(Idx)>> /*unused*/, index_sequence<Idx...> /*unused*/)
  3656. {
  3657. return { { std::forward<BasicJsonType>(j).at(Idx).template get<T>()... } };
  3658. }
  3659. template < typename BasicJsonType, typename T, std::size_t N >
  3660. auto from_json(BasicJsonType&& j, identity_tag<std::array<T, N>> tag)
  3661. -> decltype(from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {}))
  3662. {
  3663. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3664. {
  3665. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3666. }
  3667. return from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {});
  3668. }
  3669. template<typename BasicJsonType>
  3670. void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin)
  3671. {
  3672. if (JSON_HEDLEY_UNLIKELY(!j.is_binary()))
  3673. {
  3674. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j));
  3675. }
  3676. bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>();
  3677. }
  3678. template<typename BasicJsonType, typename ConstructibleObjectType,
  3679. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  3680. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  3681. {
  3682. if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
  3683. {
  3684. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j));
  3685. }
  3686. ConstructibleObjectType ret;
  3687. const auto* inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  3688. using value_type = typename ConstructibleObjectType::value_type;
  3689. std::transform(
  3690. inner_object->begin(), inner_object->end(),
  3691. std::inserter(ret, ret.begin()),
  3692. [](typename BasicJsonType::object_t::value_type const & p)
  3693. {
  3694. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  3695. });
  3696. obj = std::move(ret);
  3697. }
  3698. // overload for arithmetic types, not chosen for basic_json template arguments
  3699. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  3700. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  3701. // an arithmetic type?
  3702. template < typename BasicJsonType, typename ArithmeticType,
  3703. enable_if_t <
  3704. std::is_arithmetic<ArithmeticType>::value&&
  3705. !std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value&&
  3706. !std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value&&
  3707. !std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value&&
  3708. !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3709. int > = 0 >
  3710. void from_json(const BasicJsonType& j, ArithmeticType& val)
  3711. {
  3712. switch (static_cast<value_t>(j))
  3713. {
  3714. case value_t::number_unsigned:
  3715. {
  3716. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3717. break;
  3718. }
  3719. case value_t::number_integer:
  3720. {
  3721. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3722. break;
  3723. }
  3724. case value_t::number_float:
  3725. {
  3726. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3727. break;
  3728. }
  3729. case value_t::boolean:
  3730. {
  3731. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  3732. break;
  3733. }
  3734. case value_t::null:
  3735. case value_t::object:
  3736. case value_t::array:
  3737. case value_t::string:
  3738. case value_t::binary:
  3739. case value_t::discarded:
  3740. default:
  3741. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j));
  3742. }
  3743. }
  3744. template<typename BasicJsonType, typename... Args, std::size_t... Idx>
  3745. std::tuple<Args...> from_json_tuple_impl_base(BasicJsonType&& j, index_sequence<Idx...> /*unused*/)
  3746. {
  3747. return std::make_tuple(std::forward<BasicJsonType>(j).at(Idx).template get<Args>()...);
  3748. }
  3749. template < typename BasicJsonType, class A1, class A2 >
  3750. std::pair<A1, A2> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::pair<A1, A2>> /*unused*/, priority_tag<0> /*unused*/)
  3751. {
  3752. return {std::forward<BasicJsonType>(j).at(0).template get<A1>(),
  3753. std::forward<BasicJsonType>(j).at(1).template get<A2>()};
  3754. }
  3755. template<typename BasicJsonType, typename A1, typename A2>
  3756. void from_json_tuple_impl(BasicJsonType&& j, std::pair<A1, A2>& p, priority_tag<1> /*unused*/)
  3757. {
  3758. p = from_json_tuple_impl(std::forward<BasicJsonType>(j), identity_tag<std::pair<A1, A2>> {}, priority_tag<0> {});
  3759. }
  3760. template<typename BasicJsonType, typename... Args>
  3761. std::tuple<Args...> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::tuple<Args...>> /*unused*/, priority_tag<2> /*unused*/)
  3762. {
  3763. return from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {});
  3764. }
  3765. template<typename BasicJsonType, typename... Args>
  3766. void from_json_tuple_impl(BasicJsonType&& j, std::tuple<Args...>& t, priority_tag<3> /*unused*/)
  3767. {
  3768. t = from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {});
  3769. }
  3770. template<typename BasicJsonType, typename TupleRelated>
  3771. auto from_json(BasicJsonType&& j, TupleRelated&& t)
  3772. -> decltype(from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {}))
  3773. {
  3774. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3775. {
  3776. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3777. }
  3778. return from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {});
  3779. }
  3780. template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  3781. typename = enable_if_t < !std::is_constructible <
  3782. typename BasicJsonType::string_t, Key >::value >>
  3783. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  3784. {
  3785. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3786. {
  3787. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3788. }
  3789. m.clear();
  3790. for (const auto& p : j)
  3791. {
  3792. if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
  3793. {
  3794. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j));
  3795. }
  3796. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3797. }
  3798. }
  3799. template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  3800. typename = enable_if_t < !std::is_constructible <
  3801. typename BasicJsonType::string_t, Key >::value >>
  3802. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  3803. {
  3804. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3805. {
  3806. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
  3807. }
  3808. m.clear();
  3809. for (const auto& p : j)
  3810. {
  3811. if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
  3812. {
  3813. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j));
  3814. }
  3815. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3816. }
  3817. }
  3818. struct from_json_fn
  3819. {
  3820. template<typename BasicJsonType, typename T>
  3821. auto operator()(const BasicJsonType& j, T&& val) const
  3822. noexcept(noexcept(from_json(j, std::forward<T>(val))))
  3823. -> decltype(from_json(j, std::forward<T>(val)))
  3824. {
  3825. return from_json(j, std::forward<T>(val));
  3826. }
  3827. };
  3828. } // namespace detail
  3829. /// namespace to hold default `from_json` function
  3830. /// to see why this is required:
  3831. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  3832. namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
  3833. {
  3834. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; // NOLINT(misc-definitions-in-headers)
  3835. } // namespace
  3836. } // namespace nlohmann
  3837. // #include <nlohmann/detail/conversions/to_json.hpp>
  3838. #include <algorithm> // copy
  3839. #include <iterator> // begin, end
  3840. #include <string> // string
  3841. #include <tuple> // tuple, get
  3842. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  3843. #include <utility> // move, forward, declval, pair
  3844. #include <valarray> // valarray
  3845. #include <vector> // vector
  3846. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  3847. #include <cstddef> // size_t
  3848. #include <iterator> // input_iterator_tag
  3849. #include <string> // string, to_string
  3850. #include <tuple> // tuple_size, get, tuple_element
  3851. #include <utility> // move
  3852. // #include <nlohmann/detail/meta/type_traits.hpp>
  3853. // #include <nlohmann/detail/value_t.hpp>
  3854. namespace nlohmann
  3855. {
  3856. namespace detail
  3857. {
  3858. template<typename string_type>
  3859. void int_to_string( string_type& target, std::size_t value )
  3860. {
  3861. // For ADL
  3862. using std::to_string;
  3863. target = to_string(value);
  3864. }
  3865. template<typename IteratorType> class iteration_proxy_value
  3866. {
  3867. public:
  3868. using difference_type = std::ptrdiff_t;
  3869. using value_type = iteration_proxy_value;
  3870. using pointer = value_type * ;
  3871. using reference = value_type & ;
  3872. using iterator_category = std::input_iterator_tag;
  3873. using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type;
  3874. private:
  3875. /// the iterator
  3876. IteratorType anchor;
  3877. /// an index for arrays (used to create key names)
  3878. std::size_t array_index = 0;
  3879. /// last stringified array index
  3880. mutable std::size_t array_index_last = 0;
  3881. /// a string representation of the array index
  3882. mutable string_type array_index_str = "0";
  3883. /// an empty string (to return a reference for primitive values)
  3884. const string_type empty_str{};
  3885. public:
  3886. explicit iteration_proxy_value(IteratorType it) noexcept
  3887. : anchor(std::move(it))
  3888. {}
  3889. /// dereference operator (needed for range-based for)
  3890. iteration_proxy_value& operator*()
  3891. {
  3892. return *this;
  3893. }
  3894. /// increment operator (needed for range-based for)
  3895. iteration_proxy_value& operator++()
  3896. {
  3897. ++anchor;
  3898. ++array_index;
  3899. return *this;
  3900. }
  3901. /// equality operator (needed for InputIterator)
  3902. bool operator==(const iteration_proxy_value& o) const
  3903. {
  3904. return anchor == o.anchor;
  3905. }
  3906. /// inequality operator (needed for range-based for)
  3907. bool operator!=(const iteration_proxy_value& o) const
  3908. {
  3909. return anchor != o.anchor;
  3910. }
  3911. /// return key of the iterator
  3912. const string_type& key() const
  3913. {
  3914. JSON_ASSERT(anchor.m_object != nullptr);
  3915. switch (anchor.m_object->type())
  3916. {
  3917. // use integer array index as key
  3918. case value_t::array:
  3919. {
  3920. if (array_index != array_index_last)
  3921. {
  3922. int_to_string( array_index_str, array_index );
  3923. array_index_last = array_index;
  3924. }
  3925. return array_index_str;
  3926. }
  3927. // use key from the object
  3928. case value_t::object:
  3929. return anchor.key();
  3930. // use an empty key for all primitive types
  3931. case value_t::null:
  3932. case value_t::string:
  3933. case value_t::boolean:
  3934. case value_t::number_integer:
  3935. case value_t::number_unsigned:
  3936. case value_t::number_float:
  3937. case value_t::binary:
  3938. case value_t::discarded:
  3939. default:
  3940. return empty_str;
  3941. }
  3942. }
  3943. /// return value of the iterator
  3944. typename IteratorType::reference value() const
  3945. {
  3946. return anchor.value();
  3947. }
  3948. };
  3949. /// proxy class for the items() function
  3950. template<typename IteratorType> class iteration_proxy
  3951. {
  3952. private:
  3953. /// the container to iterate
  3954. typename IteratorType::reference container;
  3955. public:
  3956. /// construct iteration proxy from a container
  3957. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  3958. : container(cont) {}
  3959. /// return iterator begin (needed for range-based for)
  3960. iteration_proxy_value<IteratorType> begin() noexcept
  3961. {
  3962. return iteration_proxy_value<IteratorType>(container.begin());
  3963. }
  3964. /// return iterator end (needed for range-based for)
  3965. iteration_proxy_value<IteratorType> end() noexcept
  3966. {
  3967. return iteration_proxy_value<IteratorType>(container.end());
  3968. }
  3969. };
  3970. // Structured Bindings Support
  3971. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3972. // And see https://github.com/nlohmann/json/pull/1391
  3973. template<std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  3974. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  3975. {
  3976. return i.key();
  3977. }
  3978. // Structured Bindings Support
  3979. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3980. // And see https://github.com/nlohmann/json/pull/1391
  3981. template<std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  3982. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  3983. {
  3984. return i.value();
  3985. }
  3986. } // namespace detail
  3987. } // namespace nlohmann
  3988. // The Addition to the STD Namespace is required to add
  3989. // Structured Bindings Support to the iteration_proxy_value class
  3990. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3991. // And see https://github.com/nlohmann/json/pull/1391
  3992. namespace std
  3993. {
  3994. #if defined(__clang__)
  3995. // Fix: https://github.com/nlohmann/json/issues/1401
  3996. #pragma clang diagnostic push
  3997. #pragma clang diagnostic ignored "-Wmismatched-tags"
  3998. #endif
  3999. template<typename IteratorType>
  4000. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  4001. : public std::integral_constant<std::size_t, 2> {};
  4002. template<std::size_t N, typename IteratorType>
  4003. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  4004. {
  4005. public:
  4006. using type = decltype(
  4007. get<N>(std::declval <
  4008. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  4009. };
  4010. #if defined(__clang__)
  4011. #pragma clang diagnostic pop
  4012. #endif
  4013. } // namespace std
  4014. // #include <nlohmann/detail/meta/cpp_future.hpp>
  4015. // #include <nlohmann/detail/meta/type_traits.hpp>
  4016. // #include <nlohmann/detail/value_t.hpp>
  4017. namespace nlohmann
  4018. {
  4019. namespace detail
  4020. {
  4021. //////////////////
  4022. // constructors //
  4023. //////////////////
  4024. /*
  4025. * Note all external_constructor<>::construct functions need to call
  4026. * j.m_value.destroy(j.m_type) to avoid a memory leak in case j contains an
  4027. * allocated value (e.g., a string). See bug issue
  4028. * https://github.com/nlohmann/json/issues/2865 for more information.
  4029. */
  4030. template<value_t> struct external_constructor;
  4031. template<>
  4032. struct external_constructor<value_t::boolean>
  4033. {
  4034. template<typename BasicJsonType>
  4035. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  4036. {
  4037. j.m_value.destroy(j.m_type);
  4038. j.m_type = value_t::boolean;
  4039. j.m_value = b;
  4040. j.assert_invariant();
  4041. }
  4042. };
  4043. template<>
  4044. struct external_constructor<value_t::string>
  4045. {
  4046. template<typename BasicJsonType>
  4047. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  4048. {
  4049. j.m_value.destroy(j.m_type);
  4050. j.m_type = value_t::string;
  4051. j.m_value = s;
  4052. j.assert_invariant();
  4053. }
  4054. template<typename BasicJsonType>
  4055. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  4056. {
  4057. j.m_value.destroy(j.m_type);
  4058. j.m_type = value_t::string;
  4059. j.m_value = std::move(s);
  4060. j.assert_invariant();
  4061. }
  4062. template < typename BasicJsonType, typename CompatibleStringType,
  4063. enable_if_t < !std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  4064. int > = 0 >
  4065. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  4066. {
  4067. j.m_value.destroy(j.m_type);
  4068. j.m_type = value_t::string;
  4069. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  4070. j.assert_invariant();
  4071. }
  4072. };
  4073. template<>
  4074. struct external_constructor<value_t::binary>
  4075. {
  4076. template<typename BasicJsonType>
  4077. static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b)
  4078. {
  4079. j.m_value.destroy(j.m_type);
  4080. j.m_type = value_t::binary;
  4081. j.m_value = typename BasicJsonType::binary_t(b);
  4082. j.assert_invariant();
  4083. }
  4084. template<typename BasicJsonType>
  4085. static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b)
  4086. {
  4087. j.m_value.destroy(j.m_type);
  4088. j.m_type = value_t::binary;
  4089. j.m_value = typename BasicJsonType::binary_t(std::move(b));
  4090. j.assert_invariant();
  4091. }
  4092. };
  4093. template<>
  4094. struct external_constructor<value_t::number_float>
  4095. {
  4096. template<typename BasicJsonType>
  4097. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  4098. {
  4099. j.m_value.destroy(j.m_type);
  4100. j.m_type = value_t::number_float;
  4101. j.m_value = val;
  4102. j.assert_invariant();
  4103. }
  4104. };
  4105. template<>
  4106. struct external_constructor<value_t::number_unsigned>
  4107. {
  4108. template<typename BasicJsonType>
  4109. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  4110. {
  4111. j.m_value.destroy(j.m_type);
  4112. j.m_type = value_t::number_unsigned;
  4113. j.m_value = val;
  4114. j.assert_invariant();
  4115. }
  4116. };
  4117. template<>
  4118. struct external_constructor<value_t::number_integer>
  4119. {
  4120. template<typename BasicJsonType>
  4121. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  4122. {
  4123. j.m_value.destroy(j.m_type);
  4124. j.m_type = value_t::number_integer;
  4125. j.m_value = val;
  4126. j.assert_invariant();
  4127. }
  4128. };
  4129. template<>
  4130. struct external_constructor<value_t::array>
  4131. {
  4132. template<typename BasicJsonType>
  4133. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  4134. {
  4135. j.m_value.destroy(j.m_type);
  4136. j.m_type = value_t::array;
  4137. j.m_value = arr;
  4138. j.set_parents();
  4139. j.assert_invariant();
  4140. }
  4141. template<typename BasicJsonType>
  4142. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  4143. {
  4144. j.m_value.destroy(j.m_type);
  4145. j.m_type = value_t::array;
  4146. j.m_value = std::move(arr);
  4147. j.set_parents();
  4148. j.assert_invariant();
  4149. }
  4150. template < typename BasicJsonType, typename CompatibleArrayType,
  4151. enable_if_t < !std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  4152. int > = 0 >
  4153. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  4154. {
  4155. using std::begin;
  4156. using std::end;
  4157. j.m_value.destroy(j.m_type);
  4158. j.m_type = value_t::array;
  4159. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  4160. j.set_parents();
  4161. j.assert_invariant();
  4162. }
  4163. template<typename BasicJsonType>
  4164. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  4165. {
  4166. j.m_value.destroy(j.m_type);
  4167. j.m_type = value_t::array;
  4168. j.m_value = value_t::array;
  4169. j.m_value.array->reserve(arr.size());
  4170. for (const bool x : arr)
  4171. {
  4172. j.m_value.array->push_back(x);
  4173. j.set_parent(j.m_value.array->back());
  4174. }
  4175. j.assert_invariant();
  4176. }
  4177. template<typename BasicJsonType, typename T,
  4178. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  4179. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  4180. {
  4181. j.m_value.destroy(j.m_type);
  4182. j.m_type = value_t::array;
  4183. j.m_value = value_t::array;
  4184. j.m_value.array->resize(arr.size());
  4185. if (arr.size() > 0)
  4186. {
  4187. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  4188. }
  4189. j.set_parents();
  4190. j.assert_invariant();
  4191. }
  4192. };
  4193. template<>
  4194. struct external_constructor<value_t::object>
  4195. {
  4196. template<typename BasicJsonType>
  4197. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  4198. {
  4199. j.m_value.destroy(j.m_type);
  4200. j.m_type = value_t::object;
  4201. j.m_value = obj;
  4202. j.set_parents();
  4203. j.assert_invariant();
  4204. }
  4205. template<typename BasicJsonType>
  4206. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  4207. {
  4208. j.m_value.destroy(j.m_type);
  4209. j.m_type = value_t::object;
  4210. j.m_value = std::move(obj);
  4211. j.set_parents();
  4212. j.assert_invariant();
  4213. }
  4214. template < typename BasicJsonType, typename CompatibleObjectType,
  4215. enable_if_t < !std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int > = 0 >
  4216. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  4217. {
  4218. using std::begin;
  4219. using std::end;
  4220. j.m_value.destroy(j.m_type);
  4221. j.m_type = value_t::object;
  4222. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  4223. j.set_parents();
  4224. j.assert_invariant();
  4225. }
  4226. };
  4227. /////////////
  4228. // to_json //
  4229. /////////////
  4230. template<typename BasicJsonType, typename T,
  4231. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  4232. void to_json(BasicJsonType& j, T b) noexcept
  4233. {
  4234. external_constructor<value_t::boolean>::construct(j, b);
  4235. }
  4236. template<typename BasicJsonType, typename CompatibleString,
  4237. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  4238. void to_json(BasicJsonType& j, const CompatibleString& s)
  4239. {
  4240. external_constructor<value_t::string>::construct(j, s);
  4241. }
  4242. template<typename BasicJsonType>
  4243. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  4244. {
  4245. external_constructor<value_t::string>::construct(j, std::move(s));
  4246. }
  4247. template<typename BasicJsonType, typename FloatType,
  4248. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  4249. void to_json(BasicJsonType& j, FloatType val) noexcept
  4250. {
  4251. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  4252. }
  4253. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  4254. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  4255. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  4256. {
  4257. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  4258. }
  4259. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  4260. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  4261. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  4262. {
  4263. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  4264. }
  4265. template<typename BasicJsonType, typename EnumType,
  4266. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  4267. void to_json(BasicJsonType& j, EnumType e) noexcept
  4268. {
  4269. using underlying_type = typename std::underlying_type<EnumType>::type;
  4270. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  4271. }
  4272. template<typename BasicJsonType>
  4273. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  4274. {
  4275. external_constructor<value_t::array>::construct(j, e);
  4276. }
  4277. template < typename BasicJsonType, typename CompatibleArrayType,
  4278. enable_if_t < is_compatible_array_type<BasicJsonType,
  4279. CompatibleArrayType>::value&&
  4280. !is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value&&
  4281. !is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value&&
  4282. !std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value&&
  4283. !is_basic_json<CompatibleArrayType>::value,
  4284. int > = 0 >
  4285. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  4286. {
  4287. external_constructor<value_t::array>::construct(j, arr);
  4288. }
  4289. template<typename BasicJsonType>
  4290. void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin)
  4291. {
  4292. external_constructor<value_t::binary>::construct(j, bin);
  4293. }
  4294. template<typename BasicJsonType, typename T,
  4295. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  4296. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  4297. {
  4298. external_constructor<value_t::array>::construct(j, std::move(arr));
  4299. }
  4300. template<typename BasicJsonType>
  4301. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  4302. {
  4303. external_constructor<value_t::array>::construct(j, std::move(arr));
  4304. }
  4305. template < typename BasicJsonType, typename CompatibleObjectType,
  4306. enable_if_t < is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value&& !is_basic_json<CompatibleObjectType>::value, int > = 0 >
  4307. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  4308. {
  4309. external_constructor<value_t::object>::construct(j, obj);
  4310. }
  4311. template<typename BasicJsonType>
  4312. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  4313. {
  4314. external_constructor<value_t::object>::construct(j, std::move(obj));
  4315. }
  4316. template <
  4317. typename BasicJsonType, typename T, std::size_t N,
  4318. enable_if_t < !std::is_constructible<typename BasicJsonType::string_t,
  4319. const T(&)[N]>::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  4320. int > = 0 >
  4321. void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  4322. {
  4323. external_constructor<value_t::array>::construct(j, arr);
  4324. }
  4325. template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 >
  4326. void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
  4327. {
  4328. j = { p.first, p.second };
  4329. }
  4330. // for https://github.com/nlohmann/json/pull/1134
  4331. template<typename BasicJsonType, typename T,
  4332. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  4333. void to_json(BasicJsonType& j, const T& b)
  4334. {
  4335. j = { {b.key(), b.value()} };
  4336. }
  4337. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  4338. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  4339. {
  4340. j = { std::get<Idx>(t)... };
  4341. }
  4342. template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0>
  4343. void to_json(BasicJsonType& j, const T& t)
  4344. {
  4345. to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {});
  4346. }
  4347. struct to_json_fn
  4348. {
  4349. template<typename BasicJsonType, typename T>
  4350. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  4351. -> decltype(to_json(j, std::forward<T>(val)), void())
  4352. {
  4353. return to_json(j, std::forward<T>(val));
  4354. }
  4355. };
  4356. } // namespace detail
  4357. /// namespace to hold default `to_json` function
  4358. /// to see why this is required:
  4359. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  4360. namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
  4361. {
  4362. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value; // NOLINT(misc-definitions-in-headers)
  4363. } // namespace
  4364. } // namespace nlohmann
  4365. // #include <nlohmann/detail/meta/identity_tag.hpp>
  4366. // #include <nlohmann/detail/meta/type_traits.hpp>
  4367. namespace nlohmann
  4368. {
  4369. template<typename ValueType, typename>
  4370. struct adl_serializer
  4371. {
  4372. /*!
  4373. @brief convert a JSON value to any value type
  4374. This function is usually called by the `get()` function of the
  4375. @ref basic_json class (either explicit or via conversion operators).
  4376. @note This function is chosen for default-constructible value types.
  4377. @param[in] j JSON value to read from
  4378. @param[in,out] val value to write to
  4379. */
  4380. template<typename BasicJsonType, typename TargetType = ValueType>
  4381. static auto from_json(BasicJsonType && j, TargetType& val) noexcept(
  4382. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  4383. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  4384. {
  4385. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  4386. }
  4387. /*!
  4388. @brief convert a JSON value to any value type
  4389. This function is usually called by the `get()` function of the
  4390. @ref basic_json class (either explicit or via conversion operators).
  4391. @note This function is chosen for value types which are not default-constructible.
  4392. @param[in] j JSON value to read from
  4393. @return copy of the JSON value, converted to @a ValueType
  4394. */
  4395. template<typename BasicJsonType, typename TargetType = ValueType>
  4396. static auto from_json(BasicJsonType && j) noexcept(
  4397. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))
  4398. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))
  4399. {
  4400. return ::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {});
  4401. }
  4402. /*!
  4403. @brief convert any value type to a JSON value
  4404. This function is usually called by the constructors of the @ref basic_json
  4405. class.
  4406. @param[in,out] j JSON value to write to
  4407. @param[in] val value to read from
  4408. */
  4409. template<typename BasicJsonType, typename TargetType = ValueType>
  4410. static auto to_json(BasicJsonType& j, TargetType && val) noexcept(
  4411. noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))
  4412. -> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void())
  4413. {
  4414. ::nlohmann::to_json(j, std::forward<TargetType>(val));
  4415. }
  4416. };
  4417. } // namespace nlohmann
  4418. // #include <nlohmann/byte_container_with_subtype.hpp>
  4419. #include <cstdint> // uint8_t, uint64_t
  4420. #include <tuple> // tie
  4421. #include <utility> // move
  4422. namespace nlohmann
  4423. {
  4424. /*!
  4425. @brief an internal type for a backed binary type
  4426. This type extends the template parameter @a BinaryType provided to `basic_json`
  4427. with a subtype used by BSON and MessagePack. This type exists so that the user
  4428. does not have to specify a type themselves with a specific naming scheme in
  4429. order to override the binary type.
  4430. @tparam BinaryType container to store bytes (`std::vector<std::uint8_t>` by
  4431. default)
  4432. @since version 3.8.0; changed type of subtypes to std::uint64_t in 3.10.0.
  4433. */
  4434. template<typename BinaryType>
  4435. class byte_container_with_subtype : public BinaryType
  4436. {
  4437. public:
  4438. /// the type of the underlying container
  4439. using container_type = BinaryType;
  4440. /// the type of the subtype
  4441. using subtype_type = std::uint64_t;
  4442. byte_container_with_subtype() noexcept(noexcept(container_type()))
  4443. : container_type()
  4444. {}
  4445. byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b)))
  4446. : container_type(b)
  4447. {}
  4448. byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b))))
  4449. : container_type(std::move(b))
  4450. {}
  4451. byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b)))
  4452. : container_type(b)
  4453. , m_subtype(subtype_)
  4454. , m_has_subtype(true)
  4455. {}
  4456. byte_container_with_subtype(container_type&& b, subtype_type subtype_) noexcept(noexcept(container_type(std::move(b))))
  4457. : container_type(std::move(b))
  4458. , m_subtype(subtype_)
  4459. , m_has_subtype(true)
  4460. {}
  4461. bool operator==(const byte_container_with_subtype& rhs) const
  4462. {
  4463. return std::tie(static_cast<const BinaryType&>(*this), m_subtype, m_has_subtype) ==
  4464. std::tie(static_cast<const BinaryType&>(rhs), rhs.m_subtype, rhs.m_has_subtype);
  4465. }
  4466. bool operator!=(const byte_container_with_subtype& rhs) const
  4467. {
  4468. return !(rhs == *this);
  4469. }
  4470. /*!
  4471. @brief sets the binary subtype
  4472. Sets the binary subtype of the value, also flags a binary JSON value as
  4473. having a subtype, which has implications for serialization.
  4474. @complexity Constant.
  4475. @exceptionsafety No-throw guarantee: this member function never throws
  4476. exceptions.
  4477. @sa see @ref subtype() -- return the binary subtype
  4478. @sa see @ref clear_subtype() -- clears the binary subtype
  4479. @sa see @ref has_subtype() -- returns whether or not the binary value has a
  4480. subtype
  4481. @since version 3.8.0
  4482. */
  4483. void set_subtype(subtype_type subtype_) noexcept
  4484. {
  4485. m_subtype = subtype_;
  4486. m_has_subtype = true;
  4487. }
  4488. /*!
  4489. @brief return the binary subtype
  4490. Returns the numerical subtype of the value if it has a subtype. If it does
  4491. not have a subtype, this function will return subtype_type(-1) as a sentinel
  4492. value.
  4493. @return the numerical subtype of the binary value
  4494. @complexity Constant.
  4495. @exceptionsafety No-throw guarantee: this member function never throws
  4496. exceptions.
  4497. @sa see @ref set_subtype() -- sets the binary subtype
  4498. @sa see @ref clear_subtype() -- clears the binary subtype
  4499. @sa see @ref has_subtype() -- returns whether or not the binary value has a
  4500. subtype
  4501. @since version 3.8.0; fixed return value to properly return
  4502. subtype_type(-1) as documented in version 3.10.0
  4503. */
  4504. constexpr subtype_type subtype() const noexcept
  4505. {
  4506. return m_has_subtype ? m_subtype : subtype_type(-1);
  4507. }
  4508. /*!
  4509. @brief return whether the value has a subtype
  4510. @return whether the value has a subtype
  4511. @complexity Constant.
  4512. @exceptionsafety No-throw guarantee: this member function never throws
  4513. exceptions.
  4514. @sa see @ref subtype() -- return the binary subtype
  4515. @sa see @ref set_subtype() -- sets the binary subtype
  4516. @sa see @ref clear_subtype() -- clears the binary subtype
  4517. @since version 3.8.0
  4518. */
  4519. constexpr bool has_subtype() const noexcept
  4520. {
  4521. return m_has_subtype;
  4522. }
  4523. /*!
  4524. @brief clears the binary subtype
  4525. Clears the binary subtype and flags the value as not having a subtype, which
  4526. has implications for serialization; for instance MessagePack will prefer the
  4527. bin family over the ext family.
  4528. @complexity Constant.
  4529. @exceptionsafety No-throw guarantee: this member function never throws
  4530. exceptions.
  4531. @sa see @ref subtype() -- return the binary subtype
  4532. @sa see @ref set_subtype() -- sets the binary subtype
  4533. @sa see @ref has_subtype() -- returns whether or not the binary value has a
  4534. subtype
  4535. @since version 3.8.0
  4536. */
  4537. void clear_subtype() noexcept
  4538. {
  4539. m_subtype = 0;
  4540. m_has_subtype = false;
  4541. }
  4542. private:
  4543. subtype_type m_subtype = 0;
  4544. bool m_has_subtype = false;
  4545. };
  4546. } // namespace nlohmann
  4547. // #include <nlohmann/detail/conversions/from_json.hpp>
  4548. // #include <nlohmann/detail/conversions/to_json.hpp>
  4549. // #include <nlohmann/detail/exceptions.hpp>
  4550. // #include <nlohmann/detail/hash.hpp>
  4551. #include <cstdint> // uint8_t
  4552. #include <cstddef> // size_t
  4553. #include <functional> // hash
  4554. // #include <nlohmann/detail/macro_scope.hpp>
  4555. // #include <nlohmann/detail/value_t.hpp>
  4556. namespace nlohmann
  4557. {
  4558. namespace detail
  4559. {
  4560. // boost::hash_combine
  4561. inline std::size_t combine(std::size_t seed, std::size_t h) noexcept
  4562. {
  4563. seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U);
  4564. return seed;
  4565. }
  4566. /*!
  4567. @brief hash a JSON value
  4568. The hash function tries to rely on std::hash where possible. Furthermore, the
  4569. type of the JSON value is taken into account to have different hash values for
  4570. null, 0, 0U, and false, etc.
  4571. @tparam BasicJsonType basic_json specialization
  4572. @param j JSON value to hash
  4573. @return hash value of j
  4574. */
  4575. template<typename BasicJsonType>
  4576. std::size_t hash(const BasicJsonType& j)
  4577. {
  4578. using string_t = typename BasicJsonType::string_t;
  4579. using number_integer_t = typename BasicJsonType::number_integer_t;
  4580. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4581. using number_float_t = typename BasicJsonType::number_float_t;
  4582. const auto type = static_cast<std::size_t>(j.type());
  4583. switch (j.type())
  4584. {
  4585. case BasicJsonType::value_t::null:
  4586. case BasicJsonType::value_t::discarded:
  4587. {
  4588. return combine(type, 0);
  4589. }
  4590. case BasicJsonType::value_t::object:
  4591. {
  4592. auto seed = combine(type, j.size());
  4593. for (const auto& element : j.items())
  4594. {
  4595. const auto h = std::hash<string_t> {}(element.key());
  4596. seed = combine(seed, h);
  4597. seed = combine(seed, hash(element.value()));
  4598. }
  4599. return seed;
  4600. }
  4601. case BasicJsonType::value_t::array:
  4602. {
  4603. auto seed = combine(type, j.size());
  4604. for (const auto& element : j)
  4605. {
  4606. seed = combine(seed, hash(element));
  4607. }
  4608. return seed;
  4609. }
  4610. case BasicJsonType::value_t::string:
  4611. {
  4612. const auto h = std::hash<string_t> {}(j.template get_ref<const string_t&>());
  4613. return combine(type, h);
  4614. }
  4615. case BasicJsonType::value_t::boolean:
  4616. {
  4617. const auto h = std::hash<bool> {}(j.template get<bool>());
  4618. return combine(type, h);
  4619. }
  4620. case BasicJsonType::value_t::number_integer:
  4621. {
  4622. const auto h = std::hash<number_integer_t> {}(j.template get<number_integer_t>());
  4623. return combine(type, h);
  4624. }
  4625. case BasicJsonType::value_t::number_unsigned:
  4626. {
  4627. const auto h = std::hash<number_unsigned_t> {}(j.template get<number_unsigned_t>());
  4628. return combine(type, h);
  4629. }
  4630. case BasicJsonType::value_t::number_float:
  4631. {
  4632. const auto h = std::hash<number_float_t> {}(j.template get<number_float_t>());
  4633. return combine(type, h);
  4634. }
  4635. case BasicJsonType::value_t::binary:
  4636. {
  4637. auto seed = combine(type, j.get_binary().size());
  4638. const auto h = std::hash<bool> {}(j.get_binary().has_subtype());
  4639. seed = combine(seed, h);
  4640. seed = combine(seed, static_cast<std::size_t>(j.get_binary().subtype()));
  4641. for (const auto byte : j.get_binary())
  4642. {
  4643. seed = combine(seed, std::hash<std::uint8_t> {}(byte));
  4644. }
  4645. return seed;
  4646. }
  4647. default: // LCOV_EXCL_LINE
  4648. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  4649. return 0; // LCOV_EXCL_LINE
  4650. }
  4651. }
  4652. } // namespace detail
  4653. } // namespace nlohmann
  4654. // #include <nlohmann/detail/input/binary_reader.hpp>
  4655. #include <algorithm> // generate_n
  4656. #include <array> // array
  4657. #include <cmath> // ldexp
  4658. #include <cstddef> // size_t
  4659. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  4660. #include <cstdio> // snprintf
  4661. #include <cstring> // memcpy
  4662. #include <iterator> // back_inserter
  4663. #include <limits> // numeric_limits
  4664. #include <string> // char_traits, string
  4665. #include <utility> // make_pair, move
  4666. #include <vector> // vector
  4667. // #include <nlohmann/detail/exceptions.hpp>
  4668. // #include <nlohmann/detail/input/input_adapters.hpp>
  4669. #include <array> // array
  4670. #include <cstddef> // size_t
  4671. #include <cstring> // strlen
  4672. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  4673. #include <memory> // shared_ptr, make_shared, addressof
  4674. #include <numeric> // accumulate
  4675. #include <string> // string, char_traits
  4676. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  4677. #include <utility> // pair, declval
  4678. #ifndef JSON_NO_IO
  4679. #include <cstdio> // FILE *
  4680. #include <istream> // istream
  4681. #endif // JSON_NO_IO
  4682. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  4683. // #include <nlohmann/detail/macro_scope.hpp>
  4684. namespace nlohmann
  4685. {
  4686. namespace detail
  4687. {
  4688. /// the supported input formats
  4689. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  4690. ////////////////////
  4691. // input adapters //
  4692. ////////////////////
  4693. #ifndef JSON_NO_IO
  4694. /*!
  4695. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  4696. buffer. This adapter is a very low level adapter.
  4697. */
  4698. class file_input_adapter
  4699. {
  4700. public:
  4701. using char_type = char;
  4702. JSON_HEDLEY_NON_NULL(2)
  4703. explicit file_input_adapter(std::FILE* f) noexcept
  4704. : m_file(f)
  4705. {}
  4706. // make class move-only
  4707. file_input_adapter(const file_input_adapter&) = delete;
  4708. file_input_adapter(file_input_adapter&&) noexcept = default;
  4709. file_input_adapter& operator=(const file_input_adapter&) = delete;
  4710. file_input_adapter& operator=(file_input_adapter&&) = delete;
  4711. ~file_input_adapter() = default;
  4712. std::char_traits<char>::int_type get_character() noexcept
  4713. {
  4714. return std::fgetc(m_file);
  4715. }
  4716. private:
  4717. /// the file pointer to read from
  4718. std::FILE* m_file;
  4719. };
  4720. /*!
  4721. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  4722. beginning of input. Does not support changing the underlying std::streambuf
  4723. in mid-input. Maintains underlying std::istream and std::streambuf to support
  4724. subsequent use of standard std::istream operations to process any input
  4725. characters following those used in parsing the JSON input. Clears the
  4726. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  4727. subsequent call for input from the std::istream.
  4728. */
  4729. class input_stream_adapter
  4730. {
  4731. public:
  4732. using char_type = char;
  4733. ~input_stream_adapter()
  4734. {
  4735. // clear stream flags; we use underlying streambuf I/O, do not
  4736. // maintain ifstream flags, except eof
  4737. if (is != nullptr)
  4738. {
  4739. is->clear(is->rdstate() & std::ios::eofbit);
  4740. }
  4741. }
  4742. explicit input_stream_adapter(std::istream& i)
  4743. : is(&i), sb(i.rdbuf())
  4744. {}
  4745. // delete because of pointer members
  4746. input_stream_adapter(const input_stream_adapter&) = delete;
  4747. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  4748. input_stream_adapter& operator=(input_stream_adapter&&) = delete;
  4749. input_stream_adapter(input_stream_adapter&& rhs) noexcept
  4750. : is(rhs.is), sb(rhs.sb)
  4751. {
  4752. rhs.is = nullptr;
  4753. rhs.sb = nullptr;
  4754. }
  4755. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  4756. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  4757. // end up as the same value, eg. 0xFFFFFFFF.
  4758. std::char_traits<char>::int_type get_character()
  4759. {
  4760. auto res = sb->sbumpc();
  4761. // set eof manually, as we don't use the istream interface.
  4762. if (JSON_HEDLEY_UNLIKELY(res == std::char_traits<char>::eof()))
  4763. {
  4764. is->clear(is->rdstate() | std::ios::eofbit);
  4765. }
  4766. return res;
  4767. }
  4768. private:
  4769. /// the associated input stream
  4770. std::istream* is = nullptr;
  4771. std::streambuf* sb = nullptr;
  4772. };
  4773. #endif // JSON_NO_IO
  4774. // General-purpose iterator-based adapter. It might not be as fast as
  4775. // theoretically possible for some containers, but it is extremely versatile.
  4776. template<typename IteratorType>
  4777. class iterator_input_adapter
  4778. {
  4779. public:
  4780. using char_type = typename std::iterator_traits<IteratorType>::value_type;
  4781. iterator_input_adapter(IteratorType first, IteratorType last)
  4782. : current(std::move(first)), end(std::move(last))
  4783. {}
  4784. typename std::char_traits<char_type>::int_type get_character()
  4785. {
  4786. if (JSON_HEDLEY_LIKELY(current != end))
  4787. {
  4788. auto result = std::char_traits<char_type>::to_int_type(*current);
  4789. std::advance(current, 1);
  4790. return result;
  4791. }
  4792. return std::char_traits<char_type>::eof();
  4793. }
  4794. private:
  4795. IteratorType current;
  4796. IteratorType end;
  4797. template<typename BaseInputAdapter, size_t T>
  4798. friend struct wide_string_input_helper;
  4799. bool empty() const
  4800. {
  4801. return current == end;
  4802. }
  4803. };
  4804. template<typename BaseInputAdapter, size_t T>
  4805. struct wide_string_input_helper;
  4806. template<typename BaseInputAdapter>
  4807. struct wide_string_input_helper<BaseInputAdapter, 4>
  4808. {
  4809. // UTF-32
  4810. static void fill_buffer(BaseInputAdapter& input,
  4811. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4812. size_t& utf8_bytes_index,
  4813. size_t& utf8_bytes_filled)
  4814. {
  4815. utf8_bytes_index = 0;
  4816. if (JSON_HEDLEY_UNLIKELY(input.empty()))
  4817. {
  4818. utf8_bytes[0] = std::char_traits<char>::eof();
  4819. utf8_bytes_filled = 1;
  4820. }
  4821. else
  4822. {
  4823. // get the current character
  4824. const auto wc = input.get_character();
  4825. // UTF-32 to UTF-8 encoding
  4826. if (wc < 0x80)
  4827. {
  4828. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4829. utf8_bytes_filled = 1;
  4830. }
  4831. else if (wc <= 0x7FF)
  4832. {
  4833. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u) & 0x1Fu));
  4834. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4835. utf8_bytes_filled = 2;
  4836. }
  4837. else if (wc <= 0xFFFF)
  4838. {
  4839. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u) & 0x0Fu));
  4840. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4841. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4842. utf8_bytes_filled = 3;
  4843. }
  4844. else if (wc <= 0x10FFFF)
  4845. {
  4846. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((static_cast<unsigned int>(wc) >> 18u) & 0x07u));
  4847. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 12u) & 0x3Fu));
  4848. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4849. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4850. utf8_bytes_filled = 4;
  4851. }
  4852. else
  4853. {
  4854. // unknown character
  4855. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4856. utf8_bytes_filled = 1;
  4857. }
  4858. }
  4859. }
  4860. };
  4861. template<typename BaseInputAdapter>
  4862. struct wide_string_input_helper<BaseInputAdapter, 2>
  4863. {
  4864. // UTF-16
  4865. static void fill_buffer(BaseInputAdapter& input,
  4866. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4867. size_t& utf8_bytes_index,
  4868. size_t& utf8_bytes_filled)
  4869. {
  4870. utf8_bytes_index = 0;
  4871. if (JSON_HEDLEY_UNLIKELY(input.empty()))
  4872. {
  4873. utf8_bytes[0] = std::char_traits<char>::eof();
  4874. utf8_bytes_filled = 1;
  4875. }
  4876. else
  4877. {
  4878. // get the current character
  4879. const auto wc = input.get_character();
  4880. // UTF-16 to UTF-8 encoding
  4881. if (wc < 0x80)
  4882. {
  4883. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4884. utf8_bytes_filled = 1;
  4885. }
  4886. else if (wc <= 0x7FF)
  4887. {
  4888. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u)));
  4889. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4890. utf8_bytes_filled = 2;
  4891. }
  4892. else if (0xD800 > wc || wc >= 0xE000)
  4893. {
  4894. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u)));
  4895. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4896. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4897. utf8_bytes_filled = 3;
  4898. }
  4899. else
  4900. {
  4901. if (JSON_HEDLEY_UNLIKELY(!input.empty()))
  4902. {
  4903. const auto wc2 = static_cast<unsigned int>(input.get_character());
  4904. const auto charcode = 0x10000u + (((static_cast<unsigned int>(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  4905. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  4906. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  4907. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  4908. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  4909. utf8_bytes_filled = 4;
  4910. }
  4911. else
  4912. {
  4913. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4914. utf8_bytes_filled = 1;
  4915. }
  4916. }
  4917. }
  4918. }
  4919. };
  4920. // Wraps another input apdater to convert wide character types into individual bytes.
  4921. template<typename BaseInputAdapter, typename WideCharType>
  4922. class wide_string_input_adapter
  4923. {
  4924. public:
  4925. using char_type = char;
  4926. wide_string_input_adapter(BaseInputAdapter base)
  4927. : base_adapter(base) {}
  4928. typename std::char_traits<char>::int_type get_character() noexcept
  4929. {
  4930. // check if buffer needs to be filled
  4931. if (utf8_bytes_index == utf8_bytes_filled)
  4932. {
  4933. fill_buffer<sizeof(WideCharType)>();
  4934. JSON_ASSERT(utf8_bytes_filled > 0);
  4935. JSON_ASSERT(utf8_bytes_index == 0);
  4936. }
  4937. // use buffer
  4938. JSON_ASSERT(utf8_bytes_filled > 0);
  4939. JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled);
  4940. return utf8_bytes[utf8_bytes_index++];
  4941. }
  4942. private:
  4943. BaseInputAdapter base_adapter;
  4944. template<size_t T>
  4945. void fill_buffer()
  4946. {
  4947. wide_string_input_helper<BaseInputAdapter, T>::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  4948. }
  4949. /// a buffer for UTF-8 bytes
  4950. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  4951. /// index to the utf8_codes array for the next valid byte
  4952. std::size_t utf8_bytes_index = 0;
  4953. /// number of valid bytes in the utf8_codes array
  4954. std::size_t utf8_bytes_filled = 0;
  4955. };
  4956. template<typename IteratorType, typename Enable = void>
  4957. struct iterator_input_adapter_factory
  4958. {
  4959. using iterator_type = IteratorType;
  4960. using char_type = typename std::iterator_traits<iterator_type>::value_type;
  4961. using adapter_type = iterator_input_adapter<iterator_type>;
  4962. static adapter_type create(IteratorType first, IteratorType last)
  4963. {
  4964. return adapter_type(std::move(first), std::move(last));
  4965. }
  4966. };
  4967. template<typename T>
  4968. struct is_iterator_of_multibyte
  4969. {
  4970. using value_type = typename std::iterator_traits<T>::value_type;
  4971. enum
  4972. {
  4973. value = sizeof(value_type) > 1
  4974. };
  4975. };
  4976. template<typename IteratorType>
  4977. struct iterator_input_adapter_factory<IteratorType, enable_if_t<is_iterator_of_multibyte<IteratorType>::value>>
  4978. {
  4979. using iterator_type = IteratorType;
  4980. using char_type = typename std::iterator_traits<iterator_type>::value_type;
  4981. using base_adapter_type = iterator_input_adapter<iterator_type>;
  4982. using adapter_type = wide_string_input_adapter<base_adapter_type, char_type>;
  4983. static adapter_type create(IteratorType first, IteratorType last)
  4984. {
  4985. return adapter_type(base_adapter_type(std::move(first), std::move(last)));
  4986. }
  4987. };
  4988. // General purpose iterator-based input
  4989. template<typename IteratorType>
  4990. typename iterator_input_adapter_factory<IteratorType>::adapter_type input_adapter(IteratorType first, IteratorType last)
  4991. {
  4992. using factory_type = iterator_input_adapter_factory<IteratorType>;
  4993. return factory_type::create(first, last);
  4994. }
  4995. // Convenience shorthand from container to iterator
  4996. // Enables ADL on begin(container) and end(container)
  4997. // Encloses the using declarations in namespace for not to leak them to outside scope
  4998. namespace container_input_adapter_factory_impl
  4999. {
  5000. using std::begin;
  5001. using std::end;
  5002. template<typename ContainerType, typename Enable = void>
  5003. struct container_input_adapter_factory {};
  5004. template<typename ContainerType>
  5005. struct container_input_adapter_factory< ContainerType,
  5006. void_t<decltype(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>()))>>
  5007. {
  5008. using adapter_type = decltype(input_adapter(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>())));
  5009. static adapter_type create(const ContainerType& container)
  5010. {
  5011. return input_adapter(begin(container), end(container));
  5012. }
  5013. };
  5014. } // namespace container_input_adapter_factory_impl
  5015. template<typename ContainerType>
  5016. typename container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::adapter_type input_adapter(const ContainerType& container)
  5017. {
  5018. return container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::create(container);
  5019. }
  5020. #ifndef JSON_NO_IO
  5021. // Special cases with fast paths
  5022. inline file_input_adapter input_adapter(std::FILE* file)
  5023. {
  5024. return file_input_adapter(file);
  5025. }
  5026. inline input_stream_adapter input_adapter(std::istream& stream)
  5027. {
  5028. return input_stream_adapter(stream);
  5029. }
  5030. inline input_stream_adapter input_adapter(std::istream&& stream)
  5031. {
  5032. return input_stream_adapter(stream);
  5033. }
  5034. #endif // JSON_NO_IO
  5035. using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval<const char*>(), std::declval<const char*>()));
  5036. // Null-delimited strings, and the like.
  5037. template < typename CharT,
  5038. typename std::enable_if <
  5039. std::is_pointer<CharT>::value&&
  5040. !std::is_array<CharT>::value&&
  5041. std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
  5042. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  5043. int >::type = 0 >
  5044. contiguous_bytes_input_adapter input_adapter(CharT b)
  5045. {
  5046. auto length = std::strlen(reinterpret_cast<const char*>(b));
  5047. const auto* ptr = reinterpret_cast<const char*>(b);
  5048. return input_adapter(ptr, ptr + length);
  5049. }
  5050. template<typename T, std::size_t N>
  5051. 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)
  5052. {
  5053. return input_adapter(array, array + N);
  5054. }
  5055. // This class only handles inputs of input_buffer_adapter type.
  5056. // It's required so that expressions like {ptr, len} can be implicitely casted
  5057. // to the correct adapter.
  5058. class span_input_adapter
  5059. {
  5060. public:
  5061. template < typename CharT,
  5062. typename std::enable_if <
  5063. std::is_pointer<CharT>::value&&
  5064. std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
  5065. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  5066. int >::type = 0 >
  5067. span_input_adapter(CharT b, std::size_t l)
  5068. : ia(reinterpret_cast<const char*>(b), reinterpret_cast<const char*>(b) + l) {}
  5069. template<class IteratorType,
  5070. typename std::enable_if<
  5071. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  5072. int>::type = 0>
  5073. span_input_adapter(IteratorType first, IteratorType last)
  5074. : ia(input_adapter(first, last)) {}
  5075. contiguous_bytes_input_adapter&& get()
  5076. {
  5077. return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg)
  5078. }
  5079. private:
  5080. contiguous_bytes_input_adapter ia;
  5081. };
  5082. } // namespace detail
  5083. } // namespace nlohmann
  5084. // #include <nlohmann/detail/input/json_sax.hpp>
  5085. #include <cstddef>
  5086. #include <string> // string
  5087. #include <utility> // move
  5088. #include <vector> // vector
  5089. // #include <nlohmann/detail/exceptions.hpp>
  5090. // #include <nlohmann/detail/macro_scope.hpp>
  5091. namespace nlohmann
  5092. {
  5093. /*!
  5094. @brief SAX interface
  5095. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  5096. Each function is called in different situations while the input is parsed. The
  5097. boolean return value informs the parser whether to continue processing the
  5098. input.
  5099. */
  5100. template<typename BasicJsonType>
  5101. struct json_sax
  5102. {
  5103. using number_integer_t = typename BasicJsonType::number_integer_t;
  5104. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5105. using number_float_t = typename BasicJsonType::number_float_t;
  5106. using string_t = typename BasicJsonType::string_t;
  5107. using binary_t = typename BasicJsonType::binary_t;
  5108. /*!
  5109. @brief a null value was read
  5110. @return whether parsing should proceed
  5111. */
  5112. virtual bool null() = 0;
  5113. /*!
  5114. @brief a boolean value was read
  5115. @param[in] val boolean value
  5116. @return whether parsing should proceed
  5117. */
  5118. virtual bool boolean(bool val) = 0;
  5119. /*!
  5120. @brief an integer number was read
  5121. @param[in] val integer value
  5122. @return whether parsing should proceed
  5123. */
  5124. virtual bool number_integer(number_integer_t val) = 0;
  5125. /*!
  5126. @brief an unsigned integer number was read
  5127. @param[in] val unsigned integer value
  5128. @return whether parsing should proceed
  5129. */
  5130. virtual bool number_unsigned(number_unsigned_t val) = 0;
  5131. /*!
  5132. @brief an floating-point number was read
  5133. @param[in] val floating-point value
  5134. @param[in] s raw token value
  5135. @return whether parsing should proceed
  5136. */
  5137. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  5138. /*!
  5139. @brief a string was read
  5140. @param[in] val string value
  5141. @return whether parsing should proceed
  5142. @note It is safe to move the passed string.
  5143. */
  5144. virtual bool string(string_t& val) = 0;
  5145. /*!
  5146. @brief a binary string was read
  5147. @param[in] val binary value
  5148. @return whether parsing should proceed
  5149. @note It is safe to move the passed binary.
  5150. */
  5151. virtual bool binary(binary_t& val) = 0;
  5152. /*!
  5153. @brief the beginning of an object was read
  5154. @param[in] elements number of object elements or -1 if unknown
  5155. @return whether parsing should proceed
  5156. @note binary formats may report the number of elements
  5157. */
  5158. virtual bool start_object(std::size_t elements) = 0;
  5159. /*!
  5160. @brief an object key was read
  5161. @param[in] val object key
  5162. @return whether parsing should proceed
  5163. @note It is safe to move the passed string.
  5164. */
  5165. virtual bool key(string_t& val) = 0;
  5166. /*!
  5167. @brief the end of an object was read
  5168. @return whether parsing should proceed
  5169. */
  5170. virtual bool end_object() = 0;
  5171. /*!
  5172. @brief the beginning of an array was read
  5173. @param[in] elements number of array elements or -1 if unknown
  5174. @return whether parsing should proceed
  5175. @note binary formats may report the number of elements
  5176. */
  5177. virtual bool start_array(std::size_t elements) = 0;
  5178. /*!
  5179. @brief the end of an array was read
  5180. @return whether parsing should proceed
  5181. */
  5182. virtual bool end_array() = 0;
  5183. /*!
  5184. @brief a parse error occurred
  5185. @param[in] position the position in the input where the error occurs
  5186. @param[in] last_token the last read token
  5187. @param[in] ex an exception object describing the error
  5188. @return whether parsing should proceed (must return false)
  5189. */
  5190. virtual bool parse_error(std::size_t position,
  5191. const std::string& last_token,
  5192. const detail::exception& ex) = 0;
  5193. json_sax() = default;
  5194. json_sax(const json_sax&) = default;
  5195. json_sax(json_sax&&) noexcept = default;
  5196. json_sax& operator=(const json_sax&) = default;
  5197. json_sax& operator=(json_sax&&) noexcept = default;
  5198. virtual ~json_sax() = default;
  5199. };
  5200. namespace detail
  5201. {
  5202. /*!
  5203. @brief SAX implementation to create a JSON value from SAX events
  5204. This class implements the @ref json_sax interface and processes the SAX events
  5205. to create a JSON value which makes it basically a DOM parser. The structure or
  5206. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  5207. a pointer to the respective array or object for each recursion depth.
  5208. After successful parsing, the value that is passed by reference to the
  5209. constructor contains the parsed value.
  5210. @tparam BasicJsonType the JSON type
  5211. */
  5212. template<typename BasicJsonType>
  5213. class json_sax_dom_parser
  5214. {
  5215. public:
  5216. using number_integer_t = typename BasicJsonType::number_integer_t;
  5217. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5218. using number_float_t = typename BasicJsonType::number_float_t;
  5219. using string_t = typename BasicJsonType::string_t;
  5220. using binary_t = typename BasicJsonType::binary_t;
  5221. /*!
  5222. @param[in,out] r reference to a JSON value that is manipulated while
  5223. parsing
  5224. @param[in] allow_exceptions_ whether parse errors yield exceptions
  5225. */
  5226. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  5227. : root(r), allow_exceptions(allow_exceptions_)
  5228. {}
  5229. // make class move-only
  5230. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  5231. json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5232. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  5233. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5234. ~json_sax_dom_parser() = default;
  5235. bool null()
  5236. {
  5237. handle_value(nullptr);
  5238. return true;
  5239. }
  5240. bool boolean(bool val)
  5241. {
  5242. handle_value(val);
  5243. return true;
  5244. }
  5245. bool number_integer(number_integer_t val)
  5246. {
  5247. handle_value(val);
  5248. return true;
  5249. }
  5250. bool number_unsigned(number_unsigned_t val)
  5251. {
  5252. handle_value(val);
  5253. return true;
  5254. }
  5255. bool number_float(number_float_t val, const string_t& /*unused*/)
  5256. {
  5257. handle_value(val);
  5258. return true;
  5259. }
  5260. bool string(string_t& val)
  5261. {
  5262. handle_value(val);
  5263. return true;
  5264. }
  5265. bool binary(binary_t& val)
  5266. {
  5267. handle_value(std::move(val));
  5268. return true;
  5269. }
  5270. bool start_object(std::size_t len)
  5271. {
  5272. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  5273. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  5274. {
  5275. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back()));
  5276. }
  5277. return true;
  5278. }
  5279. bool key(string_t& val)
  5280. {
  5281. // add null at given key and store the reference for later
  5282. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  5283. return true;
  5284. }
  5285. bool end_object()
  5286. {
  5287. ref_stack.back()->set_parents();
  5288. ref_stack.pop_back();
  5289. return true;
  5290. }
  5291. bool start_array(std::size_t len)
  5292. {
  5293. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  5294. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  5295. {
  5296. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back()));
  5297. }
  5298. return true;
  5299. }
  5300. bool end_array()
  5301. {
  5302. ref_stack.back()->set_parents();
  5303. ref_stack.pop_back();
  5304. return true;
  5305. }
  5306. template<class Exception>
  5307. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  5308. const Exception& ex)
  5309. {
  5310. errored = true;
  5311. static_cast<void>(ex);
  5312. if (allow_exceptions)
  5313. {
  5314. JSON_THROW(ex);
  5315. }
  5316. return false;
  5317. }
  5318. constexpr bool is_errored() const
  5319. {
  5320. return errored;
  5321. }
  5322. private:
  5323. /*!
  5324. @invariant If the ref stack is empty, then the passed value will be the new
  5325. root.
  5326. @invariant If the ref stack contains a value, then it is an array or an
  5327. object to which we can add elements
  5328. */
  5329. template<typename Value>
  5330. JSON_HEDLEY_RETURNS_NON_NULL
  5331. BasicJsonType* handle_value(Value&& v)
  5332. {
  5333. if (ref_stack.empty())
  5334. {
  5335. root = BasicJsonType(std::forward<Value>(v));
  5336. return &root;
  5337. }
  5338. JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
  5339. if (ref_stack.back()->is_array())
  5340. {
  5341. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  5342. return &(ref_stack.back()->m_value.array->back());
  5343. }
  5344. JSON_ASSERT(ref_stack.back()->is_object());
  5345. JSON_ASSERT(object_element);
  5346. *object_element = BasicJsonType(std::forward<Value>(v));
  5347. return object_element;
  5348. }
  5349. /// the parsed JSON value
  5350. BasicJsonType& root;
  5351. /// stack to model hierarchy of values
  5352. std::vector<BasicJsonType*> ref_stack {};
  5353. /// helper to hold the reference for the next object element
  5354. BasicJsonType* object_element = nullptr;
  5355. /// whether a syntax error occurred
  5356. bool errored = false;
  5357. /// whether to throw exceptions in case of errors
  5358. const bool allow_exceptions = true;
  5359. };
  5360. template<typename BasicJsonType>
  5361. class json_sax_dom_callback_parser
  5362. {
  5363. public:
  5364. using number_integer_t = typename BasicJsonType::number_integer_t;
  5365. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5366. using number_float_t = typename BasicJsonType::number_float_t;
  5367. using string_t = typename BasicJsonType::string_t;
  5368. using binary_t = typename BasicJsonType::binary_t;
  5369. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  5370. using parse_event_t = typename BasicJsonType::parse_event_t;
  5371. json_sax_dom_callback_parser(BasicJsonType& r,
  5372. const parser_callback_t cb,
  5373. const bool allow_exceptions_ = true)
  5374. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  5375. {
  5376. keep_stack.push_back(true);
  5377. }
  5378. // make class move-only
  5379. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  5380. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5381. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  5382. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5383. ~json_sax_dom_callback_parser() = default;
  5384. bool null()
  5385. {
  5386. handle_value(nullptr);
  5387. return true;
  5388. }
  5389. bool boolean(bool val)
  5390. {
  5391. handle_value(val);
  5392. return true;
  5393. }
  5394. bool number_integer(number_integer_t val)
  5395. {
  5396. handle_value(val);
  5397. return true;
  5398. }
  5399. bool number_unsigned(number_unsigned_t val)
  5400. {
  5401. handle_value(val);
  5402. return true;
  5403. }
  5404. bool number_float(number_float_t val, const string_t& /*unused*/)
  5405. {
  5406. handle_value(val);
  5407. return true;
  5408. }
  5409. bool string(string_t& val)
  5410. {
  5411. handle_value(val);
  5412. return true;
  5413. }
  5414. bool binary(binary_t& val)
  5415. {
  5416. handle_value(std::move(val));
  5417. return true;
  5418. }
  5419. bool start_object(std::size_t len)
  5420. {
  5421. // check callback for object start
  5422. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  5423. keep_stack.push_back(keep);
  5424. auto val = handle_value(BasicJsonType::value_t::object, true);
  5425. ref_stack.push_back(val.second);
  5426. // check object limit
  5427. if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  5428. {
  5429. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back()));
  5430. }
  5431. return true;
  5432. }
  5433. bool key(string_t& val)
  5434. {
  5435. BasicJsonType k = BasicJsonType(val);
  5436. // check callback for key
  5437. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  5438. key_keep_stack.push_back(keep);
  5439. // add discarded value at given key and store the reference for later
  5440. if (keep && ref_stack.back())
  5441. {
  5442. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  5443. }
  5444. return true;
  5445. }
  5446. bool end_object()
  5447. {
  5448. if (ref_stack.back())
  5449. {
  5450. if (!callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  5451. {
  5452. // discard object
  5453. *ref_stack.back() = discarded;
  5454. }
  5455. else
  5456. {
  5457. ref_stack.back()->set_parents();
  5458. }
  5459. }
  5460. JSON_ASSERT(!ref_stack.empty());
  5461. JSON_ASSERT(!keep_stack.empty());
  5462. ref_stack.pop_back();
  5463. keep_stack.pop_back();
  5464. if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured())
  5465. {
  5466. // remove discarded value
  5467. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  5468. {
  5469. if (it->is_discarded())
  5470. {
  5471. ref_stack.back()->erase(it);
  5472. break;
  5473. }
  5474. }
  5475. }
  5476. return true;
  5477. }
  5478. bool start_array(std::size_t len)
  5479. {
  5480. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  5481. keep_stack.push_back(keep);
  5482. auto val = handle_value(BasicJsonType::value_t::array, true);
  5483. ref_stack.push_back(val.second);
  5484. // check array limit
  5485. if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  5486. {
  5487. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back()));
  5488. }
  5489. return true;
  5490. }
  5491. bool end_array()
  5492. {
  5493. bool keep = true;
  5494. if (ref_stack.back())
  5495. {
  5496. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  5497. if (keep)
  5498. {
  5499. ref_stack.back()->set_parents();
  5500. }
  5501. else
  5502. {
  5503. // discard array
  5504. *ref_stack.back() = discarded;
  5505. }
  5506. }
  5507. JSON_ASSERT(!ref_stack.empty());
  5508. JSON_ASSERT(!keep_stack.empty());
  5509. ref_stack.pop_back();
  5510. keep_stack.pop_back();
  5511. // remove discarded value
  5512. if (!keep && !ref_stack.empty() && ref_stack.back()->is_array())
  5513. {
  5514. ref_stack.back()->m_value.array->pop_back();
  5515. }
  5516. return true;
  5517. }
  5518. template<class Exception>
  5519. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  5520. const Exception& ex)
  5521. {
  5522. errored = true;
  5523. static_cast<void>(ex);
  5524. if (allow_exceptions)
  5525. {
  5526. JSON_THROW(ex);
  5527. }
  5528. return false;
  5529. }
  5530. constexpr bool is_errored() const
  5531. {
  5532. return errored;
  5533. }
  5534. private:
  5535. /*!
  5536. @param[in] v value to add to the JSON value we build during parsing
  5537. @param[in] skip_callback whether we should skip calling the callback
  5538. function; this is required after start_array() and
  5539. start_object() SAX events, because otherwise we would call the
  5540. callback function with an empty array or object, respectively.
  5541. @invariant If the ref stack is empty, then the passed value will be the new
  5542. root.
  5543. @invariant If the ref stack contains a value, then it is an array or an
  5544. object to which we can add elements
  5545. @return pair of boolean (whether value should be kept) and pointer (to the
  5546. passed value in the ref_stack hierarchy; nullptr if not kept)
  5547. */
  5548. template<typename Value>
  5549. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  5550. {
  5551. JSON_ASSERT(!keep_stack.empty());
  5552. // do not handle this value if we know it would be added to a discarded
  5553. // container
  5554. if (!keep_stack.back())
  5555. {
  5556. return {false, nullptr};
  5557. }
  5558. // create value
  5559. auto value = BasicJsonType(std::forward<Value>(v));
  5560. // check callback
  5561. const bool keep = skip_callback || callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  5562. // do not handle this value if we just learnt it shall be discarded
  5563. if (!keep)
  5564. {
  5565. return {false, nullptr};
  5566. }
  5567. if (ref_stack.empty())
  5568. {
  5569. root = std::move(value);
  5570. return {true, &root};
  5571. }
  5572. // skip this value if we already decided to skip the parent
  5573. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  5574. if (!ref_stack.back())
  5575. {
  5576. return {false, nullptr};
  5577. }
  5578. // we now only expect arrays and objects
  5579. JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
  5580. // array
  5581. if (ref_stack.back()->is_array())
  5582. {
  5583. ref_stack.back()->m_value.array->emplace_back(std::move(value));
  5584. return {true, &(ref_stack.back()->m_value.array->back())};
  5585. }
  5586. // object
  5587. JSON_ASSERT(ref_stack.back()->is_object());
  5588. // check if we should store an element for the current key
  5589. JSON_ASSERT(!key_keep_stack.empty());
  5590. const bool store_element = key_keep_stack.back();
  5591. key_keep_stack.pop_back();
  5592. if (!store_element)
  5593. {
  5594. return {false, nullptr};
  5595. }
  5596. JSON_ASSERT(object_element);
  5597. *object_element = std::move(value);
  5598. return {true, object_element};
  5599. }
  5600. /// the parsed JSON value
  5601. BasicJsonType& root;
  5602. /// stack to model hierarchy of values
  5603. std::vector<BasicJsonType*> ref_stack {};
  5604. /// stack to manage which values to keep
  5605. std::vector<bool> keep_stack {};
  5606. /// stack to manage which object keys to keep
  5607. std::vector<bool> key_keep_stack {};
  5608. /// helper to hold the reference for the next object element
  5609. BasicJsonType* object_element = nullptr;
  5610. /// whether a syntax error occurred
  5611. bool errored = false;
  5612. /// callback function
  5613. const parser_callback_t callback = nullptr;
  5614. /// whether to throw exceptions in case of errors
  5615. const bool allow_exceptions = true;
  5616. /// a discarded value for the callback
  5617. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  5618. };
  5619. template<typename BasicJsonType>
  5620. class json_sax_acceptor
  5621. {
  5622. public:
  5623. using number_integer_t = typename BasicJsonType::number_integer_t;
  5624. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5625. using number_float_t = typename BasicJsonType::number_float_t;
  5626. using string_t = typename BasicJsonType::string_t;
  5627. using binary_t = typename BasicJsonType::binary_t;
  5628. bool null()
  5629. {
  5630. return true;
  5631. }
  5632. bool boolean(bool /*unused*/)
  5633. {
  5634. return true;
  5635. }
  5636. bool number_integer(number_integer_t /*unused*/)
  5637. {
  5638. return true;
  5639. }
  5640. bool number_unsigned(number_unsigned_t /*unused*/)
  5641. {
  5642. return true;
  5643. }
  5644. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  5645. {
  5646. return true;
  5647. }
  5648. bool string(string_t& /*unused*/)
  5649. {
  5650. return true;
  5651. }
  5652. bool binary(binary_t& /*unused*/)
  5653. {
  5654. return true;
  5655. }
  5656. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  5657. {
  5658. return true;
  5659. }
  5660. bool key(string_t& /*unused*/)
  5661. {
  5662. return true;
  5663. }
  5664. bool end_object()
  5665. {
  5666. return true;
  5667. }
  5668. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  5669. {
  5670. return true;
  5671. }
  5672. bool end_array()
  5673. {
  5674. return true;
  5675. }
  5676. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  5677. {
  5678. return false;
  5679. }
  5680. };
  5681. } // namespace detail
  5682. } // namespace nlohmann
  5683. // #include <nlohmann/detail/input/lexer.hpp>
  5684. #include <array> // array
  5685. #include <clocale> // localeconv
  5686. #include <cstddef> // size_t
  5687. #include <cstdio> // snprintf
  5688. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  5689. #include <initializer_list> // initializer_list
  5690. #include <string> // char_traits, string
  5691. #include <utility> // move
  5692. #include <vector> // vector
  5693. // #include <nlohmann/detail/input/input_adapters.hpp>
  5694. // #include <nlohmann/detail/input/position_t.hpp>
  5695. // #include <nlohmann/detail/macro_scope.hpp>
  5696. namespace nlohmann
  5697. {
  5698. namespace detail
  5699. {
  5700. ///////////
  5701. // lexer //
  5702. ///////////
  5703. template<typename BasicJsonType>
  5704. class lexer_base
  5705. {
  5706. public:
  5707. /// token types for the parser
  5708. enum class token_type
  5709. {
  5710. uninitialized, ///< indicating the scanner is uninitialized
  5711. literal_true, ///< the `true` literal
  5712. literal_false, ///< the `false` literal
  5713. literal_null, ///< the `null` literal
  5714. value_string, ///< a string -- use get_string() for actual value
  5715. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  5716. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  5717. value_float, ///< an floating point number -- use get_number_float() for actual value
  5718. begin_array, ///< the character for array begin `[`
  5719. begin_object, ///< the character for object begin `{`
  5720. end_array, ///< the character for array end `]`
  5721. end_object, ///< the character for object end `}`
  5722. name_separator, ///< the name separator `:`
  5723. value_separator, ///< the value separator `,`
  5724. parse_error, ///< indicating a parse error
  5725. end_of_input, ///< indicating the end of the input buffer
  5726. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  5727. };
  5728. /// return name of values of type token_type (only used for errors)
  5729. JSON_HEDLEY_RETURNS_NON_NULL
  5730. JSON_HEDLEY_CONST
  5731. static const char* token_type_name(const token_type t) noexcept
  5732. {
  5733. switch (t)
  5734. {
  5735. case token_type::uninitialized:
  5736. return "<uninitialized>";
  5737. case token_type::literal_true:
  5738. return "true literal";
  5739. case token_type::literal_false:
  5740. return "false literal";
  5741. case token_type::literal_null:
  5742. return "null literal";
  5743. case token_type::value_string:
  5744. return "string literal";
  5745. case token_type::value_unsigned:
  5746. case token_type::value_integer:
  5747. case token_type::value_float:
  5748. return "number literal";
  5749. case token_type::begin_array:
  5750. return "'['";
  5751. case token_type::begin_object:
  5752. return "'{'";
  5753. case token_type::end_array:
  5754. return "']'";
  5755. case token_type::end_object:
  5756. return "'}'";
  5757. case token_type::name_separator:
  5758. return "':'";
  5759. case token_type::value_separator:
  5760. return "','";
  5761. case token_type::parse_error:
  5762. return "<parse error>";
  5763. case token_type::end_of_input:
  5764. return "end of input";
  5765. case token_type::literal_or_value:
  5766. return "'[', '{', or a literal";
  5767. // LCOV_EXCL_START
  5768. default: // catch non-enum values
  5769. return "unknown token";
  5770. // LCOV_EXCL_STOP
  5771. }
  5772. }
  5773. };
  5774. /*!
  5775. @brief lexical analysis
  5776. This class organizes the lexical analysis during JSON deserialization.
  5777. */
  5778. template<typename BasicJsonType, typename InputAdapterType>
  5779. class lexer : public lexer_base<BasicJsonType>
  5780. {
  5781. using number_integer_t = typename BasicJsonType::number_integer_t;
  5782. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5783. using number_float_t = typename BasicJsonType::number_float_t;
  5784. using string_t = typename BasicJsonType::string_t;
  5785. using char_type = typename InputAdapterType::char_type;
  5786. using char_int_type = typename std::char_traits<char_type>::int_type;
  5787. public:
  5788. using token_type = typename lexer_base<BasicJsonType>::token_type;
  5789. explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept
  5790. : ia(std::move(adapter))
  5791. , ignore_comments(ignore_comments_)
  5792. , decimal_point_char(static_cast<char_int_type>(get_decimal_point()))
  5793. {}
  5794. // delete because of pointer members
  5795. lexer(const lexer&) = delete;
  5796. lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5797. lexer& operator=(lexer&) = delete;
  5798. lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  5799. ~lexer() = default;
  5800. private:
  5801. /////////////////////
  5802. // locales
  5803. /////////////////////
  5804. /// return the locale-dependent decimal point
  5805. JSON_HEDLEY_PURE
  5806. static char get_decimal_point() noexcept
  5807. {
  5808. const auto* loc = localeconv();
  5809. JSON_ASSERT(loc != nullptr);
  5810. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  5811. }
  5812. /////////////////////
  5813. // scan functions
  5814. /////////////////////
  5815. /*!
  5816. @brief get codepoint from 4 hex characters following `\u`
  5817. For input "\u c1 c2 c3 c4" the codepoint is:
  5818. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  5819. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  5820. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  5821. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  5822. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  5823. between the ASCII value of the character and the desired integer value.
  5824. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  5825. non-hex character)
  5826. */
  5827. int get_codepoint()
  5828. {
  5829. // this function only makes sense after reading `\u`
  5830. JSON_ASSERT(current == 'u');
  5831. int codepoint = 0;
  5832. const auto factors = { 12u, 8u, 4u, 0u };
  5833. for (const auto factor : factors)
  5834. {
  5835. get();
  5836. if (current >= '0' && current <= '9')
  5837. {
  5838. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  5839. }
  5840. else if (current >= 'A' && current <= 'F')
  5841. {
  5842. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  5843. }
  5844. else if (current >= 'a' && current <= 'f')
  5845. {
  5846. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  5847. }
  5848. else
  5849. {
  5850. return -1;
  5851. }
  5852. }
  5853. JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF);
  5854. return codepoint;
  5855. }
  5856. /*!
  5857. @brief check if the next byte(s) are inside a given range
  5858. Adds the current byte and, for each passed range, reads a new byte and
  5859. checks if it is inside the range. If a violation was detected, set up an
  5860. error message and return false. Otherwise, return true.
  5861. @param[in] ranges list of integers; interpreted as list of pairs of
  5862. inclusive lower and upper bound, respectively
  5863. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  5864. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  5865. @return true if and only if no range violation was detected
  5866. */
  5867. bool next_byte_in_range(std::initializer_list<char_int_type> ranges)
  5868. {
  5869. JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6);
  5870. add(current);
  5871. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  5872. {
  5873. get();
  5874. if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range)))
  5875. {
  5876. add(current);
  5877. }
  5878. else
  5879. {
  5880. error_message = "invalid string: ill-formed UTF-8 byte";
  5881. return false;
  5882. }
  5883. }
  5884. return true;
  5885. }
  5886. /*!
  5887. @brief scan a string literal
  5888. This function scans a string according to Sect. 7 of RFC 8259. While
  5889. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  5890. function returns successfully, token_buffer is *not* null-terminated (as it
  5891. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  5892. string.
  5893. @return token_type::value_string if string could be successfully scanned,
  5894. token_type::parse_error otherwise
  5895. @note In case of errors, variable error_message contains a textual
  5896. description.
  5897. */
  5898. token_type scan_string()
  5899. {
  5900. // reset token_buffer (ignore opening quote)
  5901. reset();
  5902. // we entered the function by reading an open quote
  5903. JSON_ASSERT(current == '\"');
  5904. while (true)
  5905. {
  5906. // get next character
  5907. switch (get())
  5908. {
  5909. // end of file while parsing string
  5910. case std::char_traits<char_type>::eof():
  5911. {
  5912. error_message = "invalid string: missing closing quote";
  5913. return token_type::parse_error;
  5914. }
  5915. // closing quote
  5916. case '\"':
  5917. {
  5918. return token_type::value_string;
  5919. }
  5920. // escapes
  5921. case '\\':
  5922. {
  5923. switch (get())
  5924. {
  5925. // quotation mark
  5926. case '\"':
  5927. add('\"');
  5928. break;
  5929. // reverse solidus
  5930. case '\\':
  5931. add('\\');
  5932. break;
  5933. // solidus
  5934. case '/':
  5935. add('/');
  5936. break;
  5937. // backspace
  5938. case 'b':
  5939. add('\b');
  5940. break;
  5941. // form feed
  5942. case 'f':
  5943. add('\f');
  5944. break;
  5945. // line feed
  5946. case 'n':
  5947. add('\n');
  5948. break;
  5949. // carriage return
  5950. case 'r':
  5951. add('\r');
  5952. break;
  5953. // tab
  5954. case 't':
  5955. add('\t');
  5956. break;
  5957. // unicode escapes
  5958. case 'u':
  5959. {
  5960. const int codepoint1 = get_codepoint();
  5961. int codepoint = codepoint1; // start with codepoint1
  5962. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  5963. {
  5964. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  5965. return token_type::parse_error;
  5966. }
  5967. // check if code point is a high surrogate
  5968. if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF)
  5969. {
  5970. // expect next \uxxxx entry
  5971. if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u'))
  5972. {
  5973. const int codepoint2 = get_codepoint();
  5974. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  5975. {
  5976. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  5977. return token_type::parse_error;
  5978. }
  5979. // check if codepoint2 is a low surrogate
  5980. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF))
  5981. {
  5982. // overwrite codepoint
  5983. codepoint = static_cast<int>(
  5984. // high surrogate occupies the most significant 22 bits
  5985. (static_cast<unsigned int>(codepoint1) << 10u)
  5986. // low surrogate occupies the least significant 15 bits
  5987. + static_cast<unsigned int>(codepoint2)
  5988. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  5989. // in the result so we have to subtract with:
  5990. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  5991. - 0x35FDC00u);
  5992. }
  5993. else
  5994. {
  5995. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  5996. return token_type::parse_error;
  5997. }
  5998. }
  5999. else
  6000. {
  6001. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  6002. return token_type::parse_error;
  6003. }
  6004. }
  6005. else
  6006. {
  6007. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF))
  6008. {
  6009. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  6010. return token_type::parse_error;
  6011. }
  6012. }
  6013. // result of the above calculation yields a proper codepoint
  6014. JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF);
  6015. // translate codepoint into bytes
  6016. if (codepoint < 0x80)
  6017. {
  6018. // 1-byte characters: 0xxxxxxx (ASCII)
  6019. add(static_cast<char_int_type>(codepoint));
  6020. }
  6021. else if (codepoint <= 0x7FF)
  6022. {
  6023. // 2-byte characters: 110xxxxx 10xxxxxx
  6024. add(static_cast<char_int_type>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  6025. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6026. }
  6027. else if (codepoint <= 0xFFFF)
  6028. {
  6029. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  6030. add(static_cast<char_int_type>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  6031. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6032. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6033. }
  6034. else
  6035. {
  6036. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  6037. add(static_cast<char_int_type>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  6038. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  6039. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6040. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6041. }
  6042. break;
  6043. }
  6044. // other characters after escape
  6045. default:
  6046. error_message = "invalid string: forbidden character after backslash";
  6047. return token_type::parse_error;
  6048. }
  6049. break;
  6050. }
  6051. // invalid control characters
  6052. case 0x00:
  6053. {
  6054. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  6055. return token_type::parse_error;
  6056. }
  6057. case 0x01:
  6058. {
  6059. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  6060. return token_type::parse_error;
  6061. }
  6062. case 0x02:
  6063. {
  6064. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  6065. return token_type::parse_error;
  6066. }
  6067. case 0x03:
  6068. {
  6069. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  6070. return token_type::parse_error;
  6071. }
  6072. case 0x04:
  6073. {
  6074. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  6075. return token_type::parse_error;
  6076. }
  6077. case 0x05:
  6078. {
  6079. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  6080. return token_type::parse_error;
  6081. }
  6082. case 0x06:
  6083. {
  6084. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  6085. return token_type::parse_error;
  6086. }
  6087. case 0x07:
  6088. {
  6089. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  6090. return token_type::parse_error;
  6091. }
  6092. case 0x08:
  6093. {
  6094. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  6095. return token_type::parse_error;
  6096. }
  6097. case 0x09:
  6098. {
  6099. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  6100. return token_type::parse_error;
  6101. }
  6102. case 0x0A:
  6103. {
  6104. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  6105. return token_type::parse_error;
  6106. }
  6107. case 0x0B:
  6108. {
  6109. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  6110. return token_type::parse_error;
  6111. }
  6112. case 0x0C:
  6113. {
  6114. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  6115. return token_type::parse_error;
  6116. }
  6117. case 0x0D:
  6118. {
  6119. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  6120. return token_type::parse_error;
  6121. }
  6122. case 0x0E:
  6123. {
  6124. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  6125. return token_type::parse_error;
  6126. }
  6127. case 0x0F:
  6128. {
  6129. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  6130. return token_type::parse_error;
  6131. }
  6132. case 0x10:
  6133. {
  6134. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  6135. return token_type::parse_error;
  6136. }
  6137. case 0x11:
  6138. {
  6139. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  6140. return token_type::parse_error;
  6141. }
  6142. case 0x12:
  6143. {
  6144. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  6145. return token_type::parse_error;
  6146. }
  6147. case 0x13:
  6148. {
  6149. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  6150. return token_type::parse_error;
  6151. }
  6152. case 0x14:
  6153. {
  6154. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  6155. return token_type::parse_error;
  6156. }
  6157. case 0x15:
  6158. {
  6159. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  6160. return token_type::parse_error;
  6161. }
  6162. case 0x16:
  6163. {
  6164. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  6165. return token_type::parse_error;
  6166. }
  6167. case 0x17:
  6168. {
  6169. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  6170. return token_type::parse_error;
  6171. }
  6172. case 0x18:
  6173. {
  6174. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  6175. return token_type::parse_error;
  6176. }
  6177. case 0x19:
  6178. {
  6179. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  6180. return token_type::parse_error;
  6181. }
  6182. case 0x1A:
  6183. {
  6184. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  6185. return token_type::parse_error;
  6186. }
  6187. case 0x1B:
  6188. {
  6189. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  6190. return token_type::parse_error;
  6191. }
  6192. case 0x1C:
  6193. {
  6194. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  6195. return token_type::parse_error;
  6196. }
  6197. case 0x1D:
  6198. {
  6199. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  6200. return token_type::parse_error;
  6201. }
  6202. case 0x1E:
  6203. {
  6204. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  6205. return token_type::parse_error;
  6206. }
  6207. case 0x1F:
  6208. {
  6209. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  6210. return token_type::parse_error;
  6211. }
  6212. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  6213. case 0x20:
  6214. case 0x21:
  6215. case 0x23:
  6216. case 0x24:
  6217. case 0x25:
  6218. case 0x26:
  6219. case 0x27:
  6220. case 0x28:
  6221. case 0x29:
  6222. case 0x2A:
  6223. case 0x2B:
  6224. case 0x2C:
  6225. case 0x2D:
  6226. case 0x2E:
  6227. case 0x2F:
  6228. case 0x30:
  6229. case 0x31:
  6230. case 0x32:
  6231. case 0x33:
  6232. case 0x34:
  6233. case 0x35:
  6234. case 0x36:
  6235. case 0x37:
  6236. case 0x38:
  6237. case 0x39:
  6238. case 0x3A:
  6239. case 0x3B:
  6240. case 0x3C:
  6241. case 0x3D:
  6242. case 0x3E:
  6243. case 0x3F:
  6244. case 0x40:
  6245. case 0x41:
  6246. case 0x42:
  6247. case 0x43:
  6248. case 0x44:
  6249. case 0x45:
  6250. case 0x46:
  6251. case 0x47:
  6252. case 0x48:
  6253. case 0x49:
  6254. case 0x4A:
  6255. case 0x4B:
  6256. case 0x4C:
  6257. case 0x4D:
  6258. case 0x4E:
  6259. case 0x4F:
  6260. case 0x50:
  6261. case 0x51:
  6262. case 0x52:
  6263. case 0x53:
  6264. case 0x54:
  6265. case 0x55:
  6266. case 0x56:
  6267. case 0x57:
  6268. case 0x58:
  6269. case 0x59:
  6270. case 0x5A:
  6271. case 0x5B:
  6272. case 0x5D:
  6273. case 0x5E:
  6274. case 0x5F:
  6275. case 0x60:
  6276. case 0x61:
  6277. case 0x62:
  6278. case 0x63:
  6279. case 0x64:
  6280. case 0x65:
  6281. case 0x66:
  6282. case 0x67:
  6283. case 0x68:
  6284. case 0x69:
  6285. case 0x6A:
  6286. case 0x6B:
  6287. case 0x6C:
  6288. case 0x6D:
  6289. case 0x6E:
  6290. case 0x6F:
  6291. case 0x70:
  6292. case 0x71:
  6293. case 0x72:
  6294. case 0x73:
  6295. case 0x74:
  6296. case 0x75:
  6297. case 0x76:
  6298. case 0x77:
  6299. case 0x78:
  6300. case 0x79:
  6301. case 0x7A:
  6302. case 0x7B:
  6303. case 0x7C:
  6304. case 0x7D:
  6305. case 0x7E:
  6306. case 0x7F:
  6307. {
  6308. add(current);
  6309. break;
  6310. }
  6311. // U+0080..U+07FF: bytes C2..DF 80..BF
  6312. case 0xC2:
  6313. case 0xC3:
  6314. case 0xC4:
  6315. case 0xC5:
  6316. case 0xC6:
  6317. case 0xC7:
  6318. case 0xC8:
  6319. case 0xC9:
  6320. case 0xCA:
  6321. case 0xCB:
  6322. case 0xCC:
  6323. case 0xCD:
  6324. case 0xCE:
  6325. case 0xCF:
  6326. case 0xD0:
  6327. case 0xD1:
  6328. case 0xD2:
  6329. case 0xD3:
  6330. case 0xD4:
  6331. case 0xD5:
  6332. case 0xD6:
  6333. case 0xD7:
  6334. case 0xD8:
  6335. case 0xD9:
  6336. case 0xDA:
  6337. case 0xDB:
  6338. case 0xDC:
  6339. case 0xDD:
  6340. case 0xDE:
  6341. case 0xDF:
  6342. {
  6343. if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF})))
  6344. {
  6345. return token_type::parse_error;
  6346. }
  6347. break;
  6348. }
  6349. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  6350. case 0xE0:
  6351. {
  6352. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  6353. {
  6354. return token_type::parse_error;
  6355. }
  6356. break;
  6357. }
  6358. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  6359. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  6360. case 0xE1:
  6361. case 0xE2:
  6362. case 0xE3:
  6363. case 0xE4:
  6364. case 0xE5:
  6365. case 0xE6:
  6366. case 0xE7:
  6367. case 0xE8:
  6368. case 0xE9:
  6369. case 0xEA:
  6370. case 0xEB:
  6371. case 0xEC:
  6372. case 0xEE:
  6373. case 0xEF:
  6374. {
  6375. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  6376. {
  6377. return token_type::parse_error;
  6378. }
  6379. break;
  6380. }
  6381. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  6382. case 0xED:
  6383. {
  6384. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  6385. {
  6386. return token_type::parse_error;
  6387. }
  6388. break;
  6389. }
  6390. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  6391. case 0xF0:
  6392. {
  6393. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6394. {
  6395. return token_type::parse_error;
  6396. }
  6397. break;
  6398. }
  6399. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  6400. case 0xF1:
  6401. case 0xF2:
  6402. case 0xF3:
  6403. {
  6404. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6405. {
  6406. return token_type::parse_error;
  6407. }
  6408. break;
  6409. }
  6410. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  6411. case 0xF4:
  6412. {
  6413. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  6414. {
  6415. return token_type::parse_error;
  6416. }
  6417. break;
  6418. }
  6419. // remaining bytes (80..C1 and F5..FF) are ill-formed
  6420. default:
  6421. {
  6422. error_message = "invalid string: ill-formed UTF-8 byte";
  6423. return token_type::parse_error;
  6424. }
  6425. }
  6426. }
  6427. }
  6428. /*!
  6429. * @brief scan a comment
  6430. * @return whether comment could be scanned successfully
  6431. */
  6432. bool scan_comment()
  6433. {
  6434. switch (get())
  6435. {
  6436. // single-line comments skip input until a newline or EOF is read
  6437. case '/':
  6438. {
  6439. while (true)
  6440. {
  6441. switch (get())
  6442. {
  6443. case '\n':
  6444. case '\r':
  6445. case std::char_traits<char_type>::eof():
  6446. case '\0':
  6447. return true;
  6448. default:
  6449. break;
  6450. }
  6451. }
  6452. }
  6453. // multi-line comments skip input until */ is read
  6454. case '*':
  6455. {
  6456. while (true)
  6457. {
  6458. switch (get())
  6459. {
  6460. case std::char_traits<char_type>::eof():
  6461. case '\0':
  6462. {
  6463. error_message = "invalid comment; missing closing '*/'";
  6464. return false;
  6465. }
  6466. case '*':
  6467. {
  6468. switch (get())
  6469. {
  6470. case '/':
  6471. return true;
  6472. default:
  6473. {
  6474. unget();
  6475. continue;
  6476. }
  6477. }
  6478. }
  6479. default:
  6480. continue;
  6481. }
  6482. }
  6483. }
  6484. // unexpected character after reading '/'
  6485. default:
  6486. {
  6487. error_message = "invalid comment; expecting '/' or '*' after '/'";
  6488. return false;
  6489. }
  6490. }
  6491. }
  6492. JSON_HEDLEY_NON_NULL(2)
  6493. static void strtof(float& f, const char* str, char** endptr) noexcept
  6494. {
  6495. f = std::strtof(str, endptr);
  6496. }
  6497. JSON_HEDLEY_NON_NULL(2)
  6498. static void strtof(double& f, const char* str, char** endptr) noexcept
  6499. {
  6500. f = std::strtod(str, endptr);
  6501. }
  6502. JSON_HEDLEY_NON_NULL(2)
  6503. static void strtof(long double& f, const char* str, char** endptr) noexcept
  6504. {
  6505. f = std::strtold(str, endptr);
  6506. }
  6507. /*!
  6508. @brief scan a number literal
  6509. This function scans a string according to Sect. 6 of RFC 8259.
  6510. The function is realized with a deterministic finite state machine derived
  6511. from the grammar described in RFC 8259. Starting in state "init", the
  6512. input is read and used to determined the next state. Only state "done"
  6513. accepts the number. State "error" is a trap state to model errors. In the
  6514. table below, "anything" means any character but the ones listed before.
  6515. state | 0 | 1-9 | e E | + | - | . | anything
  6516. ---------|----------|----------|----------|---------|---------|----------|-----------
  6517. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  6518. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  6519. zero | done | done | exponent | done | done | decimal1 | done
  6520. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  6521. decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error]
  6522. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  6523. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  6524. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  6525. any2 | any2 | any2 | done | done | done | done | done
  6526. The state machine is realized with one label per state (prefixed with
  6527. "scan_number_") and `goto` statements between them. The state machine
  6528. contains cycles, but any cycle can be left when EOF is read. Therefore,
  6529. the function is guaranteed to terminate.
  6530. During scanning, the read bytes are stored in token_buffer. This string is
  6531. then converted to a signed integer, an unsigned integer, or a
  6532. floating-point number.
  6533. @return token_type::value_unsigned, token_type::value_integer, or
  6534. token_type::value_float if number could be successfully scanned,
  6535. token_type::parse_error otherwise
  6536. @note The scanner is independent of the current locale. Internally, the
  6537. locale's decimal point is used instead of `.` to work with the
  6538. locale-dependent converters.
  6539. */
  6540. token_type scan_number() // lgtm [cpp/use-of-goto]
  6541. {
  6542. // reset token_buffer to store the number's bytes
  6543. reset();
  6544. // the type of the parsed number; initially set to unsigned; will be
  6545. // changed if minus sign, decimal point or exponent is read
  6546. token_type number_type = token_type::value_unsigned;
  6547. // state (init): we just found out we need to scan a number
  6548. switch (current)
  6549. {
  6550. case '-':
  6551. {
  6552. add(current);
  6553. goto scan_number_minus;
  6554. }
  6555. case '0':
  6556. {
  6557. add(current);
  6558. goto scan_number_zero;
  6559. }
  6560. case '1':
  6561. case '2':
  6562. case '3':
  6563. case '4':
  6564. case '5':
  6565. case '6':
  6566. case '7':
  6567. case '8':
  6568. case '9':
  6569. {
  6570. add(current);
  6571. goto scan_number_any1;
  6572. }
  6573. // all other characters are rejected outside scan_number()
  6574. default: // LCOV_EXCL_LINE
  6575. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  6576. }
  6577. scan_number_minus:
  6578. // state: we just parsed a leading minus sign
  6579. number_type = token_type::value_integer;
  6580. switch (get())
  6581. {
  6582. case '0':
  6583. {
  6584. add(current);
  6585. goto scan_number_zero;
  6586. }
  6587. case '1':
  6588. case '2':
  6589. case '3':
  6590. case '4':
  6591. case '5':
  6592. case '6':
  6593. case '7':
  6594. case '8':
  6595. case '9':
  6596. {
  6597. add(current);
  6598. goto scan_number_any1;
  6599. }
  6600. default:
  6601. {
  6602. error_message = "invalid number; expected digit after '-'";
  6603. return token_type::parse_error;
  6604. }
  6605. }
  6606. scan_number_zero:
  6607. // state: we just parse a zero (maybe with a leading minus sign)
  6608. switch (get())
  6609. {
  6610. case '.':
  6611. {
  6612. add(decimal_point_char);
  6613. goto scan_number_decimal1;
  6614. }
  6615. case 'e':
  6616. case 'E':
  6617. {
  6618. add(current);
  6619. goto scan_number_exponent;
  6620. }
  6621. default:
  6622. goto scan_number_done;
  6623. }
  6624. scan_number_any1:
  6625. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  6626. switch (get())
  6627. {
  6628. case '0':
  6629. case '1':
  6630. case '2':
  6631. case '3':
  6632. case '4':
  6633. case '5':
  6634. case '6':
  6635. case '7':
  6636. case '8':
  6637. case '9':
  6638. {
  6639. add(current);
  6640. goto scan_number_any1;
  6641. }
  6642. case '.':
  6643. {
  6644. add(decimal_point_char);
  6645. goto scan_number_decimal1;
  6646. }
  6647. case 'e':
  6648. case 'E':
  6649. {
  6650. add(current);
  6651. goto scan_number_exponent;
  6652. }
  6653. default:
  6654. goto scan_number_done;
  6655. }
  6656. scan_number_decimal1:
  6657. // state: we just parsed a decimal point
  6658. number_type = token_type::value_float;
  6659. switch (get())
  6660. {
  6661. case '0':
  6662. case '1':
  6663. case '2':
  6664. case '3':
  6665. case '4':
  6666. case '5':
  6667. case '6':
  6668. case '7':
  6669. case '8':
  6670. case '9':
  6671. {
  6672. add(current);
  6673. goto scan_number_decimal2;
  6674. }
  6675. default:
  6676. {
  6677. error_message = "invalid number; expected digit after '.'";
  6678. return token_type::parse_error;
  6679. }
  6680. }
  6681. scan_number_decimal2:
  6682. // we just parsed at least one number after a decimal point
  6683. switch (get())
  6684. {
  6685. case '0':
  6686. case '1':
  6687. case '2':
  6688. case '3':
  6689. case '4':
  6690. case '5':
  6691. case '6':
  6692. case '7':
  6693. case '8':
  6694. case '9':
  6695. {
  6696. add(current);
  6697. goto scan_number_decimal2;
  6698. }
  6699. case 'e':
  6700. case 'E':
  6701. {
  6702. add(current);
  6703. goto scan_number_exponent;
  6704. }
  6705. default:
  6706. goto scan_number_done;
  6707. }
  6708. scan_number_exponent:
  6709. // we just parsed an exponent
  6710. number_type = token_type::value_float;
  6711. switch (get())
  6712. {
  6713. case '+':
  6714. case '-':
  6715. {
  6716. add(current);
  6717. goto scan_number_sign;
  6718. }
  6719. case '0':
  6720. case '1':
  6721. case '2':
  6722. case '3':
  6723. case '4':
  6724. case '5':
  6725. case '6':
  6726. case '7':
  6727. case '8':
  6728. case '9':
  6729. {
  6730. add(current);
  6731. goto scan_number_any2;
  6732. }
  6733. default:
  6734. {
  6735. error_message =
  6736. "invalid number; expected '+', '-', or digit after exponent";
  6737. return token_type::parse_error;
  6738. }
  6739. }
  6740. scan_number_sign:
  6741. // we just parsed an exponent sign
  6742. switch (get())
  6743. {
  6744. case '0':
  6745. case '1':
  6746. case '2':
  6747. case '3':
  6748. case '4':
  6749. case '5':
  6750. case '6':
  6751. case '7':
  6752. case '8':
  6753. case '9':
  6754. {
  6755. add(current);
  6756. goto scan_number_any2;
  6757. }
  6758. default:
  6759. {
  6760. error_message = "invalid number; expected digit after exponent sign";
  6761. return token_type::parse_error;
  6762. }
  6763. }
  6764. scan_number_any2:
  6765. // we just parsed a number after the exponent or exponent sign
  6766. switch (get())
  6767. {
  6768. case '0':
  6769. case '1':
  6770. case '2':
  6771. case '3':
  6772. case '4':
  6773. case '5':
  6774. case '6':
  6775. case '7':
  6776. case '8':
  6777. case '9':
  6778. {
  6779. add(current);
  6780. goto scan_number_any2;
  6781. }
  6782. default:
  6783. goto scan_number_done;
  6784. }
  6785. scan_number_done:
  6786. // unget the character after the number (we only read it to know that
  6787. // we are done scanning a number)
  6788. unget();
  6789. char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  6790. errno = 0;
  6791. // try to parse integers first and fall back to floats
  6792. if (number_type == token_type::value_unsigned)
  6793. {
  6794. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  6795. // we checked the number format before
  6796. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6797. if (errno == 0)
  6798. {
  6799. value_unsigned = static_cast<number_unsigned_t>(x);
  6800. if (value_unsigned == x)
  6801. {
  6802. return token_type::value_unsigned;
  6803. }
  6804. }
  6805. }
  6806. else if (number_type == token_type::value_integer)
  6807. {
  6808. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  6809. // we checked the number format before
  6810. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6811. if (errno == 0)
  6812. {
  6813. value_integer = static_cast<number_integer_t>(x);
  6814. if (value_integer == x)
  6815. {
  6816. return token_type::value_integer;
  6817. }
  6818. }
  6819. }
  6820. // this code is reached if we parse a floating-point number or if an
  6821. // integer conversion above failed
  6822. strtof(value_float, token_buffer.data(), &endptr);
  6823. // we checked the number format before
  6824. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  6825. return token_type::value_float;
  6826. }
  6827. /*!
  6828. @param[in] literal_text the literal text to expect
  6829. @param[in] length the length of the passed literal text
  6830. @param[in] return_type the token type to return on success
  6831. */
  6832. JSON_HEDLEY_NON_NULL(2)
  6833. token_type scan_literal(const char_type* literal_text, const std::size_t length,
  6834. token_type return_type)
  6835. {
  6836. JSON_ASSERT(std::char_traits<char_type>::to_char_type(current) == literal_text[0]);
  6837. for (std::size_t i = 1; i < length; ++i)
  6838. {
  6839. if (JSON_HEDLEY_UNLIKELY(std::char_traits<char_type>::to_char_type(get()) != literal_text[i]))
  6840. {
  6841. error_message = "invalid literal";
  6842. return token_type::parse_error;
  6843. }
  6844. }
  6845. return return_type;
  6846. }
  6847. /////////////////////
  6848. // input management
  6849. /////////////////////
  6850. /// reset token_buffer; current character is beginning of token
  6851. void reset() noexcept
  6852. {
  6853. token_buffer.clear();
  6854. token_string.clear();
  6855. token_string.push_back(std::char_traits<char_type>::to_char_type(current));
  6856. }
  6857. /*
  6858. @brief get next character from the input
  6859. This function provides the interface to the used input adapter. It does
  6860. not throw in case the input reached EOF, but returns a
  6861. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  6862. for use in error messages.
  6863. @return character read from the input
  6864. */
  6865. char_int_type get()
  6866. {
  6867. ++position.chars_read_total;
  6868. ++position.chars_read_current_line;
  6869. if (next_unget)
  6870. {
  6871. // just reset the next_unget variable and work with current
  6872. next_unget = false;
  6873. }
  6874. else
  6875. {
  6876. current = ia.get_character();
  6877. }
  6878. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
  6879. {
  6880. token_string.push_back(std::char_traits<char_type>::to_char_type(current));
  6881. }
  6882. if (current == '\n')
  6883. {
  6884. ++position.lines_read;
  6885. position.chars_read_current_line = 0;
  6886. }
  6887. return current;
  6888. }
  6889. /*!
  6890. @brief unget current character (read it again on next get)
  6891. We implement unget by setting variable next_unget to true. The input is not
  6892. changed - we just simulate ungetting by modifying chars_read_total,
  6893. chars_read_current_line, and token_string. The next call to get() will
  6894. behave as if the unget character is read again.
  6895. */
  6896. void unget()
  6897. {
  6898. next_unget = true;
  6899. --position.chars_read_total;
  6900. // in case we "unget" a newline, we have to also decrement the lines_read
  6901. if (position.chars_read_current_line == 0)
  6902. {
  6903. if (position.lines_read > 0)
  6904. {
  6905. --position.lines_read;
  6906. }
  6907. }
  6908. else
  6909. {
  6910. --position.chars_read_current_line;
  6911. }
  6912. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
  6913. {
  6914. JSON_ASSERT(!token_string.empty());
  6915. token_string.pop_back();
  6916. }
  6917. }
  6918. /// add a character to token_buffer
  6919. void add(char_int_type c)
  6920. {
  6921. token_buffer.push_back(static_cast<typename string_t::value_type>(c));
  6922. }
  6923. public:
  6924. /////////////////////
  6925. // value getters
  6926. /////////////////////
  6927. /// return integer value
  6928. constexpr number_integer_t get_number_integer() const noexcept
  6929. {
  6930. return value_integer;
  6931. }
  6932. /// return unsigned integer value
  6933. constexpr number_unsigned_t get_number_unsigned() const noexcept
  6934. {
  6935. return value_unsigned;
  6936. }
  6937. /// return floating-point value
  6938. constexpr number_float_t get_number_float() const noexcept
  6939. {
  6940. return value_float;
  6941. }
  6942. /// return current string value (implicitly resets the token; useful only once)
  6943. string_t& get_string()
  6944. {
  6945. return token_buffer;
  6946. }
  6947. /////////////////////
  6948. // diagnostics
  6949. /////////////////////
  6950. /// return position of last read token
  6951. constexpr position_t get_position() const noexcept
  6952. {
  6953. return position;
  6954. }
  6955. /// return the last read token (for errors only). Will never contain EOF
  6956. /// (an arbitrary value that is not a valid char value, often -1), because
  6957. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  6958. std::string get_token_string() const
  6959. {
  6960. // escape control characters
  6961. std::string result;
  6962. for (const auto c : token_string)
  6963. {
  6964. if (static_cast<unsigned char>(c) <= '\x1F')
  6965. {
  6966. // escape control characters
  6967. std::array<char, 9> cs{{}};
  6968. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  6969. result += cs.data();
  6970. }
  6971. else
  6972. {
  6973. // add character as is
  6974. result.push_back(static_cast<std::string::value_type>(c));
  6975. }
  6976. }
  6977. return result;
  6978. }
  6979. /// return syntax error message
  6980. JSON_HEDLEY_RETURNS_NON_NULL
  6981. constexpr const char* get_error_message() const noexcept
  6982. {
  6983. return error_message;
  6984. }
  6985. /////////////////////
  6986. // actual scanner
  6987. /////////////////////
  6988. /*!
  6989. @brief skip the UTF-8 byte order mark
  6990. @return true iff there is no BOM or the correct BOM has been skipped
  6991. */
  6992. bool skip_bom()
  6993. {
  6994. if (get() == 0xEF)
  6995. {
  6996. // check if we completely parse the BOM
  6997. return get() == 0xBB && get() == 0xBF;
  6998. }
  6999. // the first character is not the beginning of the BOM; unget it to
  7000. // process is later
  7001. unget();
  7002. return true;
  7003. }
  7004. void skip_whitespace()
  7005. {
  7006. do
  7007. {
  7008. get();
  7009. }
  7010. while (current == ' ' || current == '\t' || current == '\n' || current == '\r');
  7011. }
  7012. token_type scan()
  7013. {
  7014. // initially, skip the BOM
  7015. if (position.chars_read_total == 0 && !skip_bom())
  7016. {
  7017. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  7018. return token_type::parse_error;
  7019. }
  7020. // read next character and ignore whitespace
  7021. skip_whitespace();
  7022. // ignore comments
  7023. while (ignore_comments && current == '/')
  7024. {
  7025. if (!scan_comment())
  7026. {
  7027. return token_type::parse_error;
  7028. }
  7029. // skip following whitespace
  7030. skip_whitespace();
  7031. }
  7032. switch (current)
  7033. {
  7034. // structural characters
  7035. case '[':
  7036. return token_type::begin_array;
  7037. case ']':
  7038. return token_type::end_array;
  7039. case '{':
  7040. return token_type::begin_object;
  7041. case '}':
  7042. return token_type::end_object;
  7043. case ':':
  7044. return token_type::name_separator;
  7045. case ',':
  7046. return token_type::value_separator;
  7047. // literals
  7048. case 't':
  7049. {
  7050. std::array<char_type, 4> true_literal = {{char_type('t'), char_type('r'), char_type('u'), char_type('e')}};
  7051. return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true);
  7052. }
  7053. case 'f':
  7054. {
  7055. std::array<char_type, 5> false_literal = {{char_type('f'), char_type('a'), char_type('l'), char_type('s'), char_type('e')}};
  7056. return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false);
  7057. }
  7058. case 'n':
  7059. {
  7060. std::array<char_type, 4> null_literal = {{char_type('n'), char_type('u'), char_type('l'), char_type('l')}};
  7061. return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null);
  7062. }
  7063. // string
  7064. case '\"':
  7065. return scan_string();
  7066. // number
  7067. case '-':
  7068. case '0':
  7069. case '1':
  7070. case '2':
  7071. case '3':
  7072. case '4':
  7073. case '5':
  7074. case '6':
  7075. case '7':
  7076. case '8':
  7077. case '9':
  7078. return scan_number();
  7079. // end of input (the null byte is needed when parsing from
  7080. // string literals)
  7081. case '\0':
  7082. case std::char_traits<char_type>::eof():
  7083. return token_type::end_of_input;
  7084. // error
  7085. default:
  7086. error_message = "invalid literal";
  7087. return token_type::parse_error;
  7088. }
  7089. }
  7090. private:
  7091. /// input adapter
  7092. InputAdapterType ia;
  7093. /// whether comments should be ignored (true) or signaled as errors (false)
  7094. const bool ignore_comments = false;
  7095. /// the current character
  7096. char_int_type current = std::char_traits<char_type>::eof();
  7097. /// whether the next get() call should just return current
  7098. bool next_unget = false;
  7099. /// the start position of the current token
  7100. position_t position {};
  7101. /// raw input token string (for error messages)
  7102. std::vector<char_type> token_string {};
  7103. /// buffer for variable-length tokens (numbers, strings)
  7104. string_t token_buffer {};
  7105. /// a description of occurred lexer errors
  7106. const char* error_message = "";
  7107. // number values
  7108. number_integer_t value_integer = 0;
  7109. number_unsigned_t value_unsigned = 0;
  7110. number_float_t value_float = 0;
  7111. /// the decimal point
  7112. const char_int_type decimal_point_char = '.';
  7113. };
  7114. } // namespace detail
  7115. } // namespace nlohmann
  7116. // #include <nlohmann/detail/macro_scope.hpp>
  7117. // #include <nlohmann/detail/meta/is_sax.hpp>
  7118. #include <cstdint> // size_t
  7119. #include <utility> // declval
  7120. #include <string> // string
  7121. // #include <nlohmann/detail/meta/detected.hpp>
  7122. // #include <nlohmann/detail/meta/type_traits.hpp>
  7123. namespace nlohmann
  7124. {
  7125. namespace detail
  7126. {
  7127. template<typename T>
  7128. using null_function_t = decltype(std::declval<T&>().null());
  7129. template<typename T>
  7130. using boolean_function_t =
  7131. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  7132. template<typename T, typename Integer>
  7133. using number_integer_function_t =
  7134. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  7135. template<typename T, typename Unsigned>
  7136. using number_unsigned_function_t =
  7137. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  7138. template<typename T, typename Float, typename String>
  7139. using number_float_function_t = decltype(std::declval<T&>().number_float(
  7140. std::declval<Float>(), std::declval<const String&>()));
  7141. template<typename T, typename String>
  7142. using string_function_t =
  7143. decltype(std::declval<T&>().string(std::declval<String&>()));
  7144. template<typename T, typename Binary>
  7145. using binary_function_t =
  7146. decltype(std::declval<T&>().binary(std::declval<Binary&>()));
  7147. template<typename T>
  7148. using start_object_function_t =
  7149. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  7150. template<typename T, typename String>
  7151. using key_function_t =
  7152. decltype(std::declval<T&>().key(std::declval<String&>()));
  7153. template<typename T>
  7154. using end_object_function_t = decltype(std::declval<T&>().end_object());
  7155. template<typename T>
  7156. using start_array_function_t =
  7157. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  7158. template<typename T>
  7159. using end_array_function_t = decltype(std::declval<T&>().end_array());
  7160. template<typename T, typename Exception>
  7161. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  7162. std::declval<std::size_t>(), std::declval<const std::string&>(),
  7163. std::declval<const Exception&>()));
  7164. template<typename SAX, typename BasicJsonType>
  7165. struct is_sax
  7166. {
  7167. private:
  7168. static_assert(is_basic_json<BasicJsonType>::value,
  7169. "BasicJsonType must be of type basic_json<...>");
  7170. using number_integer_t = typename BasicJsonType::number_integer_t;
  7171. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7172. using number_float_t = typename BasicJsonType::number_float_t;
  7173. using string_t = typename BasicJsonType::string_t;
  7174. using binary_t = typename BasicJsonType::binary_t;
  7175. using exception_t = typename BasicJsonType::exception;
  7176. public:
  7177. static constexpr bool value =
  7178. is_detected_exact<bool, null_function_t, SAX>::value &&
  7179. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  7180. is_detected_exact<bool, number_integer_function_t, SAX, number_integer_t>::value &&
  7181. is_detected_exact<bool, number_unsigned_function_t, SAX, number_unsigned_t>::value &&
  7182. is_detected_exact<bool, number_float_function_t, SAX, number_float_t, string_t>::value &&
  7183. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  7184. is_detected_exact<bool, binary_function_t, SAX, binary_t>::value &&
  7185. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  7186. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  7187. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  7188. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  7189. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  7190. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  7191. };
  7192. template<typename SAX, typename BasicJsonType>
  7193. struct is_sax_static_asserts
  7194. {
  7195. private:
  7196. static_assert(is_basic_json<BasicJsonType>::value,
  7197. "BasicJsonType must be of type basic_json<...>");
  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 exception_t = typename BasicJsonType::exception;
  7204. public:
  7205. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  7206. "Missing/invalid function: bool null()");
  7207. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  7208. "Missing/invalid function: bool boolean(bool)");
  7209. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  7210. "Missing/invalid function: bool boolean(bool)");
  7211. static_assert(
  7212. is_detected_exact<bool, number_integer_function_t, SAX,
  7213. number_integer_t>::value,
  7214. "Missing/invalid function: bool number_integer(number_integer_t)");
  7215. static_assert(
  7216. is_detected_exact<bool, number_unsigned_function_t, SAX,
  7217. number_unsigned_t>::value,
  7218. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  7219. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  7220. number_float_t, string_t>::value,
  7221. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  7222. static_assert(
  7223. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  7224. "Missing/invalid function: bool string(string_t&)");
  7225. static_assert(
  7226. is_detected_exact<bool, binary_function_t, SAX, binary_t>::value,
  7227. "Missing/invalid function: bool binary(binary_t&)");
  7228. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  7229. "Missing/invalid function: bool start_object(std::size_t)");
  7230. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  7231. "Missing/invalid function: bool key(string_t&)");
  7232. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  7233. "Missing/invalid function: bool end_object()");
  7234. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  7235. "Missing/invalid function: bool start_array(std::size_t)");
  7236. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  7237. "Missing/invalid function: bool end_array()");
  7238. static_assert(
  7239. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  7240. "Missing/invalid function: bool parse_error(std::size_t, const "
  7241. "std::string&, const exception&)");
  7242. };
  7243. } // namespace detail
  7244. } // namespace nlohmann
  7245. // #include <nlohmann/detail/meta/type_traits.hpp>
  7246. // #include <nlohmann/detail/value_t.hpp>
  7247. namespace nlohmann
  7248. {
  7249. namespace detail
  7250. {
  7251. /// how to treat CBOR tags
  7252. enum class cbor_tag_handler_t
  7253. {
  7254. error, ///< throw a parse_error exception in case of a tag
  7255. ignore, ///< ignore tags
  7256. store ///< store tags as binary type
  7257. };
  7258. /*!
  7259. @brief determine system byte order
  7260. @return true if and only if system's byte order is little endian
  7261. @note from https://stackoverflow.com/a/1001328/266378
  7262. */
  7263. static inline bool little_endianess(int num = 1) noexcept
  7264. {
  7265. return *reinterpret_cast<char*>(&num) == 1;
  7266. }
  7267. ///////////////////
  7268. // binary reader //
  7269. ///////////////////
  7270. /*!
  7271. @brief deserialization of CBOR, MessagePack, and UBJSON values
  7272. */
  7273. template<typename BasicJsonType, typename InputAdapterType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  7274. class binary_reader
  7275. {
  7276. using number_integer_t = typename BasicJsonType::number_integer_t;
  7277. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7278. using number_float_t = typename BasicJsonType::number_float_t;
  7279. using string_t = typename BasicJsonType::string_t;
  7280. using binary_t = typename BasicJsonType::binary_t;
  7281. using json_sax_t = SAX;
  7282. using char_type = typename InputAdapterType::char_type;
  7283. using char_int_type = typename std::char_traits<char_type>::int_type;
  7284. public:
  7285. /*!
  7286. @brief create a binary reader
  7287. @param[in] adapter input adapter to read from
  7288. */
  7289. explicit binary_reader(InputAdapterType&& adapter) noexcept : ia(std::move(adapter))
  7290. {
  7291. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  7292. }
  7293. // make class move-only
  7294. binary_reader(const binary_reader&) = delete;
  7295. binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  7296. binary_reader& operator=(const binary_reader&) = delete;
  7297. binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
  7298. ~binary_reader() = default;
  7299. /*!
  7300. @param[in] format the binary format to parse
  7301. @param[in] sax_ a SAX event processor
  7302. @param[in] strict whether to expect the input to be consumed completed
  7303. @param[in] tag_handler how to treat CBOR tags
  7304. @return whether parsing was successful
  7305. */
  7306. JSON_HEDLEY_NON_NULL(3)
  7307. bool sax_parse(const input_format_t format,
  7308. json_sax_t* sax_,
  7309. const bool strict = true,
  7310. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  7311. {
  7312. sax = sax_;
  7313. bool result = false;
  7314. switch (format)
  7315. {
  7316. case input_format_t::bson:
  7317. result = parse_bson_internal();
  7318. break;
  7319. case input_format_t::cbor:
  7320. result = parse_cbor_internal(true, tag_handler);
  7321. break;
  7322. case input_format_t::msgpack:
  7323. result = parse_msgpack_internal();
  7324. break;
  7325. case input_format_t::ubjson:
  7326. result = parse_ubjson_internal();
  7327. break;
  7328. case input_format_t::json: // LCOV_EXCL_LINE
  7329. default: // LCOV_EXCL_LINE
  7330. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  7331. }
  7332. // strict mode: next byte must be EOF
  7333. if (result && strict)
  7334. {
  7335. if (format == input_format_t::ubjson)
  7336. {
  7337. get_ignore_noop();
  7338. }
  7339. else
  7340. {
  7341. get();
  7342. }
  7343. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char_type>::eof()))
  7344. {
  7345. return sax->parse_error(chars_read, get_token_string(),
  7346. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"), BasicJsonType()));
  7347. }
  7348. }
  7349. return result;
  7350. }
  7351. private:
  7352. //////////
  7353. // BSON //
  7354. //////////
  7355. /*!
  7356. @brief Reads in a BSON-object and passes it to the SAX-parser.
  7357. @return whether a valid BSON-value was passed to the SAX parser
  7358. */
  7359. bool parse_bson_internal()
  7360. {
  7361. std::int32_t document_size{};
  7362. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  7363. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  7364. {
  7365. return false;
  7366. }
  7367. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false)))
  7368. {
  7369. return false;
  7370. }
  7371. return sax->end_object();
  7372. }
  7373. /*!
  7374. @brief Parses a C-style string from the BSON input.
  7375. @param[in,out] result A reference to the string variable where the read
  7376. string is to be stored.
  7377. @return `true` if the \x00-byte indicating the end of the string was
  7378. encountered before the EOF; false` indicates an unexpected EOF.
  7379. */
  7380. bool get_bson_cstr(string_t& result)
  7381. {
  7382. auto out = std::back_inserter(result);
  7383. while (true)
  7384. {
  7385. get();
  7386. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring")))
  7387. {
  7388. return false;
  7389. }
  7390. if (current == 0x00)
  7391. {
  7392. return true;
  7393. }
  7394. *out++ = static_cast<typename string_t::value_type>(current);
  7395. }
  7396. }
  7397. /*!
  7398. @brief Parses a zero-terminated string of length @a len from the BSON
  7399. input.
  7400. @param[in] len The length (including the zero-byte at the end) of the
  7401. string to be read.
  7402. @param[in,out] result A reference to the string variable where the read
  7403. string is to be stored.
  7404. @tparam NumberType The type of the length @a len
  7405. @pre len >= 1
  7406. @return `true` if the string was successfully parsed
  7407. */
  7408. template<typename NumberType>
  7409. bool get_bson_string(const NumberType len, string_t& result)
  7410. {
  7411. if (JSON_HEDLEY_UNLIKELY(len < 1))
  7412. {
  7413. auto last_token = get_token_string();
  7414. 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()));
  7415. }
  7416. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) && get() != std::char_traits<char_type>::eof();
  7417. }
  7418. /*!
  7419. @brief Parses a byte array input of length @a len from the BSON input.
  7420. @param[in] len The length of the byte array to be read.
  7421. @param[in,out] result A reference to the binary variable where the read
  7422. array is to be stored.
  7423. @tparam NumberType The type of the length @a len
  7424. @pre len >= 0
  7425. @return `true` if the byte array was successfully parsed
  7426. */
  7427. template<typename NumberType>
  7428. bool get_bson_binary(const NumberType len, binary_t& result)
  7429. {
  7430. if (JSON_HEDLEY_UNLIKELY(len < 0))
  7431. {
  7432. auto last_token = get_token_string();
  7433. 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()));
  7434. }
  7435. // All BSON binary values have a subtype
  7436. std::uint8_t subtype{};
  7437. get_number<std::uint8_t>(input_format_t::bson, subtype);
  7438. result.set_subtype(subtype);
  7439. return get_binary(input_format_t::bson, len, result);
  7440. }
  7441. /*!
  7442. @brief Read a BSON document element of the given @a element_type.
  7443. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  7444. @param[in] element_type_parse_position The position in the input stream,
  7445. where the `element_type` was read.
  7446. @warning Not all BSON element types are supported yet. An unsupported
  7447. @a element_type will give rise to a parse_error.114:
  7448. Unsupported BSON record type 0x...
  7449. @return whether a valid BSON-object/array was passed to the SAX parser
  7450. */
  7451. bool parse_bson_element_internal(const char_int_type element_type,
  7452. const std::size_t element_type_parse_position)
  7453. {
  7454. switch (element_type)
  7455. {
  7456. case 0x01: // double
  7457. {
  7458. double number{};
  7459. return get_number<double, true>(input_format_t::bson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  7460. }
  7461. case 0x02: // string
  7462. {
  7463. std::int32_t len{};
  7464. string_t value;
  7465. return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value);
  7466. }
  7467. case 0x03: // object
  7468. {
  7469. return parse_bson_internal();
  7470. }
  7471. case 0x04: // array
  7472. {
  7473. return parse_bson_array();
  7474. }
  7475. case 0x05: // binary
  7476. {
  7477. std::int32_t len{};
  7478. binary_t value;
  7479. return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value);
  7480. }
  7481. case 0x08: // boolean
  7482. {
  7483. return sax->boolean(get() != 0);
  7484. }
  7485. case 0x0A: // null
  7486. {
  7487. return sax->null();
  7488. }
  7489. case 0x10: // int32
  7490. {
  7491. std::int32_t value{};
  7492. return get_number<std::int32_t, true>(input_format_t::bson, value) && sax->number_integer(value);
  7493. }
  7494. case 0x12: // int64
  7495. {
  7496. std::int64_t value{};
  7497. return get_number<std::int64_t, true>(input_format_t::bson, value) && sax->number_integer(value);
  7498. }
  7499. default: // anything else not supported (yet)
  7500. {
  7501. std::array<char, 3> cr{{}};
  7502. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  7503. 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()));
  7504. }
  7505. }
  7506. }
  7507. /*!
  7508. @brief Read a BSON element list (as specified in the BSON-spec)
  7509. The same binary layout is used for objects and arrays, hence it must be
  7510. indicated with the argument @a is_array which one is expected
  7511. (true --> array, false --> object).
  7512. @param[in] is_array Determines if the element list being read is to be
  7513. treated as an object (@a is_array == false), or as an
  7514. array (@a is_array == true).
  7515. @return whether a valid BSON-object/array was passed to the SAX parser
  7516. */
  7517. bool parse_bson_element_list(const bool is_array)
  7518. {
  7519. string_t key;
  7520. while (auto element_type = get())
  7521. {
  7522. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list")))
  7523. {
  7524. return false;
  7525. }
  7526. const std::size_t element_type_parse_position = chars_read;
  7527. if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key)))
  7528. {
  7529. return false;
  7530. }
  7531. if (!is_array && !sax->key(key))
  7532. {
  7533. return false;
  7534. }
  7535. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position)))
  7536. {
  7537. return false;
  7538. }
  7539. // get_bson_cstr only appends
  7540. key.clear();
  7541. }
  7542. return true;
  7543. }
  7544. /*!
  7545. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  7546. @return whether a valid BSON-array was passed to the SAX parser
  7547. */
  7548. bool parse_bson_array()
  7549. {
  7550. std::int32_t document_size{};
  7551. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  7552. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  7553. {
  7554. return false;
  7555. }
  7556. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true)))
  7557. {
  7558. return false;
  7559. }
  7560. return sax->end_array();
  7561. }
  7562. //////////
  7563. // CBOR //
  7564. //////////
  7565. /*!
  7566. @param[in] get_char whether a new character should be retrieved from the
  7567. input (true) or whether the last read character should
  7568. be considered instead (false)
  7569. @param[in] tag_handler how CBOR tags should be treated
  7570. @return whether a valid CBOR value was passed to the SAX parser
  7571. */
  7572. bool parse_cbor_internal(const bool get_char,
  7573. const cbor_tag_handler_t tag_handler)
  7574. {
  7575. switch (get_char ? get() : current)
  7576. {
  7577. // EOF
  7578. case std::char_traits<char_type>::eof():
  7579. return unexpect_eof(input_format_t::cbor, "value");
  7580. // Integer 0x00..0x17 (0..23)
  7581. case 0x00:
  7582. case 0x01:
  7583. case 0x02:
  7584. case 0x03:
  7585. case 0x04:
  7586. case 0x05:
  7587. case 0x06:
  7588. case 0x07:
  7589. case 0x08:
  7590. case 0x09:
  7591. case 0x0A:
  7592. case 0x0B:
  7593. case 0x0C:
  7594. case 0x0D:
  7595. case 0x0E:
  7596. case 0x0F:
  7597. case 0x10:
  7598. case 0x11:
  7599. case 0x12:
  7600. case 0x13:
  7601. case 0x14:
  7602. case 0x15:
  7603. case 0x16:
  7604. case 0x17:
  7605. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  7606. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  7607. {
  7608. std::uint8_t number{};
  7609. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7610. }
  7611. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  7612. {
  7613. std::uint16_t number{};
  7614. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7615. }
  7616. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  7617. {
  7618. std::uint32_t number{};
  7619. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7620. }
  7621. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  7622. {
  7623. std::uint64_t number{};
  7624. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  7625. }
  7626. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  7627. case 0x20:
  7628. case 0x21:
  7629. case 0x22:
  7630. case 0x23:
  7631. case 0x24:
  7632. case 0x25:
  7633. case 0x26:
  7634. case 0x27:
  7635. case 0x28:
  7636. case 0x29:
  7637. case 0x2A:
  7638. case 0x2B:
  7639. case 0x2C:
  7640. case 0x2D:
  7641. case 0x2E:
  7642. case 0x2F:
  7643. case 0x30:
  7644. case 0x31:
  7645. case 0x32:
  7646. case 0x33:
  7647. case 0x34:
  7648. case 0x35:
  7649. case 0x36:
  7650. case 0x37:
  7651. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  7652. case 0x38: // Negative integer (one-byte uint8_t follows)
  7653. {
  7654. std::uint8_t number{};
  7655. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7656. }
  7657. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  7658. {
  7659. std::uint16_t number{};
  7660. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7661. }
  7662. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  7663. {
  7664. std::uint32_t number{};
  7665. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  7666. }
  7667. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  7668. {
  7669. std::uint64_t number{};
  7670. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1)
  7671. - static_cast<number_integer_t>(number));
  7672. }
  7673. // Binary data (0x00..0x17 bytes follow)
  7674. case 0x40:
  7675. case 0x41:
  7676. case 0x42:
  7677. case 0x43:
  7678. case 0x44:
  7679. case 0x45:
  7680. case 0x46:
  7681. case 0x47:
  7682. case 0x48:
  7683. case 0x49:
  7684. case 0x4A:
  7685. case 0x4B:
  7686. case 0x4C:
  7687. case 0x4D:
  7688. case 0x4E:
  7689. case 0x4F:
  7690. case 0x50:
  7691. case 0x51:
  7692. case 0x52:
  7693. case 0x53:
  7694. case 0x54:
  7695. case 0x55:
  7696. case 0x56:
  7697. case 0x57:
  7698. case 0x58: // Binary data (one-byte uint8_t for n follows)
  7699. case 0x59: // Binary data (two-byte uint16_t for n follow)
  7700. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  7701. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  7702. case 0x5F: // Binary data (indefinite length)
  7703. {
  7704. binary_t b;
  7705. return get_cbor_binary(b) && sax->binary(b);
  7706. }
  7707. // UTF-8 string (0x00..0x17 bytes follow)
  7708. case 0x60:
  7709. case 0x61:
  7710. case 0x62:
  7711. case 0x63:
  7712. case 0x64:
  7713. case 0x65:
  7714. case 0x66:
  7715. case 0x67:
  7716. case 0x68:
  7717. case 0x69:
  7718. case 0x6A:
  7719. case 0x6B:
  7720. case 0x6C:
  7721. case 0x6D:
  7722. case 0x6E:
  7723. case 0x6F:
  7724. case 0x70:
  7725. case 0x71:
  7726. case 0x72:
  7727. case 0x73:
  7728. case 0x74:
  7729. case 0x75:
  7730. case 0x76:
  7731. case 0x77:
  7732. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  7733. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  7734. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  7735. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  7736. case 0x7F: // UTF-8 string (indefinite length)
  7737. {
  7738. string_t s;
  7739. return get_cbor_string(s) && sax->string(s);
  7740. }
  7741. // array (0x00..0x17 data items follow)
  7742. case 0x80:
  7743. case 0x81:
  7744. case 0x82:
  7745. case 0x83:
  7746. case 0x84:
  7747. case 0x85:
  7748. case 0x86:
  7749. case 0x87:
  7750. case 0x88:
  7751. case 0x89:
  7752. case 0x8A:
  7753. case 0x8B:
  7754. case 0x8C:
  7755. case 0x8D:
  7756. case 0x8E:
  7757. case 0x8F:
  7758. case 0x90:
  7759. case 0x91:
  7760. case 0x92:
  7761. case 0x93:
  7762. case 0x94:
  7763. case 0x95:
  7764. case 0x96:
  7765. case 0x97:
  7766. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler);
  7767. case 0x98: // array (one-byte uint8_t for n follows)
  7768. {
  7769. std::uint8_t len{};
  7770. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7771. }
  7772. case 0x99: // array (two-byte uint16_t for n follow)
  7773. {
  7774. std::uint16_t len{};
  7775. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7776. }
  7777. case 0x9A: // array (four-byte uint32_t for n follow)
  7778. {
  7779. std::uint32_t len{};
  7780. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
  7781. }
  7782. case 0x9B: // array (eight-byte uint64_t for n follow)
  7783. {
  7784. std::uint64_t len{};
  7785. return get_number(input_format_t::cbor, len) && get_cbor_array(detail::conditional_static_cast<std::size_t>(len), tag_handler);
  7786. }
  7787. case 0x9F: // array (indefinite length)
  7788. return get_cbor_array(std::size_t(-1), tag_handler);
  7789. // map (0x00..0x17 pairs of data items follow)
  7790. case 0xA0:
  7791. case 0xA1:
  7792. case 0xA2:
  7793. case 0xA3:
  7794. case 0xA4:
  7795. case 0xA5:
  7796. case 0xA6:
  7797. case 0xA7:
  7798. case 0xA8:
  7799. case 0xA9:
  7800. case 0xAA:
  7801. case 0xAB:
  7802. case 0xAC:
  7803. case 0xAD:
  7804. case 0xAE:
  7805. case 0xAF:
  7806. case 0xB0:
  7807. case 0xB1:
  7808. case 0xB2:
  7809. case 0xB3:
  7810. case 0xB4:
  7811. case 0xB5:
  7812. case 0xB6:
  7813. case 0xB7:
  7814. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler);
  7815. case 0xB8: // map (one-byte uint8_t for n follows)
  7816. {
  7817. std::uint8_t len{};
  7818. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7819. }
  7820. case 0xB9: // map (two-byte uint16_t for n follow)
  7821. {
  7822. std::uint16_t len{};
  7823. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7824. }
  7825. case 0xBA: // map (four-byte uint32_t for n follow)
  7826. {
  7827. std::uint32_t len{};
  7828. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
  7829. }
  7830. case 0xBB: // map (eight-byte uint64_t for n follow)
  7831. {
  7832. std::uint64_t len{};
  7833. return get_number(input_format_t::cbor, len) && get_cbor_object(detail::conditional_static_cast<std::size_t>(len), tag_handler);
  7834. }
  7835. case 0xBF: // map (indefinite length)
  7836. return get_cbor_object(std::size_t(-1), tag_handler);
  7837. case 0xC6: // tagged item
  7838. case 0xC7:
  7839. case 0xC8:
  7840. case 0xC9:
  7841. case 0xCA:
  7842. case 0xCB:
  7843. case 0xCC:
  7844. case 0xCD:
  7845. case 0xCE:
  7846. case 0xCF:
  7847. case 0xD0:
  7848. case 0xD1:
  7849. case 0xD2:
  7850. case 0xD3:
  7851. case 0xD4:
  7852. case 0xD8: // tagged item (1 bytes follow)
  7853. case 0xD9: // tagged item (2 bytes follow)
  7854. case 0xDA: // tagged item (4 bytes follow)
  7855. case 0xDB: // tagged item (8 bytes follow)
  7856. {
  7857. switch (tag_handler)
  7858. {
  7859. case cbor_tag_handler_t::error:
  7860. {
  7861. auto last_token = get_token_string();
  7862. 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()));
  7863. }
  7864. case cbor_tag_handler_t::ignore:
  7865. {
  7866. // ignore binary subtype
  7867. switch (current)
  7868. {
  7869. case 0xD8:
  7870. {
  7871. std::uint8_t subtype_to_ignore{};
  7872. get_number(input_format_t::cbor, subtype_to_ignore);
  7873. break;
  7874. }
  7875. case 0xD9:
  7876. {
  7877. std::uint16_t subtype_to_ignore{};
  7878. get_number(input_format_t::cbor, subtype_to_ignore);
  7879. break;
  7880. }
  7881. case 0xDA:
  7882. {
  7883. std::uint32_t subtype_to_ignore{};
  7884. get_number(input_format_t::cbor, subtype_to_ignore);
  7885. break;
  7886. }
  7887. case 0xDB:
  7888. {
  7889. std::uint64_t subtype_to_ignore{};
  7890. get_number(input_format_t::cbor, subtype_to_ignore);
  7891. break;
  7892. }
  7893. default:
  7894. break;
  7895. }
  7896. return parse_cbor_internal(true, tag_handler);
  7897. }
  7898. case cbor_tag_handler_t::store:
  7899. {
  7900. binary_t b;
  7901. // use binary subtype and store in binary container
  7902. switch (current)
  7903. {
  7904. case 0xD8:
  7905. {
  7906. std::uint8_t subtype{};
  7907. get_number(input_format_t::cbor, subtype);
  7908. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7909. break;
  7910. }
  7911. case 0xD9:
  7912. {
  7913. std::uint16_t subtype{};
  7914. get_number(input_format_t::cbor, subtype);
  7915. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7916. break;
  7917. }
  7918. case 0xDA:
  7919. {
  7920. std::uint32_t subtype{};
  7921. get_number(input_format_t::cbor, subtype);
  7922. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7923. break;
  7924. }
  7925. case 0xDB:
  7926. {
  7927. std::uint64_t subtype{};
  7928. get_number(input_format_t::cbor, subtype);
  7929. b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
  7930. break;
  7931. }
  7932. default:
  7933. return parse_cbor_internal(true, tag_handler);
  7934. }
  7935. get();
  7936. return get_cbor_binary(b) && sax->binary(b);
  7937. }
  7938. default: // LCOV_EXCL_LINE
  7939. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  7940. return false; // LCOV_EXCL_LINE
  7941. }
  7942. }
  7943. case 0xF4: // false
  7944. return sax->boolean(false);
  7945. case 0xF5: // true
  7946. return sax->boolean(true);
  7947. case 0xF6: // null
  7948. return sax->null();
  7949. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  7950. {
  7951. const auto byte1_raw = get();
  7952. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
  7953. {
  7954. return false;
  7955. }
  7956. const auto byte2_raw = get();
  7957. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
  7958. {
  7959. return false;
  7960. }
  7961. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  7962. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  7963. // code from RFC 7049, Appendix D, Figure 3:
  7964. // As half-precision floating-point numbers were only added
  7965. // to IEEE 754 in 2008, today's programming platforms often
  7966. // still only have limited support for them. It is very
  7967. // easy to include at least decoding support for them even
  7968. // without such support. An example of a small decoder for
  7969. // half-precision floating-point numbers in the C language
  7970. // is shown in Fig. 3.
  7971. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  7972. const double val = [&half]
  7973. {
  7974. const int exp = (half >> 10u) & 0x1Fu;
  7975. const unsigned int mant = half & 0x3FFu;
  7976. JSON_ASSERT(0 <= exp&& exp <= 32);
  7977. JSON_ASSERT(mant <= 1024);
  7978. switch (exp)
  7979. {
  7980. case 0:
  7981. return std::ldexp(mant, -24);
  7982. case 31:
  7983. return (mant == 0)
  7984. ? std::numeric_limits<double>::infinity()
  7985. : std::numeric_limits<double>::quiet_NaN();
  7986. default:
  7987. return std::ldexp(mant + 1024, exp - 25);
  7988. }
  7989. }();
  7990. return sax->number_float((half & 0x8000u) != 0
  7991. ? static_cast<number_float_t>(-val)
  7992. : static_cast<number_float_t>(val), "");
  7993. }
  7994. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  7995. {
  7996. float number{};
  7997. return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
  7998. }
  7999. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  8000. {
  8001. double number{};
  8002. return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8003. }
  8004. default: // anything else (0xFF is handled inside the other types)
  8005. {
  8006. auto last_token = get_token_string();
  8007. 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()));
  8008. }
  8009. }
  8010. }
  8011. /*!
  8012. @brief reads a CBOR string
  8013. This function first reads starting bytes to determine the expected
  8014. string length and then copies this number of bytes into a string.
  8015. Additionally, CBOR's strings with indefinite lengths are supported.
  8016. @param[out] result created string
  8017. @return whether string creation completed
  8018. */
  8019. bool get_cbor_string(string_t& result)
  8020. {
  8021. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string")))
  8022. {
  8023. return false;
  8024. }
  8025. switch (current)
  8026. {
  8027. // UTF-8 string (0x00..0x17 bytes follow)
  8028. case 0x60:
  8029. case 0x61:
  8030. case 0x62:
  8031. case 0x63:
  8032. case 0x64:
  8033. case 0x65:
  8034. case 0x66:
  8035. case 0x67:
  8036. case 0x68:
  8037. case 0x69:
  8038. case 0x6A:
  8039. case 0x6B:
  8040. case 0x6C:
  8041. case 0x6D:
  8042. case 0x6E:
  8043. case 0x6F:
  8044. case 0x70:
  8045. case 0x71:
  8046. case 0x72:
  8047. case 0x73:
  8048. case 0x74:
  8049. case 0x75:
  8050. case 0x76:
  8051. case 0x77:
  8052. {
  8053. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  8054. }
  8055. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  8056. {
  8057. std::uint8_t len{};
  8058. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  8059. }
  8060. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  8061. {
  8062. std::uint16_t len{};
  8063. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  8064. }
  8065. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  8066. {
  8067. std::uint32_t len{};
  8068. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  8069. }
  8070. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  8071. {
  8072. std::uint64_t len{};
  8073. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  8074. }
  8075. case 0x7F: // UTF-8 string (indefinite length)
  8076. {
  8077. while (get() != 0xFF)
  8078. {
  8079. string_t chunk;
  8080. if (!get_cbor_string(chunk))
  8081. {
  8082. return false;
  8083. }
  8084. result.append(chunk);
  8085. }
  8086. return true;
  8087. }
  8088. default:
  8089. {
  8090. auto last_token = get_token_string();
  8091. 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()));
  8092. }
  8093. }
  8094. }
  8095. /*!
  8096. @brief reads a CBOR byte array
  8097. This function first reads starting bytes to determine the expected
  8098. byte array length and then copies this number of bytes into the byte array.
  8099. Additionally, CBOR's byte arrays with indefinite lengths are supported.
  8100. @param[out] result created byte array
  8101. @return whether byte array creation completed
  8102. */
  8103. bool get_cbor_binary(binary_t& result)
  8104. {
  8105. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary")))
  8106. {
  8107. return false;
  8108. }
  8109. switch (current)
  8110. {
  8111. // Binary data (0x00..0x17 bytes follow)
  8112. case 0x40:
  8113. case 0x41:
  8114. case 0x42:
  8115. case 0x43:
  8116. case 0x44:
  8117. case 0x45:
  8118. case 0x46:
  8119. case 0x47:
  8120. case 0x48:
  8121. case 0x49:
  8122. case 0x4A:
  8123. case 0x4B:
  8124. case 0x4C:
  8125. case 0x4D:
  8126. case 0x4E:
  8127. case 0x4F:
  8128. case 0x50:
  8129. case 0x51:
  8130. case 0x52:
  8131. case 0x53:
  8132. case 0x54:
  8133. case 0x55:
  8134. case 0x56:
  8135. case 0x57:
  8136. {
  8137. return get_binary(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  8138. }
  8139. case 0x58: // Binary data (one-byte uint8_t for n follows)
  8140. {
  8141. std::uint8_t len{};
  8142. return get_number(input_format_t::cbor, len) &&
  8143. get_binary(input_format_t::cbor, len, result);
  8144. }
  8145. case 0x59: // Binary data (two-byte uint16_t for n follow)
  8146. {
  8147. std::uint16_t len{};
  8148. return get_number(input_format_t::cbor, len) &&
  8149. get_binary(input_format_t::cbor, len, result);
  8150. }
  8151. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  8152. {
  8153. std::uint32_t len{};
  8154. return get_number(input_format_t::cbor, len) &&
  8155. get_binary(input_format_t::cbor, len, result);
  8156. }
  8157. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  8158. {
  8159. std::uint64_t len{};
  8160. return get_number(input_format_t::cbor, len) &&
  8161. get_binary(input_format_t::cbor, len, result);
  8162. }
  8163. case 0x5F: // Binary data (indefinite length)
  8164. {
  8165. while (get() != 0xFF)
  8166. {
  8167. binary_t chunk;
  8168. if (!get_cbor_binary(chunk))
  8169. {
  8170. return false;
  8171. }
  8172. result.insert(result.end(), chunk.begin(), chunk.end());
  8173. }
  8174. return true;
  8175. }
  8176. default:
  8177. {
  8178. auto last_token = get_token_string();
  8179. 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()));
  8180. }
  8181. }
  8182. }
  8183. /*!
  8184. @param[in] len the length of the array or std::size_t(-1) for an
  8185. array of indefinite size
  8186. @param[in] tag_handler how CBOR tags should be treated
  8187. @return whether array creation completed
  8188. */
  8189. bool get_cbor_array(const std::size_t len,
  8190. const cbor_tag_handler_t tag_handler)
  8191. {
  8192. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
  8193. {
  8194. return false;
  8195. }
  8196. if (len != std::size_t(-1))
  8197. {
  8198. for (std::size_t i = 0; i < len; ++i)
  8199. {
  8200. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  8201. {
  8202. return false;
  8203. }
  8204. }
  8205. }
  8206. else
  8207. {
  8208. while (get() != 0xFF)
  8209. {
  8210. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler)))
  8211. {
  8212. return false;
  8213. }
  8214. }
  8215. }
  8216. return sax->end_array();
  8217. }
  8218. /*!
  8219. @param[in] len the length of the object or std::size_t(-1) for an
  8220. object of indefinite size
  8221. @param[in] tag_handler how CBOR tags should be treated
  8222. @return whether object creation completed
  8223. */
  8224. bool get_cbor_object(const std::size_t len,
  8225. const cbor_tag_handler_t tag_handler)
  8226. {
  8227. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
  8228. {
  8229. return false;
  8230. }
  8231. if (len != 0)
  8232. {
  8233. string_t key;
  8234. if (len != std::size_t(-1))
  8235. {
  8236. for (std::size_t i = 0; i < len; ++i)
  8237. {
  8238. get();
  8239. if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
  8240. {
  8241. return false;
  8242. }
  8243. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  8244. {
  8245. return false;
  8246. }
  8247. key.clear();
  8248. }
  8249. }
  8250. else
  8251. {
  8252. while (get() != 0xFF)
  8253. {
  8254. if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
  8255. {
  8256. return false;
  8257. }
  8258. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
  8259. {
  8260. return false;
  8261. }
  8262. key.clear();
  8263. }
  8264. }
  8265. }
  8266. return sax->end_object();
  8267. }
  8268. /////////////
  8269. // MsgPack //
  8270. /////////////
  8271. /*!
  8272. @return whether a valid MessagePack value was passed to the SAX parser
  8273. */
  8274. bool parse_msgpack_internal()
  8275. {
  8276. switch (get())
  8277. {
  8278. // EOF
  8279. case std::char_traits<char_type>::eof():
  8280. return unexpect_eof(input_format_t::msgpack, "value");
  8281. // positive fixint
  8282. case 0x00:
  8283. case 0x01:
  8284. case 0x02:
  8285. case 0x03:
  8286. case 0x04:
  8287. case 0x05:
  8288. case 0x06:
  8289. case 0x07:
  8290. case 0x08:
  8291. case 0x09:
  8292. case 0x0A:
  8293. case 0x0B:
  8294. case 0x0C:
  8295. case 0x0D:
  8296. case 0x0E:
  8297. case 0x0F:
  8298. case 0x10:
  8299. case 0x11:
  8300. case 0x12:
  8301. case 0x13:
  8302. case 0x14:
  8303. case 0x15:
  8304. case 0x16:
  8305. case 0x17:
  8306. case 0x18:
  8307. case 0x19:
  8308. case 0x1A:
  8309. case 0x1B:
  8310. case 0x1C:
  8311. case 0x1D:
  8312. case 0x1E:
  8313. case 0x1F:
  8314. case 0x20:
  8315. case 0x21:
  8316. case 0x22:
  8317. case 0x23:
  8318. case 0x24:
  8319. case 0x25:
  8320. case 0x26:
  8321. case 0x27:
  8322. case 0x28:
  8323. case 0x29:
  8324. case 0x2A:
  8325. case 0x2B:
  8326. case 0x2C:
  8327. case 0x2D:
  8328. case 0x2E:
  8329. case 0x2F:
  8330. case 0x30:
  8331. case 0x31:
  8332. case 0x32:
  8333. case 0x33:
  8334. case 0x34:
  8335. case 0x35:
  8336. case 0x36:
  8337. case 0x37:
  8338. case 0x38:
  8339. case 0x39:
  8340. case 0x3A:
  8341. case 0x3B:
  8342. case 0x3C:
  8343. case 0x3D:
  8344. case 0x3E:
  8345. case 0x3F:
  8346. case 0x40:
  8347. case 0x41:
  8348. case 0x42:
  8349. case 0x43:
  8350. case 0x44:
  8351. case 0x45:
  8352. case 0x46:
  8353. case 0x47:
  8354. case 0x48:
  8355. case 0x49:
  8356. case 0x4A:
  8357. case 0x4B:
  8358. case 0x4C:
  8359. case 0x4D:
  8360. case 0x4E:
  8361. case 0x4F:
  8362. case 0x50:
  8363. case 0x51:
  8364. case 0x52:
  8365. case 0x53:
  8366. case 0x54:
  8367. case 0x55:
  8368. case 0x56:
  8369. case 0x57:
  8370. case 0x58:
  8371. case 0x59:
  8372. case 0x5A:
  8373. case 0x5B:
  8374. case 0x5C:
  8375. case 0x5D:
  8376. case 0x5E:
  8377. case 0x5F:
  8378. case 0x60:
  8379. case 0x61:
  8380. case 0x62:
  8381. case 0x63:
  8382. case 0x64:
  8383. case 0x65:
  8384. case 0x66:
  8385. case 0x67:
  8386. case 0x68:
  8387. case 0x69:
  8388. case 0x6A:
  8389. case 0x6B:
  8390. case 0x6C:
  8391. case 0x6D:
  8392. case 0x6E:
  8393. case 0x6F:
  8394. case 0x70:
  8395. case 0x71:
  8396. case 0x72:
  8397. case 0x73:
  8398. case 0x74:
  8399. case 0x75:
  8400. case 0x76:
  8401. case 0x77:
  8402. case 0x78:
  8403. case 0x79:
  8404. case 0x7A:
  8405. case 0x7B:
  8406. case 0x7C:
  8407. case 0x7D:
  8408. case 0x7E:
  8409. case 0x7F:
  8410. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  8411. // fixmap
  8412. case 0x80:
  8413. case 0x81:
  8414. case 0x82:
  8415. case 0x83:
  8416. case 0x84:
  8417. case 0x85:
  8418. case 0x86:
  8419. case 0x87:
  8420. case 0x88:
  8421. case 0x89:
  8422. case 0x8A:
  8423. case 0x8B:
  8424. case 0x8C:
  8425. case 0x8D:
  8426. case 0x8E:
  8427. case 0x8F:
  8428. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  8429. // fixarray
  8430. case 0x90:
  8431. case 0x91:
  8432. case 0x92:
  8433. case 0x93:
  8434. case 0x94:
  8435. case 0x95:
  8436. case 0x96:
  8437. case 0x97:
  8438. case 0x98:
  8439. case 0x99:
  8440. case 0x9A:
  8441. case 0x9B:
  8442. case 0x9C:
  8443. case 0x9D:
  8444. case 0x9E:
  8445. case 0x9F:
  8446. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  8447. // fixstr
  8448. case 0xA0:
  8449. case 0xA1:
  8450. case 0xA2:
  8451. case 0xA3:
  8452. case 0xA4:
  8453. case 0xA5:
  8454. case 0xA6:
  8455. case 0xA7:
  8456. case 0xA8:
  8457. case 0xA9:
  8458. case 0xAA:
  8459. case 0xAB:
  8460. case 0xAC:
  8461. case 0xAD:
  8462. case 0xAE:
  8463. case 0xAF:
  8464. case 0xB0:
  8465. case 0xB1:
  8466. case 0xB2:
  8467. case 0xB3:
  8468. case 0xB4:
  8469. case 0xB5:
  8470. case 0xB6:
  8471. case 0xB7:
  8472. case 0xB8:
  8473. case 0xB9:
  8474. case 0xBA:
  8475. case 0xBB:
  8476. case 0xBC:
  8477. case 0xBD:
  8478. case 0xBE:
  8479. case 0xBF:
  8480. case 0xD9: // str 8
  8481. case 0xDA: // str 16
  8482. case 0xDB: // str 32
  8483. {
  8484. string_t s;
  8485. return get_msgpack_string(s) && sax->string(s);
  8486. }
  8487. case 0xC0: // nil
  8488. return sax->null();
  8489. case 0xC2: // false
  8490. return sax->boolean(false);
  8491. case 0xC3: // true
  8492. return sax->boolean(true);
  8493. case 0xC4: // bin 8
  8494. case 0xC5: // bin 16
  8495. case 0xC6: // bin 32
  8496. case 0xC7: // ext 8
  8497. case 0xC8: // ext 16
  8498. case 0xC9: // ext 32
  8499. case 0xD4: // fixext 1
  8500. case 0xD5: // fixext 2
  8501. case 0xD6: // fixext 4
  8502. case 0xD7: // fixext 8
  8503. case 0xD8: // fixext 16
  8504. {
  8505. binary_t b;
  8506. return get_msgpack_binary(b) && sax->binary(b);
  8507. }
  8508. case 0xCA: // float 32
  8509. {
  8510. float number{};
  8511. return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8512. }
  8513. case 0xCB: // float 64
  8514. {
  8515. double number{};
  8516. return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
  8517. }
  8518. case 0xCC: // uint 8
  8519. {
  8520. std::uint8_t number{};
  8521. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8522. }
  8523. case 0xCD: // uint 16
  8524. {
  8525. std::uint16_t number{};
  8526. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8527. }
  8528. case 0xCE: // uint 32
  8529. {
  8530. std::uint32_t number{};
  8531. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8532. }
  8533. case 0xCF: // uint 64
  8534. {
  8535. std::uint64_t number{};
  8536. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  8537. }
  8538. case 0xD0: // int 8
  8539. {
  8540. std::int8_t number{};
  8541. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8542. }
  8543. case 0xD1: // int 16
  8544. {
  8545. std::int16_t number{};
  8546. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8547. }
  8548. case 0xD2: // int 32
  8549. {
  8550. std::int32_t number{};
  8551. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8552. }
  8553. case 0xD3: // int 64
  8554. {
  8555. std::int64_t number{};
  8556. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  8557. }
  8558. case 0xDC: // array 16
  8559. {
  8560. std::uint16_t len{};
  8561. return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
  8562. }
  8563. case 0xDD: // array 32
  8564. {
  8565. std::uint32_t len{};
  8566. return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
  8567. }
  8568. case 0xDE: // map 16
  8569. {
  8570. std::uint16_t len{};
  8571. return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
  8572. }
  8573. case 0xDF: // map 32
  8574. {
  8575. std::uint32_t len{};
  8576. return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
  8577. }
  8578. // negative fixint
  8579. case 0xE0:
  8580. case 0xE1:
  8581. case 0xE2:
  8582. case 0xE3:
  8583. case 0xE4:
  8584. case 0xE5:
  8585. case 0xE6:
  8586. case 0xE7:
  8587. case 0xE8:
  8588. case 0xE9:
  8589. case 0xEA:
  8590. case 0xEB:
  8591. case 0xEC:
  8592. case 0xED:
  8593. case 0xEE:
  8594. case 0xEF:
  8595. case 0xF0:
  8596. case 0xF1:
  8597. case 0xF2:
  8598. case 0xF3:
  8599. case 0xF4:
  8600. case 0xF5:
  8601. case 0xF6:
  8602. case 0xF7:
  8603. case 0xF8:
  8604. case 0xF9:
  8605. case 0xFA:
  8606. case 0xFB:
  8607. case 0xFC:
  8608. case 0xFD:
  8609. case 0xFE:
  8610. case 0xFF:
  8611. return sax->number_integer(static_cast<std::int8_t>(current));
  8612. default: // anything else
  8613. {
  8614. auto last_token = get_token_string();
  8615. 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()));
  8616. }
  8617. }
  8618. }
  8619. /*!
  8620. @brief reads a MessagePack string
  8621. This function first reads starting bytes to determine the expected
  8622. string length and then copies this number of bytes into a string.
  8623. @param[out] result created string
  8624. @return whether string creation completed
  8625. */
  8626. bool get_msgpack_string(string_t& result)
  8627. {
  8628. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string")))
  8629. {
  8630. return false;
  8631. }
  8632. switch (current)
  8633. {
  8634. // fixstr
  8635. case 0xA0:
  8636. case 0xA1:
  8637. case 0xA2:
  8638. case 0xA3:
  8639. case 0xA4:
  8640. case 0xA5:
  8641. case 0xA6:
  8642. case 0xA7:
  8643. case 0xA8:
  8644. case 0xA9:
  8645. case 0xAA:
  8646. case 0xAB:
  8647. case 0xAC:
  8648. case 0xAD:
  8649. case 0xAE:
  8650. case 0xAF:
  8651. case 0xB0:
  8652. case 0xB1:
  8653. case 0xB2:
  8654. case 0xB3:
  8655. case 0xB4:
  8656. case 0xB5:
  8657. case 0xB6:
  8658. case 0xB7:
  8659. case 0xB8:
  8660. case 0xB9:
  8661. case 0xBA:
  8662. case 0xBB:
  8663. case 0xBC:
  8664. case 0xBD:
  8665. case 0xBE:
  8666. case 0xBF:
  8667. {
  8668. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  8669. }
  8670. case 0xD9: // str 8
  8671. {
  8672. std::uint8_t len{};
  8673. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8674. }
  8675. case 0xDA: // str 16
  8676. {
  8677. std::uint16_t len{};
  8678. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8679. }
  8680. case 0xDB: // str 32
  8681. {
  8682. std::uint32_t len{};
  8683. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  8684. }
  8685. default:
  8686. {
  8687. auto last_token = get_token_string();
  8688. 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()));
  8689. }
  8690. }
  8691. }
  8692. /*!
  8693. @brief reads a MessagePack byte array
  8694. This function first reads starting bytes to determine the expected
  8695. byte array length and then copies this number of bytes into a byte array.
  8696. @param[out] result created byte array
  8697. @return whether byte array creation completed
  8698. */
  8699. bool get_msgpack_binary(binary_t& result)
  8700. {
  8701. // helper function to set the subtype
  8702. auto assign_and_return_true = [&result](std::int8_t subtype)
  8703. {
  8704. result.set_subtype(static_cast<std::uint8_t>(subtype));
  8705. return true;
  8706. };
  8707. switch (current)
  8708. {
  8709. case 0xC4: // bin 8
  8710. {
  8711. std::uint8_t len{};
  8712. return get_number(input_format_t::msgpack, len) &&
  8713. get_binary(input_format_t::msgpack, len, result);
  8714. }
  8715. case 0xC5: // bin 16
  8716. {
  8717. std::uint16_t len{};
  8718. return get_number(input_format_t::msgpack, len) &&
  8719. get_binary(input_format_t::msgpack, len, result);
  8720. }
  8721. case 0xC6: // bin 32
  8722. {
  8723. std::uint32_t len{};
  8724. return get_number(input_format_t::msgpack, len) &&
  8725. get_binary(input_format_t::msgpack, len, result);
  8726. }
  8727. case 0xC7: // ext 8
  8728. {
  8729. std::uint8_t len{};
  8730. std::int8_t subtype{};
  8731. return get_number(input_format_t::msgpack, len) &&
  8732. get_number(input_format_t::msgpack, subtype) &&
  8733. get_binary(input_format_t::msgpack, len, result) &&
  8734. assign_and_return_true(subtype);
  8735. }
  8736. case 0xC8: // ext 16
  8737. {
  8738. std::uint16_t len{};
  8739. std::int8_t subtype{};
  8740. return get_number(input_format_t::msgpack, len) &&
  8741. get_number(input_format_t::msgpack, subtype) &&
  8742. get_binary(input_format_t::msgpack, len, result) &&
  8743. assign_and_return_true(subtype);
  8744. }
  8745. case 0xC9: // ext 32
  8746. {
  8747. std::uint32_t len{};
  8748. std::int8_t subtype{};
  8749. return get_number(input_format_t::msgpack, len) &&
  8750. get_number(input_format_t::msgpack, subtype) &&
  8751. get_binary(input_format_t::msgpack, len, result) &&
  8752. assign_and_return_true(subtype);
  8753. }
  8754. case 0xD4: // fixext 1
  8755. {
  8756. std::int8_t subtype{};
  8757. return get_number(input_format_t::msgpack, subtype) &&
  8758. get_binary(input_format_t::msgpack, 1, result) &&
  8759. assign_and_return_true(subtype);
  8760. }
  8761. case 0xD5: // fixext 2
  8762. {
  8763. std::int8_t subtype{};
  8764. return get_number(input_format_t::msgpack, subtype) &&
  8765. get_binary(input_format_t::msgpack, 2, result) &&
  8766. assign_and_return_true(subtype);
  8767. }
  8768. case 0xD6: // fixext 4
  8769. {
  8770. std::int8_t subtype{};
  8771. return get_number(input_format_t::msgpack, subtype) &&
  8772. get_binary(input_format_t::msgpack, 4, result) &&
  8773. assign_and_return_true(subtype);
  8774. }
  8775. case 0xD7: // fixext 8
  8776. {
  8777. std::int8_t subtype{};
  8778. return get_number(input_format_t::msgpack, subtype) &&
  8779. get_binary(input_format_t::msgpack, 8, result) &&
  8780. assign_and_return_true(subtype);
  8781. }
  8782. case 0xD8: // fixext 16
  8783. {
  8784. std::int8_t subtype{};
  8785. return get_number(input_format_t::msgpack, subtype) &&
  8786. get_binary(input_format_t::msgpack, 16, result) &&
  8787. assign_and_return_true(subtype);
  8788. }
  8789. default: // LCOV_EXCL_LINE
  8790. return false; // LCOV_EXCL_LINE
  8791. }
  8792. }
  8793. /*!
  8794. @param[in] len the length of the array
  8795. @return whether array creation completed
  8796. */
  8797. bool get_msgpack_array(const std::size_t len)
  8798. {
  8799. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
  8800. {
  8801. return false;
  8802. }
  8803. for (std::size_t i = 0; i < len; ++i)
  8804. {
  8805. if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
  8806. {
  8807. return false;
  8808. }
  8809. }
  8810. return sax->end_array();
  8811. }
  8812. /*!
  8813. @param[in] len the length of the object
  8814. @return whether object creation completed
  8815. */
  8816. bool get_msgpack_object(const std::size_t len)
  8817. {
  8818. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
  8819. {
  8820. return false;
  8821. }
  8822. string_t key;
  8823. for (std::size_t i = 0; i < len; ++i)
  8824. {
  8825. get();
  8826. if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key)))
  8827. {
  8828. return false;
  8829. }
  8830. if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
  8831. {
  8832. return false;
  8833. }
  8834. key.clear();
  8835. }
  8836. return sax->end_object();
  8837. }
  8838. ////////////
  8839. // UBJSON //
  8840. ////////////
  8841. /*!
  8842. @param[in] get_char whether a new character should be retrieved from the
  8843. input (true, default) or whether the last read
  8844. character should be considered instead
  8845. @return whether a valid UBJSON value was passed to the SAX parser
  8846. */
  8847. bool parse_ubjson_internal(const bool get_char = true)
  8848. {
  8849. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  8850. }
  8851. /*!
  8852. @brief reads a UBJSON string
  8853. This function is either called after reading the 'S' byte explicitly
  8854. indicating a string, or in case of an object key where the 'S' byte can be
  8855. left out.
  8856. @param[out] result created string
  8857. @param[in] get_char whether a new character should be retrieved from the
  8858. input (true, default) or whether the last read
  8859. character should be considered instead
  8860. @return whether string creation completed
  8861. */
  8862. bool get_ubjson_string(string_t& result, const bool get_char = true)
  8863. {
  8864. if (get_char)
  8865. {
  8866. get(); // TODO(niels): may we ignore N here?
  8867. }
  8868. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
  8869. {
  8870. return false;
  8871. }
  8872. switch (current)
  8873. {
  8874. case 'U':
  8875. {
  8876. std::uint8_t len{};
  8877. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8878. }
  8879. case 'i':
  8880. {
  8881. std::int8_t len{};
  8882. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8883. }
  8884. case 'I':
  8885. {
  8886. std::int16_t len{};
  8887. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8888. }
  8889. case 'l':
  8890. {
  8891. std::int32_t len{};
  8892. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8893. }
  8894. case 'L':
  8895. {
  8896. std::int64_t len{};
  8897. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  8898. }
  8899. default:
  8900. auto last_token = get_token_string();
  8901. 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()));
  8902. }
  8903. }
  8904. /*!
  8905. @param[out] result determined size
  8906. @return whether size determination completed
  8907. */
  8908. bool get_ubjson_size_value(std::size_t& result)
  8909. {
  8910. switch (get_ignore_noop())
  8911. {
  8912. case 'U':
  8913. {
  8914. std::uint8_t number{};
  8915. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8916. {
  8917. return false;
  8918. }
  8919. result = static_cast<std::size_t>(number);
  8920. return true;
  8921. }
  8922. case 'i':
  8923. {
  8924. std::int8_t number{};
  8925. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8926. {
  8927. return false;
  8928. }
  8929. result = static_cast<std::size_t>(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char
  8930. return true;
  8931. }
  8932. case 'I':
  8933. {
  8934. std::int16_t number{};
  8935. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8936. {
  8937. return false;
  8938. }
  8939. result = static_cast<std::size_t>(number);
  8940. return true;
  8941. }
  8942. case 'l':
  8943. {
  8944. std::int32_t number{};
  8945. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8946. {
  8947. return false;
  8948. }
  8949. result = static_cast<std::size_t>(number);
  8950. return true;
  8951. }
  8952. case 'L':
  8953. {
  8954. std::int64_t number{};
  8955. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  8956. {
  8957. return false;
  8958. }
  8959. result = static_cast<std::size_t>(number);
  8960. return true;
  8961. }
  8962. default:
  8963. {
  8964. auto last_token = get_token_string();
  8965. 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()));
  8966. }
  8967. }
  8968. }
  8969. /*!
  8970. @brief determine the type and size for a container
  8971. In the optimized UBJSON format, a type and a size can be provided to allow
  8972. for a more compact representation.
  8973. @param[out] result pair of the size and the type
  8974. @return whether pair creation completed
  8975. */
  8976. bool get_ubjson_size_type(std::pair<std::size_t, char_int_type>& result)
  8977. {
  8978. result.first = string_t::npos; // size
  8979. result.second = 0; // type
  8980. get_ignore_noop();
  8981. if (current == '$')
  8982. {
  8983. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  8984. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type")))
  8985. {
  8986. return false;
  8987. }
  8988. get_ignore_noop();
  8989. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  8990. {
  8991. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
  8992. {
  8993. return false;
  8994. }
  8995. auto last_token = get_token_string();
  8996. 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()));
  8997. }
  8998. return get_ubjson_size_value(result.first);
  8999. }
  9000. if (current == '#')
  9001. {
  9002. return get_ubjson_size_value(result.first);
  9003. }
  9004. return true;
  9005. }
  9006. /*!
  9007. @param prefix the previously read or set type prefix
  9008. @return whether value creation completed
  9009. */
  9010. bool get_ubjson_value(const char_int_type prefix)
  9011. {
  9012. switch (prefix)
  9013. {
  9014. case std::char_traits<char_type>::eof(): // EOF
  9015. return unexpect_eof(input_format_t::ubjson, "value");
  9016. case 'T': // true
  9017. return sax->boolean(true);
  9018. case 'F': // false
  9019. return sax->boolean(false);
  9020. case 'Z': // null
  9021. return sax->null();
  9022. case 'U':
  9023. {
  9024. std::uint8_t number{};
  9025. return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number);
  9026. }
  9027. case 'i':
  9028. {
  9029. std::int8_t number{};
  9030. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  9031. }
  9032. case 'I':
  9033. {
  9034. std::int16_t number{};
  9035. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  9036. }
  9037. case 'l':
  9038. {
  9039. std::int32_t number{};
  9040. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  9041. }
  9042. case 'L':
  9043. {
  9044. std::int64_t number{};
  9045. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  9046. }
  9047. case 'd':
  9048. {
  9049. float number{};
  9050. return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  9051. }
  9052. case 'D':
  9053. {
  9054. double number{};
  9055. return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  9056. }
  9057. case 'H':
  9058. {
  9059. return get_ubjson_high_precision_number();
  9060. }
  9061. case 'C': // char
  9062. {
  9063. get();
  9064. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char")))
  9065. {
  9066. return false;
  9067. }
  9068. if (JSON_HEDLEY_UNLIKELY(current > 127))
  9069. {
  9070. auto last_token = get_token_string();
  9071. 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()));
  9072. }
  9073. string_t s(1, static_cast<typename string_t::value_type>(current));
  9074. return sax->string(s);
  9075. }
  9076. case 'S': // string
  9077. {
  9078. string_t s;
  9079. return get_ubjson_string(s) && sax->string(s);
  9080. }
  9081. case '[': // array
  9082. return get_ubjson_array();
  9083. case '{': // object
  9084. return get_ubjson_object();
  9085. default: // anything else
  9086. {
  9087. auto last_token = get_token_string();
  9088. 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()));
  9089. }
  9090. }
  9091. }
  9092. /*!
  9093. @return whether array creation completed
  9094. */
  9095. bool get_ubjson_array()
  9096. {
  9097. std::pair<std::size_t, char_int_type> size_and_type;
  9098. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
  9099. {
  9100. return false;
  9101. }
  9102. if (size_and_type.first != string_t::npos)
  9103. {
  9104. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first)))
  9105. {
  9106. return false;
  9107. }
  9108. if (size_and_type.second != 0)
  9109. {
  9110. if (size_and_type.second != 'N')
  9111. {
  9112. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9113. {
  9114. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
  9115. {
  9116. return false;
  9117. }
  9118. }
  9119. }
  9120. }
  9121. else
  9122. {
  9123. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9124. {
  9125. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  9126. {
  9127. return false;
  9128. }
  9129. }
  9130. }
  9131. }
  9132. else
  9133. {
  9134. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  9135. {
  9136. return false;
  9137. }
  9138. while (current != ']')
  9139. {
  9140. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false)))
  9141. {
  9142. return false;
  9143. }
  9144. get_ignore_noop();
  9145. }
  9146. }
  9147. return sax->end_array();
  9148. }
  9149. /*!
  9150. @return whether object creation completed
  9151. */
  9152. bool get_ubjson_object()
  9153. {
  9154. std::pair<std::size_t, char_int_type> size_and_type;
  9155. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
  9156. {
  9157. return false;
  9158. }
  9159. string_t key;
  9160. if (size_and_type.first != string_t::npos)
  9161. {
  9162. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first)))
  9163. {
  9164. return false;
  9165. }
  9166. if (size_and_type.second != 0)
  9167. {
  9168. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9169. {
  9170. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
  9171. {
  9172. return false;
  9173. }
  9174. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
  9175. {
  9176. return false;
  9177. }
  9178. key.clear();
  9179. }
  9180. }
  9181. else
  9182. {
  9183. for (std::size_t i = 0; i < size_and_type.first; ++i)
  9184. {
  9185. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
  9186. {
  9187. return false;
  9188. }
  9189. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  9190. {
  9191. return false;
  9192. }
  9193. key.clear();
  9194. }
  9195. }
  9196. }
  9197. else
  9198. {
  9199. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  9200. {
  9201. return false;
  9202. }
  9203. while (current != '}')
  9204. {
  9205. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key)))
  9206. {
  9207. return false;
  9208. }
  9209. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  9210. {
  9211. return false;
  9212. }
  9213. get_ignore_noop();
  9214. key.clear();
  9215. }
  9216. }
  9217. return sax->end_object();
  9218. }
  9219. // Note, no reader for UBJSON binary types is implemented because they do
  9220. // not exist
  9221. bool get_ubjson_high_precision_number()
  9222. {
  9223. // get size of following number string
  9224. std::size_t size{};
  9225. auto res = get_ubjson_size_value(size);
  9226. if (JSON_HEDLEY_UNLIKELY(!res))
  9227. {
  9228. return res;
  9229. }
  9230. // get number string
  9231. std::vector<char> number_vector;
  9232. for (std::size_t i = 0; i < size; ++i)
  9233. {
  9234. get();
  9235. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number")))
  9236. {
  9237. return false;
  9238. }
  9239. number_vector.push_back(static_cast<char>(current));
  9240. }
  9241. // parse number string
  9242. using ia_type = decltype(detail::input_adapter(number_vector));
  9243. auto number_lexer = detail::lexer<BasicJsonType, ia_type>(detail::input_adapter(number_vector), false);
  9244. const auto result_number = number_lexer.scan();
  9245. const auto number_string = number_lexer.get_token_string();
  9246. const auto result_remainder = number_lexer.scan();
  9247. using token_type = typename detail::lexer_base<BasicJsonType>::token_type;
  9248. if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input))
  9249. {
  9250. 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()));
  9251. }
  9252. switch (result_number)
  9253. {
  9254. case token_type::value_integer:
  9255. return sax->number_integer(number_lexer.get_number_integer());
  9256. case token_type::value_unsigned:
  9257. return sax->number_unsigned(number_lexer.get_number_unsigned());
  9258. case token_type::value_float:
  9259. return sax->number_float(number_lexer.get_number_float(), std::move(number_string));
  9260. case token_type::uninitialized:
  9261. case token_type::literal_true:
  9262. case token_type::literal_false:
  9263. case token_type::literal_null:
  9264. case token_type::value_string:
  9265. case token_type::begin_array:
  9266. case token_type::begin_object:
  9267. case token_type::end_array:
  9268. case token_type::end_object:
  9269. case token_type::name_separator:
  9270. case token_type::value_separator:
  9271. case token_type::parse_error:
  9272. case token_type::end_of_input:
  9273. case token_type::literal_or_value:
  9274. default:
  9275. 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()));
  9276. }
  9277. }
  9278. ///////////////////////
  9279. // Utility functions //
  9280. ///////////////////////
  9281. /*!
  9282. @brief get next character from the input
  9283. This function provides the interface to the used input adapter. It does
  9284. not throw in case the input reached EOF, but returns a -'ve valued
  9285. `std::char_traits<char_type>::eof()` in that case.
  9286. @return character read from the input
  9287. */
  9288. char_int_type get()
  9289. {
  9290. ++chars_read;
  9291. return current = ia.get_character();
  9292. }
  9293. /*!
  9294. @return character read from the input after ignoring all 'N' entries
  9295. */
  9296. char_int_type get_ignore_noop()
  9297. {
  9298. do
  9299. {
  9300. get();
  9301. }
  9302. while (current == 'N');
  9303. return current;
  9304. }
  9305. /*
  9306. @brief read a number from the input
  9307. @tparam NumberType the type of the number
  9308. @param[in] format the current format (for diagnostics)
  9309. @param[out] result number of type @a NumberType
  9310. @return whether conversion completed
  9311. @note This function needs to respect the system's endianess, because
  9312. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  9313. (big endian) and therefore need reordering on little endian systems.
  9314. */
  9315. template<typename NumberType, bool InputIsLittleEndian = false>
  9316. bool get_number(const input_format_t format, NumberType& result)
  9317. {
  9318. // step 1: read input into array with system's byte order
  9319. std::array<std::uint8_t, sizeof(NumberType)> vec{};
  9320. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  9321. {
  9322. get();
  9323. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number")))
  9324. {
  9325. return false;
  9326. }
  9327. // reverse byte order prior to conversion if necessary
  9328. if (is_little_endian != InputIsLittleEndian)
  9329. {
  9330. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  9331. }
  9332. else
  9333. {
  9334. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  9335. }
  9336. }
  9337. // step 2: convert array into number of type T and return
  9338. std::memcpy(&result, vec.data(), sizeof(NumberType));
  9339. return true;
  9340. }
  9341. /*!
  9342. @brief create a string by reading characters from the input
  9343. @tparam NumberType the type of the number
  9344. @param[in] format the current format (for diagnostics)
  9345. @param[in] len number of characters to read
  9346. @param[out] result string created by reading @a len bytes
  9347. @return whether string creation completed
  9348. @note We can not reserve @a len bytes for the result, because @a len
  9349. may be too large. Usually, @ref unexpect_eof() detects the end of
  9350. the input before we run out of string memory.
  9351. */
  9352. template<typename NumberType>
  9353. bool get_string(const input_format_t format,
  9354. const NumberType len,
  9355. string_t& result)
  9356. {
  9357. bool success = true;
  9358. for (NumberType i = 0; i < len; i++)
  9359. {
  9360. get();
  9361. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string")))
  9362. {
  9363. success = false;
  9364. break;
  9365. }
  9366. result.push_back(static_cast<typename string_t::value_type>(current));
  9367. }
  9368. return success;
  9369. }
  9370. /*!
  9371. @brief create a byte array by reading bytes from the input
  9372. @tparam NumberType the type of the number
  9373. @param[in] format the current format (for diagnostics)
  9374. @param[in] len number of bytes to read
  9375. @param[out] result byte array created by reading @a len bytes
  9376. @return whether byte array creation completed
  9377. @note We can not reserve @a len bytes for the result, because @a len
  9378. may be too large. Usually, @ref unexpect_eof() detects the end of
  9379. the input before we run out of memory.
  9380. */
  9381. template<typename NumberType>
  9382. bool get_binary(const input_format_t format,
  9383. const NumberType len,
  9384. binary_t& result)
  9385. {
  9386. bool success = true;
  9387. for (NumberType i = 0; i < len; i++)
  9388. {
  9389. get();
  9390. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary")))
  9391. {
  9392. success = false;
  9393. break;
  9394. }
  9395. result.push_back(static_cast<std::uint8_t>(current));
  9396. }
  9397. return success;
  9398. }
  9399. /*!
  9400. @param[in] format the current format (for diagnostics)
  9401. @param[in] context further context information (for diagnostics)
  9402. @return whether the last read character is not EOF
  9403. */
  9404. JSON_HEDLEY_NON_NULL(3)
  9405. bool unexpect_eof(const input_format_t format, const char* context) const
  9406. {
  9407. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char_type>::eof()))
  9408. {
  9409. return sax->parse_error(chars_read, "<end of file>",
  9410. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), BasicJsonType()));
  9411. }
  9412. return true;
  9413. }
  9414. /*!
  9415. @return a string representation of the last read byte
  9416. */
  9417. std::string get_token_string() const
  9418. {
  9419. std::array<char, 3> cr{{}};
  9420. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  9421. return std::string{cr.data()};
  9422. }
  9423. /*!
  9424. @param[in] format the current format
  9425. @param[in] detail a detailed error message
  9426. @param[in] context further context information
  9427. @return a message string to use in the parse_error exceptions
  9428. */
  9429. std::string exception_message(const input_format_t format,
  9430. const std::string& detail,
  9431. const std::string& context) const
  9432. {
  9433. std::string error_msg = "syntax error while parsing ";
  9434. switch (format)
  9435. {
  9436. case input_format_t::cbor:
  9437. error_msg += "CBOR";
  9438. break;
  9439. case input_format_t::msgpack:
  9440. error_msg += "MessagePack";
  9441. break;
  9442. case input_format_t::ubjson:
  9443. error_msg += "UBJSON";
  9444. break;
  9445. case input_format_t::bson:
  9446. error_msg += "BSON";
  9447. break;
  9448. case input_format_t::json: // LCOV_EXCL_LINE
  9449. default: // LCOV_EXCL_LINE
  9450. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  9451. }
  9452. return error_msg + " " + context + ": " + detail;
  9453. }
  9454. private:
  9455. /// input adapter
  9456. InputAdapterType ia;
  9457. /// the current character
  9458. char_int_type current = std::char_traits<char_type>::eof();
  9459. /// the number of characters read
  9460. std::size_t chars_read = 0;
  9461. /// whether we can assume little endianess
  9462. const bool is_little_endian = little_endianess();
  9463. /// the SAX parser
  9464. json_sax_t* sax = nullptr;
  9465. };
  9466. } // namespace detail
  9467. } // namespace nlohmann
  9468. // #include <nlohmann/detail/input/input_adapters.hpp>
  9469. // #include <nlohmann/detail/input/lexer.hpp>
  9470. // #include <nlohmann/detail/input/parser.hpp>
  9471. #include <cmath> // isfinite
  9472. #include <cstdint> // uint8_t
  9473. #include <functional> // function
  9474. #include <string> // string
  9475. #include <utility> // move
  9476. #include <vector> // vector
  9477. // #include <nlohmann/detail/exceptions.hpp>
  9478. // #include <nlohmann/detail/input/input_adapters.hpp>
  9479. // #include <nlohmann/detail/input/json_sax.hpp>
  9480. // #include <nlohmann/detail/input/lexer.hpp>
  9481. // #include <nlohmann/detail/macro_scope.hpp>
  9482. // #include <nlohmann/detail/meta/is_sax.hpp>
  9483. // #include <nlohmann/detail/value_t.hpp>
  9484. namespace nlohmann
  9485. {
  9486. namespace detail
  9487. {
  9488. ////////////
  9489. // parser //
  9490. ////////////
  9491. enum class parse_event_t : std::uint8_t
  9492. {
  9493. /// the parser read `{` and started to process a JSON object
  9494. object_start,
  9495. /// the parser read `}` and finished processing a JSON object
  9496. object_end,
  9497. /// the parser read `[` and started to process a JSON array
  9498. array_start,
  9499. /// the parser read `]` and finished processing a JSON array
  9500. array_end,
  9501. /// the parser read a key of a value in an object
  9502. key,
  9503. /// the parser finished reading a JSON value
  9504. value
  9505. };
  9506. template<typename BasicJsonType>
  9507. using parser_callback_t =
  9508. std::function<bool(int /*depth*/, parse_event_t /*event*/, BasicJsonType& /*parsed*/)>;
  9509. /*!
  9510. @brief syntax analysis
  9511. This class implements a recursive descent parser.
  9512. */
  9513. template<typename BasicJsonType, typename InputAdapterType>
  9514. class parser
  9515. {
  9516. using number_integer_t = typename BasicJsonType::number_integer_t;
  9517. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  9518. using number_float_t = typename BasicJsonType::number_float_t;
  9519. using string_t = typename BasicJsonType::string_t;
  9520. using lexer_t = lexer<BasicJsonType, InputAdapterType>;
  9521. using token_type = typename lexer_t::token_type;
  9522. public:
  9523. /// a parser reading from an input adapter
  9524. explicit parser(InputAdapterType&& adapter,
  9525. const parser_callback_t<BasicJsonType> cb = nullptr,
  9526. const bool allow_exceptions_ = true,
  9527. const bool skip_comments = false)
  9528. : callback(cb)
  9529. , m_lexer(std::move(adapter), skip_comments)
  9530. , allow_exceptions(allow_exceptions_)
  9531. {
  9532. // read first token
  9533. get_token();
  9534. }
  9535. /*!
  9536. @brief public parser interface
  9537. @param[in] strict whether to expect the last token to be EOF
  9538. @param[in,out] result parsed JSON value
  9539. @throw parse_error.101 in case of an unexpected token
  9540. @throw parse_error.102 if to_unicode fails or surrogate error
  9541. @throw parse_error.103 if to_unicode fails
  9542. */
  9543. void parse(const bool strict, BasicJsonType& result)
  9544. {
  9545. if (callback)
  9546. {
  9547. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  9548. sax_parse_internal(&sdp);
  9549. // in strict mode, input must be completely read
  9550. if (strict && (get_token() != token_type::end_of_input))
  9551. {
  9552. sdp.parse_error(m_lexer.get_position(),
  9553. m_lexer.get_token_string(),
  9554. parse_error::create(101, m_lexer.get_position(),
  9555. exception_message(token_type::end_of_input, "value"), BasicJsonType()));
  9556. }
  9557. // in case of an error, return discarded value
  9558. if (sdp.is_errored())
  9559. {
  9560. result = value_t::discarded;
  9561. return;
  9562. }
  9563. // set top-level value to null if it was discarded by the callback
  9564. // function
  9565. if (result.is_discarded())
  9566. {
  9567. result = nullptr;
  9568. }
  9569. }
  9570. else
  9571. {
  9572. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  9573. sax_parse_internal(&sdp);
  9574. // in strict mode, input must be completely read
  9575. if (strict && (get_token() != token_type::end_of_input))
  9576. {
  9577. sdp.parse_error(m_lexer.get_position(),
  9578. m_lexer.get_token_string(),
  9579. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType()));
  9580. }
  9581. // in case of an error, return discarded value
  9582. if (sdp.is_errored())
  9583. {
  9584. result = value_t::discarded;
  9585. return;
  9586. }
  9587. }
  9588. result.assert_invariant();
  9589. }
  9590. /*!
  9591. @brief public accept interface
  9592. @param[in] strict whether to expect the last token to be EOF
  9593. @return whether the input is a proper JSON text
  9594. */
  9595. bool accept(const bool strict = true)
  9596. {
  9597. json_sax_acceptor<BasicJsonType> sax_acceptor;
  9598. return sax_parse(&sax_acceptor, strict);
  9599. }
  9600. template<typename SAX>
  9601. JSON_HEDLEY_NON_NULL(2)
  9602. bool sax_parse(SAX* sax, const bool strict = true)
  9603. {
  9604. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  9605. const bool result = sax_parse_internal(sax);
  9606. // strict mode: next byte must be EOF
  9607. if (result && strict && (get_token() != token_type::end_of_input))
  9608. {
  9609. return sax->parse_error(m_lexer.get_position(),
  9610. m_lexer.get_token_string(),
  9611. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType()));
  9612. }
  9613. return result;
  9614. }
  9615. private:
  9616. template<typename SAX>
  9617. JSON_HEDLEY_NON_NULL(2)
  9618. bool sax_parse_internal(SAX* sax)
  9619. {
  9620. // stack to remember the hierarchy of structured values we are parsing
  9621. // true = array; false = object
  9622. std::vector<bool> states;
  9623. // value to avoid a goto (see comment where set to true)
  9624. bool skip_to_state_evaluation = false;
  9625. while (true)
  9626. {
  9627. if (!skip_to_state_evaluation)
  9628. {
  9629. // invariant: get_token() was called before each iteration
  9630. switch (last_token)
  9631. {
  9632. case token_type::begin_object:
  9633. {
  9634. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  9635. {
  9636. return false;
  9637. }
  9638. // closing } -> we are done
  9639. if (get_token() == token_type::end_object)
  9640. {
  9641. if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
  9642. {
  9643. return false;
  9644. }
  9645. break;
  9646. }
  9647. // parse key
  9648. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  9649. {
  9650. return sax->parse_error(m_lexer.get_position(),
  9651. m_lexer.get_token_string(),
  9652. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType()));
  9653. }
  9654. if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
  9655. {
  9656. return false;
  9657. }
  9658. // parse separator (:)
  9659. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  9660. {
  9661. return sax->parse_error(m_lexer.get_position(),
  9662. m_lexer.get_token_string(),
  9663. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType()));
  9664. }
  9665. // remember we are now inside an object
  9666. states.push_back(false);
  9667. // parse values
  9668. get_token();
  9669. continue;
  9670. }
  9671. case token_type::begin_array:
  9672. {
  9673. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  9674. {
  9675. return false;
  9676. }
  9677. // closing ] -> we are done
  9678. if (get_token() == token_type::end_array)
  9679. {
  9680. if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
  9681. {
  9682. return false;
  9683. }
  9684. break;
  9685. }
  9686. // remember we are now inside an array
  9687. states.push_back(true);
  9688. // parse values (no need to call get_token)
  9689. continue;
  9690. }
  9691. case token_type::value_float:
  9692. {
  9693. const auto res = m_lexer.get_number_float();
  9694. if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res)))
  9695. {
  9696. return sax->parse_error(m_lexer.get_position(),
  9697. m_lexer.get_token_string(),
  9698. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'", BasicJsonType()));
  9699. }
  9700. if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string())))
  9701. {
  9702. return false;
  9703. }
  9704. break;
  9705. }
  9706. case token_type::literal_false:
  9707. {
  9708. if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false)))
  9709. {
  9710. return false;
  9711. }
  9712. break;
  9713. }
  9714. case token_type::literal_null:
  9715. {
  9716. if (JSON_HEDLEY_UNLIKELY(!sax->null()))
  9717. {
  9718. return false;
  9719. }
  9720. break;
  9721. }
  9722. case token_type::literal_true:
  9723. {
  9724. if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true)))
  9725. {
  9726. return false;
  9727. }
  9728. break;
  9729. }
  9730. case token_type::value_integer:
  9731. {
  9732. if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer())))
  9733. {
  9734. return false;
  9735. }
  9736. break;
  9737. }
  9738. case token_type::value_string:
  9739. {
  9740. if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string())))
  9741. {
  9742. return false;
  9743. }
  9744. break;
  9745. }
  9746. case token_type::value_unsigned:
  9747. {
  9748. if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned())))
  9749. {
  9750. return false;
  9751. }
  9752. break;
  9753. }
  9754. case token_type::parse_error:
  9755. {
  9756. // using "uninitialized" to avoid "expected" message
  9757. return sax->parse_error(m_lexer.get_position(),
  9758. m_lexer.get_token_string(),
  9759. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), BasicJsonType()));
  9760. }
  9761. case token_type::uninitialized:
  9762. case token_type::end_array:
  9763. case token_type::end_object:
  9764. case token_type::name_separator:
  9765. case token_type::value_separator:
  9766. case token_type::end_of_input:
  9767. case token_type::literal_or_value:
  9768. default: // the last token was unexpected
  9769. {
  9770. return sax->parse_error(m_lexer.get_position(),
  9771. m_lexer.get_token_string(),
  9772. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), BasicJsonType()));
  9773. }
  9774. }
  9775. }
  9776. else
  9777. {
  9778. skip_to_state_evaluation = false;
  9779. }
  9780. // we reached this line after we successfully parsed a value
  9781. if (states.empty())
  9782. {
  9783. // empty stack: we reached the end of the hierarchy: done
  9784. return true;
  9785. }
  9786. if (states.back()) // array
  9787. {
  9788. // comma -> next value
  9789. if (get_token() == token_type::value_separator)
  9790. {
  9791. // parse a new value
  9792. get_token();
  9793. continue;
  9794. }
  9795. // closing ]
  9796. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  9797. {
  9798. if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
  9799. {
  9800. return false;
  9801. }
  9802. // We are done with this array. Before we can parse a
  9803. // new value, we need to evaluate the new state first.
  9804. // By setting skip_to_state_evaluation to false, we
  9805. // are effectively jumping to the beginning of this if.
  9806. JSON_ASSERT(!states.empty());
  9807. states.pop_back();
  9808. skip_to_state_evaluation = true;
  9809. continue;
  9810. }
  9811. return sax->parse_error(m_lexer.get_position(),
  9812. m_lexer.get_token_string(),
  9813. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), BasicJsonType()));
  9814. }
  9815. // states.back() is false -> object
  9816. // comma -> next value
  9817. if (get_token() == token_type::value_separator)
  9818. {
  9819. // parse key
  9820. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  9821. {
  9822. return sax->parse_error(m_lexer.get_position(),
  9823. m_lexer.get_token_string(),
  9824. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType()));
  9825. }
  9826. if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
  9827. {
  9828. return false;
  9829. }
  9830. // parse separator (:)
  9831. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  9832. {
  9833. return sax->parse_error(m_lexer.get_position(),
  9834. m_lexer.get_token_string(),
  9835. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType()));
  9836. }
  9837. // parse values
  9838. get_token();
  9839. continue;
  9840. }
  9841. // closing }
  9842. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  9843. {
  9844. if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
  9845. {
  9846. return false;
  9847. }
  9848. // We are done with this object. Before we can parse a
  9849. // new value, we need to evaluate the new state first.
  9850. // By setting skip_to_state_evaluation to false, we
  9851. // are effectively jumping to the beginning of this if.
  9852. JSON_ASSERT(!states.empty());
  9853. states.pop_back();
  9854. skip_to_state_evaluation = true;
  9855. continue;
  9856. }
  9857. return sax->parse_error(m_lexer.get_position(),
  9858. m_lexer.get_token_string(),
  9859. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), BasicJsonType()));
  9860. }
  9861. }
  9862. /// get next token from lexer
  9863. token_type get_token()
  9864. {
  9865. return last_token = m_lexer.scan();
  9866. }
  9867. std::string exception_message(const token_type expected, const std::string& context)
  9868. {
  9869. std::string error_msg = "syntax error ";
  9870. if (!context.empty())
  9871. {
  9872. error_msg += "while parsing " + context + " ";
  9873. }
  9874. error_msg += "- ";
  9875. if (last_token == token_type::parse_error)
  9876. {
  9877. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  9878. m_lexer.get_token_string() + "'";
  9879. }
  9880. else
  9881. {
  9882. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  9883. }
  9884. if (expected != token_type::uninitialized)
  9885. {
  9886. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  9887. }
  9888. return error_msg;
  9889. }
  9890. private:
  9891. /// callback function
  9892. const parser_callback_t<BasicJsonType> callback = nullptr;
  9893. /// the type of the last read token
  9894. token_type last_token = token_type::uninitialized;
  9895. /// the lexer
  9896. lexer_t m_lexer;
  9897. /// whether to throw exceptions in case of errors
  9898. const bool allow_exceptions = true;
  9899. };
  9900. } // namespace detail
  9901. } // namespace nlohmann
  9902. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  9903. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  9904. #include <cstddef> // ptrdiff_t
  9905. #include <limits> // numeric_limits
  9906. // #include <nlohmann/detail/macro_scope.hpp>
  9907. namespace nlohmann
  9908. {
  9909. namespace detail
  9910. {
  9911. /*
  9912. @brief an iterator for primitive JSON types
  9913. This class models an iterator for primitive JSON types (boolean, number,
  9914. string). It's only purpose is to allow the iterator/const_iterator classes
  9915. to "iterate" over primitive values. Internally, the iterator is modeled by
  9916. a `difference_type` variable. Value begin_value (`0`) models the begin,
  9917. end_value (`1`) models past the end.
  9918. */
  9919. class primitive_iterator_t
  9920. {
  9921. private:
  9922. using difference_type = std::ptrdiff_t;
  9923. static constexpr difference_type begin_value = 0;
  9924. static constexpr difference_type end_value = begin_value + 1;
  9925. JSON_PRIVATE_UNLESS_TESTED:
  9926. /// iterator as signed integer type
  9927. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  9928. public:
  9929. constexpr difference_type get_value() const noexcept
  9930. {
  9931. return m_it;
  9932. }
  9933. /// set iterator to a defined beginning
  9934. void set_begin() noexcept
  9935. {
  9936. m_it = begin_value;
  9937. }
  9938. /// set iterator to a defined past the end
  9939. void set_end() noexcept
  9940. {
  9941. m_it = end_value;
  9942. }
  9943. /// return whether the iterator can be dereferenced
  9944. constexpr bool is_begin() const noexcept
  9945. {
  9946. return m_it == begin_value;
  9947. }
  9948. /// return whether the iterator is at end
  9949. constexpr bool is_end() const noexcept
  9950. {
  9951. return m_it == end_value;
  9952. }
  9953. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  9954. {
  9955. return lhs.m_it == rhs.m_it;
  9956. }
  9957. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  9958. {
  9959. return lhs.m_it < rhs.m_it;
  9960. }
  9961. primitive_iterator_t operator+(difference_type n) noexcept
  9962. {
  9963. auto result = *this;
  9964. result += n;
  9965. return result;
  9966. }
  9967. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  9968. {
  9969. return lhs.m_it - rhs.m_it;
  9970. }
  9971. primitive_iterator_t& operator++() noexcept
  9972. {
  9973. ++m_it;
  9974. return *this;
  9975. }
  9976. primitive_iterator_t const operator++(int) noexcept // NOLINT(readability-const-return-type)
  9977. {
  9978. auto result = *this;
  9979. ++m_it;
  9980. return result;
  9981. }
  9982. primitive_iterator_t& operator--() noexcept
  9983. {
  9984. --m_it;
  9985. return *this;
  9986. }
  9987. primitive_iterator_t const operator--(int) noexcept // NOLINT(readability-const-return-type)
  9988. {
  9989. auto result = *this;
  9990. --m_it;
  9991. return result;
  9992. }
  9993. primitive_iterator_t& operator+=(difference_type n) noexcept
  9994. {
  9995. m_it += n;
  9996. return *this;
  9997. }
  9998. primitive_iterator_t& operator-=(difference_type n) noexcept
  9999. {
  10000. m_it -= n;
  10001. return *this;
  10002. }
  10003. };
  10004. } // namespace detail
  10005. } // namespace nlohmann
  10006. namespace nlohmann
  10007. {
  10008. namespace detail
  10009. {
  10010. /*!
  10011. @brief an iterator value
  10012. @note This structure could easily be a union, but MSVC currently does not allow
  10013. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  10014. */
  10015. template<typename BasicJsonType> struct internal_iterator
  10016. {
  10017. /// iterator for JSON objects
  10018. typename BasicJsonType::object_t::iterator object_iterator {};
  10019. /// iterator for JSON arrays
  10020. typename BasicJsonType::array_t::iterator array_iterator {};
  10021. /// generic iterator for all other types
  10022. primitive_iterator_t primitive_iterator {};
  10023. };
  10024. } // namespace detail
  10025. } // namespace nlohmann
  10026. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  10027. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  10028. #include <type_traits> // conditional, is_const, remove_const
  10029. // #include <nlohmann/detail/exceptions.hpp>
  10030. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  10031. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  10032. // #include <nlohmann/detail/macro_scope.hpp>
  10033. // #include <nlohmann/detail/meta/cpp_future.hpp>
  10034. // #include <nlohmann/detail/meta/type_traits.hpp>
  10035. // #include <nlohmann/detail/value_t.hpp>
  10036. namespace nlohmann
  10037. {
  10038. namespace detail
  10039. {
  10040. // forward declare, to be able to friend it later on
  10041. template<typename IteratorType> class iteration_proxy;
  10042. template<typename IteratorType> class iteration_proxy_value;
  10043. /*!
  10044. @brief a template for a bidirectional iterator for the @ref basic_json class
  10045. This class implements a both iterators (iterator and const_iterator) for the
  10046. @ref basic_json class.
  10047. @note An iterator is called *initialized* when a pointer to a JSON value has
  10048. been set (e.g., by a constructor or a copy assignment). If the iterator is
  10049. default-constructed, it is *uninitialized* and most methods are undefined.
  10050. **The library uses assertions to detect calls on uninitialized iterators.**
  10051. @requirement The class satisfies the following concept requirements:
  10052. -
  10053. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  10054. The iterator that can be moved can be moved in both directions (i.e.
  10055. incremented and decremented).
  10056. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  10057. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  10058. */
  10059. template<typename BasicJsonType>
  10060. class iter_impl
  10061. {
  10062. /// the iterator with BasicJsonType of different const-ness
  10063. using other_iter_impl = iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  10064. /// allow basic_json to access private members
  10065. friend other_iter_impl;
  10066. friend BasicJsonType;
  10067. friend iteration_proxy<iter_impl>;
  10068. friend iteration_proxy_value<iter_impl>;
  10069. using object_t = typename BasicJsonType::object_t;
  10070. using array_t = typename BasicJsonType::array_t;
  10071. // make sure BasicJsonType is basic_json or const basic_json
  10072. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  10073. "iter_impl only accepts (const) basic_json");
  10074. public:
  10075. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  10076. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  10077. /// A user-defined iterator should provide publicly accessible typedefs named
  10078. /// iterator_category, value_type, difference_type, pointer, and reference.
  10079. /// Note that value_type is required to be non-const, even for constant iterators.
  10080. using iterator_category = std::bidirectional_iterator_tag;
  10081. /// the type of the values when the iterator is dereferenced
  10082. using value_type = typename BasicJsonType::value_type;
  10083. /// a type to represent differences between iterators
  10084. using difference_type = typename BasicJsonType::difference_type;
  10085. /// defines a pointer to the type iterated over (value_type)
  10086. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  10087. typename BasicJsonType::const_pointer,
  10088. typename BasicJsonType::pointer>::type;
  10089. /// defines a reference to the type iterated over (value_type)
  10090. using reference =
  10091. typename std::conditional<std::is_const<BasicJsonType>::value,
  10092. typename BasicJsonType::const_reference,
  10093. typename BasicJsonType::reference>::type;
  10094. iter_impl() = default;
  10095. ~iter_impl() = default;
  10096. iter_impl(iter_impl&&) noexcept = default;
  10097. iter_impl& operator=(iter_impl&&) noexcept = default;
  10098. /*!
  10099. @brief constructor for a given JSON instance
  10100. @param[in] object pointer to a JSON object for this iterator
  10101. @pre object != nullptr
  10102. @post The iterator is initialized; i.e. `m_object != nullptr`.
  10103. */
  10104. explicit iter_impl(pointer object) noexcept : m_object(object)
  10105. {
  10106. JSON_ASSERT(m_object != nullptr);
  10107. switch (m_object->m_type)
  10108. {
  10109. case value_t::object:
  10110. {
  10111. m_it.object_iterator = typename object_t::iterator();
  10112. break;
  10113. }
  10114. case value_t::array:
  10115. {
  10116. m_it.array_iterator = typename array_t::iterator();
  10117. break;
  10118. }
  10119. case value_t::null:
  10120. case value_t::string:
  10121. case value_t::boolean:
  10122. case value_t::number_integer:
  10123. case value_t::number_unsigned:
  10124. case value_t::number_float:
  10125. case value_t::binary:
  10126. case value_t::discarded:
  10127. default:
  10128. {
  10129. m_it.primitive_iterator = primitive_iterator_t();
  10130. break;
  10131. }
  10132. }
  10133. }
  10134. /*!
  10135. @note The conventional copy constructor and copy assignment are implicitly
  10136. defined. Combined with the following converting constructor and
  10137. assignment, they support: (1) copy from iterator to iterator, (2)
  10138. copy from const iterator to const iterator, and (3) conversion from
  10139. iterator to const iterator. However conversion from const iterator
  10140. to iterator is not defined.
  10141. */
  10142. /*!
  10143. @brief const copy constructor
  10144. @param[in] other const iterator to copy from
  10145. @note This copy constructor had to be defined explicitly to circumvent a bug
  10146. occurring on msvc v19.0 compiler (VS 2015) debug build. For more
  10147. information refer to: https://github.com/nlohmann/json/issues/1608
  10148. */
  10149. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  10150. : m_object(other.m_object), m_it(other.m_it)
  10151. {}
  10152. /*!
  10153. @brief converting assignment
  10154. @param[in] other const iterator to copy from
  10155. @return const/non-const iterator
  10156. @note It is not checked whether @a other is initialized.
  10157. */
  10158. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  10159. {
  10160. if (&other != this)
  10161. {
  10162. m_object = other.m_object;
  10163. m_it = other.m_it;
  10164. }
  10165. return *this;
  10166. }
  10167. /*!
  10168. @brief converting constructor
  10169. @param[in] other non-const iterator to copy from
  10170. @note It is not checked whether @a other is initialized.
  10171. */
  10172. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  10173. : m_object(other.m_object), m_it(other.m_it)
  10174. {}
  10175. /*!
  10176. @brief converting assignment
  10177. @param[in] other non-const iterator to copy from
  10178. @return const/non-const iterator
  10179. @note It is not checked whether @a other is initialized.
  10180. */
  10181. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept // NOLINT(cert-oop54-cpp)
  10182. {
  10183. m_object = other.m_object;
  10184. m_it = other.m_it;
  10185. return *this;
  10186. }
  10187. JSON_PRIVATE_UNLESS_TESTED:
  10188. /*!
  10189. @brief set the iterator to the first value
  10190. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10191. */
  10192. void set_begin() noexcept
  10193. {
  10194. JSON_ASSERT(m_object != nullptr);
  10195. switch (m_object->m_type)
  10196. {
  10197. case value_t::object:
  10198. {
  10199. m_it.object_iterator = m_object->m_value.object->begin();
  10200. break;
  10201. }
  10202. case value_t::array:
  10203. {
  10204. m_it.array_iterator = m_object->m_value.array->begin();
  10205. break;
  10206. }
  10207. case value_t::null:
  10208. {
  10209. // set to end so begin()==end() is true: null is empty
  10210. m_it.primitive_iterator.set_end();
  10211. break;
  10212. }
  10213. case value_t::string:
  10214. case value_t::boolean:
  10215. case value_t::number_integer:
  10216. case value_t::number_unsigned:
  10217. case value_t::number_float:
  10218. case value_t::binary:
  10219. case value_t::discarded:
  10220. default:
  10221. {
  10222. m_it.primitive_iterator.set_begin();
  10223. break;
  10224. }
  10225. }
  10226. }
  10227. /*!
  10228. @brief set the iterator past the last value
  10229. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10230. */
  10231. void set_end() noexcept
  10232. {
  10233. JSON_ASSERT(m_object != nullptr);
  10234. switch (m_object->m_type)
  10235. {
  10236. case value_t::object:
  10237. {
  10238. m_it.object_iterator = m_object->m_value.object->end();
  10239. break;
  10240. }
  10241. case value_t::array:
  10242. {
  10243. m_it.array_iterator = m_object->m_value.array->end();
  10244. break;
  10245. }
  10246. case value_t::null:
  10247. case value_t::string:
  10248. case value_t::boolean:
  10249. case value_t::number_integer:
  10250. case value_t::number_unsigned:
  10251. case value_t::number_float:
  10252. case value_t::binary:
  10253. case value_t::discarded:
  10254. default:
  10255. {
  10256. m_it.primitive_iterator.set_end();
  10257. break;
  10258. }
  10259. }
  10260. }
  10261. public:
  10262. /*!
  10263. @brief return a reference to the value pointed to by the iterator
  10264. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10265. */
  10266. reference operator*() const
  10267. {
  10268. JSON_ASSERT(m_object != nullptr);
  10269. switch (m_object->m_type)
  10270. {
  10271. case value_t::object:
  10272. {
  10273. JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
  10274. return m_it.object_iterator->second;
  10275. }
  10276. case value_t::array:
  10277. {
  10278. JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
  10279. return *m_it.array_iterator;
  10280. }
  10281. case value_t::null:
  10282. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10283. case value_t::string:
  10284. case value_t::boolean:
  10285. case value_t::number_integer:
  10286. case value_t::number_unsigned:
  10287. case value_t::number_float:
  10288. case value_t::binary:
  10289. case value_t::discarded:
  10290. default:
  10291. {
  10292. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  10293. {
  10294. return *m_object;
  10295. }
  10296. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10297. }
  10298. }
  10299. }
  10300. /*!
  10301. @brief dereference the iterator
  10302. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10303. */
  10304. pointer operator->() const
  10305. {
  10306. JSON_ASSERT(m_object != nullptr);
  10307. switch (m_object->m_type)
  10308. {
  10309. case value_t::object:
  10310. {
  10311. JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
  10312. return &(m_it.object_iterator->second);
  10313. }
  10314. case value_t::array:
  10315. {
  10316. JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
  10317. return &*m_it.array_iterator;
  10318. }
  10319. case value_t::null:
  10320. case value_t::string:
  10321. case value_t::boolean:
  10322. case value_t::number_integer:
  10323. case value_t::number_unsigned:
  10324. case value_t::number_float:
  10325. case value_t::binary:
  10326. case value_t::discarded:
  10327. default:
  10328. {
  10329. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  10330. {
  10331. return m_object;
  10332. }
  10333. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10334. }
  10335. }
  10336. }
  10337. /*!
  10338. @brief post-increment (it++)
  10339. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10340. */
  10341. iter_impl const operator++(int) // NOLINT(readability-const-return-type)
  10342. {
  10343. auto result = *this;
  10344. ++(*this);
  10345. return result;
  10346. }
  10347. /*!
  10348. @brief pre-increment (++it)
  10349. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10350. */
  10351. iter_impl& operator++()
  10352. {
  10353. JSON_ASSERT(m_object != nullptr);
  10354. switch (m_object->m_type)
  10355. {
  10356. case value_t::object:
  10357. {
  10358. std::advance(m_it.object_iterator, 1);
  10359. break;
  10360. }
  10361. case value_t::array:
  10362. {
  10363. std::advance(m_it.array_iterator, 1);
  10364. break;
  10365. }
  10366. case value_t::null:
  10367. case value_t::string:
  10368. case value_t::boolean:
  10369. case value_t::number_integer:
  10370. case value_t::number_unsigned:
  10371. case value_t::number_float:
  10372. case value_t::binary:
  10373. case value_t::discarded:
  10374. default:
  10375. {
  10376. ++m_it.primitive_iterator;
  10377. break;
  10378. }
  10379. }
  10380. return *this;
  10381. }
  10382. /*!
  10383. @brief post-decrement (it--)
  10384. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10385. */
  10386. iter_impl const operator--(int) // NOLINT(readability-const-return-type)
  10387. {
  10388. auto result = *this;
  10389. --(*this);
  10390. return result;
  10391. }
  10392. /*!
  10393. @brief pre-decrement (--it)
  10394. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10395. */
  10396. iter_impl& operator--()
  10397. {
  10398. JSON_ASSERT(m_object != nullptr);
  10399. switch (m_object->m_type)
  10400. {
  10401. case value_t::object:
  10402. {
  10403. std::advance(m_it.object_iterator, -1);
  10404. break;
  10405. }
  10406. case value_t::array:
  10407. {
  10408. std::advance(m_it.array_iterator, -1);
  10409. break;
  10410. }
  10411. case value_t::null:
  10412. case value_t::string:
  10413. case value_t::boolean:
  10414. case value_t::number_integer:
  10415. case value_t::number_unsigned:
  10416. case value_t::number_float:
  10417. case value_t::binary:
  10418. case value_t::discarded:
  10419. default:
  10420. {
  10421. --m_it.primitive_iterator;
  10422. break;
  10423. }
  10424. }
  10425. return *this;
  10426. }
  10427. /*!
  10428. @brief comparison: equal
  10429. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10430. */
  10431. 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 >
  10432. bool operator==(const IterImpl& other) const
  10433. {
  10434. // if objects are not the same, the comparison is undefined
  10435. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  10436. {
  10437. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object));
  10438. }
  10439. JSON_ASSERT(m_object != nullptr);
  10440. switch (m_object->m_type)
  10441. {
  10442. case value_t::object:
  10443. return (m_it.object_iterator == other.m_it.object_iterator);
  10444. case value_t::array:
  10445. return (m_it.array_iterator == other.m_it.array_iterator);
  10446. case value_t::null:
  10447. case value_t::string:
  10448. case value_t::boolean:
  10449. case value_t::number_integer:
  10450. case value_t::number_unsigned:
  10451. case value_t::number_float:
  10452. case value_t::binary:
  10453. case value_t::discarded:
  10454. default:
  10455. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  10456. }
  10457. }
  10458. /*!
  10459. @brief comparison: not equal
  10460. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10461. */
  10462. 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 >
  10463. bool operator!=(const IterImpl& other) const
  10464. {
  10465. return !operator==(other);
  10466. }
  10467. /*!
  10468. @brief comparison: smaller
  10469. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10470. */
  10471. bool operator<(const iter_impl& other) const
  10472. {
  10473. // if objects are not the same, the comparison is undefined
  10474. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  10475. {
  10476. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object));
  10477. }
  10478. JSON_ASSERT(m_object != nullptr);
  10479. switch (m_object->m_type)
  10480. {
  10481. case value_t::object:
  10482. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", *m_object));
  10483. case value_t::array:
  10484. return (m_it.array_iterator < other.m_it.array_iterator);
  10485. case value_t::null:
  10486. case value_t::string:
  10487. case value_t::boolean:
  10488. case value_t::number_integer:
  10489. case value_t::number_unsigned:
  10490. case value_t::number_float:
  10491. case value_t::binary:
  10492. case value_t::discarded:
  10493. default:
  10494. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  10495. }
  10496. }
  10497. /*!
  10498. @brief comparison: less than or equal
  10499. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10500. */
  10501. bool operator<=(const iter_impl& other) const
  10502. {
  10503. return !other.operator < (*this);
  10504. }
  10505. /*!
  10506. @brief comparison: greater than
  10507. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10508. */
  10509. bool operator>(const iter_impl& other) const
  10510. {
  10511. return !operator<=(other);
  10512. }
  10513. /*!
  10514. @brief comparison: greater than or equal
  10515. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10516. */
  10517. bool operator>=(const iter_impl& other) const
  10518. {
  10519. return !operator<(other);
  10520. }
  10521. /*!
  10522. @brief add to iterator
  10523. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10524. */
  10525. iter_impl& operator+=(difference_type i)
  10526. {
  10527. JSON_ASSERT(m_object != nullptr);
  10528. switch (m_object->m_type)
  10529. {
  10530. case value_t::object:
  10531. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object));
  10532. case value_t::array:
  10533. {
  10534. std::advance(m_it.array_iterator, i);
  10535. break;
  10536. }
  10537. case value_t::null:
  10538. case value_t::string:
  10539. case value_t::boolean:
  10540. case value_t::number_integer:
  10541. case value_t::number_unsigned:
  10542. case value_t::number_float:
  10543. case value_t::binary:
  10544. case value_t::discarded:
  10545. default:
  10546. {
  10547. m_it.primitive_iterator += i;
  10548. break;
  10549. }
  10550. }
  10551. return *this;
  10552. }
  10553. /*!
  10554. @brief subtract from iterator
  10555. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10556. */
  10557. iter_impl& operator-=(difference_type i)
  10558. {
  10559. return operator+=(-i);
  10560. }
  10561. /*!
  10562. @brief add to iterator
  10563. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10564. */
  10565. iter_impl operator+(difference_type i) const
  10566. {
  10567. auto result = *this;
  10568. result += i;
  10569. return result;
  10570. }
  10571. /*!
  10572. @brief addition of distance and iterator
  10573. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10574. */
  10575. friend iter_impl operator+(difference_type i, const iter_impl& it)
  10576. {
  10577. auto result = it;
  10578. result += i;
  10579. return result;
  10580. }
  10581. /*!
  10582. @brief subtract from iterator
  10583. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10584. */
  10585. iter_impl operator-(difference_type i) const
  10586. {
  10587. auto result = *this;
  10588. result -= i;
  10589. return result;
  10590. }
  10591. /*!
  10592. @brief return difference
  10593. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10594. */
  10595. difference_type operator-(const iter_impl& other) const
  10596. {
  10597. JSON_ASSERT(m_object != nullptr);
  10598. switch (m_object->m_type)
  10599. {
  10600. case value_t::object:
  10601. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object));
  10602. case value_t::array:
  10603. return m_it.array_iterator - other.m_it.array_iterator;
  10604. case value_t::null:
  10605. case value_t::string:
  10606. case value_t::boolean:
  10607. case value_t::number_integer:
  10608. case value_t::number_unsigned:
  10609. case value_t::number_float:
  10610. case value_t::binary:
  10611. case value_t::discarded:
  10612. default:
  10613. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  10614. }
  10615. }
  10616. /*!
  10617. @brief access to successor
  10618. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10619. */
  10620. reference operator[](difference_type n) const
  10621. {
  10622. JSON_ASSERT(m_object != nullptr);
  10623. switch (m_object->m_type)
  10624. {
  10625. case value_t::object:
  10626. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", *m_object));
  10627. case value_t::array:
  10628. return *std::next(m_it.array_iterator, n);
  10629. case value_t::null:
  10630. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10631. case value_t::string:
  10632. case value_t::boolean:
  10633. case value_t::number_integer:
  10634. case value_t::number_unsigned:
  10635. case value_t::number_float:
  10636. case value_t::binary:
  10637. case value_t::discarded:
  10638. default:
  10639. {
  10640. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  10641. {
  10642. return *m_object;
  10643. }
  10644. JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
  10645. }
  10646. }
  10647. }
  10648. /*!
  10649. @brief return the key of an object iterator
  10650. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10651. */
  10652. const typename object_t::key_type& key() const
  10653. {
  10654. JSON_ASSERT(m_object != nullptr);
  10655. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  10656. {
  10657. return m_it.object_iterator->first;
  10658. }
  10659. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", *m_object));
  10660. }
  10661. /*!
  10662. @brief return the value of an iterator
  10663. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  10664. */
  10665. reference value() const
  10666. {
  10667. return operator*();
  10668. }
  10669. JSON_PRIVATE_UNLESS_TESTED:
  10670. /// associated JSON instance
  10671. pointer m_object = nullptr;
  10672. /// the actual iterator of the associated instance
  10673. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  10674. };
  10675. } // namespace detail
  10676. } // namespace nlohmann
  10677. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  10678. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  10679. #include <cstddef> // ptrdiff_t
  10680. #include <iterator> // reverse_iterator
  10681. #include <utility> // declval
  10682. namespace nlohmann
  10683. {
  10684. namespace detail
  10685. {
  10686. //////////////////////
  10687. // reverse_iterator //
  10688. //////////////////////
  10689. /*!
  10690. @brief a template for a reverse iterator class
  10691. @tparam Base the base iterator type to reverse. Valid types are @ref
  10692. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  10693. create @ref const_reverse_iterator).
  10694. @requirement The class satisfies the following concept requirements:
  10695. -
  10696. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  10697. The iterator that can be moved can be moved in both directions (i.e.
  10698. incremented and decremented).
  10699. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  10700. It is possible to write to the pointed-to element (only if @a Base is
  10701. @ref iterator).
  10702. @since version 1.0.0
  10703. */
  10704. template<typename Base>
  10705. class json_reverse_iterator : public std::reverse_iterator<Base>
  10706. {
  10707. public:
  10708. using difference_type = std::ptrdiff_t;
  10709. /// shortcut to the reverse iterator adapter
  10710. using base_iterator = std::reverse_iterator<Base>;
  10711. /// the reference type for the pointed-to element
  10712. using reference = typename Base::reference;
  10713. /// create reverse iterator from iterator
  10714. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  10715. : base_iterator(it) {}
  10716. /// create reverse iterator from base class
  10717. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  10718. /// post-increment (it++)
  10719. json_reverse_iterator const operator++(int) // NOLINT(readability-const-return-type)
  10720. {
  10721. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  10722. }
  10723. /// pre-increment (++it)
  10724. json_reverse_iterator& operator++()
  10725. {
  10726. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  10727. }
  10728. /// post-decrement (it--)
  10729. json_reverse_iterator const operator--(int) // NOLINT(readability-const-return-type)
  10730. {
  10731. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  10732. }
  10733. /// pre-decrement (--it)
  10734. json_reverse_iterator& operator--()
  10735. {
  10736. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  10737. }
  10738. /// add to iterator
  10739. json_reverse_iterator& operator+=(difference_type i)
  10740. {
  10741. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  10742. }
  10743. /// add to iterator
  10744. json_reverse_iterator operator+(difference_type i) const
  10745. {
  10746. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  10747. }
  10748. /// subtract from iterator
  10749. json_reverse_iterator operator-(difference_type i) const
  10750. {
  10751. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  10752. }
  10753. /// return difference
  10754. difference_type operator-(const json_reverse_iterator& other) const
  10755. {
  10756. return base_iterator(*this) - base_iterator(other);
  10757. }
  10758. /// access to successor
  10759. reference operator[](difference_type n) const
  10760. {
  10761. return *(this->operator+(n));
  10762. }
  10763. /// return the key of an object iterator
  10764. auto key() const -> decltype(std::declval<Base>().key())
  10765. {
  10766. auto it = --this->base();
  10767. return it.key();
  10768. }
  10769. /// return the value of an iterator
  10770. reference value() const
  10771. {
  10772. auto it = --this->base();
  10773. return it.operator * ();
  10774. }
  10775. };
  10776. } // namespace detail
  10777. } // namespace nlohmann
  10778. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  10779. // #include <nlohmann/detail/json_pointer.hpp>
  10780. #include <algorithm> // all_of
  10781. #include <cctype> // isdigit
  10782. #include <limits> // max
  10783. #include <numeric> // accumulate
  10784. #include <string> // string
  10785. #include <utility> // move
  10786. #include <vector> // vector
  10787. // #include <nlohmann/detail/exceptions.hpp>
  10788. // #include <nlohmann/detail/macro_scope.hpp>
  10789. // #include <nlohmann/detail/string_escape.hpp>
  10790. // #include <nlohmann/detail/value_t.hpp>
  10791. namespace nlohmann
  10792. {
  10793. template<typename BasicJsonType>
  10794. class json_pointer
  10795. {
  10796. // allow basic_json to access private members
  10797. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  10798. friend class basic_json;
  10799. public:
  10800. /*!
  10801. @brief create JSON pointer
  10802. Create a JSON pointer according to the syntax described in
  10803. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  10804. @param[in] s string representing the JSON pointer; if omitted, the empty
  10805. string is assumed which references the whole JSON value
  10806. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  10807. not begin with a slash (`/`); see example below
  10808. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  10809. not followed by `0` (representing `~`) or `1` (representing `/`); see
  10810. example below
  10811. @liveexample{The example shows the construction several valid JSON pointers
  10812. as well as the exceptional behavior.,json_pointer}
  10813. @since version 2.0.0
  10814. */
  10815. explicit json_pointer(const std::string& s = "")
  10816. : reference_tokens(split(s))
  10817. {}
  10818. /*!
  10819. @brief return a string representation of the JSON pointer
  10820. @invariant For each JSON pointer `ptr`, it holds:
  10821. @code {.cpp}
  10822. ptr == json_pointer(ptr.to_string());
  10823. @endcode
  10824. @return a string representation of the JSON pointer
  10825. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  10826. @since version 2.0.0
  10827. */
  10828. std::string to_string() const
  10829. {
  10830. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  10831. std::string{},
  10832. [](const std::string & a, const std::string & b)
  10833. {
  10834. return a + "/" + detail::escape(b);
  10835. });
  10836. }
  10837. /// @copydoc to_string()
  10838. operator std::string() const
  10839. {
  10840. return to_string();
  10841. }
  10842. /*!
  10843. @brief append another JSON pointer at the end of this JSON pointer
  10844. @param[in] ptr JSON pointer to append
  10845. @return JSON pointer with @a ptr appended
  10846. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  10847. @complexity Linear in the length of @a ptr.
  10848. @sa see @ref operator/=(std::string) to append a reference token
  10849. @sa see @ref operator/=(std::size_t) to append an array index
  10850. @sa see @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  10851. @since version 3.6.0
  10852. */
  10853. json_pointer& operator/=(const json_pointer& ptr)
  10854. {
  10855. reference_tokens.insert(reference_tokens.end(),
  10856. ptr.reference_tokens.begin(),
  10857. ptr.reference_tokens.end());
  10858. return *this;
  10859. }
  10860. /*!
  10861. @brief append an unescaped reference token at the end of this JSON pointer
  10862. @param[in] token reference token to append
  10863. @return JSON pointer with @a token appended without escaping @a token
  10864. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  10865. @complexity Amortized constant.
  10866. @sa see @ref operator/=(const json_pointer&) to append a JSON pointer
  10867. @sa see @ref operator/=(std::size_t) to append an array index
  10868. @sa see @ref operator/(const json_pointer&, std::size_t) for a binary operator
  10869. @since version 3.6.0
  10870. */
  10871. json_pointer& operator/=(std::string token)
  10872. {
  10873. push_back(std::move(token));
  10874. return *this;
  10875. }
  10876. /*!
  10877. @brief append an array index at the end of this JSON pointer
  10878. @param[in] array_idx array index to append
  10879. @return JSON pointer with @a array_idx appended
  10880. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  10881. @complexity Amortized constant.
  10882. @sa see @ref operator/=(const json_pointer&) to append a JSON pointer
  10883. @sa see @ref operator/=(std::string) to append a reference token
  10884. @sa see @ref operator/(const json_pointer&, std::string) for a binary operator
  10885. @since version 3.6.0
  10886. */
  10887. json_pointer& operator/=(std::size_t array_idx)
  10888. {
  10889. return *this /= std::to_string(array_idx);
  10890. }
  10891. /*!
  10892. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  10893. @param[in] lhs JSON pointer
  10894. @param[in] rhs JSON pointer
  10895. @return a new JSON pointer with @a rhs appended to @a lhs
  10896. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  10897. @complexity Linear in the length of @a lhs and @a rhs.
  10898. @sa see @ref operator/=(const json_pointer&) to append a JSON pointer
  10899. @since version 3.6.0
  10900. */
  10901. friend json_pointer operator/(const json_pointer& lhs,
  10902. const json_pointer& rhs)
  10903. {
  10904. return json_pointer(lhs) /= rhs;
  10905. }
  10906. /*!
  10907. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  10908. @param[in] ptr JSON pointer
  10909. @param[in] token reference token
  10910. @return a new JSON pointer with unescaped @a token appended to @a ptr
  10911. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  10912. @complexity Linear in the length of @a ptr.
  10913. @sa see @ref operator/=(std::string) to append a reference token
  10914. @since version 3.6.0
  10915. */
  10916. friend json_pointer operator/(const json_pointer& ptr, std::string token) // NOLINT(performance-unnecessary-value-param)
  10917. {
  10918. return json_pointer(ptr) /= std::move(token);
  10919. }
  10920. /*!
  10921. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  10922. @param[in] ptr JSON pointer
  10923. @param[in] array_idx array index
  10924. @return a new JSON pointer with @a array_idx appended to @a ptr
  10925. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  10926. @complexity Linear in the length of @a ptr.
  10927. @sa see @ref operator/=(std::size_t) to append an array index
  10928. @since version 3.6.0
  10929. */
  10930. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_idx)
  10931. {
  10932. return json_pointer(ptr) /= array_idx;
  10933. }
  10934. /*!
  10935. @brief returns the parent of this JSON pointer
  10936. @return parent of this JSON pointer; in case this JSON pointer is the root,
  10937. the root itself is returned
  10938. @complexity Linear in the length of the JSON pointer.
  10939. @liveexample{The example shows the result of `parent_pointer` for different
  10940. JSON Pointers.,json_pointer__parent_pointer}
  10941. @since version 3.6.0
  10942. */
  10943. json_pointer parent_pointer() const
  10944. {
  10945. if (empty())
  10946. {
  10947. return *this;
  10948. }
  10949. json_pointer res = *this;
  10950. res.pop_back();
  10951. return res;
  10952. }
  10953. /*!
  10954. @brief remove last reference token
  10955. @pre not `empty()`
  10956. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  10957. @complexity Constant.
  10958. @throw out_of_range.405 if JSON pointer has no parent
  10959. @since version 3.6.0
  10960. */
  10961. void pop_back()
  10962. {
  10963. if (JSON_HEDLEY_UNLIKELY(empty()))
  10964. {
  10965. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  10966. }
  10967. reference_tokens.pop_back();
  10968. }
  10969. /*!
  10970. @brief return last reference token
  10971. @pre not `empty()`
  10972. @return last reference token
  10973. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  10974. @complexity Constant.
  10975. @throw out_of_range.405 if JSON pointer has no parent
  10976. @since version 3.6.0
  10977. */
  10978. const std::string& back() const
  10979. {
  10980. if (JSON_HEDLEY_UNLIKELY(empty()))
  10981. {
  10982. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  10983. }
  10984. return reference_tokens.back();
  10985. }
  10986. /*!
  10987. @brief append an unescaped token at the end of the reference pointer
  10988. @param[in] token token to add
  10989. @complexity Amortized constant.
  10990. @liveexample{The example shows the result of `push_back` for different
  10991. JSON Pointers.,json_pointer__push_back}
  10992. @since version 3.6.0
  10993. */
  10994. void push_back(const std::string& token)
  10995. {
  10996. reference_tokens.push_back(token);
  10997. }
  10998. /// @copydoc push_back(const std::string&)
  10999. void push_back(std::string&& token)
  11000. {
  11001. reference_tokens.push_back(std::move(token));
  11002. }
  11003. /*!
  11004. @brief return whether pointer points to the root document
  11005. @return true iff the JSON pointer points to the root document
  11006. @complexity Constant.
  11007. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11008. @liveexample{The example shows the result of `empty` for different JSON
  11009. Pointers.,json_pointer__empty}
  11010. @since version 3.6.0
  11011. */
  11012. bool empty() const noexcept
  11013. {
  11014. return reference_tokens.empty();
  11015. }
  11016. private:
  11017. /*!
  11018. @param[in] s reference token to be converted into an array index
  11019. @return integer representation of @a s
  11020. @throw parse_error.106 if an array index begins with '0'
  11021. @throw parse_error.109 if an array index begins not with a digit
  11022. @throw out_of_range.404 if string @a s could not be converted to an integer
  11023. @throw out_of_range.410 if an array index exceeds size_type
  11024. */
  11025. static typename BasicJsonType::size_type array_index(const std::string& s)
  11026. {
  11027. using size_type = typename BasicJsonType::size_type;
  11028. // error condition (cf. RFC 6901, Sect. 4)
  11029. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0'))
  11030. {
  11031. JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType()));
  11032. }
  11033. // error condition (cf. RFC 6901, Sect. 4)
  11034. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9')))
  11035. {
  11036. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType()));
  11037. }
  11038. std::size_t processed_chars = 0;
  11039. unsigned long long res = 0; // NOLINT(runtime/int)
  11040. JSON_TRY
  11041. {
  11042. res = std::stoull(s, &processed_chars);
  11043. }
  11044. JSON_CATCH(std::out_of_range&)
  11045. {
  11046. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType()));
  11047. }
  11048. // check if the string was completely read
  11049. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  11050. {
  11051. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType()));
  11052. }
  11053. // only triggered on special platforms (like 32bit), see also
  11054. // https://github.com/nlohmann/json/pull/2203
  11055. if (res >= static_cast<unsigned long long>((std::numeric_limits<size_type>::max)())) // NOLINT(runtime/int)
  11056. {
  11057. JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE
  11058. }
  11059. return static_cast<size_type>(res);
  11060. }
  11061. JSON_PRIVATE_UNLESS_TESTED:
  11062. json_pointer top() const
  11063. {
  11064. if (JSON_HEDLEY_UNLIKELY(empty()))
  11065. {
  11066. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  11067. }
  11068. json_pointer result = *this;
  11069. result.reference_tokens = {reference_tokens[0]};
  11070. return result;
  11071. }
  11072. private:
  11073. /*!
  11074. @brief create and return a reference to the pointed to value
  11075. @complexity Linear in the number of reference tokens.
  11076. @throw parse_error.109 if array index is not a number
  11077. @throw type_error.313 if value cannot be unflattened
  11078. */
  11079. BasicJsonType& get_and_create(BasicJsonType& j) const
  11080. {
  11081. auto* result = &j;
  11082. // in case no reference tokens exist, return a reference to the JSON value
  11083. // j which will be overwritten by a primitive value
  11084. for (const auto& reference_token : reference_tokens)
  11085. {
  11086. switch (result->type())
  11087. {
  11088. case detail::value_t::null:
  11089. {
  11090. if (reference_token == "0")
  11091. {
  11092. // start a new array if reference token is 0
  11093. result = &result->operator[](0);
  11094. }
  11095. else
  11096. {
  11097. // start a new object otherwise
  11098. result = &result->operator[](reference_token);
  11099. }
  11100. break;
  11101. }
  11102. case detail::value_t::object:
  11103. {
  11104. // create an entry in the object
  11105. result = &result->operator[](reference_token);
  11106. break;
  11107. }
  11108. case detail::value_t::array:
  11109. {
  11110. // create an entry in the array
  11111. result = &result->operator[](array_index(reference_token));
  11112. break;
  11113. }
  11114. /*
  11115. The following code is only reached if there exists a reference
  11116. token _and_ the current value is primitive. In this case, we have
  11117. an error situation, because primitive values may only occur as
  11118. single value; that is, with an empty list of reference tokens.
  11119. */
  11120. case detail::value_t::string:
  11121. case detail::value_t::boolean:
  11122. case detail::value_t::number_integer:
  11123. case detail::value_t::number_unsigned:
  11124. case detail::value_t::number_float:
  11125. case detail::value_t::binary:
  11126. case detail::value_t::discarded:
  11127. default:
  11128. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j));
  11129. }
  11130. }
  11131. return *result;
  11132. }
  11133. /*!
  11134. @brief return a reference to the pointed to value
  11135. @note This version does not throw if a value is not present, but tries to
  11136. create nested values instead. For instance, calling this function
  11137. with pointer `"/this/that"` on a null value is equivalent to calling
  11138. `operator[]("this").operator[]("that")` on that value, effectively
  11139. changing the null value to an object.
  11140. @param[in] ptr a JSON value
  11141. @return reference to the JSON value pointed to by the JSON pointer
  11142. @complexity Linear in the length of the JSON pointer.
  11143. @throw parse_error.106 if an array index begins with '0'
  11144. @throw parse_error.109 if an array index was not a number
  11145. @throw out_of_range.404 if the JSON pointer can not be resolved
  11146. */
  11147. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  11148. {
  11149. for (const auto& reference_token : reference_tokens)
  11150. {
  11151. // convert null values to arrays or objects before continuing
  11152. if (ptr->is_null())
  11153. {
  11154. // check if reference token is a number
  11155. const bool nums =
  11156. std::all_of(reference_token.begin(), reference_token.end(),
  11157. [](const unsigned char x)
  11158. {
  11159. return std::isdigit(x);
  11160. });
  11161. // change value to array for numbers or "-" or to object otherwise
  11162. *ptr = (nums || reference_token == "-")
  11163. ? detail::value_t::array
  11164. : detail::value_t::object;
  11165. }
  11166. switch (ptr->type())
  11167. {
  11168. case detail::value_t::object:
  11169. {
  11170. // use unchecked object access
  11171. ptr = &ptr->operator[](reference_token);
  11172. break;
  11173. }
  11174. case detail::value_t::array:
  11175. {
  11176. if (reference_token == "-")
  11177. {
  11178. // explicitly treat "-" as index beyond the end
  11179. ptr = &ptr->operator[](ptr->m_value.array->size());
  11180. }
  11181. else
  11182. {
  11183. // convert array index to number; unchecked access
  11184. ptr = &ptr->operator[](array_index(reference_token));
  11185. }
  11186. break;
  11187. }
  11188. case detail::value_t::null:
  11189. case detail::value_t::string:
  11190. case detail::value_t::boolean:
  11191. case detail::value_t::number_integer:
  11192. case detail::value_t::number_unsigned:
  11193. case detail::value_t::number_float:
  11194. case detail::value_t::binary:
  11195. case detail::value_t::discarded:
  11196. default:
  11197. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11198. }
  11199. }
  11200. return *ptr;
  11201. }
  11202. /*!
  11203. @throw parse_error.106 if an array index begins with '0'
  11204. @throw parse_error.109 if an array index was not a number
  11205. @throw out_of_range.402 if the array index '-' is used
  11206. @throw out_of_range.404 if the JSON pointer can not be resolved
  11207. */
  11208. BasicJsonType& get_checked(BasicJsonType* ptr) const
  11209. {
  11210. for (const auto& reference_token : reference_tokens)
  11211. {
  11212. switch (ptr->type())
  11213. {
  11214. case detail::value_t::object:
  11215. {
  11216. // note: at performs range check
  11217. ptr = &ptr->at(reference_token);
  11218. break;
  11219. }
  11220. case detail::value_t::array:
  11221. {
  11222. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11223. {
  11224. // "-" always fails the range check
  11225. JSON_THROW(detail::out_of_range::create(402,
  11226. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  11227. ") is out of range", *ptr));
  11228. }
  11229. // note: at performs range check
  11230. ptr = &ptr->at(array_index(reference_token));
  11231. break;
  11232. }
  11233. case detail::value_t::null:
  11234. case detail::value_t::string:
  11235. case detail::value_t::boolean:
  11236. case detail::value_t::number_integer:
  11237. case detail::value_t::number_unsigned:
  11238. case detail::value_t::number_float:
  11239. case detail::value_t::binary:
  11240. case detail::value_t::discarded:
  11241. default:
  11242. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11243. }
  11244. }
  11245. return *ptr;
  11246. }
  11247. /*!
  11248. @brief return a const reference to the pointed to value
  11249. @param[in] ptr a JSON value
  11250. @return const reference to the JSON value pointed to by the JSON
  11251. pointer
  11252. @throw parse_error.106 if an array index begins with '0'
  11253. @throw parse_error.109 if an array index was not a number
  11254. @throw out_of_range.402 if the array index '-' is used
  11255. @throw out_of_range.404 if the JSON pointer can not be resolved
  11256. */
  11257. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  11258. {
  11259. for (const auto& reference_token : reference_tokens)
  11260. {
  11261. switch (ptr->type())
  11262. {
  11263. case detail::value_t::object:
  11264. {
  11265. // use unchecked object access
  11266. ptr = &ptr->operator[](reference_token);
  11267. break;
  11268. }
  11269. case detail::value_t::array:
  11270. {
  11271. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11272. {
  11273. // "-" cannot be used for const access
  11274. JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr));
  11275. }
  11276. // use unchecked array access
  11277. ptr = &ptr->operator[](array_index(reference_token));
  11278. break;
  11279. }
  11280. case detail::value_t::null:
  11281. case detail::value_t::string:
  11282. case detail::value_t::boolean:
  11283. case detail::value_t::number_integer:
  11284. case detail::value_t::number_unsigned:
  11285. case detail::value_t::number_float:
  11286. case detail::value_t::binary:
  11287. case detail::value_t::discarded:
  11288. default:
  11289. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11290. }
  11291. }
  11292. return *ptr;
  11293. }
  11294. /*!
  11295. @throw parse_error.106 if an array index begins with '0'
  11296. @throw parse_error.109 if an array index was not a number
  11297. @throw out_of_range.402 if the array index '-' is used
  11298. @throw out_of_range.404 if the JSON pointer can not be resolved
  11299. */
  11300. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  11301. {
  11302. for (const auto& reference_token : reference_tokens)
  11303. {
  11304. switch (ptr->type())
  11305. {
  11306. case detail::value_t::object:
  11307. {
  11308. // note: at performs range check
  11309. ptr = &ptr->at(reference_token);
  11310. break;
  11311. }
  11312. case detail::value_t::array:
  11313. {
  11314. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11315. {
  11316. // "-" always fails the range check
  11317. JSON_THROW(detail::out_of_range::create(402,
  11318. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  11319. ") is out of range", *ptr));
  11320. }
  11321. // note: at performs range check
  11322. ptr = &ptr->at(array_index(reference_token));
  11323. break;
  11324. }
  11325. case detail::value_t::null:
  11326. case detail::value_t::string:
  11327. case detail::value_t::boolean:
  11328. case detail::value_t::number_integer:
  11329. case detail::value_t::number_unsigned:
  11330. case detail::value_t::number_float:
  11331. case detail::value_t::binary:
  11332. case detail::value_t::discarded:
  11333. default:
  11334. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  11335. }
  11336. }
  11337. return *ptr;
  11338. }
  11339. /*!
  11340. @throw parse_error.106 if an array index begins with '0'
  11341. @throw parse_error.109 if an array index was not a number
  11342. */
  11343. bool contains(const BasicJsonType* ptr) const
  11344. {
  11345. for (const auto& reference_token : reference_tokens)
  11346. {
  11347. switch (ptr->type())
  11348. {
  11349. case detail::value_t::object:
  11350. {
  11351. if (!ptr->contains(reference_token))
  11352. {
  11353. // we did not find the key in the object
  11354. return false;
  11355. }
  11356. ptr = &ptr->operator[](reference_token);
  11357. break;
  11358. }
  11359. case detail::value_t::array:
  11360. {
  11361. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  11362. {
  11363. // "-" always fails the range check
  11364. return false;
  11365. }
  11366. if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9")))
  11367. {
  11368. // invalid char
  11369. return false;
  11370. }
  11371. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1))
  11372. {
  11373. if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9')))
  11374. {
  11375. // first char should be between '1' and '9'
  11376. return false;
  11377. }
  11378. for (std::size_t i = 1; i < reference_token.size(); i++)
  11379. {
  11380. if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9')))
  11381. {
  11382. // other char should be between '0' and '9'
  11383. return false;
  11384. }
  11385. }
  11386. }
  11387. const auto idx = array_index(reference_token);
  11388. if (idx >= ptr->size())
  11389. {
  11390. // index out of range
  11391. return false;
  11392. }
  11393. ptr = &ptr->operator[](idx);
  11394. break;
  11395. }
  11396. case detail::value_t::null:
  11397. case detail::value_t::string:
  11398. case detail::value_t::boolean:
  11399. case detail::value_t::number_integer:
  11400. case detail::value_t::number_unsigned:
  11401. case detail::value_t::number_float:
  11402. case detail::value_t::binary:
  11403. case detail::value_t::discarded:
  11404. default:
  11405. {
  11406. // we do not expect primitive values if there is still a
  11407. // reference token to process
  11408. return false;
  11409. }
  11410. }
  11411. }
  11412. // no reference token left means we found a primitive value
  11413. return true;
  11414. }
  11415. /*!
  11416. @brief split the string input to reference tokens
  11417. @note This function is only called by the json_pointer constructor.
  11418. All exceptions below are documented there.
  11419. @throw parse_error.107 if the pointer is not empty or begins with '/'
  11420. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  11421. */
  11422. static std::vector<std::string> split(const std::string& reference_string)
  11423. {
  11424. std::vector<std::string> result;
  11425. // special case: empty reference string -> no reference tokens
  11426. if (reference_string.empty())
  11427. {
  11428. return result;
  11429. }
  11430. // check if nonempty reference string begins with slash
  11431. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  11432. {
  11433. JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType()));
  11434. }
  11435. // extract the reference tokens:
  11436. // - slash: position of the last read slash (or end of string)
  11437. // - start: position after the previous slash
  11438. for (
  11439. // search for the first slash after the first character
  11440. std::size_t slash = reference_string.find_first_of('/', 1),
  11441. // set the beginning of the first reference token
  11442. start = 1;
  11443. // we can stop if start == 0 (if slash == std::string::npos)
  11444. start != 0;
  11445. // set the beginning of the next reference token
  11446. // (will eventually be 0 if slash == std::string::npos)
  11447. start = (slash == std::string::npos) ? 0 : slash + 1,
  11448. // find next slash
  11449. slash = reference_string.find_first_of('/', start))
  11450. {
  11451. // use the text between the beginning of the reference token
  11452. // (start) and the last slash (slash).
  11453. auto reference_token = reference_string.substr(start, slash - start);
  11454. // check reference tokens are properly escaped
  11455. for (std::size_t pos = reference_token.find_first_of('~');
  11456. pos != std::string::npos;
  11457. pos = reference_token.find_first_of('~', pos + 1))
  11458. {
  11459. JSON_ASSERT(reference_token[pos] == '~');
  11460. // ~ must be followed by 0 or 1
  11461. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 ||
  11462. (reference_token[pos + 1] != '0' &&
  11463. reference_token[pos + 1] != '1')))
  11464. {
  11465. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType()));
  11466. }
  11467. }
  11468. // finally, store the reference token
  11469. detail::unescape(reference_token);
  11470. result.push_back(reference_token);
  11471. }
  11472. return result;
  11473. }
  11474. private:
  11475. /*!
  11476. @param[in] reference_string the reference string to the current value
  11477. @param[in] value the value to consider
  11478. @param[in,out] result the result object to insert values to
  11479. @note Empty objects or arrays are flattened to `null`.
  11480. */
  11481. static void flatten(const std::string& reference_string,
  11482. const BasicJsonType& value,
  11483. BasicJsonType& result)
  11484. {
  11485. switch (value.type())
  11486. {
  11487. case detail::value_t::array:
  11488. {
  11489. if (value.m_value.array->empty())
  11490. {
  11491. // flatten empty array as null
  11492. result[reference_string] = nullptr;
  11493. }
  11494. else
  11495. {
  11496. // iterate array and use index as reference string
  11497. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  11498. {
  11499. flatten(reference_string + "/" + std::to_string(i),
  11500. value.m_value.array->operator[](i), result);
  11501. }
  11502. }
  11503. break;
  11504. }
  11505. case detail::value_t::object:
  11506. {
  11507. if (value.m_value.object->empty())
  11508. {
  11509. // flatten empty object as null
  11510. result[reference_string] = nullptr;
  11511. }
  11512. else
  11513. {
  11514. // iterate object and use keys as reference string
  11515. for (const auto& element : *value.m_value.object)
  11516. {
  11517. flatten(reference_string + "/" + detail::escape(element.first), element.second, result);
  11518. }
  11519. }
  11520. break;
  11521. }
  11522. case detail::value_t::null:
  11523. case detail::value_t::string:
  11524. case detail::value_t::boolean:
  11525. case detail::value_t::number_integer:
  11526. case detail::value_t::number_unsigned:
  11527. case detail::value_t::number_float:
  11528. case detail::value_t::binary:
  11529. case detail::value_t::discarded:
  11530. default:
  11531. {
  11532. // add primitive value with its reference string
  11533. result[reference_string] = value;
  11534. break;
  11535. }
  11536. }
  11537. }
  11538. /*!
  11539. @param[in] value flattened JSON
  11540. @return unflattened JSON
  11541. @throw parse_error.109 if array index is not a number
  11542. @throw type_error.314 if value is not an object
  11543. @throw type_error.315 if object values are not primitive
  11544. @throw type_error.313 if value cannot be unflattened
  11545. */
  11546. static BasicJsonType
  11547. unflatten(const BasicJsonType& value)
  11548. {
  11549. if (JSON_HEDLEY_UNLIKELY(!value.is_object()))
  11550. {
  11551. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value));
  11552. }
  11553. BasicJsonType result;
  11554. // iterate the JSON object values
  11555. for (const auto& element : *value.m_value.object)
  11556. {
  11557. if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive()))
  11558. {
  11559. JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second));
  11560. }
  11561. // assign value to reference pointed to by JSON pointer; Note that if
  11562. // the JSON pointer is "" (i.e., points to the whole value), function
  11563. // get_and_create returns a reference to result itself. An assignment
  11564. // will then create a primitive value.
  11565. json_pointer(element.first).get_and_create(result) = element.second;
  11566. }
  11567. return result;
  11568. }
  11569. /*!
  11570. @brief compares two JSON pointers for equality
  11571. @param[in] lhs JSON pointer to compare
  11572. @param[in] rhs JSON pointer to compare
  11573. @return whether @a lhs is equal to @a rhs
  11574. @complexity Linear in the length of the JSON pointer
  11575. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11576. */
  11577. friend bool operator==(json_pointer const& lhs,
  11578. json_pointer const& rhs) noexcept
  11579. {
  11580. return lhs.reference_tokens == rhs.reference_tokens;
  11581. }
  11582. /*!
  11583. @brief compares two JSON pointers for inequality
  11584. @param[in] lhs JSON pointer to compare
  11585. @param[in] rhs JSON pointer to compare
  11586. @return whether @a lhs is not equal @a rhs
  11587. @complexity Linear in the length of the JSON pointer
  11588. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11589. */
  11590. friend bool operator!=(json_pointer const& lhs,
  11591. json_pointer const& rhs) noexcept
  11592. {
  11593. return !(lhs == rhs);
  11594. }
  11595. /// the reference tokens
  11596. std::vector<std::string> reference_tokens;
  11597. };
  11598. } // namespace nlohmann
  11599. // #include <nlohmann/detail/json_ref.hpp>
  11600. #include <initializer_list>
  11601. #include <utility>
  11602. // #include <nlohmann/detail/meta/type_traits.hpp>
  11603. namespace nlohmann
  11604. {
  11605. namespace detail
  11606. {
  11607. template<typename BasicJsonType>
  11608. class json_ref
  11609. {
  11610. public:
  11611. using value_type = BasicJsonType;
  11612. json_ref(value_type&& value)
  11613. : owned_value(std::move(value))
  11614. {}
  11615. json_ref(const value_type& value)
  11616. : value_ref(&value)
  11617. {}
  11618. json_ref(std::initializer_list<json_ref> init)
  11619. : owned_value(init)
  11620. {}
  11621. template <
  11622. class... Args,
  11623. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  11624. json_ref(Args && ... args)
  11625. : owned_value(std::forward<Args>(args)...)
  11626. {}
  11627. // class should be movable only
  11628. json_ref(json_ref&&) noexcept = default;
  11629. json_ref(const json_ref&) = delete;
  11630. json_ref& operator=(const json_ref&) = delete;
  11631. json_ref& operator=(json_ref&&) = delete;
  11632. ~json_ref() = default;
  11633. value_type moved_or_copied() const
  11634. {
  11635. if (value_ref == nullptr)
  11636. {
  11637. return std::move(owned_value);
  11638. }
  11639. return *value_ref;
  11640. }
  11641. value_type const& operator*() const
  11642. {
  11643. return value_ref ? *value_ref : owned_value;
  11644. }
  11645. value_type const* operator->() const
  11646. {
  11647. return &** this;
  11648. }
  11649. private:
  11650. mutable value_type owned_value = nullptr;
  11651. value_type const* value_ref = nullptr;
  11652. };
  11653. } // namespace detail
  11654. } // namespace nlohmann
  11655. // #include <nlohmann/detail/macro_scope.hpp>
  11656. // #include <nlohmann/detail/string_escape.hpp>
  11657. // #include <nlohmann/detail/meta/cpp_future.hpp>
  11658. // #include <nlohmann/detail/meta/type_traits.hpp>
  11659. // #include <nlohmann/detail/output/binary_writer.hpp>
  11660. #include <algorithm> // reverse
  11661. #include <array> // array
  11662. #include <cmath> // isnan, isinf
  11663. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  11664. #include <cstring> // memcpy
  11665. #include <limits> // numeric_limits
  11666. #include <string> // string
  11667. #include <utility> // move
  11668. // #include <nlohmann/detail/input/binary_reader.hpp>
  11669. // #include <nlohmann/detail/macro_scope.hpp>
  11670. // #include <nlohmann/detail/output/output_adapters.hpp>
  11671. #include <algorithm> // copy
  11672. #include <cstddef> // size_t
  11673. #include <iterator> // back_inserter
  11674. #include <memory> // shared_ptr, make_shared
  11675. #include <string> // basic_string
  11676. #include <vector> // vector
  11677. #ifndef JSON_NO_IO
  11678. #include <ios> // streamsize
  11679. #include <ostream> // basic_ostream
  11680. #endif // JSON_NO_IO
  11681. // #include <nlohmann/detail/macro_scope.hpp>
  11682. namespace nlohmann
  11683. {
  11684. namespace detail
  11685. {
  11686. /// abstract output adapter interface
  11687. template<typename CharType> struct output_adapter_protocol
  11688. {
  11689. virtual void write_character(CharType c) = 0;
  11690. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  11691. virtual ~output_adapter_protocol() = default;
  11692. output_adapter_protocol() = default;
  11693. output_adapter_protocol(const output_adapter_protocol&) = default;
  11694. output_adapter_protocol(output_adapter_protocol&&) noexcept = default;
  11695. output_adapter_protocol& operator=(const output_adapter_protocol&) = default;
  11696. output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default;
  11697. };
  11698. /// a type to simplify interfaces
  11699. template<typename CharType>
  11700. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  11701. /// output adapter for byte vectors
  11702. template<typename CharType, typename AllocatorType = std::allocator<CharType>>
  11703. class output_vector_adapter : public output_adapter_protocol<CharType>
  11704. {
  11705. public:
  11706. explicit output_vector_adapter(std::vector<CharType, AllocatorType>& vec) noexcept
  11707. : v(vec)
  11708. {}
  11709. void write_character(CharType c) override
  11710. {
  11711. v.push_back(c);
  11712. }
  11713. JSON_HEDLEY_NON_NULL(2)
  11714. void write_characters(const CharType* s, std::size_t length) override
  11715. {
  11716. std::copy(s, s + length, std::back_inserter(v));
  11717. }
  11718. private:
  11719. std::vector<CharType, AllocatorType>& v;
  11720. };
  11721. #ifndef JSON_NO_IO
  11722. /// output adapter for output streams
  11723. template<typename CharType>
  11724. class output_stream_adapter : public output_adapter_protocol<CharType>
  11725. {
  11726. public:
  11727. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  11728. : stream(s)
  11729. {}
  11730. void write_character(CharType c) override
  11731. {
  11732. stream.put(c);
  11733. }
  11734. JSON_HEDLEY_NON_NULL(2)
  11735. void write_characters(const CharType* s, std::size_t length) override
  11736. {
  11737. stream.write(s, static_cast<std::streamsize>(length));
  11738. }
  11739. private:
  11740. std::basic_ostream<CharType>& stream;
  11741. };
  11742. #endif // JSON_NO_IO
  11743. /// output adapter for basic_string
  11744. template<typename CharType, typename StringType = std::basic_string<CharType>>
  11745. class output_string_adapter : public output_adapter_protocol<CharType>
  11746. {
  11747. public:
  11748. explicit output_string_adapter(StringType& s) noexcept
  11749. : str(s)
  11750. {}
  11751. void write_character(CharType c) override
  11752. {
  11753. str.push_back(c);
  11754. }
  11755. JSON_HEDLEY_NON_NULL(2)
  11756. void write_characters(const CharType* s, std::size_t length) override
  11757. {
  11758. str.append(s, length);
  11759. }
  11760. private:
  11761. StringType& str;
  11762. };
  11763. template<typename CharType, typename StringType = std::basic_string<CharType>>
  11764. class output_adapter
  11765. {
  11766. public:
  11767. template<typename AllocatorType = std::allocator<CharType>>
  11768. output_adapter(std::vector<CharType, AllocatorType>& vec)
  11769. : oa(std::make_shared<output_vector_adapter<CharType, AllocatorType>>(vec)) {}
  11770. #ifndef JSON_NO_IO
  11771. output_adapter(std::basic_ostream<CharType>& s)
  11772. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  11773. #endif // JSON_NO_IO
  11774. output_adapter(StringType& s)
  11775. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  11776. operator output_adapter_t<CharType>()
  11777. {
  11778. return oa;
  11779. }
  11780. private:
  11781. output_adapter_t<CharType> oa = nullptr;
  11782. };
  11783. } // namespace detail
  11784. } // namespace nlohmann
  11785. namespace nlohmann
  11786. {
  11787. namespace detail
  11788. {
  11789. ///////////////////
  11790. // binary writer //
  11791. ///////////////////
  11792. /*!
  11793. @brief serialization to CBOR and MessagePack values
  11794. */
  11795. template<typename BasicJsonType, typename CharType>
  11796. class binary_writer
  11797. {
  11798. using string_t = typename BasicJsonType::string_t;
  11799. using binary_t = typename BasicJsonType::binary_t;
  11800. using number_float_t = typename BasicJsonType::number_float_t;
  11801. public:
  11802. /*!
  11803. @brief create a binary writer
  11804. @param[in] adapter output adapter to write to
  11805. */
  11806. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(std::move(adapter))
  11807. {
  11808. JSON_ASSERT(oa);
  11809. }
  11810. /*!
  11811. @param[in] j JSON value to serialize
  11812. @pre j.type() == value_t::object
  11813. */
  11814. void write_bson(const BasicJsonType& j)
  11815. {
  11816. switch (j.type())
  11817. {
  11818. case value_t::object:
  11819. {
  11820. write_bson_object(*j.m_value.object);
  11821. break;
  11822. }
  11823. case value_t::null:
  11824. case value_t::array:
  11825. case value_t::string:
  11826. case value_t::boolean:
  11827. case value_t::number_integer:
  11828. case value_t::number_unsigned:
  11829. case value_t::number_float:
  11830. case value_t::binary:
  11831. case value_t::discarded:
  11832. default:
  11833. {
  11834. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j));
  11835. }
  11836. }
  11837. }
  11838. /*!
  11839. @param[in] j JSON value to serialize
  11840. */
  11841. void write_cbor(const BasicJsonType& j)
  11842. {
  11843. switch (j.type())
  11844. {
  11845. case value_t::null:
  11846. {
  11847. oa->write_character(to_char_type(0xF6));
  11848. break;
  11849. }
  11850. case value_t::boolean:
  11851. {
  11852. oa->write_character(j.m_value.boolean
  11853. ? to_char_type(0xF5)
  11854. : to_char_type(0xF4));
  11855. break;
  11856. }
  11857. case value_t::number_integer:
  11858. {
  11859. if (j.m_value.number_integer >= 0)
  11860. {
  11861. // CBOR does not differentiate between positive signed
  11862. // integers and unsigned integers. Therefore, we used the
  11863. // code from the value_t::number_unsigned case here.
  11864. if (j.m_value.number_integer <= 0x17)
  11865. {
  11866. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11867. }
  11868. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  11869. {
  11870. oa->write_character(to_char_type(0x18));
  11871. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11872. }
  11873. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  11874. {
  11875. oa->write_character(to_char_type(0x19));
  11876. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  11877. }
  11878. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  11879. {
  11880. oa->write_character(to_char_type(0x1A));
  11881. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  11882. }
  11883. else
  11884. {
  11885. oa->write_character(to_char_type(0x1B));
  11886. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  11887. }
  11888. }
  11889. else
  11890. {
  11891. // The conversions below encode the sign in the first
  11892. // byte, and the value is converted to a positive number.
  11893. const auto positive_number = -1 - j.m_value.number_integer;
  11894. if (j.m_value.number_integer >= -24)
  11895. {
  11896. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  11897. }
  11898. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  11899. {
  11900. oa->write_character(to_char_type(0x38));
  11901. write_number(static_cast<std::uint8_t>(positive_number));
  11902. }
  11903. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  11904. {
  11905. oa->write_character(to_char_type(0x39));
  11906. write_number(static_cast<std::uint16_t>(positive_number));
  11907. }
  11908. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  11909. {
  11910. oa->write_character(to_char_type(0x3A));
  11911. write_number(static_cast<std::uint32_t>(positive_number));
  11912. }
  11913. else
  11914. {
  11915. oa->write_character(to_char_type(0x3B));
  11916. write_number(static_cast<std::uint64_t>(positive_number));
  11917. }
  11918. }
  11919. break;
  11920. }
  11921. case value_t::number_unsigned:
  11922. {
  11923. if (j.m_value.number_unsigned <= 0x17)
  11924. {
  11925. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  11926. }
  11927. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  11928. {
  11929. oa->write_character(to_char_type(0x18));
  11930. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  11931. }
  11932. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  11933. {
  11934. oa->write_character(to_char_type(0x19));
  11935. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  11936. }
  11937. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  11938. {
  11939. oa->write_character(to_char_type(0x1A));
  11940. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  11941. }
  11942. else
  11943. {
  11944. oa->write_character(to_char_type(0x1B));
  11945. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  11946. }
  11947. break;
  11948. }
  11949. case value_t::number_float:
  11950. {
  11951. if (std::isnan(j.m_value.number_float))
  11952. {
  11953. // NaN is 0xf97e00 in CBOR
  11954. oa->write_character(to_char_type(0xF9));
  11955. oa->write_character(to_char_type(0x7E));
  11956. oa->write_character(to_char_type(0x00));
  11957. }
  11958. else if (std::isinf(j.m_value.number_float))
  11959. {
  11960. // Infinity is 0xf97c00, -Infinity is 0xf9fc00
  11961. oa->write_character(to_char_type(0xf9));
  11962. oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC));
  11963. oa->write_character(to_char_type(0x00));
  11964. }
  11965. else
  11966. {
  11967. write_compact_float(j.m_value.number_float, detail::input_format_t::cbor);
  11968. }
  11969. break;
  11970. }
  11971. case value_t::string:
  11972. {
  11973. // step 1: write control byte and the string length
  11974. const auto N = j.m_value.string->size();
  11975. if (N <= 0x17)
  11976. {
  11977. write_number(static_cast<std::uint8_t>(0x60 + N));
  11978. }
  11979. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11980. {
  11981. oa->write_character(to_char_type(0x78));
  11982. write_number(static_cast<std::uint8_t>(N));
  11983. }
  11984. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11985. {
  11986. oa->write_character(to_char_type(0x79));
  11987. write_number(static_cast<std::uint16_t>(N));
  11988. }
  11989. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11990. {
  11991. oa->write_character(to_char_type(0x7A));
  11992. write_number(static_cast<std::uint32_t>(N));
  11993. }
  11994. // LCOV_EXCL_START
  11995. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  11996. {
  11997. oa->write_character(to_char_type(0x7B));
  11998. write_number(static_cast<std::uint64_t>(N));
  11999. }
  12000. // LCOV_EXCL_STOP
  12001. // step 2: write the string
  12002. oa->write_characters(
  12003. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  12004. j.m_value.string->size());
  12005. break;
  12006. }
  12007. case value_t::array:
  12008. {
  12009. // step 1: write control byte and the array size
  12010. const auto N = j.m_value.array->size();
  12011. if (N <= 0x17)
  12012. {
  12013. write_number(static_cast<std::uint8_t>(0x80 + N));
  12014. }
  12015. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12016. {
  12017. oa->write_character(to_char_type(0x98));
  12018. write_number(static_cast<std::uint8_t>(N));
  12019. }
  12020. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12021. {
  12022. oa->write_character(to_char_type(0x99));
  12023. write_number(static_cast<std::uint16_t>(N));
  12024. }
  12025. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12026. {
  12027. oa->write_character(to_char_type(0x9A));
  12028. write_number(static_cast<std::uint32_t>(N));
  12029. }
  12030. // LCOV_EXCL_START
  12031. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  12032. {
  12033. oa->write_character(to_char_type(0x9B));
  12034. write_number(static_cast<std::uint64_t>(N));
  12035. }
  12036. // LCOV_EXCL_STOP
  12037. // step 2: write each element
  12038. for (const auto& el : *j.m_value.array)
  12039. {
  12040. write_cbor(el);
  12041. }
  12042. break;
  12043. }
  12044. case value_t::binary:
  12045. {
  12046. if (j.m_value.binary->has_subtype())
  12047. {
  12048. if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint8_t>::max)())
  12049. {
  12050. write_number(static_cast<std::uint8_t>(0xd8));
  12051. write_number(static_cast<std::uint8_t>(j.m_value.binary->subtype()));
  12052. }
  12053. else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint16_t>::max)())
  12054. {
  12055. write_number(static_cast<std::uint8_t>(0xd9));
  12056. write_number(static_cast<std::uint16_t>(j.m_value.binary->subtype()));
  12057. }
  12058. else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint32_t>::max)())
  12059. {
  12060. write_number(static_cast<std::uint8_t>(0xda));
  12061. write_number(static_cast<std::uint32_t>(j.m_value.binary->subtype()));
  12062. }
  12063. else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint64_t>::max)())
  12064. {
  12065. write_number(static_cast<std::uint8_t>(0xdb));
  12066. write_number(static_cast<std::uint64_t>(j.m_value.binary->subtype()));
  12067. }
  12068. }
  12069. // step 1: write control byte and the binary array size
  12070. const auto N = j.m_value.binary->size();
  12071. if (N <= 0x17)
  12072. {
  12073. write_number(static_cast<std::uint8_t>(0x40 + N));
  12074. }
  12075. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12076. {
  12077. oa->write_character(to_char_type(0x58));
  12078. write_number(static_cast<std::uint8_t>(N));
  12079. }
  12080. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12081. {
  12082. oa->write_character(to_char_type(0x59));
  12083. write_number(static_cast<std::uint16_t>(N));
  12084. }
  12085. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12086. {
  12087. oa->write_character(to_char_type(0x5A));
  12088. write_number(static_cast<std::uint32_t>(N));
  12089. }
  12090. // LCOV_EXCL_START
  12091. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  12092. {
  12093. oa->write_character(to_char_type(0x5B));
  12094. write_number(static_cast<std::uint64_t>(N));
  12095. }
  12096. // LCOV_EXCL_STOP
  12097. // step 2: write each element
  12098. oa->write_characters(
  12099. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  12100. N);
  12101. break;
  12102. }
  12103. case value_t::object:
  12104. {
  12105. // step 1: write control byte and the object size
  12106. const auto N = j.m_value.object->size();
  12107. if (N <= 0x17)
  12108. {
  12109. write_number(static_cast<std::uint8_t>(0xA0 + N));
  12110. }
  12111. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12112. {
  12113. oa->write_character(to_char_type(0xB8));
  12114. write_number(static_cast<std::uint8_t>(N));
  12115. }
  12116. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12117. {
  12118. oa->write_character(to_char_type(0xB9));
  12119. write_number(static_cast<std::uint16_t>(N));
  12120. }
  12121. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12122. {
  12123. oa->write_character(to_char_type(0xBA));
  12124. write_number(static_cast<std::uint32_t>(N));
  12125. }
  12126. // LCOV_EXCL_START
  12127. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  12128. {
  12129. oa->write_character(to_char_type(0xBB));
  12130. write_number(static_cast<std::uint64_t>(N));
  12131. }
  12132. // LCOV_EXCL_STOP
  12133. // step 2: write each element
  12134. for (const auto& el : *j.m_value.object)
  12135. {
  12136. write_cbor(el.first);
  12137. write_cbor(el.second);
  12138. }
  12139. break;
  12140. }
  12141. case value_t::discarded:
  12142. default:
  12143. break;
  12144. }
  12145. }
  12146. /*!
  12147. @param[in] j JSON value to serialize
  12148. */
  12149. void write_msgpack(const BasicJsonType& j)
  12150. {
  12151. switch (j.type())
  12152. {
  12153. case value_t::null: // nil
  12154. {
  12155. oa->write_character(to_char_type(0xC0));
  12156. break;
  12157. }
  12158. case value_t::boolean: // true and false
  12159. {
  12160. oa->write_character(j.m_value.boolean
  12161. ? to_char_type(0xC3)
  12162. : to_char_type(0xC2));
  12163. break;
  12164. }
  12165. case value_t::number_integer:
  12166. {
  12167. if (j.m_value.number_integer >= 0)
  12168. {
  12169. // MessagePack does not differentiate between positive
  12170. // signed integers and unsigned integers. Therefore, we used
  12171. // the code from the value_t::number_unsigned case here.
  12172. if (j.m_value.number_unsigned < 128)
  12173. {
  12174. // positive fixnum
  12175. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12176. }
  12177. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  12178. {
  12179. // uint 8
  12180. oa->write_character(to_char_type(0xCC));
  12181. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12182. }
  12183. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  12184. {
  12185. // uint 16
  12186. oa->write_character(to_char_type(0xCD));
  12187. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  12188. }
  12189. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  12190. {
  12191. // uint 32
  12192. oa->write_character(to_char_type(0xCE));
  12193. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  12194. }
  12195. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  12196. {
  12197. // uint 64
  12198. oa->write_character(to_char_type(0xCF));
  12199. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  12200. }
  12201. }
  12202. else
  12203. {
  12204. if (j.m_value.number_integer >= -32)
  12205. {
  12206. // negative fixnum
  12207. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  12208. }
  12209. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() &&
  12210. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  12211. {
  12212. // int 8
  12213. oa->write_character(to_char_type(0xD0));
  12214. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  12215. }
  12216. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() &&
  12217. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  12218. {
  12219. // int 16
  12220. oa->write_character(to_char_type(0xD1));
  12221. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  12222. }
  12223. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() &&
  12224. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  12225. {
  12226. // int 32
  12227. oa->write_character(to_char_type(0xD2));
  12228. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  12229. }
  12230. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() &&
  12231. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  12232. {
  12233. // int 64
  12234. oa->write_character(to_char_type(0xD3));
  12235. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  12236. }
  12237. }
  12238. break;
  12239. }
  12240. case value_t::number_unsigned:
  12241. {
  12242. if (j.m_value.number_unsigned < 128)
  12243. {
  12244. // positive fixnum
  12245. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12246. }
  12247. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  12248. {
  12249. // uint 8
  12250. oa->write_character(to_char_type(0xCC));
  12251. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  12252. }
  12253. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  12254. {
  12255. // uint 16
  12256. oa->write_character(to_char_type(0xCD));
  12257. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  12258. }
  12259. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  12260. {
  12261. // uint 32
  12262. oa->write_character(to_char_type(0xCE));
  12263. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  12264. }
  12265. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  12266. {
  12267. // uint 64
  12268. oa->write_character(to_char_type(0xCF));
  12269. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  12270. }
  12271. break;
  12272. }
  12273. case value_t::number_float:
  12274. {
  12275. write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack);
  12276. break;
  12277. }
  12278. case value_t::string:
  12279. {
  12280. // step 1: write control byte and the string length
  12281. const auto N = j.m_value.string->size();
  12282. if (N <= 31)
  12283. {
  12284. // fixstr
  12285. write_number(static_cast<std::uint8_t>(0xA0 | N));
  12286. }
  12287. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12288. {
  12289. // str 8
  12290. oa->write_character(to_char_type(0xD9));
  12291. write_number(static_cast<std::uint8_t>(N));
  12292. }
  12293. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12294. {
  12295. // str 16
  12296. oa->write_character(to_char_type(0xDA));
  12297. write_number(static_cast<std::uint16_t>(N));
  12298. }
  12299. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12300. {
  12301. // str 32
  12302. oa->write_character(to_char_type(0xDB));
  12303. write_number(static_cast<std::uint32_t>(N));
  12304. }
  12305. // step 2: write the string
  12306. oa->write_characters(
  12307. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  12308. j.m_value.string->size());
  12309. break;
  12310. }
  12311. case value_t::array:
  12312. {
  12313. // step 1: write control byte and the array size
  12314. const auto N = j.m_value.array->size();
  12315. if (N <= 15)
  12316. {
  12317. // fixarray
  12318. write_number(static_cast<std::uint8_t>(0x90 | N));
  12319. }
  12320. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12321. {
  12322. // array 16
  12323. oa->write_character(to_char_type(0xDC));
  12324. write_number(static_cast<std::uint16_t>(N));
  12325. }
  12326. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12327. {
  12328. // array 32
  12329. oa->write_character(to_char_type(0xDD));
  12330. write_number(static_cast<std::uint32_t>(N));
  12331. }
  12332. // step 2: write each element
  12333. for (const auto& el : *j.m_value.array)
  12334. {
  12335. write_msgpack(el);
  12336. }
  12337. break;
  12338. }
  12339. case value_t::binary:
  12340. {
  12341. // step 0: determine if the binary type has a set subtype to
  12342. // determine whether or not to use the ext or fixext types
  12343. const bool use_ext = j.m_value.binary->has_subtype();
  12344. // step 1: write control byte and the byte string length
  12345. const auto N = j.m_value.binary->size();
  12346. if (N <= (std::numeric_limits<std::uint8_t>::max)())
  12347. {
  12348. std::uint8_t output_type{};
  12349. bool fixed = true;
  12350. if (use_ext)
  12351. {
  12352. switch (N)
  12353. {
  12354. case 1:
  12355. output_type = 0xD4; // fixext 1
  12356. break;
  12357. case 2:
  12358. output_type = 0xD5; // fixext 2
  12359. break;
  12360. case 4:
  12361. output_type = 0xD6; // fixext 4
  12362. break;
  12363. case 8:
  12364. output_type = 0xD7; // fixext 8
  12365. break;
  12366. case 16:
  12367. output_type = 0xD8; // fixext 16
  12368. break;
  12369. default:
  12370. output_type = 0xC7; // ext 8
  12371. fixed = false;
  12372. break;
  12373. }
  12374. }
  12375. else
  12376. {
  12377. output_type = 0xC4; // bin 8
  12378. fixed = false;
  12379. }
  12380. oa->write_character(to_char_type(output_type));
  12381. if (!fixed)
  12382. {
  12383. write_number(static_cast<std::uint8_t>(N));
  12384. }
  12385. }
  12386. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12387. {
  12388. std::uint8_t output_type = use_ext
  12389. ? 0xC8 // ext 16
  12390. : 0xC5; // bin 16
  12391. oa->write_character(to_char_type(output_type));
  12392. write_number(static_cast<std::uint16_t>(N));
  12393. }
  12394. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12395. {
  12396. std::uint8_t output_type = use_ext
  12397. ? 0xC9 // ext 32
  12398. : 0xC6; // bin 32
  12399. oa->write_character(to_char_type(output_type));
  12400. write_number(static_cast<std::uint32_t>(N));
  12401. }
  12402. // step 1.5: if this is an ext type, write the subtype
  12403. if (use_ext)
  12404. {
  12405. write_number(static_cast<std::int8_t>(j.m_value.binary->subtype()));
  12406. }
  12407. // step 2: write the byte string
  12408. oa->write_characters(
  12409. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  12410. N);
  12411. break;
  12412. }
  12413. case value_t::object:
  12414. {
  12415. // step 1: write control byte and the object size
  12416. const auto N = j.m_value.object->size();
  12417. if (N <= 15)
  12418. {
  12419. // fixmap
  12420. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  12421. }
  12422. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  12423. {
  12424. // map 16
  12425. oa->write_character(to_char_type(0xDE));
  12426. write_number(static_cast<std::uint16_t>(N));
  12427. }
  12428. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  12429. {
  12430. // map 32
  12431. oa->write_character(to_char_type(0xDF));
  12432. write_number(static_cast<std::uint32_t>(N));
  12433. }
  12434. // step 2: write each element
  12435. for (const auto& el : *j.m_value.object)
  12436. {
  12437. write_msgpack(el.first);
  12438. write_msgpack(el.second);
  12439. }
  12440. break;
  12441. }
  12442. case value_t::discarded:
  12443. default:
  12444. break;
  12445. }
  12446. }
  12447. /*!
  12448. @param[in] j JSON value to serialize
  12449. @param[in] use_count whether to use '#' prefixes (optimized format)
  12450. @param[in] use_type whether to use '$' prefixes (optimized format)
  12451. @param[in] add_prefix whether prefixes need to be used for this value
  12452. */
  12453. void write_ubjson(const BasicJsonType& j, const bool use_count,
  12454. const bool use_type, const bool add_prefix = true)
  12455. {
  12456. switch (j.type())
  12457. {
  12458. case value_t::null:
  12459. {
  12460. if (add_prefix)
  12461. {
  12462. oa->write_character(to_char_type('Z'));
  12463. }
  12464. break;
  12465. }
  12466. case value_t::boolean:
  12467. {
  12468. if (add_prefix)
  12469. {
  12470. oa->write_character(j.m_value.boolean
  12471. ? to_char_type('T')
  12472. : to_char_type('F'));
  12473. }
  12474. break;
  12475. }
  12476. case value_t::number_integer:
  12477. {
  12478. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  12479. break;
  12480. }
  12481. case value_t::number_unsigned:
  12482. {
  12483. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  12484. break;
  12485. }
  12486. case value_t::number_float:
  12487. {
  12488. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  12489. break;
  12490. }
  12491. case value_t::string:
  12492. {
  12493. if (add_prefix)
  12494. {
  12495. oa->write_character(to_char_type('S'));
  12496. }
  12497. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  12498. oa->write_characters(
  12499. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  12500. j.m_value.string->size());
  12501. break;
  12502. }
  12503. case value_t::array:
  12504. {
  12505. if (add_prefix)
  12506. {
  12507. oa->write_character(to_char_type('['));
  12508. }
  12509. bool prefix_required = true;
  12510. if (use_type && !j.m_value.array->empty())
  12511. {
  12512. JSON_ASSERT(use_count);
  12513. const CharType first_prefix = ubjson_prefix(j.front());
  12514. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  12515. [this, first_prefix](const BasicJsonType & v)
  12516. {
  12517. return ubjson_prefix(v) == first_prefix;
  12518. });
  12519. if (same_prefix)
  12520. {
  12521. prefix_required = false;
  12522. oa->write_character(to_char_type('$'));
  12523. oa->write_character(first_prefix);
  12524. }
  12525. }
  12526. if (use_count)
  12527. {
  12528. oa->write_character(to_char_type('#'));
  12529. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  12530. }
  12531. for (const auto& el : *j.m_value.array)
  12532. {
  12533. write_ubjson(el, use_count, use_type, prefix_required);
  12534. }
  12535. if (!use_count)
  12536. {
  12537. oa->write_character(to_char_type(']'));
  12538. }
  12539. break;
  12540. }
  12541. case value_t::binary:
  12542. {
  12543. if (add_prefix)
  12544. {
  12545. oa->write_character(to_char_type('['));
  12546. }
  12547. if (use_type && !j.m_value.binary->empty())
  12548. {
  12549. JSON_ASSERT(use_count);
  12550. oa->write_character(to_char_type('$'));
  12551. oa->write_character('U');
  12552. }
  12553. if (use_count)
  12554. {
  12555. oa->write_character(to_char_type('#'));
  12556. write_number_with_ubjson_prefix(j.m_value.binary->size(), true);
  12557. }
  12558. if (use_type)
  12559. {
  12560. oa->write_characters(
  12561. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  12562. j.m_value.binary->size());
  12563. }
  12564. else
  12565. {
  12566. for (size_t i = 0; i < j.m_value.binary->size(); ++i)
  12567. {
  12568. oa->write_character(to_char_type('U'));
  12569. oa->write_character(j.m_value.binary->data()[i]);
  12570. }
  12571. }
  12572. if (!use_count)
  12573. {
  12574. oa->write_character(to_char_type(']'));
  12575. }
  12576. break;
  12577. }
  12578. case value_t::object:
  12579. {
  12580. if (add_prefix)
  12581. {
  12582. oa->write_character(to_char_type('{'));
  12583. }
  12584. bool prefix_required = true;
  12585. if (use_type && !j.m_value.object->empty())
  12586. {
  12587. JSON_ASSERT(use_count);
  12588. const CharType first_prefix = ubjson_prefix(j.front());
  12589. const bool same_prefix = std::all_of(j.begin(), j.end(),
  12590. [this, first_prefix](const BasicJsonType & v)
  12591. {
  12592. return ubjson_prefix(v) == first_prefix;
  12593. });
  12594. if (same_prefix)
  12595. {
  12596. prefix_required = false;
  12597. oa->write_character(to_char_type('$'));
  12598. oa->write_character(first_prefix);
  12599. }
  12600. }
  12601. if (use_count)
  12602. {
  12603. oa->write_character(to_char_type('#'));
  12604. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  12605. }
  12606. for (const auto& el : *j.m_value.object)
  12607. {
  12608. write_number_with_ubjson_prefix(el.first.size(), true);
  12609. oa->write_characters(
  12610. reinterpret_cast<const CharType*>(el.first.c_str()),
  12611. el.first.size());
  12612. write_ubjson(el.second, use_count, use_type, prefix_required);
  12613. }
  12614. if (!use_count)
  12615. {
  12616. oa->write_character(to_char_type('}'));
  12617. }
  12618. break;
  12619. }
  12620. case value_t::discarded:
  12621. default:
  12622. break;
  12623. }
  12624. }
  12625. private:
  12626. //////////
  12627. // BSON //
  12628. //////////
  12629. /*!
  12630. @return The size of a BSON document entry header, including the id marker
  12631. and the entry name size (and its null-terminator).
  12632. */
  12633. static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j)
  12634. {
  12635. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  12636. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  12637. {
  12638. JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j));
  12639. static_cast<void>(j);
  12640. }
  12641. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  12642. }
  12643. /*!
  12644. @brief Writes the given @a element_type and @a name to the output adapter
  12645. */
  12646. void write_bson_entry_header(const string_t& name,
  12647. const std::uint8_t element_type)
  12648. {
  12649. oa->write_character(to_char_type(element_type)); // boolean
  12650. oa->write_characters(
  12651. reinterpret_cast<const CharType*>(name.c_str()),
  12652. name.size() + 1u);
  12653. }
  12654. /*!
  12655. @brief Writes a BSON element with key @a name and boolean value @a value
  12656. */
  12657. void write_bson_boolean(const string_t& name,
  12658. const bool value)
  12659. {
  12660. write_bson_entry_header(name, 0x08);
  12661. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  12662. }
  12663. /*!
  12664. @brief Writes a BSON element with key @a name and double value @a value
  12665. */
  12666. void write_bson_double(const string_t& name,
  12667. const double value)
  12668. {
  12669. write_bson_entry_header(name, 0x01);
  12670. write_number<double, true>(value);
  12671. }
  12672. /*!
  12673. @return The size of the BSON-encoded string in @a value
  12674. */
  12675. static std::size_t calc_bson_string_size(const string_t& value)
  12676. {
  12677. return sizeof(std::int32_t) + value.size() + 1ul;
  12678. }
  12679. /*!
  12680. @brief Writes a BSON element with key @a name and string value @a value
  12681. */
  12682. void write_bson_string(const string_t& name,
  12683. const string_t& value)
  12684. {
  12685. write_bson_entry_header(name, 0x02);
  12686. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  12687. oa->write_characters(
  12688. reinterpret_cast<const CharType*>(value.c_str()),
  12689. value.size() + 1);
  12690. }
  12691. /*!
  12692. @brief Writes a BSON element with key @a name and null value
  12693. */
  12694. void write_bson_null(const string_t& name)
  12695. {
  12696. write_bson_entry_header(name, 0x0A);
  12697. }
  12698. /*!
  12699. @return The size of the BSON-encoded integer @a value
  12700. */
  12701. static std::size_t calc_bson_integer_size(const std::int64_t value)
  12702. {
  12703. return (std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)()
  12704. ? sizeof(std::int32_t)
  12705. : sizeof(std::int64_t);
  12706. }
  12707. /*!
  12708. @brief Writes a BSON element with key @a name and integer @a value
  12709. */
  12710. void write_bson_integer(const string_t& name,
  12711. const std::int64_t value)
  12712. {
  12713. if ((std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)())
  12714. {
  12715. write_bson_entry_header(name, 0x10); // int32
  12716. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  12717. }
  12718. else
  12719. {
  12720. write_bson_entry_header(name, 0x12); // int64
  12721. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  12722. }
  12723. }
  12724. /*!
  12725. @return The size of the BSON-encoded unsigned integer in @a j
  12726. */
  12727. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  12728. {
  12729. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12730. ? sizeof(std::int32_t)
  12731. : sizeof(std::int64_t);
  12732. }
  12733. /*!
  12734. @brief Writes a BSON element with key @a name and unsigned @a value
  12735. */
  12736. void write_bson_unsigned(const string_t& name,
  12737. const BasicJsonType& j)
  12738. {
  12739. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12740. {
  12741. write_bson_entry_header(name, 0x10 /* int32 */);
  12742. write_number<std::int32_t, true>(static_cast<std::int32_t>(j.m_value.number_unsigned));
  12743. }
  12744. else if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  12745. {
  12746. write_bson_entry_header(name, 0x12 /* int64 */);
  12747. write_number<std::int64_t, true>(static_cast<std::int64_t>(j.m_value.number_unsigned));
  12748. }
  12749. else
  12750. {
  12751. 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));
  12752. }
  12753. }
  12754. /*!
  12755. @brief Writes a BSON element with key @a name and object @a value
  12756. */
  12757. void write_bson_object_entry(const string_t& name,
  12758. const typename BasicJsonType::object_t& value)
  12759. {
  12760. write_bson_entry_header(name, 0x03); // object
  12761. write_bson_object(value);
  12762. }
  12763. /*!
  12764. @return The size of the BSON-encoded array @a value
  12765. */
  12766. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  12767. {
  12768. std::size_t array_index = 0ul;
  12769. const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), std::size_t(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el)
  12770. {
  12771. return result + calc_bson_element_size(std::to_string(array_index++), el);
  12772. });
  12773. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  12774. }
  12775. /*!
  12776. @return The size of the BSON-encoded binary array @a value
  12777. */
  12778. static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value)
  12779. {
  12780. return sizeof(std::int32_t) + value.size() + 1ul;
  12781. }
  12782. /*!
  12783. @brief Writes a BSON element with key @a name and array @a value
  12784. */
  12785. void write_bson_array(const string_t& name,
  12786. const typename BasicJsonType::array_t& value)
  12787. {
  12788. write_bson_entry_header(name, 0x04); // array
  12789. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  12790. std::size_t array_index = 0ul;
  12791. for (const auto& el : value)
  12792. {
  12793. write_bson_element(std::to_string(array_index++), el);
  12794. }
  12795. oa->write_character(to_char_type(0x00));
  12796. }
  12797. /*!
  12798. @brief Writes a BSON element with key @a name and binary value @a value
  12799. */
  12800. void write_bson_binary(const string_t& name,
  12801. const binary_t& value)
  12802. {
  12803. write_bson_entry_header(name, 0x05);
  12804. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size()));
  12805. write_number(value.has_subtype() ? static_cast<std::uint8_t>(value.subtype()) : std::uint8_t(0x00));
  12806. oa->write_characters(reinterpret_cast<const CharType*>(value.data()), value.size());
  12807. }
  12808. /*!
  12809. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  12810. @return The calculated size for the BSON document entry for @a j with the given @a name.
  12811. */
  12812. static std::size_t calc_bson_element_size(const string_t& name,
  12813. const BasicJsonType& j)
  12814. {
  12815. const auto header_size = calc_bson_entry_header_size(name, j);
  12816. switch (j.type())
  12817. {
  12818. case value_t::object:
  12819. return header_size + calc_bson_object_size(*j.m_value.object);
  12820. case value_t::array:
  12821. return header_size + calc_bson_array_size(*j.m_value.array);
  12822. case value_t::binary:
  12823. return header_size + calc_bson_binary_size(*j.m_value.binary);
  12824. case value_t::boolean:
  12825. return header_size + 1ul;
  12826. case value_t::number_float:
  12827. return header_size + 8ul;
  12828. case value_t::number_integer:
  12829. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  12830. case value_t::number_unsigned:
  12831. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  12832. case value_t::string:
  12833. return header_size + calc_bson_string_size(*j.m_value.string);
  12834. case value_t::null:
  12835. return header_size + 0ul;
  12836. // LCOV_EXCL_START
  12837. case value_t::discarded:
  12838. default:
  12839. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
  12840. return 0ul;
  12841. // LCOV_EXCL_STOP
  12842. }
  12843. }
  12844. /*!
  12845. @brief Serializes the JSON value @a j to BSON and associates it with the
  12846. key @a name.
  12847. @param name The name to associate with the JSON entity @a j within the
  12848. current BSON document
  12849. */
  12850. void write_bson_element(const string_t& name,
  12851. const BasicJsonType& j)
  12852. {
  12853. switch (j.type())
  12854. {
  12855. case value_t::object:
  12856. return write_bson_object_entry(name, *j.m_value.object);
  12857. case value_t::array:
  12858. return write_bson_array(name, *j.m_value.array);
  12859. case value_t::binary:
  12860. return write_bson_binary(name, *j.m_value.binary);
  12861. case value_t::boolean:
  12862. return write_bson_boolean(name, j.m_value.boolean);
  12863. case value_t::number_float:
  12864. return write_bson_double(name, j.m_value.number_float);
  12865. case value_t::number_integer:
  12866. return write_bson_integer(name, j.m_value.number_integer);
  12867. case value_t::number_unsigned:
  12868. return write_bson_unsigned(name, j);
  12869. case value_t::string:
  12870. return write_bson_string(name, *j.m_value.string);
  12871. case value_t::null:
  12872. return write_bson_null(name);
  12873. // LCOV_EXCL_START
  12874. case value_t::discarded:
  12875. default:
  12876. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
  12877. return;
  12878. // LCOV_EXCL_STOP
  12879. }
  12880. }
  12881. /*!
  12882. @brief Calculates the size of the BSON serialization of the given
  12883. JSON-object @a j.
  12884. @param[in] value JSON value to serialize
  12885. @pre value.type() == value_t::object
  12886. */
  12887. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  12888. {
  12889. std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0),
  12890. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  12891. {
  12892. return result += calc_bson_element_size(el.first, el.second);
  12893. });
  12894. return sizeof(std::int32_t) + document_size + 1ul;
  12895. }
  12896. /*!
  12897. @param[in] value JSON value to serialize
  12898. @pre value.type() == value_t::object
  12899. */
  12900. void write_bson_object(const typename BasicJsonType::object_t& value)
  12901. {
  12902. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  12903. for (const auto& el : value)
  12904. {
  12905. write_bson_element(el.first, el.second);
  12906. }
  12907. oa->write_character(to_char_type(0x00));
  12908. }
  12909. //////////
  12910. // CBOR //
  12911. //////////
  12912. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  12913. {
  12914. return to_char_type(0xFA); // Single-Precision Float
  12915. }
  12916. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  12917. {
  12918. return to_char_type(0xFB); // Double-Precision Float
  12919. }
  12920. /////////////
  12921. // MsgPack //
  12922. /////////////
  12923. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  12924. {
  12925. return to_char_type(0xCA); // float 32
  12926. }
  12927. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  12928. {
  12929. return to_char_type(0xCB); // float 64
  12930. }
  12931. ////////////
  12932. // UBJSON //
  12933. ////////////
  12934. // UBJSON: write number (floating point)
  12935. template<typename NumberType, typename std::enable_if<
  12936. std::is_floating_point<NumberType>::value, int>::type = 0>
  12937. void write_number_with_ubjson_prefix(const NumberType n,
  12938. const bool add_prefix)
  12939. {
  12940. if (add_prefix)
  12941. {
  12942. oa->write_character(get_ubjson_float_prefix(n));
  12943. }
  12944. write_number(n);
  12945. }
  12946. // UBJSON: write number (unsigned integer)
  12947. template<typename NumberType, typename std::enable_if<
  12948. std::is_unsigned<NumberType>::value, int>::type = 0>
  12949. void write_number_with_ubjson_prefix(const NumberType n,
  12950. const bool add_prefix)
  12951. {
  12952. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  12953. {
  12954. if (add_prefix)
  12955. {
  12956. oa->write_character(to_char_type('i')); // int8
  12957. }
  12958. write_number(static_cast<std::uint8_t>(n));
  12959. }
  12960. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  12961. {
  12962. if (add_prefix)
  12963. {
  12964. oa->write_character(to_char_type('U')); // uint8
  12965. }
  12966. write_number(static_cast<std::uint8_t>(n));
  12967. }
  12968. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  12969. {
  12970. if (add_prefix)
  12971. {
  12972. oa->write_character(to_char_type('I')); // int16
  12973. }
  12974. write_number(static_cast<std::int16_t>(n));
  12975. }
  12976. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  12977. {
  12978. if (add_prefix)
  12979. {
  12980. oa->write_character(to_char_type('l')); // int32
  12981. }
  12982. write_number(static_cast<std::int32_t>(n));
  12983. }
  12984. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  12985. {
  12986. if (add_prefix)
  12987. {
  12988. oa->write_character(to_char_type('L')); // int64
  12989. }
  12990. write_number(static_cast<std::int64_t>(n));
  12991. }
  12992. else
  12993. {
  12994. if (add_prefix)
  12995. {
  12996. oa->write_character(to_char_type('H')); // high-precision number
  12997. }
  12998. const auto number = BasicJsonType(n).dump();
  12999. write_number_with_ubjson_prefix(number.size(), true);
  13000. for (std::size_t i = 0; i < number.size(); ++i)
  13001. {
  13002. oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
  13003. }
  13004. }
  13005. }
  13006. // UBJSON: write number (signed integer)
  13007. template < typename NumberType, typename std::enable_if <
  13008. std::is_signed<NumberType>::value&&
  13009. !std::is_floating_point<NumberType>::value, int >::type = 0 >
  13010. void write_number_with_ubjson_prefix(const NumberType n,
  13011. const bool add_prefix)
  13012. {
  13013. if ((std::numeric_limits<std::int8_t>::min)() <= n && n <= (std::numeric_limits<std::int8_t>::max)())
  13014. {
  13015. if (add_prefix)
  13016. {
  13017. oa->write_character(to_char_type('i')); // int8
  13018. }
  13019. write_number(static_cast<std::int8_t>(n));
  13020. }
  13021. 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)()))
  13022. {
  13023. if (add_prefix)
  13024. {
  13025. oa->write_character(to_char_type('U')); // uint8
  13026. }
  13027. write_number(static_cast<std::uint8_t>(n));
  13028. }
  13029. else if ((std::numeric_limits<std::int16_t>::min)() <= n && n <= (std::numeric_limits<std::int16_t>::max)())
  13030. {
  13031. if (add_prefix)
  13032. {
  13033. oa->write_character(to_char_type('I')); // int16
  13034. }
  13035. write_number(static_cast<std::int16_t>(n));
  13036. }
  13037. else if ((std::numeric_limits<std::int32_t>::min)() <= n && n <= (std::numeric_limits<std::int32_t>::max)())
  13038. {
  13039. if (add_prefix)
  13040. {
  13041. oa->write_character(to_char_type('l')); // int32
  13042. }
  13043. write_number(static_cast<std::int32_t>(n));
  13044. }
  13045. else if ((std::numeric_limits<std::int64_t>::min)() <= n && n <= (std::numeric_limits<std::int64_t>::max)())
  13046. {
  13047. if (add_prefix)
  13048. {
  13049. oa->write_character(to_char_type('L')); // int64
  13050. }
  13051. write_number(static_cast<std::int64_t>(n));
  13052. }
  13053. // LCOV_EXCL_START
  13054. else
  13055. {
  13056. if (add_prefix)
  13057. {
  13058. oa->write_character(to_char_type('H')); // high-precision number
  13059. }
  13060. const auto number = BasicJsonType(n).dump();
  13061. write_number_with_ubjson_prefix(number.size(), true);
  13062. for (std::size_t i = 0; i < number.size(); ++i)
  13063. {
  13064. oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
  13065. }
  13066. }
  13067. // LCOV_EXCL_STOP
  13068. }
  13069. /*!
  13070. @brief determine the type prefix of container values
  13071. */
  13072. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  13073. {
  13074. switch (j.type())
  13075. {
  13076. case value_t::null:
  13077. return 'Z';
  13078. case value_t::boolean:
  13079. return j.m_value.boolean ? 'T' : 'F';
  13080. case value_t::number_integer:
  13081. {
  13082. 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)())
  13083. {
  13084. return 'i';
  13085. }
  13086. 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)())
  13087. {
  13088. return 'U';
  13089. }
  13090. 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)())
  13091. {
  13092. return 'I';
  13093. }
  13094. 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)())
  13095. {
  13096. return 'l';
  13097. }
  13098. 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)())
  13099. {
  13100. return 'L';
  13101. }
  13102. // anything else is treated as high-precision number
  13103. return 'H'; // LCOV_EXCL_LINE
  13104. }
  13105. case value_t::number_unsigned:
  13106. {
  13107. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  13108. {
  13109. return 'i';
  13110. }
  13111. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  13112. {
  13113. return 'U';
  13114. }
  13115. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  13116. {
  13117. return 'I';
  13118. }
  13119. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  13120. {
  13121. return 'l';
  13122. }
  13123. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  13124. {
  13125. return 'L';
  13126. }
  13127. // anything else is treated as high-precision number
  13128. return 'H'; // LCOV_EXCL_LINE
  13129. }
  13130. case value_t::number_float:
  13131. return get_ubjson_float_prefix(j.m_value.number_float);
  13132. case value_t::string:
  13133. return 'S';
  13134. case value_t::array: // fallthrough
  13135. case value_t::binary:
  13136. return '[';
  13137. case value_t::object:
  13138. return '{';
  13139. case value_t::discarded:
  13140. default: // discarded values
  13141. return 'N';
  13142. }
  13143. }
  13144. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  13145. {
  13146. return 'd'; // float 32
  13147. }
  13148. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  13149. {
  13150. return 'D'; // float 64
  13151. }
  13152. ///////////////////////
  13153. // Utility functions //
  13154. ///////////////////////
  13155. /*
  13156. @brief write a number to output input
  13157. @param[in] n number of type @a NumberType
  13158. @tparam NumberType the type of the number
  13159. @tparam OutputIsLittleEndian Set to true if output data is
  13160. required to be little endian
  13161. @note This function needs to respect the system's endianess, because bytes
  13162. in CBOR, MessagePack, and UBJSON are stored in network order (big
  13163. endian) and therefore need reordering on little endian systems.
  13164. */
  13165. template<typename NumberType, bool OutputIsLittleEndian = false>
  13166. void write_number(const NumberType n)
  13167. {
  13168. // step 1: write number to array of length NumberType
  13169. std::array<CharType, sizeof(NumberType)> vec{};
  13170. std::memcpy(vec.data(), &n, sizeof(NumberType));
  13171. // step 2: write array to output (with possible reordering)
  13172. if (is_little_endian != OutputIsLittleEndian)
  13173. {
  13174. // reverse byte order prior to conversion if necessary
  13175. std::reverse(vec.begin(), vec.end());
  13176. }
  13177. oa->write_characters(vec.data(), sizeof(NumberType));
  13178. }
  13179. void write_compact_float(const number_float_t n, detail::input_format_t format)
  13180. {
  13181. #ifdef __GNUC__
  13182. #pragma GCC diagnostic push
  13183. #pragma GCC diagnostic ignored "-Wfloat-equal"
  13184. #endif
  13185. if (static_cast<double>(n) >= static_cast<double>(std::numeric_limits<float>::lowest()) &&
  13186. static_cast<double>(n) <= static_cast<double>((std::numeric_limits<float>::max)()) &&
  13187. static_cast<double>(static_cast<float>(n)) == static_cast<double>(n))
  13188. {
  13189. oa->write_character(format == detail::input_format_t::cbor
  13190. ? get_cbor_float_prefix(static_cast<float>(n))
  13191. : get_msgpack_float_prefix(static_cast<float>(n)));
  13192. write_number(static_cast<float>(n));
  13193. }
  13194. else
  13195. {
  13196. oa->write_character(format == detail::input_format_t::cbor
  13197. ? get_cbor_float_prefix(n)
  13198. : get_msgpack_float_prefix(n));
  13199. write_number(n);
  13200. }
  13201. #ifdef __GNUC__
  13202. #pragma GCC diagnostic pop
  13203. #endif
  13204. }
  13205. public:
  13206. // The following to_char_type functions are implement the conversion
  13207. // between uint8_t and CharType. In case CharType is not unsigned,
  13208. // such a conversion is required to allow values greater than 128.
  13209. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  13210. template < typename C = CharType,
  13211. enable_if_t < std::is_signed<C>::value && std::is_signed<char>::value > * = nullptr >
  13212. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  13213. {
  13214. return *reinterpret_cast<char*>(&x);
  13215. }
  13216. template < typename C = CharType,
  13217. enable_if_t < std::is_signed<C>::value && std::is_unsigned<char>::value > * = nullptr >
  13218. static CharType to_char_type(std::uint8_t x) noexcept
  13219. {
  13220. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  13221. static_assert(std::is_trivial<CharType>::value, "CharType must be trivial");
  13222. CharType result;
  13223. std::memcpy(&result, &x, sizeof(x));
  13224. return result;
  13225. }
  13226. template<typename C = CharType,
  13227. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  13228. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  13229. {
  13230. return x;
  13231. }
  13232. template < typename InputCharType, typename C = CharType,
  13233. enable_if_t <
  13234. std::is_signed<C>::value &&
  13235. std::is_signed<char>::value &&
  13236. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  13237. > * = nullptr >
  13238. static constexpr CharType to_char_type(InputCharType x) noexcept
  13239. {
  13240. return x;
  13241. }
  13242. private:
  13243. /// whether we can assume little endianess
  13244. const bool is_little_endian = little_endianess();
  13245. /// the output
  13246. output_adapter_t<CharType> oa = nullptr;
  13247. };
  13248. } // namespace detail
  13249. } // namespace nlohmann
  13250. // #include <nlohmann/detail/output/output_adapters.hpp>
  13251. // #include <nlohmann/detail/output/serializer.hpp>
  13252. #include <algorithm> // reverse, remove, fill, find, none_of
  13253. #include <array> // array
  13254. #include <clocale> // localeconv, lconv
  13255. #include <cmath> // labs, isfinite, isnan, signbit
  13256. #include <cstddef> // size_t, ptrdiff_t
  13257. #include <cstdint> // uint8_t
  13258. #include <cstdio> // snprintf
  13259. #include <limits> // numeric_limits
  13260. #include <string> // string, char_traits
  13261. #include <type_traits> // is_same
  13262. #include <utility> // move
  13263. // #include <nlohmann/detail/conversions/to_chars.hpp>
  13264. #include <array> // array
  13265. #include <cmath> // signbit, isfinite
  13266. #include <cstdint> // intN_t, uintN_t
  13267. #include <cstring> // memcpy, memmove
  13268. #include <limits> // numeric_limits
  13269. #include <type_traits> // conditional
  13270. // #include <nlohmann/detail/macro_scope.hpp>
  13271. namespace nlohmann
  13272. {
  13273. namespace detail
  13274. {
  13275. /*!
  13276. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  13277. conversion.
  13278. This implementation is a slightly modified version of the reference
  13279. implementation which may be obtained from
  13280. http://florian.loitsch.com/publications (bench.tar.gz).
  13281. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  13282. For a detailed description of the algorithm see:
  13283. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  13284. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  13285. Language Design and Implementation, PLDI 2010
  13286. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  13287. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  13288. Design and Implementation, PLDI 1996
  13289. */
  13290. namespace dtoa_impl
  13291. {
  13292. template<typename Target, typename Source>
  13293. Target reinterpret_bits(const Source source)
  13294. {
  13295. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  13296. Target target;
  13297. std::memcpy(&target, &source, sizeof(Source));
  13298. return target;
  13299. }
  13300. struct diyfp // f * 2^e
  13301. {
  13302. static constexpr int kPrecision = 64; // = q
  13303. std::uint64_t f = 0;
  13304. int e = 0;
  13305. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  13306. /*!
  13307. @brief returns x - y
  13308. @pre x.e == y.e and x.f >= y.f
  13309. */
  13310. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  13311. {
  13312. JSON_ASSERT(x.e == y.e);
  13313. JSON_ASSERT(x.f >= y.f);
  13314. return {x.f - y.f, x.e};
  13315. }
  13316. /*!
  13317. @brief returns x * y
  13318. @note The result is rounded. (Only the upper q bits are returned.)
  13319. */
  13320. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  13321. {
  13322. static_assert(kPrecision == 64, "internal error");
  13323. // Computes:
  13324. // f = round((x.f * y.f) / 2^q)
  13325. // e = x.e + y.e + q
  13326. // Emulate the 64-bit * 64-bit multiplication:
  13327. //
  13328. // p = u * v
  13329. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  13330. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  13331. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  13332. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  13333. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  13334. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  13335. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  13336. //
  13337. // (Since Q might be larger than 2^32 - 1)
  13338. //
  13339. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  13340. //
  13341. // (Q_hi + H does not overflow a 64-bit int)
  13342. //
  13343. // = p_lo + 2^64 p_hi
  13344. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  13345. const std::uint64_t u_hi = x.f >> 32u;
  13346. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  13347. const std::uint64_t v_hi = y.f >> 32u;
  13348. const std::uint64_t p0 = u_lo * v_lo;
  13349. const std::uint64_t p1 = u_lo * v_hi;
  13350. const std::uint64_t p2 = u_hi * v_lo;
  13351. const std::uint64_t p3 = u_hi * v_hi;
  13352. const std::uint64_t p0_hi = p0 >> 32u;
  13353. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  13354. const std::uint64_t p1_hi = p1 >> 32u;
  13355. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  13356. const std::uint64_t p2_hi = p2 >> 32u;
  13357. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  13358. // The full product might now be computed as
  13359. //
  13360. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  13361. // p_lo = p0_lo + (Q << 32)
  13362. //
  13363. // But in this particular case here, the full p_lo is not required.
  13364. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  13365. // Q_hi + 1 does not overflow).
  13366. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  13367. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  13368. return {h, x.e + y.e + 64};
  13369. }
  13370. /*!
  13371. @brief normalize x such that the significand is >= 2^(q-1)
  13372. @pre x.f != 0
  13373. */
  13374. static diyfp normalize(diyfp x) noexcept
  13375. {
  13376. JSON_ASSERT(x.f != 0);
  13377. while ((x.f >> 63u) == 0)
  13378. {
  13379. x.f <<= 1u;
  13380. x.e--;
  13381. }
  13382. return x;
  13383. }
  13384. /*!
  13385. @brief normalize x such that the result has the exponent E
  13386. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  13387. */
  13388. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  13389. {
  13390. const int delta = x.e - target_exponent;
  13391. JSON_ASSERT(delta >= 0);
  13392. JSON_ASSERT(((x.f << delta) >> delta) == x.f);
  13393. return {x.f << delta, target_exponent};
  13394. }
  13395. };
  13396. struct boundaries
  13397. {
  13398. diyfp w;
  13399. diyfp minus;
  13400. diyfp plus;
  13401. };
  13402. /*!
  13403. Compute the (normalized) diyfp representing the input number 'value' and its
  13404. boundaries.
  13405. @pre value must be finite and positive
  13406. */
  13407. template<typename FloatType>
  13408. boundaries compute_boundaries(FloatType value)
  13409. {
  13410. JSON_ASSERT(std::isfinite(value));
  13411. JSON_ASSERT(value > 0);
  13412. // Convert the IEEE representation into a diyfp.
  13413. //
  13414. // If v is denormal:
  13415. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  13416. // If v is normalized:
  13417. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  13418. static_assert(std::numeric_limits<FloatType>::is_iec559,
  13419. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  13420. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  13421. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  13422. constexpr int kMinExp = 1 - kBias;
  13423. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  13424. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  13425. const auto bits = static_cast<std::uint64_t>(reinterpret_bits<bits_type>(value));
  13426. const std::uint64_t E = bits >> (kPrecision - 1);
  13427. const std::uint64_t F = bits & (kHiddenBit - 1);
  13428. const bool is_denormal = E == 0;
  13429. const diyfp v = is_denormal
  13430. ? diyfp(F, kMinExp)
  13431. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  13432. // Compute the boundaries m- and m+ of the floating-point value
  13433. // v = f * 2^e.
  13434. //
  13435. // Determine v- and v+, the floating-point predecessor and successor if v,
  13436. // respectively.
  13437. //
  13438. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  13439. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  13440. //
  13441. // v+ = v + 2^e
  13442. //
  13443. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  13444. // between m- and m+ round to v, regardless of how the input rounding
  13445. // algorithm breaks ties.
  13446. //
  13447. // ---+-------------+-------------+-------------+-------------+--- (A)
  13448. // v- m- v m+ v+
  13449. //
  13450. // -----------------+------+------+-------------+-------------+--- (B)
  13451. // v- m- v m+ v+
  13452. const bool lower_boundary_is_closer = F == 0 && E > 1;
  13453. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  13454. const diyfp m_minus = lower_boundary_is_closer
  13455. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  13456. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  13457. // Determine the normalized w+ = m+.
  13458. const diyfp w_plus = diyfp::normalize(m_plus);
  13459. // Determine w- = m- such that e_(w-) = e_(w+).
  13460. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  13461. return {diyfp::normalize(v), w_minus, w_plus};
  13462. }
  13463. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  13464. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  13465. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  13466. //
  13467. // alpha <= e = e_c + e_w + q <= gamma
  13468. //
  13469. // or
  13470. //
  13471. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  13472. // <= f_c * f_w * 2^gamma
  13473. //
  13474. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  13475. //
  13476. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  13477. //
  13478. // or
  13479. //
  13480. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  13481. //
  13482. // The choice of (alpha,gamma) determines the size of the table and the form of
  13483. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  13484. // in practice:
  13485. //
  13486. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  13487. // processed independently: An integral part p1, and a fractional part p2:
  13488. //
  13489. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  13490. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  13491. // = p1 + p2 * 2^e
  13492. //
  13493. // The conversion of p1 into decimal form requires a series of divisions and
  13494. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  13495. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  13496. // achieved by choosing
  13497. //
  13498. // -e >= 32 or e <= -32 := gamma
  13499. //
  13500. // In order to convert the fractional part
  13501. //
  13502. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  13503. //
  13504. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  13505. // d[-i] are extracted in order:
  13506. //
  13507. // (10 * p2) div 2^-e = d[-1]
  13508. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  13509. //
  13510. // The multiplication by 10 must not overflow. It is sufficient to choose
  13511. //
  13512. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  13513. //
  13514. // Since p2 = f mod 2^-e < 2^-e,
  13515. //
  13516. // -e <= 60 or e >= -60 := alpha
  13517. constexpr int kAlpha = -60;
  13518. constexpr int kGamma = -32;
  13519. struct cached_power // c = f * 2^e ~= 10^k
  13520. {
  13521. std::uint64_t f;
  13522. int e;
  13523. int k;
  13524. };
  13525. /*!
  13526. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  13527. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  13528. satisfies (Definition 3.2 from [1])
  13529. alpha <= e_c + e + q <= gamma.
  13530. */
  13531. inline cached_power get_cached_power_for_binary_exponent(int e)
  13532. {
  13533. // Now
  13534. //
  13535. // alpha <= e_c + e + q <= gamma (1)
  13536. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  13537. //
  13538. // and since the c's are normalized, 2^(q-1) <= f_c,
  13539. //
  13540. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  13541. // ==> 2^(alpha - e - 1) <= c
  13542. //
  13543. // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
  13544. //
  13545. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  13546. // = ceil( (alpha - e - 1) * log_10(2) )
  13547. //
  13548. // From the paper:
  13549. // "In theory the result of the procedure could be wrong since c is rounded,
  13550. // and the computation itself is approximated [...]. In practice, however,
  13551. // this simple function is sufficient."
  13552. //
  13553. // For IEEE double precision floating-point numbers converted into
  13554. // normalized diyfp's w = f * 2^e, with q = 64,
  13555. //
  13556. // e >= -1022 (min IEEE exponent)
  13557. // -52 (p - 1)
  13558. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  13559. // -11 (normalize the diyfp)
  13560. // = -1137
  13561. //
  13562. // and
  13563. //
  13564. // e <= +1023 (max IEEE exponent)
  13565. // -52 (p - 1)
  13566. // -11 (normalize the diyfp)
  13567. // = 960
  13568. //
  13569. // This binary exponent range [-1137,960] results in a decimal exponent
  13570. // range [-307,324]. One does not need to store a cached power for each
  13571. // k in this range. For each such k it suffices to find a cached power
  13572. // such that the exponent of the product lies in [alpha,gamma].
  13573. // This implies that the difference of the decimal exponents of adjacent
  13574. // table entries must be less than or equal to
  13575. //
  13576. // floor( (gamma - alpha) * log_10(2) ) = 8.
  13577. //
  13578. // (A smaller distance gamma-alpha would require a larger table.)
  13579. // NB:
  13580. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  13581. constexpr int kCachedPowersMinDecExp = -300;
  13582. constexpr int kCachedPowersDecStep = 8;
  13583. static constexpr std::array<cached_power, 79> kCachedPowers =
  13584. {
  13585. {
  13586. { 0xAB70FE17C79AC6CA, -1060, -300 },
  13587. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  13588. { 0xBE5691EF416BD60C, -1007, -284 },
  13589. { 0x8DD01FAD907FFC3C, -980, -276 },
  13590. { 0xD3515C2831559A83, -954, -268 },
  13591. { 0x9D71AC8FADA6C9B5, -927, -260 },
  13592. { 0xEA9C227723EE8BCB, -901, -252 },
  13593. { 0xAECC49914078536D, -874, -244 },
  13594. { 0x823C12795DB6CE57, -847, -236 },
  13595. { 0xC21094364DFB5637, -821, -228 },
  13596. { 0x9096EA6F3848984F, -794, -220 },
  13597. { 0xD77485CB25823AC7, -768, -212 },
  13598. { 0xA086CFCD97BF97F4, -741, -204 },
  13599. { 0xEF340A98172AACE5, -715, -196 },
  13600. { 0xB23867FB2A35B28E, -688, -188 },
  13601. { 0x84C8D4DFD2C63F3B, -661, -180 },
  13602. { 0xC5DD44271AD3CDBA, -635, -172 },
  13603. { 0x936B9FCEBB25C996, -608, -164 },
  13604. { 0xDBAC6C247D62A584, -582, -156 },
  13605. { 0xA3AB66580D5FDAF6, -555, -148 },
  13606. { 0xF3E2F893DEC3F126, -529, -140 },
  13607. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  13608. { 0x87625F056C7C4A8B, -475, -124 },
  13609. { 0xC9BCFF6034C13053, -449, -116 },
  13610. { 0x964E858C91BA2655, -422, -108 },
  13611. { 0xDFF9772470297EBD, -396, -100 },
  13612. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  13613. { 0xF8A95FCF88747D94, -343, -84 },
  13614. { 0xB94470938FA89BCF, -316, -76 },
  13615. { 0x8A08F0F8BF0F156B, -289, -68 },
  13616. { 0xCDB02555653131B6, -263, -60 },
  13617. { 0x993FE2C6D07B7FAC, -236, -52 },
  13618. { 0xE45C10C42A2B3B06, -210, -44 },
  13619. { 0xAA242499697392D3, -183, -36 },
  13620. { 0xFD87B5F28300CA0E, -157, -28 },
  13621. { 0xBCE5086492111AEB, -130, -20 },
  13622. { 0x8CBCCC096F5088CC, -103, -12 },
  13623. { 0xD1B71758E219652C, -77, -4 },
  13624. { 0x9C40000000000000, -50, 4 },
  13625. { 0xE8D4A51000000000, -24, 12 },
  13626. { 0xAD78EBC5AC620000, 3, 20 },
  13627. { 0x813F3978F8940984, 30, 28 },
  13628. { 0xC097CE7BC90715B3, 56, 36 },
  13629. { 0x8F7E32CE7BEA5C70, 83, 44 },
  13630. { 0xD5D238A4ABE98068, 109, 52 },
  13631. { 0x9F4F2726179A2245, 136, 60 },
  13632. { 0xED63A231D4C4FB27, 162, 68 },
  13633. { 0xB0DE65388CC8ADA8, 189, 76 },
  13634. { 0x83C7088E1AAB65DB, 216, 84 },
  13635. { 0xC45D1DF942711D9A, 242, 92 },
  13636. { 0x924D692CA61BE758, 269, 100 },
  13637. { 0xDA01EE641A708DEA, 295, 108 },
  13638. { 0xA26DA3999AEF774A, 322, 116 },
  13639. { 0xF209787BB47D6B85, 348, 124 },
  13640. { 0xB454E4A179DD1877, 375, 132 },
  13641. { 0x865B86925B9BC5C2, 402, 140 },
  13642. { 0xC83553C5C8965D3D, 428, 148 },
  13643. { 0x952AB45CFA97A0B3, 455, 156 },
  13644. { 0xDE469FBD99A05FE3, 481, 164 },
  13645. { 0xA59BC234DB398C25, 508, 172 },
  13646. { 0xF6C69A72A3989F5C, 534, 180 },
  13647. { 0xB7DCBF5354E9BECE, 561, 188 },
  13648. { 0x88FCF317F22241E2, 588, 196 },
  13649. { 0xCC20CE9BD35C78A5, 614, 204 },
  13650. { 0x98165AF37B2153DF, 641, 212 },
  13651. { 0xE2A0B5DC971F303A, 667, 220 },
  13652. { 0xA8D9D1535CE3B396, 694, 228 },
  13653. { 0xFB9B7CD9A4A7443C, 720, 236 },
  13654. { 0xBB764C4CA7A44410, 747, 244 },
  13655. { 0x8BAB8EEFB6409C1A, 774, 252 },
  13656. { 0xD01FEF10A657842C, 800, 260 },
  13657. { 0x9B10A4E5E9913129, 827, 268 },
  13658. { 0xE7109BFBA19C0C9D, 853, 276 },
  13659. { 0xAC2820D9623BF429, 880, 284 },
  13660. { 0x80444B5E7AA7CF85, 907, 292 },
  13661. { 0xBF21E44003ACDD2D, 933, 300 },
  13662. { 0x8E679C2F5E44FF8F, 960, 308 },
  13663. { 0xD433179D9C8CB841, 986, 316 },
  13664. { 0x9E19DB92B4E31BA9, 1013, 324 },
  13665. }
  13666. };
  13667. // This computation gives exactly the same results for k as
  13668. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  13669. // for |e| <= 1500, but doesn't require floating-point operations.
  13670. // NB: log_10(2) ~= 78913 / 2^18
  13671. JSON_ASSERT(e >= -1500);
  13672. JSON_ASSERT(e <= 1500);
  13673. const int f = kAlpha - e - 1;
  13674. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  13675. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  13676. JSON_ASSERT(index >= 0);
  13677. JSON_ASSERT(static_cast<std::size_t>(index) < kCachedPowers.size());
  13678. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  13679. JSON_ASSERT(kAlpha <= cached.e + e + 64);
  13680. JSON_ASSERT(kGamma >= cached.e + e + 64);
  13681. return cached;
  13682. }
  13683. /*!
  13684. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  13685. For n == 0, returns 1 and sets pow10 := 1.
  13686. */
  13687. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  13688. {
  13689. // LCOV_EXCL_START
  13690. if (n >= 1000000000)
  13691. {
  13692. pow10 = 1000000000;
  13693. return 10;
  13694. }
  13695. // LCOV_EXCL_STOP
  13696. if (n >= 100000000)
  13697. {
  13698. pow10 = 100000000;
  13699. return 9;
  13700. }
  13701. if (n >= 10000000)
  13702. {
  13703. pow10 = 10000000;
  13704. return 8;
  13705. }
  13706. if (n >= 1000000)
  13707. {
  13708. pow10 = 1000000;
  13709. return 7;
  13710. }
  13711. if (n >= 100000)
  13712. {
  13713. pow10 = 100000;
  13714. return 6;
  13715. }
  13716. if (n >= 10000)
  13717. {
  13718. pow10 = 10000;
  13719. return 5;
  13720. }
  13721. if (n >= 1000)
  13722. {
  13723. pow10 = 1000;
  13724. return 4;
  13725. }
  13726. if (n >= 100)
  13727. {
  13728. pow10 = 100;
  13729. return 3;
  13730. }
  13731. if (n >= 10)
  13732. {
  13733. pow10 = 10;
  13734. return 2;
  13735. }
  13736. pow10 = 1;
  13737. return 1;
  13738. }
  13739. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  13740. std::uint64_t rest, std::uint64_t ten_k)
  13741. {
  13742. JSON_ASSERT(len >= 1);
  13743. JSON_ASSERT(dist <= delta);
  13744. JSON_ASSERT(rest <= delta);
  13745. JSON_ASSERT(ten_k > 0);
  13746. // <--------------------------- delta ---->
  13747. // <---- dist --------->
  13748. // --------------[------------------+-------------------]--------------
  13749. // M- w M+
  13750. //
  13751. // ten_k
  13752. // <------>
  13753. // <---- rest ---->
  13754. // --------------[------------------+----+--------------]--------------
  13755. // w V
  13756. // = buf * 10^k
  13757. //
  13758. // ten_k represents a unit-in-the-last-place in the decimal representation
  13759. // stored in buf.
  13760. // Decrement buf by ten_k while this takes buf closer to w.
  13761. // The tests are written in this order to avoid overflow in unsigned
  13762. // integer arithmetic.
  13763. while (rest < dist
  13764. && delta - rest >= ten_k
  13765. && (rest + ten_k < dist || dist - rest > rest + ten_k - dist))
  13766. {
  13767. JSON_ASSERT(buf[len - 1] != '0');
  13768. buf[len - 1]--;
  13769. rest += ten_k;
  13770. }
  13771. }
  13772. /*!
  13773. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  13774. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  13775. */
  13776. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  13777. diyfp M_minus, diyfp w, diyfp M_plus)
  13778. {
  13779. static_assert(kAlpha >= -60, "internal error");
  13780. static_assert(kGamma <= -32, "internal error");
  13781. // Generates the digits (and the exponent) of a decimal floating-point
  13782. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  13783. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  13784. //
  13785. // <--------------------------- delta ---->
  13786. // <---- dist --------->
  13787. // --------------[------------------+-------------------]--------------
  13788. // M- w M+
  13789. //
  13790. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  13791. // V is in [M-,M+].
  13792. JSON_ASSERT(M_plus.e >= kAlpha);
  13793. JSON_ASSERT(M_plus.e <= kGamma);
  13794. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  13795. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  13796. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  13797. //
  13798. // M+ = f * 2^e
  13799. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  13800. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  13801. // = p1 + p2 * 2^e
  13802. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  13803. 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.)
  13804. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  13805. // 1)
  13806. //
  13807. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  13808. JSON_ASSERT(p1 > 0);
  13809. std::uint32_t pow10{};
  13810. const int k = find_largest_pow10(p1, pow10);
  13811. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  13812. //
  13813. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  13814. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  13815. //
  13816. // M+ = p1 + p2 * 2^e
  13817. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  13818. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  13819. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  13820. //
  13821. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  13822. //
  13823. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  13824. //
  13825. // but stop as soon as
  13826. //
  13827. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  13828. int n = k;
  13829. while (n > 0)
  13830. {
  13831. // Invariants:
  13832. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  13833. // pow10 = 10^(n-1) <= p1 < 10^n
  13834. //
  13835. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  13836. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  13837. //
  13838. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  13839. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  13840. //
  13841. JSON_ASSERT(d <= 9);
  13842. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  13843. //
  13844. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  13845. //
  13846. p1 = r;
  13847. n--;
  13848. //
  13849. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  13850. // pow10 = 10^n
  13851. //
  13852. // Now check if enough digits have been generated.
  13853. // Compute
  13854. //
  13855. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  13856. //
  13857. // Note:
  13858. // Since rest and delta share the same exponent e, it suffices to
  13859. // compare the significands.
  13860. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  13861. if (rest <= delta)
  13862. {
  13863. // V = buffer * 10^n, with M- <= V <= M+.
  13864. decimal_exponent += n;
  13865. // We may now just stop. But instead look if the buffer could be
  13866. // decremented to bring V closer to w.
  13867. //
  13868. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  13869. // The rounding procedure works with diyfp's with an implicit
  13870. // exponent of e.
  13871. //
  13872. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  13873. //
  13874. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  13875. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  13876. return;
  13877. }
  13878. pow10 /= 10;
  13879. //
  13880. // pow10 = 10^(n-1) <= p1 < 10^n
  13881. // Invariants restored.
  13882. }
  13883. // 2)
  13884. //
  13885. // The digits of the integral part have been generated:
  13886. //
  13887. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  13888. // = buffer + p2 * 2^e
  13889. //
  13890. // Now generate the digits of the fractional part p2 * 2^e.
  13891. //
  13892. // Note:
  13893. // No decimal point is generated: the exponent is adjusted instead.
  13894. //
  13895. // p2 actually represents the fraction
  13896. //
  13897. // p2 * 2^e
  13898. // = p2 / 2^-e
  13899. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  13900. //
  13901. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  13902. //
  13903. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  13904. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  13905. //
  13906. // using
  13907. //
  13908. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  13909. // = ( d) * 2^-e + ( r)
  13910. //
  13911. // or
  13912. // 10^m * p2 * 2^e = d + r * 2^e
  13913. //
  13914. // i.e.
  13915. //
  13916. // M+ = buffer + p2 * 2^e
  13917. // = buffer + 10^-m * (d + r * 2^e)
  13918. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  13919. //
  13920. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  13921. JSON_ASSERT(p2 > delta);
  13922. int m = 0;
  13923. for (;;)
  13924. {
  13925. // Invariant:
  13926. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  13927. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  13928. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  13929. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  13930. //
  13931. JSON_ASSERT(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  13932. p2 *= 10;
  13933. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  13934. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  13935. //
  13936. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  13937. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  13938. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  13939. //
  13940. JSON_ASSERT(d <= 9);
  13941. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  13942. //
  13943. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  13944. //
  13945. p2 = r;
  13946. m++;
  13947. //
  13948. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  13949. // Invariant restored.
  13950. // Check if enough digits have been generated.
  13951. //
  13952. // 10^-m * p2 * 2^e <= delta * 2^e
  13953. // p2 * 2^e <= 10^m * delta * 2^e
  13954. // p2 <= 10^m * delta
  13955. delta *= 10;
  13956. dist *= 10;
  13957. if (p2 <= delta)
  13958. {
  13959. break;
  13960. }
  13961. }
  13962. // V = buffer * 10^-m, with M- <= V <= M+.
  13963. decimal_exponent -= m;
  13964. // 1 ulp in the decimal representation is now 10^-m.
  13965. // Since delta and dist are now scaled by 10^m, we need to do the
  13966. // same with ulp in order to keep the units in sync.
  13967. //
  13968. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  13969. //
  13970. const std::uint64_t ten_m = one.f;
  13971. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  13972. // By construction this algorithm generates the shortest possible decimal
  13973. // number (Loitsch, Theorem 6.2) which rounds back to w.
  13974. // For an input number of precision p, at least
  13975. //
  13976. // N = 1 + ceil(p * log_10(2))
  13977. //
  13978. // decimal digits are sufficient to identify all binary floating-point
  13979. // numbers (Matula, "In-and-Out conversions").
  13980. // This implies that the algorithm does not produce more than N decimal
  13981. // digits.
  13982. //
  13983. // N = 17 for p = 53 (IEEE double precision)
  13984. // N = 9 for p = 24 (IEEE single precision)
  13985. }
  13986. /*!
  13987. v = buf * 10^decimal_exponent
  13988. len is the length of the buffer (number of decimal digits)
  13989. The buffer must be large enough, i.e. >= max_digits10.
  13990. */
  13991. JSON_HEDLEY_NON_NULL(1)
  13992. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  13993. diyfp m_minus, diyfp v, diyfp m_plus)
  13994. {
  13995. JSON_ASSERT(m_plus.e == m_minus.e);
  13996. JSON_ASSERT(m_plus.e == v.e);
  13997. // --------(-----------------------+-----------------------)-------- (A)
  13998. // m- v m+
  13999. //
  14000. // --------------------(-----------+-----------------------)-------- (B)
  14001. // m- v m+
  14002. //
  14003. // First scale v (and m- and m+) such that the exponent is in the range
  14004. // [alpha, gamma].
  14005. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  14006. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  14007. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  14008. const diyfp w = diyfp::mul(v, c_minus_k);
  14009. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  14010. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  14011. // ----(---+---)---------------(---+---)---------------(---+---)----
  14012. // w- w w+
  14013. // = c*m- = c*v = c*m+
  14014. //
  14015. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  14016. // w+ are now off by a small amount.
  14017. // In fact:
  14018. //
  14019. // w - v * 10^k < 1 ulp
  14020. //
  14021. // To account for this inaccuracy, add resp. subtract 1 ulp.
  14022. //
  14023. // --------+---[---------------(---+---)---------------]---+--------
  14024. // w- M- w M+ w+
  14025. //
  14026. // Now any number in [M-, M+] (bounds included) will round to w when input,
  14027. // regardless of how the input rounding algorithm breaks ties.
  14028. //
  14029. // And digit_gen generates the shortest possible such number in [M-, M+].
  14030. // Note that this does not mean that Grisu2 always generates the shortest
  14031. // possible number in the interval (m-, m+).
  14032. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  14033. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  14034. decimal_exponent = -cached.k; // = -(-k) = k
  14035. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  14036. }
  14037. /*!
  14038. v = buf * 10^decimal_exponent
  14039. len is the length of the buffer (number of decimal digits)
  14040. The buffer must be large enough, i.e. >= max_digits10.
  14041. */
  14042. template<typename FloatType>
  14043. JSON_HEDLEY_NON_NULL(1)
  14044. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  14045. {
  14046. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  14047. "internal error: not enough precision");
  14048. JSON_ASSERT(std::isfinite(value));
  14049. JSON_ASSERT(value > 0);
  14050. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  14051. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  14052. // decimal representations are not exactly "short".
  14053. //
  14054. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  14055. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  14056. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  14057. // does.
  14058. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  14059. // representation using the corresponding std::from_chars function recovers value exactly". That
  14060. // indicates that single precision floating-point numbers should be recovered using
  14061. // 'std::strtof'.
  14062. //
  14063. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  14064. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  14065. // value is off by 1 ulp.
  14066. #if 0
  14067. const boundaries w = compute_boundaries(static_cast<double>(value));
  14068. #else
  14069. const boundaries w = compute_boundaries(value);
  14070. #endif
  14071. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  14072. }
  14073. /*!
  14074. @brief appends a decimal representation of e to buf
  14075. @return a pointer to the element following the exponent.
  14076. @pre -1000 < e < 1000
  14077. */
  14078. JSON_HEDLEY_NON_NULL(1)
  14079. JSON_HEDLEY_RETURNS_NON_NULL
  14080. inline char* append_exponent(char* buf, int e)
  14081. {
  14082. JSON_ASSERT(e > -1000);
  14083. JSON_ASSERT(e < 1000);
  14084. if (e < 0)
  14085. {
  14086. e = -e;
  14087. *buf++ = '-';
  14088. }
  14089. else
  14090. {
  14091. *buf++ = '+';
  14092. }
  14093. auto k = static_cast<std::uint32_t>(e);
  14094. if (k < 10)
  14095. {
  14096. // Always print at least two digits in the exponent.
  14097. // This is for compatibility with printf("%g").
  14098. *buf++ = '0';
  14099. *buf++ = static_cast<char>('0' + k);
  14100. }
  14101. else if (k < 100)
  14102. {
  14103. *buf++ = static_cast<char>('0' + k / 10);
  14104. k %= 10;
  14105. *buf++ = static_cast<char>('0' + k);
  14106. }
  14107. else
  14108. {
  14109. *buf++ = static_cast<char>('0' + k / 100);
  14110. k %= 100;
  14111. *buf++ = static_cast<char>('0' + k / 10);
  14112. k %= 10;
  14113. *buf++ = static_cast<char>('0' + k);
  14114. }
  14115. return buf;
  14116. }
  14117. /*!
  14118. @brief prettify v = buf * 10^decimal_exponent
  14119. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  14120. notation. Otherwise it will be printed in exponential notation.
  14121. @pre min_exp < 0
  14122. @pre max_exp > 0
  14123. */
  14124. JSON_HEDLEY_NON_NULL(1)
  14125. JSON_HEDLEY_RETURNS_NON_NULL
  14126. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  14127. int min_exp, int max_exp)
  14128. {
  14129. JSON_ASSERT(min_exp < 0);
  14130. JSON_ASSERT(max_exp > 0);
  14131. const int k = len;
  14132. const int n = len + decimal_exponent;
  14133. // v = buf * 10^(n-k)
  14134. // k is the length of the buffer (number of decimal digits)
  14135. // n is the position of the decimal point relative to the start of the buffer.
  14136. if (k <= n && n <= max_exp)
  14137. {
  14138. // digits[000]
  14139. // len <= max_exp + 2
  14140. std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k));
  14141. // Make it look like a floating-point number (#362, #378)
  14142. buf[n + 0] = '.';
  14143. buf[n + 1] = '0';
  14144. return buf + (static_cast<size_t>(n) + 2);
  14145. }
  14146. if (0 < n && n <= max_exp)
  14147. {
  14148. // dig.its
  14149. // len <= max_digits10 + 1
  14150. JSON_ASSERT(k > n);
  14151. std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n));
  14152. buf[n] = '.';
  14153. return buf + (static_cast<size_t>(k) + 1U);
  14154. }
  14155. if (min_exp < n && n <= 0)
  14156. {
  14157. // 0.[000]digits
  14158. // len <= 2 + (-min_exp - 1) + max_digits10
  14159. std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k));
  14160. buf[0] = '0';
  14161. buf[1] = '.';
  14162. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  14163. return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k));
  14164. }
  14165. if (k == 1)
  14166. {
  14167. // dE+123
  14168. // len <= 1 + 5
  14169. buf += 1;
  14170. }
  14171. else
  14172. {
  14173. // d.igitsE+123
  14174. // len <= max_digits10 + 1 + 5
  14175. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1);
  14176. buf[1] = '.';
  14177. buf += 1 + static_cast<size_t>(k);
  14178. }
  14179. *buf++ = 'e';
  14180. return append_exponent(buf, n - 1);
  14181. }
  14182. } // namespace dtoa_impl
  14183. /*!
  14184. @brief generates a decimal representation of the floating-point number value in [first, last).
  14185. The format of the resulting decimal representation is similar to printf's %g
  14186. format. Returns an iterator pointing past-the-end of the decimal representation.
  14187. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  14188. @note The buffer must be large enough.
  14189. @note The result is NOT null-terminated.
  14190. */
  14191. template<typename FloatType>
  14192. JSON_HEDLEY_NON_NULL(1, 2)
  14193. JSON_HEDLEY_RETURNS_NON_NULL
  14194. char* to_chars(char* first, const char* last, FloatType value)
  14195. {
  14196. static_cast<void>(last); // maybe unused - fix warning
  14197. JSON_ASSERT(std::isfinite(value));
  14198. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  14199. if (std::signbit(value))
  14200. {
  14201. value = -value;
  14202. *first++ = '-';
  14203. }
  14204. #ifdef __GNUC__
  14205. #pragma GCC diagnostic push
  14206. #pragma GCC diagnostic ignored "-Wfloat-equal"
  14207. #endif
  14208. if (value == 0) // +-0
  14209. {
  14210. *first++ = '0';
  14211. // Make it look like a floating-point number (#362, #378)
  14212. *first++ = '.';
  14213. *first++ = '0';
  14214. return first;
  14215. }
  14216. #ifdef __GNUC__
  14217. #pragma GCC diagnostic pop
  14218. #endif
  14219. JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10);
  14220. // Compute v = buffer * 10^decimal_exponent.
  14221. // The decimal digits are stored in the buffer, which needs to be interpreted
  14222. // as an unsigned decimal integer.
  14223. // len is the length of the buffer, i.e. the number of decimal digits.
  14224. int len = 0;
  14225. int decimal_exponent = 0;
  14226. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  14227. JSON_ASSERT(len <= std::numeric_limits<FloatType>::max_digits10);
  14228. // Format the buffer like printf("%.*g", prec, value)
  14229. constexpr int kMinExp = -4;
  14230. // Use digits10 here to increase compatibility with version 2.
  14231. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  14232. JSON_ASSERT(last - first >= kMaxExp + 2);
  14233. JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  14234. JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  14235. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  14236. }
  14237. } // namespace detail
  14238. } // namespace nlohmann
  14239. // #include <nlohmann/detail/exceptions.hpp>
  14240. // #include <nlohmann/detail/macro_scope.hpp>
  14241. // #include <nlohmann/detail/meta/cpp_future.hpp>
  14242. // #include <nlohmann/detail/output/binary_writer.hpp>
  14243. // #include <nlohmann/detail/output/output_adapters.hpp>
  14244. // #include <nlohmann/detail/value_t.hpp>
  14245. namespace nlohmann
  14246. {
  14247. namespace detail
  14248. {
  14249. ///////////////////
  14250. // serialization //
  14251. ///////////////////
  14252. /// how to treat decoding errors
  14253. enum class error_handler_t
  14254. {
  14255. strict, ///< throw a type_error exception in case of invalid UTF-8
  14256. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  14257. ignore ///< ignore invalid UTF-8 sequences
  14258. };
  14259. template<typename BasicJsonType>
  14260. class serializer
  14261. {
  14262. using string_t = typename BasicJsonType::string_t;
  14263. using number_float_t = typename BasicJsonType::number_float_t;
  14264. using number_integer_t = typename BasicJsonType::number_integer_t;
  14265. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  14266. using binary_char_t = typename BasicJsonType::binary_t::value_type;
  14267. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  14268. static constexpr std::uint8_t UTF8_REJECT = 1;
  14269. public:
  14270. /*!
  14271. @param[in] s output stream to serialize to
  14272. @param[in] ichar indentation character to use
  14273. @param[in] error_handler_ how to react on decoding errors
  14274. */
  14275. serializer(output_adapter_t<char> s, const char ichar,
  14276. error_handler_t error_handler_ = error_handler_t::strict)
  14277. : o(std::move(s))
  14278. , loc(std::localeconv())
  14279. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->thousands_sep)))
  14280. , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->decimal_point)))
  14281. , indent_char(ichar)
  14282. , indent_string(512, indent_char)
  14283. , error_handler(error_handler_)
  14284. {}
  14285. // delete because of pointer members
  14286. serializer(const serializer&) = delete;
  14287. serializer& operator=(const serializer&) = delete;
  14288. serializer(serializer&&) = delete;
  14289. serializer& operator=(serializer&&) = delete;
  14290. ~serializer() = default;
  14291. /*!
  14292. @brief internal implementation of the serialization function
  14293. This function is called by the public member function dump and organizes
  14294. the serialization internally. The indentation level is propagated as
  14295. additional parameter. In case of arrays and objects, the function is
  14296. called recursively.
  14297. - strings and object keys are escaped using `escape_string()`
  14298. - integer numbers are converted implicitly via `operator<<`
  14299. - floating-point numbers are converted to a string using `"%g"` format
  14300. - binary values are serialized as objects containing the subtype and the
  14301. byte array
  14302. @param[in] val value to serialize
  14303. @param[in] pretty_print whether the output shall be pretty-printed
  14304. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  14305. in the output are escaped with `\uXXXX` sequences, and the result consists
  14306. of ASCII characters only.
  14307. @param[in] indent_step the indent level
  14308. @param[in] current_indent the current indent level (only used internally)
  14309. */
  14310. void dump(const BasicJsonType& val,
  14311. const bool pretty_print,
  14312. const bool ensure_ascii,
  14313. const unsigned int indent_step,
  14314. const unsigned int current_indent = 0)
  14315. {
  14316. switch (val.m_type)
  14317. {
  14318. case value_t::object:
  14319. {
  14320. if (val.m_value.object->empty())
  14321. {
  14322. o->write_characters("{}", 2);
  14323. return;
  14324. }
  14325. if (pretty_print)
  14326. {
  14327. o->write_characters("{\n", 2);
  14328. // variable to hold indentation for recursive calls
  14329. const auto new_indent = current_indent + indent_step;
  14330. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  14331. {
  14332. indent_string.resize(indent_string.size() * 2, ' ');
  14333. }
  14334. // first n-1 elements
  14335. auto i = val.m_value.object->cbegin();
  14336. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  14337. {
  14338. o->write_characters(indent_string.c_str(), new_indent);
  14339. o->write_character('\"');
  14340. dump_escaped(i->first, ensure_ascii);
  14341. o->write_characters("\": ", 3);
  14342. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  14343. o->write_characters(",\n", 2);
  14344. }
  14345. // last element
  14346. JSON_ASSERT(i != val.m_value.object->cend());
  14347. JSON_ASSERT(std::next(i) == val.m_value.object->cend());
  14348. o->write_characters(indent_string.c_str(), new_indent);
  14349. o->write_character('\"');
  14350. dump_escaped(i->first, ensure_ascii);
  14351. o->write_characters("\": ", 3);
  14352. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  14353. o->write_character('\n');
  14354. o->write_characters(indent_string.c_str(), current_indent);
  14355. o->write_character('}');
  14356. }
  14357. else
  14358. {
  14359. o->write_character('{');
  14360. // first n-1 elements
  14361. auto i = val.m_value.object->cbegin();
  14362. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  14363. {
  14364. o->write_character('\"');
  14365. dump_escaped(i->first, ensure_ascii);
  14366. o->write_characters("\":", 2);
  14367. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  14368. o->write_character(',');
  14369. }
  14370. // last element
  14371. JSON_ASSERT(i != val.m_value.object->cend());
  14372. JSON_ASSERT(std::next(i) == val.m_value.object->cend());
  14373. o->write_character('\"');
  14374. dump_escaped(i->first, ensure_ascii);
  14375. o->write_characters("\":", 2);
  14376. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  14377. o->write_character('}');
  14378. }
  14379. return;
  14380. }
  14381. case value_t::array:
  14382. {
  14383. if (val.m_value.array->empty())
  14384. {
  14385. o->write_characters("[]", 2);
  14386. return;
  14387. }
  14388. if (pretty_print)
  14389. {
  14390. o->write_characters("[\n", 2);
  14391. // variable to hold indentation for recursive calls
  14392. const auto new_indent = current_indent + indent_step;
  14393. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  14394. {
  14395. indent_string.resize(indent_string.size() * 2, ' ');
  14396. }
  14397. // first n-1 elements
  14398. for (auto i = val.m_value.array->cbegin();
  14399. i != val.m_value.array->cend() - 1; ++i)
  14400. {
  14401. o->write_characters(indent_string.c_str(), new_indent);
  14402. dump(*i, true, ensure_ascii, indent_step, new_indent);
  14403. o->write_characters(",\n", 2);
  14404. }
  14405. // last element
  14406. JSON_ASSERT(!val.m_value.array->empty());
  14407. o->write_characters(indent_string.c_str(), new_indent);
  14408. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  14409. o->write_character('\n');
  14410. o->write_characters(indent_string.c_str(), current_indent);
  14411. o->write_character(']');
  14412. }
  14413. else
  14414. {
  14415. o->write_character('[');
  14416. // first n-1 elements
  14417. for (auto i = val.m_value.array->cbegin();
  14418. i != val.m_value.array->cend() - 1; ++i)
  14419. {
  14420. dump(*i, false, ensure_ascii, indent_step, current_indent);
  14421. o->write_character(',');
  14422. }
  14423. // last element
  14424. JSON_ASSERT(!val.m_value.array->empty());
  14425. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  14426. o->write_character(']');
  14427. }
  14428. return;
  14429. }
  14430. case value_t::string:
  14431. {
  14432. o->write_character('\"');
  14433. dump_escaped(*val.m_value.string, ensure_ascii);
  14434. o->write_character('\"');
  14435. return;
  14436. }
  14437. case value_t::binary:
  14438. {
  14439. if (pretty_print)
  14440. {
  14441. o->write_characters("{\n", 2);
  14442. // variable to hold indentation for recursive calls
  14443. const auto new_indent = current_indent + indent_step;
  14444. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  14445. {
  14446. indent_string.resize(indent_string.size() * 2, ' ');
  14447. }
  14448. o->write_characters(indent_string.c_str(), new_indent);
  14449. o->write_characters("\"bytes\": [", 10);
  14450. if (!val.m_value.binary->empty())
  14451. {
  14452. for (auto i = val.m_value.binary->cbegin();
  14453. i != val.m_value.binary->cend() - 1; ++i)
  14454. {
  14455. dump_integer(*i);
  14456. o->write_characters(", ", 2);
  14457. }
  14458. dump_integer(val.m_value.binary->back());
  14459. }
  14460. o->write_characters("],\n", 3);
  14461. o->write_characters(indent_string.c_str(), new_indent);
  14462. o->write_characters("\"subtype\": ", 11);
  14463. if (val.m_value.binary->has_subtype())
  14464. {
  14465. dump_integer(val.m_value.binary->subtype());
  14466. }
  14467. else
  14468. {
  14469. o->write_characters("null", 4);
  14470. }
  14471. o->write_character('\n');
  14472. o->write_characters(indent_string.c_str(), current_indent);
  14473. o->write_character('}');
  14474. }
  14475. else
  14476. {
  14477. o->write_characters("{\"bytes\":[", 10);
  14478. if (!val.m_value.binary->empty())
  14479. {
  14480. for (auto i = val.m_value.binary->cbegin();
  14481. i != val.m_value.binary->cend() - 1; ++i)
  14482. {
  14483. dump_integer(*i);
  14484. o->write_character(',');
  14485. }
  14486. dump_integer(val.m_value.binary->back());
  14487. }
  14488. o->write_characters("],\"subtype\":", 12);
  14489. if (val.m_value.binary->has_subtype())
  14490. {
  14491. dump_integer(val.m_value.binary->subtype());
  14492. o->write_character('}');
  14493. }
  14494. else
  14495. {
  14496. o->write_characters("null}", 5);
  14497. }
  14498. }
  14499. return;
  14500. }
  14501. case value_t::boolean:
  14502. {
  14503. if (val.m_value.boolean)
  14504. {
  14505. o->write_characters("true", 4);
  14506. }
  14507. else
  14508. {
  14509. o->write_characters("false", 5);
  14510. }
  14511. return;
  14512. }
  14513. case value_t::number_integer:
  14514. {
  14515. dump_integer(val.m_value.number_integer);
  14516. return;
  14517. }
  14518. case value_t::number_unsigned:
  14519. {
  14520. dump_integer(val.m_value.number_unsigned);
  14521. return;
  14522. }
  14523. case value_t::number_float:
  14524. {
  14525. dump_float(val.m_value.number_float);
  14526. return;
  14527. }
  14528. case value_t::discarded:
  14529. {
  14530. o->write_characters("<discarded>", 11);
  14531. return;
  14532. }
  14533. case value_t::null:
  14534. {
  14535. o->write_characters("null", 4);
  14536. return;
  14537. }
  14538. default: // LCOV_EXCL_LINE
  14539. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14540. }
  14541. }
  14542. JSON_PRIVATE_UNLESS_TESTED:
  14543. /*!
  14544. @brief dump escaped string
  14545. Escape a string by replacing certain special characters by a sequence of an
  14546. escape character (backslash) and another character and other control
  14547. characters by a sequence of "\u" followed by a four-digit hex
  14548. representation. The escaped string is written to output stream @a o.
  14549. @param[in] s the string to escape
  14550. @param[in] ensure_ascii whether to escape non-ASCII characters with
  14551. \uXXXX sequences
  14552. @complexity Linear in the length of string @a s.
  14553. */
  14554. void dump_escaped(const string_t& s, const bool ensure_ascii)
  14555. {
  14556. std::uint32_t codepoint{};
  14557. std::uint8_t state = UTF8_ACCEPT;
  14558. std::size_t bytes = 0; // number of bytes written to string_buffer
  14559. // number of bytes written at the point of the last valid byte
  14560. std::size_t bytes_after_last_accept = 0;
  14561. std::size_t undumped_chars = 0;
  14562. for (std::size_t i = 0; i < s.size(); ++i)
  14563. {
  14564. const auto byte = static_cast<std::uint8_t>(s[i]);
  14565. switch (decode(state, codepoint, byte))
  14566. {
  14567. case UTF8_ACCEPT: // decode found a new code point
  14568. {
  14569. switch (codepoint)
  14570. {
  14571. case 0x08: // backspace
  14572. {
  14573. string_buffer[bytes++] = '\\';
  14574. string_buffer[bytes++] = 'b';
  14575. break;
  14576. }
  14577. case 0x09: // horizontal tab
  14578. {
  14579. string_buffer[bytes++] = '\\';
  14580. string_buffer[bytes++] = 't';
  14581. break;
  14582. }
  14583. case 0x0A: // newline
  14584. {
  14585. string_buffer[bytes++] = '\\';
  14586. string_buffer[bytes++] = 'n';
  14587. break;
  14588. }
  14589. case 0x0C: // formfeed
  14590. {
  14591. string_buffer[bytes++] = '\\';
  14592. string_buffer[bytes++] = 'f';
  14593. break;
  14594. }
  14595. case 0x0D: // carriage return
  14596. {
  14597. string_buffer[bytes++] = '\\';
  14598. string_buffer[bytes++] = 'r';
  14599. break;
  14600. }
  14601. case 0x22: // quotation mark
  14602. {
  14603. string_buffer[bytes++] = '\\';
  14604. string_buffer[bytes++] = '\"';
  14605. break;
  14606. }
  14607. case 0x5C: // reverse solidus
  14608. {
  14609. string_buffer[bytes++] = '\\';
  14610. string_buffer[bytes++] = '\\';
  14611. break;
  14612. }
  14613. default:
  14614. {
  14615. // escape control characters (0x00..0x1F) or, if
  14616. // ensure_ascii parameter is used, non-ASCII characters
  14617. if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F)))
  14618. {
  14619. if (codepoint <= 0xFFFF)
  14620. {
  14621. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14622. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  14623. static_cast<std::uint16_t>(codepoint));
  14624. bytes += 6;
  14625. }
  14626. else
  14627. {
  14628. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14629. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  14630. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  14631. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  14632. bytes += 12;
  14633. }
  14634. }
  14635. else
  14636. {
  14637. // copy byte to buffer (all previous bytes
  14638. // been copied have in default case above)
  14639. string_buffer[bytes++] = s[i];
  14640. }
  14641. break;
  14642. }
  14643. }
  14644. // write buffer and reset index; there must be 13 bytes
  14645. // left, as this is the maximal number of bytes to be
  14646. // written ("\uxxxx\uxxxx\0") for one code point
  14647. if (string_buffer.size() - bytes < 13)
  14648. {
  14649. o->write_characters(string_buffer.data(), bytes);
  14650. bytes = 0;
  14651. }
  14652. // remember the byte position of this accept
  14653. bytes_after_last_accept = bytes;
  14654. undumped_chars = 0;
  14655. break;
  14656. }
  14657. case UTF8_REJECT: // decode found invalid UTF-8 byte
  14658. {
  14659. switch (error_handler)
  14660. {
  14661. case error_handler_t::strict:
  14662. {
  14663. std::string sn(9, '\0');
  14664. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14665. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  14666. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn, BasicJsonType()));
  14667. }
  14668. case error_handler_t::ignore:
  14669. case error_handler_t::replace:
  14670. {
  14671. // in case we saw this character the first time, we
  14672. // would like to read it again, because the byte
  14673. // may be OK for itself, but just not OK for the
  14674. // previous sequence
  14675. if (undumped_chars > 0)
  14676. {
  14677. --i;
  14678. }
  14679. // reset length buffer to the last accepted index;
  14680. // thus removing/ignoring the invalid characters
  14681. bytes = bytes_after_last_accept;
  14682. if (error_handler == error_handler_t::replace)
  14683. {
  14684. // add a replacement character
  14685. if (ensure_ascii)
  14686. {
  14687. string_buffer[bytes++] = '\\';
  14688. string_buffer[bytes++] = 'u';
  14689. string_buffer[bytes++] = 'f';
  14690. string_buffer[bytes++] = 'f';
  14691. string_buffer[bytes++] = 'f';
  14692. string_buffer[bytes++] = 'd';
  14693. }
  14694. else
  14695. {
  14696. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  14697. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  14698. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  14699. }
  14700. // write buffer and reset index; there must be 13 bytes
  14701. // left, as this is the maximal number of bytes to be
  14702. // written ("\uxxxx\uxxxx\0") for one code point
  14703. if (string_buffer.size() - bytes < 13)
  14704. {
  14705. o->write_characters(string_buffer.data(), bytes);
  14706. bytes = 0;
  14707. }
  14708. bytes_after_last_accept = bytes;
  14709. }
  14710. undumped_chars = 0;
  14711. // continue processing the string
  14712. state = UTF8_ACCEPT;
  14713. break;
  14714. }
  14715. default: // LCOV_EXCL_LINE
  14716. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14717. }
  14718. break;
  14719. }
  14720. default: // decode found yet incomplete multi-byte code point
  14721. {
  14722. if (!ensure_ascii)
  14723. {
  14724. // code point will not be escaped - copy byte to buffer
  14725. string_buffer[bytes++] = s[i];
  14726. }
  14727. ++undumped_chars;
  14728. break;
  14729. }
  14730. }
  14731. }
  14732. // we finished processing the string
  14733. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  14734. {
  14735. // write buffer
  14736. if (bytes > 0)
  14737. {
  14738. o->write_characters(string_buffer.data(), bytes);
  14739. }
  14740. }
  14741. else
  14742. {
  14743. // we finish reading, but do not accept: string was incomplete
  14744. switch (error_handler)
  14745. {
  14746. case error_handler_t::strict:
  14747. {
  14748. std::string sn(9, '\0');
  14749. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14750. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  14751. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn, BasicJsonType()));
  14752. }
  14753. case error_handler_t::ignore:
  14754. {
  14755. // write all accepted bytes
  14756. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  14757. break;
  14758. }
  14759. case error_handler_t::replace:
  14760. {
  14761. // write all accepted bytes
  14762. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  14763. // add a replacement character
  14764. if (ensure_ascii)
  14765. {
  14766. o->write_characters("\\ufffd", 6);
  14767. }
  14768. else
  14769. {
  14770. o->write_characters("\xEF\xBF\xBD", 3);
  14771. }
  14772. break;
  14773. }
  14774. default: // LCOV_EXCL_LINE
  14775. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  14776. }
  14777. }
  14778. }
  14779. private:
  14780. /*!
  14781. @brief count digits
  14782. Count the number of decimal (base 10) digits for an input unsigned integer.
  14783. @param[in] x unsigned integer number to count its digits
  14784. @return number of decimal digits
  14785. */
  14786. inline unsigned int count_digits(number_unsigned_t x) noexcept
  14787. {
  14788. unsigned int n_digits = 1;
  14789. for (;;)
  14790. {
  14791. if (x < 10)
  14792. {
  14793. return n_digits;
  14794. }
  14795. if (x < 100)
  14796. {
  14797. return n_digits + 1;
  14798. }
  14799. if (x < 1000)
  14800. {
  14801. return n_digits + 2;
  14802. }
  14803. if (x < 10000)
  14804. {
  14805. return n_digits + 3;
  14806. }
  14807. x = x / 10000u;
  14808. n_digits += 4;
  14809. }
  14810. }
  14811. /*!
  14812. @brief dump an integer
  14813. Dump a given integer to output stream @a o. Works internally with
  14814. @a number_buffer.
  14815. @param[in] x integer number (signed or unsigned) to dump
  14816. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  14817. */
  14818. template < typename NumberType, detail::enable_if_t <
  14819. std::is_integral<NumberType>::value ||
  14820. std::is_same<NumberType, number_unsigned_t>::value ||
  14821. std::is_same<NumberType, number_integer_t>::value ||
  14822. std::is_same<NumberType, binary_char_t>::value,
  14823. int > = 0 >
  14824. void dump_integer(NumberType x)
  14825. {
  14826. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  14827. {
  14828. {
  14829. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  14830. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  14831. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  14832. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  14833. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  14834. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  14835. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  14836. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  14837. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  14838. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  14839. }
  14840. };
  14841. // special case for "0"
  14842. if (x == 0)
  14843. {
  14844. o->write_character('0');
  14845. return;
  14846. }
  14847. // use a pointer to fill the buffer
  14848. auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14849. const bool is_negative = std::is_signed<NumberType>::value && !(x >= 0); // see issue #755
  14850. number_unsigned_t abs_value;
  14851. unsigned int n_chars{};
  14852. if (is_negative)
  14853. {
  14854. *buffer_ptr = '-';
  14855. abs_value = remove_sign(static_cast<number_integer_t>(x));
  14856. // account one more byte for the minus sign
  14857. n_chars = 1 + count_digits(abs_value);
  14858. }
  14859. else
  14860. {
  14861. abs_value = static_cast<number_unsigned_t>(x);
  14862. n_chars = count_digits(abs_value);
  14863. }
  14864. // spare 1 byte for '\0'
  14865. JSON_ASSERT(n_chars < number_buffer.size() - 1);
  14866. // jump to the end to generate the string from backward
  14867. // so we later avoid reversing the result
  14868. buffer_ptr += n_chars;
  14869. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  14870. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  14871. while (abs_value >= 100)
  14872. {
  14873. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  14874. abs_value /= 100;
  14875. *(--buffer_ptr) = digits_to_99[digits_index][1];
  14876. *(--buffer_ptr) = digits_to_99[digits_index][0];
  14877. }
  14878. if (abs_value >= 10)
  14879. {
  14880. const auto digits_index = static_cast<unsigned>(abs_value);
  14881. *(--buffer_ptr) = digits_to_99[digits_index][1];
  14882. *(--buffer_ptr) = digits_to_99[digits_index][0];
  14883. }
  14884. else
  14885. {
  14886. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  14887. }
  14888. o->write_characters(number_buffer.data(), n_chars);
  14889. }
  14890. /*!
  14891. @brief dump a floating-point number
  14892. Dump a given floating-point number to output stream @a o. Works internally
  14893. with @a number_buffer.
  14894. @param[in] x floating-point number to dump
  14895. */
  14896. void dump_float(number_float_t x)
  14897. {
  14898. // NaN / inf
  14899. if (!std::isfinite(x))
  14900. {
  14901. o->write_characters("null", 4);
  14902. return;
  14903. }
  14904. // If number_float_t is an IEEE-754 single or double precision number,
  14905. // use the Grisu2 algorithm to produce short numbers which are
  14906. // guaranteed to round-trip, using strtof and strtod, resp.
  14907. //
  14908. // NB: The test below works if <long double> == <double>.
  14909. static constexpr bool is_ieee_single_or_double
  14910. = (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) ||
  14911. (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);
  14912. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  14913. }
  14914. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  14915. {
  14916. auto* begin = number_buffer.data();
  14917. auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  14918. o->write_characters(begin, static_cast<size_t>(end - begin));
  14919. }
  14920. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  14921. {
  14922. // get number of digits for a float -> text -> float round-trip
  14923. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  14924. // the actual conversion
  14925. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
  14926. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  14927. // negative value indicates an error
  14928. JSON_ASSERT(len > 0);
  14929. // check if buffer was large enough
  14930. JSON_ASSERT(static_cast<std::size_t>(len) < number_buffer.size());
  14931. // erase thousands separator
  14932. if (thousands_sep != '\0')
  14933. {
  14934. auto* const end = std::remove(number_buffer.begin(),
  14935. number_buffer.begin() + len, thousands_sep);
  14936. std::fill(end, number_buffer.end(), '\0');
  14937. JSON_ASSERT((end - number_buffer.begin()) <= len);
  14938. len = (end - number_buffer.begin());
  14939. }
  14940. // convert decimal point to '.'
  14941. if (decimal_point != '\0' && decimal_point != '.')
  14942. {
  14943. auto* const dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  14944. if (dec_pos != number_buffer.end())
  14945. {
  14946. *dec_pos = '.';
  14947. }
  14948. }
  14949. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  14950. // determine if need to append ".0"
  14951. const bool value_is_int_like =
  14952. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  14953. [](char c)
  14954. {
  14955. return c == '.' || c == 'e';
  14956. });
  14957. if (value_is_int_like)
  14958. {
  14959. o->write_characters(".0", 2);
  14960. }
  14961. }
  14962. /*!
  14963. @brief check whether a string is UTF-8 encoded
  14964. The function checks each byte of a string whether it is UTF-8 encoded. The
  14965. result of the check is stored in the @a state parameter. The function must
  14966. be called initially with state 0 (accept). State 1 means the string must
  14967. be rejected, because the current byte is not allowed. If the string is
  14968. completely processed, but the state is non-zero, the string ended
  14969. prematurely; that is, the last byte indicated more bytes should have
  14970. followed.
  14971. @param[in,out] state the state of the decoding
  14972. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  14973. @param[in] byte next byte to decode
  14974. @return new state
  14975. @note The function has been edited: a std::array is used.
  14976. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  14977. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  14978. */
  14979. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  14980. {
  14981. static const std::array<std::uint8_t, 400> utf8d =
  14982. {
  14983. {
  14984. 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
  14985. 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
  14986. 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
  14987. 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
  14988. 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
  14989. 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
  14990. 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
  14991. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  14992. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  14993. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  14994. 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
  14995. 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
  14996. 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
  14997. 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
  14998. }
  14999. };
  15000. JSON_ASSERT(byte < utf8d.size());
  15001. const std::uint8_t type = utf8d[byte];
  15002. codep = (state != UTF8_ACCEPT)
  15003. ? (byte & 0x3fu) | (codep << 6u)
  15004. : (0xFFu >> type) & (byte);
  15005. std::size_t index = 256u + static_cast<size_t>(state) * 16u + static_cast<size_t>(type);
  15006. JSON_ASSERT(index < 400);
  15007. state = utf8d[index];
  15008. return state;
  15009. }
  15010. /*
  15011. * Overload to make the compiler happy while it is instantiating
  15012. * dump_integer for number_unsigned_t.
  15013. * Must never be called.
  15014. */
  15015. number_unsigned_t remove_sign(number_unsigned_t x)
  15016. {
  15017. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  15018. return x; // LCOV_EXCL_LINE
  15019. }
  15020. /*
  15021. * Helper function for dump_integer
  15022. *
  15023. * This function takes a negative signed integer and returns its absolute
  15024. * value as unsigned integer. The plus/minus shuffling is necessary as we can
  15025. * not directly remove the sign of an arbitrary signed integer as the
  15026. * absolute values of INT_MIN and INT_MAX are usually not the same. See
  15027. * #1708 for details.
  15028. */
  15029. inline number_unsigned_t remove_sign(number_integer_t x) noexcept
  15030. {
  15031. JSON_ASSERT(x < 0 && x < (std::numeric_limits<number_integer_t>::max)()); // NOLINT(misc-redundant-expression)
  15032. return static_cast<number_unsigned_t>(-(x + 1)) + 1;
  15033. }
  15034. private:
  15035. /// the output of the serializer
  15036. output_adapter_t<char> o = nullptr;
  15037. /// a (hopefully) large enough character buffer
  15038. std::array<char, 64> number_buffer{{}};
  15039. /// the locale
  15040. const std::lconv* loc = nullptr;
  15041. /// the locale's thousand separator character
  15042. const char thousands_sep = '\0';
  15043. /// the locale's decimal point character
  15044. const char decimal_point = '\0';
  15045. /// string buffer
  15046. std::array<char, 512> string_buffer{{}};
  15047. /// the indentation character
  15048. const char indent_char;
  15049. /// the indentation string
  15050. string_t indent_string;
  15051. /// error_handler how to react on decoding errors
  15052. const error_handler_t error_handler;
  15053. };
  15054. } // namespace detail
  15055. } // namespace nlohmann
  15056. // #include <nlohmann/detail/value_t.hpp>
  15057. // #include <nlohmann/json_fwd.hpp>
  15058. // #include <nlohmann/ordered_map.hpp>
  15059. #include <functional> // less
  15060. #include <initializer_list> // initializer_list
  15061. #include <iterator> // input_iterator_tag, iterator_traits
  15062. #include <memory> // allocator
  15063. #include <stdexcept> // for out_of_range
  15064. #include <type_traits> // enable_if, is_convertible
  15065. #include <utility> // pair
  15066. #include <vector> // vector
  15067. // #include <nlohmann/detail/macro_scope.hpp>
  15068. namespace nlohmann
  15069. {
  15070. /// ordered_map: a minimal map-like container that preserves insertion order
  15071. /// for use within nlohmann::basic_json<ordered_map>
  15072. template <class Key, class T, class IgnoredLess = std::less<Key>,
  15073. class Allocator = std::allocator<std::pair<const Key, T>>>
  15074. struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>
  15075. {
  15076. using key_type = Key;
  15077. using mapped_type = T;
  15078. using Container = std::vector<std::pair<const Key, T>, Allocator>;
  15079. using typename Container::iterator;
  15080. using typename Container::const_iterator;
  15081. using typename Container::size_type;
  15082. using typename Container::value_type;
  15083. // Explicit constructors instead of `using Container::Container`
  15084. // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4)
  15085. ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {}
  15086. template <class It>
  15087. ordered_map(It first, It last, const Allocator& alloc = Allocator())
  15088. : Container{first, last, alloc} {}
  15089. ordered_map(std::initializer_list<T> init, const Allocator& alloc = Allocator() )
  15090. : Container{init, alloc} {}
  15091. std::pair<iterator, bool> emplace(const key_type& key, T&& t)
  15092. {
  15093. for (auto it = this->begin(); it != this->end(); ++it)
  15094. {
  15095. if (it->first == key)
  15096. {
  15097. return {it, false};
  15098. }
  15099. }
  15100. Container::emplace_back(key, t);
  15101. return {--this->end(), true};
  15102. }
  15103. T& operator[](const Key& key)
  15104. {
  15105. return emplace(key, T{}).first->second;
  15106. }
  15107. const T& operator[](const Key& key) const
  15108. {
  15109. return at(key);
  15110. }
  15111. T& at(const Key& key)
  15112. {
  15113. for (auto it = this->begin(); it != this->end(); ++it)
  15114. {
  15115. if (it->first == key)
  15116. {
  15117. return it->second;
  15118. }
  15119. }
  15120. JSON_THROW(std::out_of_range("key not found"));
  15121. }
  15122. const T& at(const Key& key) const
  15123. {
  15124. for (auto it = this->begin(); it != this->end(); ++it)
  15125. {
  15126. if (it->first == key)
  15127. {
  15128. return it->second;
  15129. }
  15130. }
  15131. JSON_THROW(std::out_of_range("key not found"));
  15132. }
  15133. size_type erase(const Key& key)
  15134. {
  15135. for (auto it = this->begin(); it != this->end(); ++it)
  15136. {
  15137. if (it->first == key)
  15138. {
  15139. // Since we cannot move const Keys, re-construct them in place
  15140. for (auto next = it; ++next != this->end(); ++it)
  15141. {
  15142. it->~value_type(); // Destroy but keep allocation
  15143. new (&*it) value_type{std::move(*next)};
  15144. }
  15145. Container::pop_back();
  15146. return 1;
  15147. }
  15148. }
  15149. return 0;
  15150. }
  15151. iterator erase(iterator pos)
  15152. {
  15153. auto it = pos;
  15154. // Since we cannot move const Keys, re-construct them in place
  15155. for (auto next = it; ++next != this->end(); ++it)
  15156. {
  15157. it->~value_type(); // Destroy but keep allocation
  15158. new (&*it) value_type{std::move(*next)};
  15159. }
  15160. Container::pop_back();
  15161. return pos;
  15162. }
  15163. size_type count(const Key& key) const
  15164. {
  15165. for (auto it = this->begin(); it != this->end(); ++it)
  15166. {
  15167. if (it->first == key)
  15168. {
  15169. return 1;
  15170. }
  15171. }
  15172. return 0;
  15173. }
  15174. iterator find(const Key& key)
  15175. {
  15176. for (auto it = this->begin(); it != this->end(); ++it)
  15177. {
  15178. if (it->first == key)
  15179. {
  15180. return it;
  15181. }
  15182. }
  15183. return Container::end();
  15184. }
  15185. const_iterator find(const Key& key) const
  15186. {
  15187. for (auto it = this->begin(); it != this->end(); ++it)
  15188. {
  15189. if (it->first == key)
  15190. {
  15191. return it;
  15192. }
  15193. }
  15194. return Container::end();
  15195. }
  15196. std::pair<iterator, bool> insert( value_type&& value )
  15197. {
  15198. return emplace(value.first, std::move(value.second));
  15199. }
  15200. std::pair<iterator, bool> insert( const value_type& value )
  15201. {
  15202. for (auto it = this->begin(); it != this->end(); ++it)
  15203. {
  15204. if (it->first == value.first)
  15205. {
  15206. return {it, false};
  15207. }
  15208. }
  15209. Container::push_back(value);
  15210. return {--this->end(), true};
  15211. }
  15212. template<typename InputIt>
  15213. using require_input_iter = typename std::enable_if<std::is_convertible<typename std::iterator_traits<InputIt>::iterator_category,
  15214. std::input_iterator_tag>::value>::type;
  15215. template<typename InputIt, typename = require_input_iter<InputIt>>
  15216. void insert(InputIt first, InputIt last)
  15217. {
  15218. for (auto it = first; it != last; ++it)
  15219. {
  15220. insert(*it);
  15221. }
  15222. }
  15223. };
  15224. } // namespace nlohmann
  15225. #if defined(JSON_HAS_CPP_17)
  15226. #include <string_view>
  15227. #endif
  15228. /*!
  15229. @brief namespace for Niels Lohmann
  15230. @see https://github.com/nlohmann
  15231. @since version 1.0.0
  15232. */
  15233. namespace nlohmann
  15234. {
  15235. /*!
  15236. @brief a class to store JSON values
  15237. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  15238. in @ref object_t)
  15239. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  15240. in @ref array_t)
  15241. @tparam StringType type for JSON strings and object keys (`std::string` by
  15242. default; will be used in @ref string_t)
  15243. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  15244. in @ref boolean_t)
  15245. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  15246. default; will be used in @ref number_integer_t)
  15247. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  15248. `uint64_t` by default; will be used in @ref number_unsigned_t)
  15249. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  15250. default; will be used in @ref number_float_t)
  15251. @tparam BinaryType type for packed binary data for compatibility with binary
  15252. serialization formats (`std::vector<std::uint8_t>` by default; will be used in
  15253. @ref binary_t)
  15254. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  15255. default)
  15256. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  15257. and `from_json()` (@ref adl_serializer by default)
  15258. @requirement The class satisfies the following concept requirements:
  15259. - Basic
  15260. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  15261. JSON values can be default constructed. The result will be a JSON null
  15262. value.
  15263. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  15264. A JSON value can be constructed from an rvalue argument.
  15265. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  15266. A JSON value can be copy-constructed from an lvalue expression.
  15267. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  15268. A JSON value van be assigned from an rvalue argument.
  15269. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  15270. A JSON value can be copy-assigned from an lvalue expression.
  15271. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  15272. JSON values can be destructed.
  15273. - Layout
  15274. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  15275. JSON values have
  15276. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  15277. All non-static data members are private and standard layout types, the
  15278. class has no virtual functions or (virtual) base classes.
  15279. - Library-wide
  15280. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  15281. JSON values can be compared with `==`, see @ref
  15282. operator==(const_reference,const_reference).
  15283. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  15284. JSON values can be compared with `<`, see @ref
  15285. operator<(const_reference,const_reference).
  15286. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  15287. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  15288. other compatible types, using unqualified function call @ref swap().
  15289. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  15290. JSON values can be compared against `std::nullptr_t` objects which are used
  15291. to model the `null` value.
  15292. - Container
  15293. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  15294. JSON values can be used like STL containers and provide iterator access.
  15295. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  15296. JSON values can be used like STL containers and provide reverse iterator
  15297. access.
  15298. @invariant The member variables @a m_value and @a m_type have the following
  15299. relationship:
  15300. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  15301. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  15302. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  15303. The invariants are checked by member function assert_invariant().
  15304. @internal
  15305. @note ObjectType trick from https://stackoverflow.com/a/9860911
  15306. @endinternal
  15307. @see [RFC 8259: The JavaScript Object Notation (JSON) Data Interchange
  15308. Format](https://tools.ietf.org/html/rfc8259)
  15309. @since version 1.0.0
  15310. @nosubgrouping
  15311. */
  15312. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  15313. class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)
  15314. {
  15315. private:
  15316. template<detail::value_t> friend struct detail::external_constructor;
  15317. friend ::nlohmann::json_pointer<basic_json>;
  15318. template<typename BasicJsonType, typename InputType>
  15319. friend class ::nlohmann::detail::parser;
  15320. friend ::nlohmann::detail::serializer<basic_json>;
  15321. template<typename BasicJsonType>
  15322. friend class ::nlohmann::detail::iter_impl;
  15323. template<typename BasicJsonType, typename CharType>
  15324. friend class ::nlohmann::detail::binary_writer;
  15325. template<typename BasicJsonType, typename InputType, typename SAX>
  15326. friend class ::nlohmann::detail::binary_reader;
  15327. template<typename BasicJsonType>
  15328. friend class ::nlohmann::detail::json_sax_dom_parser;
  15329. template<typename BasicJsonType>
  15330. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  15331. friend class ::nlohmann::detail::exception;
  15332. /// workaround type for MSVC
  15333. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  15334. JSON_PRIVATE_UNLESS_TESTED:
  15335. // convenience aliases for types residing in namespace detail;
  15336. using lexer = ::nlohmann::detail::lexer_base<basic_json>;
  15337. template<typename InputAdapterType>
  15338. static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser(
  15339. InputAdapterType adapter,
  15340. detail::parser_callback_t<basic_json>cb = nullptr,
  15341. const bool allow_exceptions = true,
  15342. const bool ignore_comments = false
  15343. )
  15344. {
  15345. return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter),
  15346. std::move(cb), allow_exceptions, ignore_comments);
  15347. }
  15348. private:
  15349. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  15350. template<typename BasicJsonType>
  15351. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  15352. template<typename BasicJsonType>
  15353. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  15354. template<typename Iterator>
  15355. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  15356. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  15357. template<typename CharType>
  15358. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  15359. template<typename InputType>
  15360. using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
  15361. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  15362. JSON_PRIVATE_UNLESS_TESTED:
  15363. using serializer = ::nlohmann::detail::serializer<basic_json>;
  15364. public:
  15365. using value_t = detail::value_t;
  15366. /// JSON Pointer, see @ref nlohmann::json_pointer
  15367. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  15368. template<typename T, typename SFINAE>
  15369. using json_serializer = JSONSerializer<T, SFINAE>;
  15370. /// how to treat decoding errors
  15371. using error_handler_t = detail::error_handler_t;
  15372. /// how to treat CBOR tags
  15373. using cbor_tag_handler_t = detail::cbor_tag_handler_t;
  15374. /// helper type for initializer lists of basic_json values
  15375. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  15376. using input_format_t = detail::input_format_t;
  15377. /// SAX interface type, see @ref nlohmann::json_sax
  15378. using json_sax_t = json_sax<basic_json>;
  15379. ////////////////
  15380. // exceptions //
  15381. ////////////////
  15382. /// @name exceptions
  15383. /// Classes to implement user-defined exceptions.
  15384. /// @{
  15385. /// @copydoc detail::exception
  15386. using exception = detail::exception;
  15387. /// @copydoc detail::parse_error
  15388. using parse_error = detail::parse_error;
  15389. /// @copydoc detail::invalid_iterator
  15390. using invalid_iterator = detail::invalid_iterator;
  15391. /// @copydoc detail::type_error
  15392. using type_error = detail::type_error;
  15393. /// @copydoc detail::out_of_range
  15394. using out_of_range = detail::out_of_range;
  15395. /// @copydoc detail::other_error
  15396. using other_error = detail::other_error;
  15397. /// @}
  15398. /////////////////////
  15399. // container types //
  15400. /////////////////////
  15401. /// @name container types
  15402. /// The canonic container types to use @ref basic_json like any other STL
  15403. /// container.
  15404. /// @{
  15405. /// the type of elements in a basic_json container
  15406. using value_type = basic_json;
  15407. /// the type of an element reference
  15408. using reference = value_type&;
  15409. /// the type of an element const reference
  15410. using const_reference = const value_type&;
  15411. /// a type to represent differences between iterators
  15412. using difference_type = std::ptrdiff_t;
  15413. /// a type to represent container sizes
  15414. using size_type = std::size_t;
  15415. /// the allocator type
  15416. using allocator_type = AllocatorType<basic_json>;
  15417. /// the type of an element pointer
  15418. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  15419. /// the type of an element const pointer
  15420. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  15421. /// an iterator for a basic_json container
  15422. using iterator = iter_impl<basic_json>;
  15423. /// a const iterator for a basic_json container
  15424. using const_iterator = iter_impl<const basic_json>;
  15425. /// a reverse iterator for a basic_json container
  15426. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  15427. /// a const reverse iterator for a basic_json container
  15428. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  15429. /// @}
  15430. /*!
  15431. @brief returns the allocator associated with the container
  15432. */
  15433. static allocator_type get_allocator()
  15434. {
  15435. return allocator_type();
  15436. }
  15437. /*!
  15438. @brief returns version information on the library
  15439. This function returns a JSON object with information about the library,
  15440. including the version number and information on the platform and compiler.
  15441. @return JSON object holding version information
  15442. key | description
  15443. ----------- | ---------------
  15444. `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version).
  15445. `copyright` | The copyright line for the library as string.
  15446. `name` | The name of the library as string.
  15447. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  15448. `url` | The URL of the project as string.
  15449. `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string).
  15450. @liveexample{The following code shows an example output of the `meta()`
  15451. function.,meta}
  15452. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15453. changes to any JSON value.
  15454. @complexity Constant.
  15455. @since 2.1.0
  15456. */
  15457. JSON_HEDLEY_WARN_UNUSED_RESULT
  15458. static basic_json meta()
  15459. {
  15460. basic_json result;
  15461. result["copyright"] = "(C) 2013-2021 Niels Lohmann";
  15462. result["name"] = "JSON for Modern C++";
  15463. result["url"] = "https://github.com/nlohmann/json";
  15464. result["version"]["string"] =
  15465. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  15466. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  15467. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  15468. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  15469. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  15470. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  15471. #ifdef _WIN32
  15472. result["platform"] = "win32";
  15473. #elif defined __linux__
  15474. result["platform"] = "linux";
  15475. #elif defined __APPLE__
  15476. result["platform"] = "apple";
  15477. #elif defined __unix__
  15478. result["platform"] = "unix";
  15479. #else
  15480. result["platform"] = "unknown";
  15481. #endif
  15482. #if defined(__ICC) || defined(__INTEL_COMPILER)
  15483. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  15484. #elif defined(__clang__)
  15485. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  15486. #elif defined(__GNUC__) || defined(__GNUG__)
  15487. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  15488. #elif defined(__HP_cc) || defined(__HP_aCC)
  15489. result["compiler"] = "hp"
  15490. #elif defined(__IBMCPP__)
  15491. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  15492. #elif defined(_MSC_VER)
  15493. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  15494. #elif defined(__PGI)
  15495. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  15496. #elif defined(__SUNPRO_CC)
  15497. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  15498. #else
  15499. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  15500. #endif
  15501. #ifdef __cplusplus
  15502. result["compiler"]["c++"] = std::to_string(__cplusplus);
  15503. #else
  15504. result["compiler"]["c++"] = "unknown";
  15505. #endif
  15506. return result;
  15507. }
  15508. ///////////////////////////
  15509. // JSON value data types //
  15510. ///////////////////////////
  15511. /// @name JSON value data types
  15512. /// The data types to store a JSON value. These types are derived from
  15513. /// the template arguments passed to class @ref basic_json.
  15514. /// @{
  15515. #if defined(JSON_HAS_CPP_14)
  15516. // Use transparent comparator if possible, combined with perfect forwarding
  15517. // on find() and count() calls prevents unnecessary string construction.
  15518. using object_comparator_t = std::less<>;
  15519. #else
  15520. using object_comparator_t = std::less<StringType>;
  15521. #endif
  15522. /*!
  15523. @brief a type for an object
  15524. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON objects as follows:
  15525. > An object is an unordered collection of zero or more name/value pairs,
  15526. > where a name is a string and a value is a string, number, boolean, null,
  15527. > object, or array.
  15528. To store objects in C++, a type is defined by the template parameters
  15529. described below.
  15530. @tparam ObjectType the container to store objects (e.g., `std::map` or
  15531. `std::unordered_map`)
  15532. @tparam StringType the type of the keys or names (e.g., `std::string`).
  15533. The comparison function `std::less<StringType>` is used to order elements
  15534. inside the container.
  15535. @tparam AllocatorType the allocator to use for objects (e.g.,
  15536. `std::allocator`)
  15537. #### Default type
  15538. With the default values for @a ObjectType (`std::map`), @a StringType
  15539. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  15540. value for @a object_t is:
  15541. @code {.cpp}
  15542. std::map<
  15543. std::string, // key_type
  15544. basic_json, // value_type
  15545. std::less<std::string>, // key_compare
  15546. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  15547. >
  15548. @endcode
  15549. #### Behavior
  15550. The choice of @a object_t influences the behavior of the JSON class. With
  15551. the default type, objects have the following behavior:
  15552. - When all names are unique, objects will be interoperable in the sense
  15553. that all software implementations receiving that object will agree on
  15554. the name-value mappings.
  15555. - When the names within an object are not unique, it is unspecified which
  15556. one of the values for a given key will be chosen. For instance,
  15557. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  15558. `{"key": 2}`.
  15559. - Internally, name/value pairs are stored in lexicographical order of the
  15560. names. Objects will also be serialized (see @ref dump) in this order.
  15561. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  15562. and serialized as `{"a": 2, "b": 1}`.
  15563. - When comparing objects, the order of the name/value pairs is irrelevant.
  15564. This makes objects interoperable in the sense that they will not be
  15565. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  15566. `{"a": 2, "b": 1}` will be treated as equal.
  15567. #### Limits
  15568. [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
  15569. > An implementation may set limits on the maximum depth of nesting.
  15570. In this class, the object's limit of nesting is not explicitly constrained.
  15571. However, a maximum depth of nesting may be introduced by the compiler or
  15572. runtime environment. A theoretical limit can be queried by calling the
  15573. @ref max_size function of a JSON object.
  15574. #### Storage
  15575. Objects are stored as pointers in a @ref basic_json type. That is, for any
  15576. access to object values, a pointer of type `object_t*` must be
  15577. dereferenced.
  15578. @sa see @ref array_t -- type for an array value
  15579. @since version 1.0.0
  15580. @note The order name/value pairs are added to the object is *not*
  15581. preserved by the library. Therefore, iterating an object may return
  15582. name/value pairs in a different order than they were originally stored. In
  15583. fact, keys will be traversed in alphabetical order as `std::map` with
  15584. `std::less` is used by default. Please note this behavior conforms to [RFC
  15585. 8259](https://tools.ietf.org/html/rfc8259), because any order implements the
  15586. specified "unordered" nature of JSON objects.
  15587. */
  15588. using object_t = ObjectType<StringType,
  15589. basic_json,
  15590. object_comparator_t,
  15591. AllocatorType<std::pair<const StringType,
  15592. basic_json>>>;
  15593. /*!
  15594. @brief a type for an array
  15595. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON arrays as follows:
  15596. > An array is an ordered sequence of zero or more values.
  15597. To store objects in C++, a type is defined by the template parameters
  15598. explained below.
  15599. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  15600. `std::list`)
  15601. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  15602. #### Default type
  15603. With the default values for @a ArrayType (`std::vector`) and @a
  15604. AllocatorType (`std::allocator`), the default value for @a array_t is:
  15605. @code {.cpp}
  15606. std::vector<
  15607. basic_json, // value_type
  15608. std::allocator<basic_json> // allocator_type
  15609. >
  15610. @endcode
  15611. #### Limits
  15612. [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
  15613. > An implementation may set limits on the maximum depth of nesting.
  15614. In this class, the array's limit of nesting is not explicitly constrained.
  15615. However, a maximum depth of nesting may be introduced by the compiler or
  15616. runtime environment. A theoretical limit can be queried by calling the
  15617. @ref max_size function of a JSON array.
  15618. #### Storage
  15619. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  15620. access to array values, a pointer of type `array_t*` must be dereferenced.
  15621. @sa see @ref object_t -- type for an object value
  15622. @since version 1.0.0
  15623. */
  15624. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  15625. /*!
  15626. @brief a type for a string
  15627. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON strings as follows:
  15628. > A string is a sequence of zero or more Unicode characters.
  15629. To store objects in C++, a type is defined by the template parameter
  15630. described below. Unicode values are split by the JSON class into
  15631. byte-sized characters during deserialization.
  15632. @tparam StringType the container to store strings (e.g., `std::string`).
  15633. Note this container is used for keys/names in objects, see @ref object_t.
  15634. #### Default type
  15635. With the default values for @a StringType (`std::string`), the default
  15636. value for @a string_t is:
  15637. @code {.cpp}
  15638. std::string
  15639. @endcode
  15640. #### Encoding
  15641. Strings are stored in UTF-8 encoding. Therefore, functions like
  15642. `std::string::size()` or `std::string::length()` return the number of
  15643. bytes in the string rather than the number of characters or glyphs.
  15644. #### String comparison
  15645. [RFC 8259](https://tools.ietf.org/html/rfc8259) states:
  15646. > Software implementations are typically required to test names of object
  15647. > members for equality. Implementations that transform the textual
  15648. > representation into sequences of Unicode code units and then perform the
  15649. > comparison numerically, code unit by code unit, are interoperable in the
  15650. > sense that implementations will agree in all cases on equality or
  15651. > inequality of two strings. For example, implementations that compare
  15652. > strings with escaped characters unconverted may incorrectly find that
  15653. > `"a\\b"` and `"a\u005Cb"` are not equal.
  15654. This implementation is interoperable as it does compare strings code unit
  15655. by code unit.
  15656. #### Storage
  15657. String values are stored as pointers in a @ref basic_json type. That is,
  15658. for any access to string values, a pointer of type `string_t*` must be
  15659. dereferenced.
  15660. @since version 1.0.0
  15661. */
  15662. using string_t = StringType;
  15663. /*!
  15664. @brief a type for a boolean
  15665. [RFC 8259](https://tools.ietf.org/html/rfc8259) implicitly describes a boolean as a
  15666. type which differentiates the two literals `true` and `false`.
  15667. To store objects in C++, a type is defined by the template parameter @a
  15668. BooleanType which chooses the type to use.
  15669. #### Default type
  15670. With the default values for @a BooleanType (`bool`), the default value for
  15671. @a boolean_t is:
  15672. @code {.cpp}
  15673. bool
  15674. @endcode
  15675. #### Storage
  15676. Boolean values are stored directly inside a @ref basic_json type.
  15677. @since version 1.0.0
  15678. */
  15679. using boolean_t = BooleanType;
  15680. /*!
  15681. @brief a type for a number (integer)
  15682. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows:
  15683. > The representation of numbers is similar to that used in most
  15684. > programming languages. A number is represented in base 10 using decimal
  15685. > digits. It contains an integer component that may be prefixed with an
  15686. > optional minus sign, which may be followed by a fraction part and/or an
  15687. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  15688. > cannot be represented in the grammar below (such as Infinity and NaN)
  15689. > are not permitted.
  15690. This description includes both integer and floating-point numbers.
  15691. However, C++ allows more precise storage if it is known whether the number
  15692. is a signed integer, an unsigned integer or a floating-point number.
  15693. Therefore, three different types, @ref number_integer_t, @ref
  15694. number_unsigned_t and @ref number_float_t are used.
  15695. To store integer numbers in C++, a type is defined by the template
  15696. parameter @a NumberIntegerType which chooses the type to use.
  15697. #### Default type
  15698. With the default values for @a NumberIntegerType (`int64_t`), the default
  15699. value for @a number_integer_t is:
  15700. @code {.cpp}
  15701. int64_t
  15702. @endcode
  15703. #### Default behavior
  15704. - The restrictions about leading zeros is not enforced in C++. Instead,
  15705. leading zeros in integer literals lead to an interpretation as octal
  15706. number. Internally, the value will be stored as decimal number. For
  15707. instance, the C++ integer literal `010` will be serialized to `8`.
  15708. During deserialization, leading zeros yield an error.
  15709. - Not-a-number (NaN) values will be serialized to `null`.
  15710. #### Limits
  15711. [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
  15712. > An implementation may set limits on the range and precision of numbers.
  15713. When the default type is used, the maximal integer number that can be
  15714. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  15715. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  15716. that are out of range will yield over/underflow when used in a
  15717. constructor. During deserialization, too large or small integer numbers
  15718. will be automatically be stored as @ref number_unsigned_t or @ref
  15719. number_float_t.
  15720. [RFC 8259](https://tools.ietf.org/html/rfc8259) further states:
  15721. > Note that when such software is used, numbers that are integers and are
  15722. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  15723. > that implementations will agree exactly on their numeric values.
  15724. As this range is a subrange of the exactly supported range [INT64_MIN,
  15725. INT64_MAX], this class's integer type is interoperable.
  15726. #### Storage
  15727. Integer number values are stored directly inside a @ref basic_json type.
  15728. @sa see @ref number_float_t -- type for number values (floating-point)
  15729. @sa see @ref number_unsigned_t -- type for number values (unsigned integer)
  15730. @since version 1.0.0
  15731. */
  15732. using number_integer_t = NumberIntegerType;
  15733. /*!
  15734. @brief a type for a number (unsigned)
  15735. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows:
  15736. > The representation of numbers is similar to that used in most
  15737. > programming languages. A number is represented in base 10 using decimal
  15738. > digits. It contains an integer component that may be prefixed with an
  15739. > optional minus sign, which may be followed by a fraction part and/or an
  15740. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  15741. > cannot be represented in the grammar below (such as Infinity and NaN)
  15742. > are not permitted.
  15743. This description includes both integer and floating-point numbers.
  15744. However, C++ allows more precise storage if it is known whether the number
  15745. is a signed integer, an unsigned integer or a floating-point number.
  15746. Therefore, three different types, @ref number_integer_t, @ref
  15747. number_unsigned_t and @ref number_float_t are used.
  15748. To store unsigned integer numbers in C++, a type is defined by the
  15749. template parameter @a NumberUnsignedType which chooses the type to use.
  15750. #### Default type
  15751. With the default values for @a NumberUnsignedType (`uint64_t`), the
  15752. default value for @a number_unsigned_t is:
  15753. @code {.cpp}
  15754. uint64_t
  15755. @endcode
  15756. #### Default behavior
  15757. - The restrictions about leading zeros is not enforced in C++. Instead,
  15758. leading zeros in integer literals lead to an interpretation as octal
  15759. number. Internally, the value will be stored as decimal number. For
  15760. instance, the C++ integer literal `010` will be serialized to `8`.
  15761. During deserialization, leading zeros yield an error.
  15762. - Not-a-number (NaN) values will be serialized to `null`.
  15763. #### Limits
  15764. [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
  15765. > An implementation may set limits on the range and precision of numbers.
  15766. When the default type is used, the maximal integer number that can be
  15767. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  15768. number that can be stored is `0`. Integer numbers that are out of range
  15769. will yield over/underflow when used in a constructor. During
  15770. deserialization, too large or small integer numbers will be automatically
  15771. be stored as @ref number_integer_t or @ref number_float_t.
  15772. [RFC 8259](https://tools.ietf.org/html/rfc8259) further states:
  15773. > Note that when such software is used, numbers that are integers and are
  15774. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  15775. > that implementations will agree exactly on their numeric values.
  15776. As this range is a subrange (when considered in conjunction with the
  15777. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  15778. this class's integer type is interoperable.
  15779. #### Storage
  15780. Integer number values are stored directly inside a @ref basic_json type.
  15781. @sa see @ref number_float_t -- type for number values (floating-point)
  15782. @sa see @ref number_integer_t -- type for number values (integer)
  15783. @since version 2.0.0
  15784. */
  15785. using number_unsigned_t = NumberUnsignedType;
  15786. /*!
  15787. @brief a type for a number (floating-point)
  15788. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows:
  15789. > The representation of numbers is similar to that used in most
  15790. > programming languages. A number is represented in base 10 using decimal
  15791. > digits. It contains an integer component that may be prefixed with an
  15792. > optional minus sign, which may be followed by a fraction part and/or an
  15793. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  15794. > cannot be represented in the grammar below (such as Infinity and NaN)
  15795. > are not permitted.
  15796. This description includes both integer and floating-point numbers.
  15797. However, C++ allows more precise storage if it is known whether the number
  15798. is a signed integer, an unsigned integer or a floating-point number.
  15799. Therefore, three different types, @ref number_integer_t, @ref
  15800. number_unsigned_t and @ref number_float_t are used.
  15801. To store floating-point numbers in C++, a type is defined by the template
  15802. parameter @a NumberFloatType which chooses the type to use.
  15803. #### Default type
  15804. With the default values for @a NumberFloatType (`double`), the default
  15805. value for @a number_float_t is:
  15806. @code {.cpp}
  15807. double
  15808. @endcode
  15809. #### Default behavior
  15810. - The restrictions about leading zeros is not enforced in C++. Instead,
  15811. leading zeros in floating-point literals will be ignored. Internally,
  15812. the value will be stored as decimal number. For instance, the C++
  15813. floating-point literal `01.2` will be serialized to `1.2`. During
  15814. deserialization, leading zeros yield an error.
  15815. - Not-a-number (NaN) values will be serialized to `null`.
  15816. #### Limits
  15817. [RFC 8259](https://tools.ietf.org/html/rfc8259) states:
  15818. > This specification allows implementations to set limits on the range and
  15819. > precision of numbers accepted. Since software that implements IEEE
  15820. > 754-2008 binary64 (double precision) numbers is generally available and
  15821. > widely used, good interoperability can be achieved by implementations
  15822. > that expect no more precision or range than these provide, in the sense
  15823. > that implementations will approximate JSON numbers within the expected
  15824. > precision.
  15825. This implementation does exactly follow this approach, as it uses double
  15826. precision floating-point numbers. Note values smaller than
  15827. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  15828. will be stored as NaN internally and be serialized to `null`.
  15829. #### Storage
  15830. Floating-point number values are stored directly inside a @ref basic_json
  15831. type.
  15832. @sa see @ref number_integer_t -- type for number values (integer)
  15833. @sa see @ref number_unsigned_t -- type for number values (unsigned integer)
  15834. @since version 1.0.0
  15835. */
  15836. using number_float_t = NumberFloatType;
  15837. /*!
  15838. @brief a type for a packed binary type
  15839. This type is a type designed to carry binary data that appears in various
  15840. serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and
  15841. BSON's generic binary subtype. This type is NOT a part of standard JSON and
  15842. exists solely for compatibility with these binary types. As such, it is
  15843. simply defined as an ordered sequence of zero or more byte values.
  15844. Additionally, as an implementation detail, the subtype of the binary data is
  15845. carried around as a `std::uint8_t`, which is compatible with both of the
  15846. binary data formats that use binary subtyping, (though the specific
  15847. numbering is incompatible with each other, and it is up to the user to
  15848. translate between them).
  15849. [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type
  15850. as:
  15851. > Major type 2: a byte string. The string's length in bytes is represented
  15852. > following the rules for positive integers (major type 0).
  15853. [MessagePack's documentation on the bin type
  15854. family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family)
  15855. describes this type as:
  15856. > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes
  15857. > in addition to the size of the byte array.
  15858. [BSON's specifications](http://bsonspec.org/spec.html) describe several
  15859. binary types; however, this type is intended to represent the generic binary
  15860. type which has the description:
  15861. > Generic binary subtype - This is the most commonly used binary subtype and
  15862. > should be the 'default' for drivers and tools.
  15863. None of these impose any limitations on the internal representation other
  15864. than the basic unit of storage be some type of array whose parts are
  15865. decomposable into bytes.
  15866. The default representation of this binary format is a
  15867. `std::vector<std::uint8_t>`, which is a very common way to represent a byte
  15868. array in modern C++.
  15869. #### Default type
  15870. The default values for @a BinaryType is `std::vector<std::uint8_t>`
  15871. #### Storage
  15872. Binary Arrays are stored as pointers in a @ref basic_json type. That is,
  15873. for any access to array values, a pointer of the type `binary_t*` must be
  15874. dereferenced.
  15875. #### Notes on subtypes
  15876. - CBOR
  15877. - Binary values are represented as byte strings. Subtypes are serialized
  15878. as tagged values.
  15879. - MessagePack
  15880. - If a subtype is given and the binary array contains exactly 1, 2, 4, 8,
  15881. or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8)
  15882. is used. For other sizes, the ext family (ext8, ext16, ext32) is used.
  15883. The subtype is then added as singed 8-bit integer.
  15884. - If no subtype is given, the bin family (bin8, bin16, bin32) is used.
  15885. - BSON
  15886. - If a subtype is given, it is used and added as unsigned 8-bit integer.
  15887. - If no subtype is given, the generic binary subtype 0x00 is used.
  15888. @sa see @ref binary -- create a binary array
  15889. @since version 3.8.0
  15890. */
  15891. using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;
  15892. /// @}
  15893. private:
  15894. /// helper for exception-safe object creation
  15895. template<typename T, typename... Args>
  15896. JSON_HEDLEY_RETURNS_NON_NULL
  15897. static T* create(Args&& ... args)
  15898. {
  15899. AllocatorType<T> alloc;
  15900. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  15901. auto deleter = [&](T * obj)
  15902. {
  15903. AllocatorTraits::deallocate(alloc, obj, 1);
  15904. };
  15905. std::unique_ptr<T, decltype(deleter)> obj(AllocatorTraits::allocate(alloc, 1), deleter);
  15906. AllocatorTraits::construct(alloc, obj.get(), std::forward<Args>(args)...);
  15907. JSON_ASSERT(obj != nullptr);
  15908. return obj.release();
  15909. }
  15910. ////////////////////////
  15911. // JSON value storage //
  15912. ////////////////////////
  15913. JSON_PRIVATE_UNLESS_TESTED:
  15914. /*!
  15915. @brief a JSON value
  15916. The actual storage for a JSON value of the @ref basic_json class. This
  15917. union combines the different storage types for the JSON value types
  15918. defined in @ref value_t.
  15919. JSON type | value_t type | used type
  15920. --------- | --------------- | ------------------------
  15921. object | object | pointer to @ref object_t
  15922. array | array | pointer to @ref array_t
  15923. string | string | pointer to @ref string_t
  15924. boolean | boolean | @ref boolean_t
  15925. number | number_integer | @ref number_integer_t
  15926. number | number_unsigned | @ref number_unsigned_t
  15927. number | number_float | @ref number_float_t
  15928. binary | binary | pointer to @ref binary_t
  15929. null | null | *no value is stored*
  15930. @note Variable-length types (objects, arrays, and strings) are stored as
  15931. pointers. The size of the union should not exceed 64 bits if the default
  15932. value types are used.
  15933. @since version 1.0.0
  15934. */
  15935. union json_value
  15936. {
  15937. /// object (stored with pointer to save storage)
  15938. object_t* object;
  15939. /// array (stored with pointer to save storage)
  15940. array_t* array;
  15941. /// string (stored with pointer to save storage)
  15942. string_t* string;
  15943. /// binary (stored with pointer to save storage)
  15944. binary_t* binary;
  15945. /// boolean
  15946. boolean_t boolean;
  15947. /// number (integer)
  15948. number_integer_t number_integer;
  15949. /// number (unsigned integer)
  15950. number_unsigned_t number_unsigned;
  15951. /// number (floating-point)
  15952. number_float_t number_float;
  15953. /// default constructor (for null values)
  15954. json_value() = default;
  15955. /// constructor for booleans
  15956. json_value(boolean_t v) noexcept : boolean(v) {}
  15957. /// constructor for numbers (integer)
  15958. json_value(number_integer_t v) noexcept : number_integer(v) {}
  15959. /// constructor for numbers (unsigned)
  15960. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  15961. /// constructor for numbers (floating-point)
  15962. json_value(number_float_t v) noexcept : number_float(v) {}
  15963. /// constructor for empty values of a given type
  15964. json_value(value_t t)
  15965. {
  15966. switch (t)
  15967. {
  15968. case value_t::object:
  15969. {
  15970. object = create<object_t>();
  15971. break;
  15972. }
  15973. case value_t::array:
  15974. {
  15975. array = create<array_t>();
  15976. break;
  15977. }
  15978. case value_t::string:
  15979. {
  15980. string = create<string_t>("");
  15981. break;
  15982. }
  15983. case value_t::binary:
  15984. {
  15985. binary = create<binary_t>();
  15986. break;
  15987. }
  15988. case value_t::boolean:
  15989. {
  15990. boolean = boolean_t(false);
  15991. break;
  15992. }
  15993. case value_t::number_integer:
  15994. {
  15995. number_integer = number_integer_t(0);
  15996. break;
  15997. }
  15998. case value_t::number_unsigned:
  15999. {
  16000. number_unsigned = number_unsigned_t(0);
  16001. break;
  16002. }
  16003. case value_t::number_float:
  16004. {
  16005. number_float = number_float_t(0.0);
  16006. break;
  16007. }
  16008. case value_t::null:
  16009. {
  16010. object = nullptr; // silence warning, see #821
  16011. break;
  16012. }
  16013. case value_t::discarded:
  16014. default:
  16015. {
  16016. object = nullptr; // silence warning, see #821
  16017. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  16018. {
  16019. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.10.2", basic_json())); // LCOV_EXCL_LINE
  16020. }
  16021. break;
  16022. }
  16023. }
  16024. }
  16025. /// constructor for strings
  16026. json_value(const string_t& value)
  16027. {
  16028. string = create<string_t>(value);
  16029. }
  16030. /// constructor for rvalue strings
  16031. json_value(string_t&& value)
  16032. {
  16033. string = create<string_t>(std::move(value));
  16034. }
  16035. /// constructor for objects
  16036. json_value(const object_t& value)
  16037. {
  16038. object = create<object_t>(value);
  16039. }
  16040. /// constructor for rvalue objects
  16041. json_value(object_t&& value)
  16042. {
  16043. object = create<object_t>(std::move(value));
  16044. }
  16045. /// constructor for arrays
  16046. json_value(const array_t& value)
  16047. {
  16048. array = create<array_t>(value);
  16049. }
  16050. /// constructor for rvalue arrays
  16051. json_value(array_t&& value)
  16052. {
  16053. array = create<array_t>(std::move(value));
  16054. }
  16055. /// constructor for binary arrays
  16056. json_value(const typename binary_t::container_type& value)
  16057. {
  16058. binary = create<binary_t>(value);
  16059. }
  16060. /// constructor for rvalue binary arrays
  16061. json_value(typename binary_t::container_type&& value)
  16062. {
  16063. binary = create<binary_t>(std::move(value));
  16064. }
  16065. /// constructor for binary arrays (internal type)
  16066. json_value(const binary_t& value)
  16067. {
  16068. binary = create<binary_t>(value);
  16069. }
  16070. /// constructor for rvalue binary arrays (internal type)
  16071. json_value(binary_t&& value)
  16072. {
  16073. binary = create<binary_t>(std::move(value));
  16074. }
  16075. void destroy(value_t t)
  16076. {
  16077. if (t == value_t::array || t == value_t::object)
  16078. {
  16079. // flatten the current json_value to a heap-allocated stack
  16080. std::vector<basic_json> stack;
  16081. // move the top-level items to stack
  16082. if (t == value_t::array)
  16083. {
  16084. stack.reserve(array->size());
  16085. std::move(array->begin(), array->end(), std::back_inserter(stack));
  16086. }
  16087. else
  16088. {
  16089. stack.reserve(object->size());
  16090. for (auto&& it : *object)
  16091. {
  16092. stack.push_back(std::move(it.second));
  16093. }
  16094. }
  16095. while (!stack.empty())
  16096. {
  16097. // move the last item to local variable to be processed
  16098. basic_json current_item(std::move(stack.back()));
  16099. stack.pop_back();
  16100. // if current_item is array/object, move
  16101. // its children to the stack to be processed later
  16102. if (current_item.is_array())
  16103. {
  16104. std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack));
  16105. current_item.m_value.array->clear();
  16106. }
  16107. else if (current_item.is_object())
  16108. {
  16109. for (auto&& it : *current_item.m_value.object)
  16110. {
  16111. stack.push_back(std::move(it.second));
  16112. }
  16113. current_item.m_value.object->clear();
  16114. }
  16115. // it's now safe that current_item get destructed
  16116. // since it doesn't have any children
  16117. }
  16118. }
  16119. switch (t)
  16120. {
  16121. case value_t::object:
  16122. {
  16123. AllocatorType<object_t> alloc;
  16124. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  16125. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  16126. break;
  16127. }
  16128. case value_t::array:
  16129. {
  16130. AllocatorType<array_t> alloc;
  16131. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  16132. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  16133. break;
  16134. }
  16135. case value_t::string:
  16136. {
  16137. AllocatorType<string_t> alloc;
  16138. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  16139. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  16140. break;
  16141. }
  16142. case value_t::binary:
  16143. {
  16144. AllocatorType<binary_t> alloc;
  16145. std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
  16146. std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
  16147. break;
  16148. }
  16149. case value_t::null:
  16150. case value_t::boolean:
  16151. case value_t::number_integer:
  16152. case value_t::number_unsigned:
  16153. case value_t::number_float:
  16154. case value_t::discarded:
  16155. default:
  16156. {
  16157. break;
  16158. }
  16159. }
  16160. }
  16161. };
  16162. private:
  16163. /*!
  16164. @brief checks the class invariants
  16165. This function asserts the class invariants. It needs to be called at the
  16166. end of every constructor to make sure that created objects respect the
  16167. invariant. Furthermore, it has to be called each time the type of a JSON
  16168. value is changed, because the invariant expresses a relationship between
  16169. @a m_type and @a m_value.
  16170. Furthermore, the parent relation is checked for arrays and objects: If
  16171. @a check_parents true and the value is an array or object, then the
  16172. container's elements must have the current value as parent.
  16173. @param[in] check_parents whether the parent relation should be checked.
  16174. The value is true by default and should only be set to false
  16175. during destruction of objects when the invariant does not
  16176. need to hold.
  16177. */
  16178. void assert_invariant(bool check_parents = true) const noexcept
  16179. {
  16180. JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr);
  16181. JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr);
  16182. JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr);
  16183. JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr);
  16184. #if JSON_DIAGNOSTICS
  16185. JSON_TRY
  16186. {
  16187. // cppcheck-suppress assertWithSideEffect
  16188. JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j)
  16189. {
  16190. return j.m_parent == this;
  16191. }));
  16192. }
  16193. JSON_CATCH(...) {} // LCOV_EXCL_LINE
  16194. #endif
  16195. static_cast<void>(check_parents);
  16196. }
  16197. void set_parents()
  16198. {
  16199. #if JSON_DIAGNOSTICS
  16200. switch (m_type)
  16201. {
  16202. case value_t::array:
  16203. {
  16204. for (auto& element : *m_value.array)
  16205. {
  16206. element.m_parent = this;
  16207. }
  16208. break;
  16209. }
  16210. case value_t::object:
  16211. {
  16212. for (auto& element : *m_value.object)
  16213. {
  16214. element.second.m_parent = this;
  16215. }
  16216. break;
  16217. }
  16218. case value_t::null:
  16219. case value_t::string:
  16220. case value_t::boolean:
  16221. case value_t::number_integer:
  16222. case value_t::number_unsigned:
  16223. case value_t::number_float:
  16224. case value_t::binary:
  16225. case value_t::discarded:
  16226. default:
  16227. break;
  16228. }
  16229. #endif
  16230. }
  16231. iterator set_parents(iterator it, typename iterator::difference_type count)
  16232. {
  16233. #if JSON_DIAGNOSTICS
  16234. for (typename iterator::difference_type i = 0; i < count; ++i)
  16235. {
  16236. (it + i)->m_parent = this;
  16237. }
  16238. #else
  16239. static_cast<void>(count);
  16240. #endif
  16241. return it;
  16242. }
  16243. reference set_parent(reference j, std::size_t old_capacity = std::size_t(-1))
  16244. {
  16245. #if JSON_DIAGNOSTICS
  16246. if (old_capacity != std::size_t(-1))
  16247. {
  16248. // see https://github.com/nlohmann/json/issues/2838
  16249. JSON_ASSERT(type() == value_t::array);
  16250. if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity))
  16251. {
  16252. // capacity has changed: update all parents
  16253. set_parents();
  16254. return j;
  16255. }
  16256. }
  16257. // ordered_json uses a vector internally, so pointers could have
  16258. // been invalidated; see https://github.com/nlohmann/json/issues/2962
  16259. #ifdef JSON_HEDLEY_MSVC_VERSION
  16260. #pragma warning(push )
  16261. #pragma warning(disable : 4127) // ignore warning to replace if with if constexpr
  16262. #endif
  16263. if (detail::is_ordered_map<object_t>::value)
  16264. {
  16265. set_parents();
  16266. return j;
  16267. }
  16268. #ifdef JSON_HEDLEY_MSVC_VERSION
  16269. #pragma warning( pop )
  16270. #endif
  16271. j.m_parent = this;
  16272. #else
  16273. static_cast<void>(j);
  16274. static_cast<void>(old_capacity);
  16275. #endif
  16276. return j;
  16277. }
  16278. public:
  16279. //////////////////////////
  16280. // JSON parser callback //
  16281. //////////////////////////
  16282. /*!
  16283. @brief parser event types
  16284. The parser callback distinguishes the following events:
  16285. - `object_start`: the parser read `{` and started to process a JSON object
  16286. - `key`: the parser read a key of a value in an object
  16287. - `object_end`: the parser read `}` and finished processing a JSON object
  16288. - `array_start`: the parser read `[` and started to process a JSON array
  16289. - `array_end`: the parser read `]` and finished processing a JSON array
  16290. - `value`: the parser finished reading a JSON value
  16291. @image html callback_events.png "Example when certain parse events are triggered"
  16292. @sa see @ref parser_callback_t for more information and examples
  16293. */
  16294. using parse_event_t = detail::parse_event_t;
  16295. /*!
  16296. @brief per-element parser callback type
  16297. With a parser callback function, the result of parsing a JSON text can be
  16298. influenced. When passed to @ref parse, it is called on certain events
  16299. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  16300. depth @a depth and context JSON value @a parsed. The return value of the
  16301. callback function is a boolean indicating whether the element that emitted
  16302. the callback shall be kept or not.
  16303. We distinguish six scenarios (determined by the event type) in which the
  16304. callback function can be called. The following table describes the values
  16305. of the parameters @a depth, @a event, and @a parsed.
  16306. parameter @a event | description | parameter @a depth | parameter @a parsed
  16307. ------------------ | ----------- | ------------------ | -------------------
  16308. parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded
  16309. parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key
  16310. parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object
  16311. parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded
  16312. parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array
  16313. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  16314. @image html callback_events.png "Example when certain parse events are triggered"
  16315. Discarding a value (i.e., returning `false`) has different effects
  16316. depending on the context in which function was called:
  16317. - Discarded values in structured types are skipped. That is, the parser
  16318. will behave as if the discarded value was never read.
  16319. - In case a value outside a structured type is skipped, it is replaced
  16320. with `null`. This case happens if the top-level element is skipped.
  16321. @param[in] depth the depth of the recursion during parsing
  16322. @param[in] event an event of type parse_event_t indicating the context in
  16323. the callback function has been called
  16324. @param[in,out] parsed the current intermediate parse result; note that
  16325. writing to this value has no effect for parse_event_t::key events
  16326. @return Whether the JSON value which called the function during parsing
  16327. should be kept (`true`) or not (`false`). In the latter case, it is either
  16328. skipped completely or replaced by an empty discarded object.
  16329. @sa see @ref parse for examples
  16330. @since version 1.0.0
  16331. */
  16332. using parser_callback_t = detail::parser_callback_t<basic_json>;
  16333. //////////////////
  16334. // constructors //
  16335. //////////////////
  16336. /// @name constructors and destructors
  16337. /// Constructors of class @ref basic_json, copy/move constructor, copy
  16338. /// assignment, static functions creating objects, and the destructor.
  16339. /// @{
  16340. /*!
  16341. @brief create an empty value with a given type
  16342. Create an empty JSON value with a given type. The value will be default
  16343. initialized with an empty value which depends on the type:
  16344. Value type | initial value
  16345. ----------- | -------------
  16346. null | `null`
  16347. boolean | `false`
  16348. string | `""`
  16349. number | `0`
  16350. object | `{}`
  16351. array | `[]`
  16352. binary | empty array
  16353. @param[in] v the type of the value to create
  16354. @complexity Constant.
  16355. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16356. changes to any JSON value.
  16357. @liveexample{The following code shows the constructor for different @ref
  16358. value_t values,basic_json__value_t}
  16359. @sa see @ref clear() -- restores the postcondition of this constructor
  16360. @since version 1.0.0
  16361. */
  16362. basic_json(const value_t v)
  16363. : m_type(v), m_value(v)
  16364. {
  16365. assert_invariant();
  16366. }
  16367. /*!
  16368. @brief create a null object
  16369. Create a `null` JSON value. It either takes a null pointer as parameter
  16370. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  16371. The passed null pointer itself is not read -- it is only used to choose
  16372. the right constructor.
  16373. @complexity Constant.
  16374. @exceptionsafety No-throw guarantee: this constructor never throws
  16375. exceptions.
  16376. @liveexample{The following code shows the constructor with and without a
  16377. null pointer parameter.,basic_json__nullptr_t}
  16378. @since version 1.0.0
  16379. */
  16380. basic_json(std::nullptr_t = nullptr) noexcept
  16381. : basic_json(value_t::null)
  16382. {
  16383. assert_invariant();
  16384. }
  16385. /*!
  16386. @brief create a JSON value
  16387. This is a "catch all" constructor for all compatible JSON types; that is,
  16388. types for which a `to_json()` method exists. The constructor forwards the
  16389. parameter @a val to that method (to `json_serializer<U>::to_json` method
  16390. with `U = uncvref_t<CompatibleType>`, to be exact).
  16391. Template type @a CompatibleType includes, but is not limited to, the
  16392. following types:
  16393. - **arrays**: @ref array_t and all kinds of compatible containers such as
  16394. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  16395. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  16396. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  16397. which a @ref basic_json value can be constructed.
  16398. - **objects**: @ref object_t and all kinds of compatible associative
  16399. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  16400. and `std::unordered_multimap` with a `key_type` compatible to
  16401. @ref string_t and a `value_type` from which a @ref basic_json value can
  16402. be constructed.
  16403. - **strings**: @ref string_t, string literals, and all compatible string
  16404. containers can be used.
  16405. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  16406. @ref number_float_t, and all convertible number types such as `int`,
  16407. `size_t`, `int64_t`, `float` or `double` can be used.
  16408. - **boolean**: @ref boolean_t / `bool` can be used.
  16409. - **binary**: @ref binary_t / `std::vector<std::uint8_t>` may be used,
  16410. unfortunately because string literals cannot be distinguished from binary
  16411. character arrays by the C++ type system, all types compatible with `const
  16412. char*` will be directed to the string constructor instead. This is both
  16413. for backwards compatibility, and due to the fact that a binary type is not
  16414. a standard JSON type.
  16415. See the examples below.
  16416. @tparam CompatibleType a type such that:
  16417. - @a CompatibleType is not derived from `std::istream`,
  16418. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  16419. constructors),
  16420. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  16421. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  16422. @ref json_pointer, @ref iterator, etc ...)
  16423. - `json_serializer<U>` has a `to_json(basic_json_t&, CompatibleType&&)` method
  16424. @tparam U = `uncvref_t<CompatibleType>`
  16425. @param[in] val the value to be forwarded to the respective constructor
  16426. @complexity Usually linear in the size of the passed @a val, also
  16427. depending on the implementation of the called `to_json()`
  16428. method.
  16429. @exceptionsafety Depends on the called constructor. For types directly
  16430. supported by the library (i.e., all types for which no `to_json()` function
  16431. was provided), strong guarantee holds: if an exception is thrown, there are
  16432. no changes to any JSON value.
  16433. @liveexample{The following code shows the constructor with several
  16434. compatible types.,basic_json__CompatibleType}
  16435. @since version 2.1.0
  16436. */
  16437. template < typename CompatibleType,
  16438. typename U = detail::uncvref_t<CompatibleType>,
  16439. detail::enable_if_t <
  16440. !detail::is_basic_json<U>::value && detail::is_compatible_type<basic_json_t, U>::value, int > = 0 >
  16441. basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape)
  16442. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  16443. std::forward<CompatibleType>(val))))
  16444. {
  16445. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  16446. set_parents();
  16447. assert_invariant();
  16448. }
  16449. /*!
  16450. @brief create a JSON value from an existing one
  16451. This is a constructor for existing @ref basic_json types.
  16452. It does not hijack copy/move constructors, since the parameter has different
  16453. template arguments than the current ones.
  16454. The constructor tries to convert the internal @ref m_value of the parameter.
  16455. @tparam BasicJsonType a type such that:
  16456. - @a BasicJsonType is a @ref basic_json type.
  16457. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  16458. @param[in] val the @ref basic_json value to be converted.
  16459. @complexity Usually linear in the size of the passed @a val, also
  16460. depending on the implementation of the called `to_json()`
  16461. method.
  16462. @exceptionsafety Depends on the called constructor. For types directly
  16463. supported by the library (i.e., all types for which no `to_json()` function
  16464. was provided), strong guarantee holds: if an exception is thrown, there are
  16465. no changes to any JSON value.
  16466. @since version 3.2.0
  16467. */
  16468. template < typename BasicJsonType,
  16469. detail::enable_if_t <
  16470. detail::is_basic_json<BasicJsonType>::value&& !std::is_same<basic_json, BasicJsonType>::value, int > = 0 >
  16471. basic_json(const BasicJsonType& val)
  16472. {
  16473. using other_boolean_t = typename BasicJsonType::boolean_t;
  16474. using other_number_float_t = typename BasicJsonType::number_float_t;
  16475. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  16476. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  16477. using other_string_t = typename BasicJsonType::string_t;
  16478. using other_object_t = typename BasicJsonType::object_t;
  16479. using other_array_t = typename BasicJsonType::array_t;
  16480. using other_binary_t = typename BasicJsonType::binary_t;
  16481. switch (val.type())
  16482. {
  16483. case value_t::boolean:
  16484. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  16485. break;
  16486. case value_t::number_float:
  16487. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  16488. break;
  16489. case value_t::number_integer:
  16490. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  16491. break;
  16492. case value_t::number_unsigned:
  16493. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  16494. break;
  16495. case value_t::string:
  16496. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  16497. break;
  16498. case value_t::object:
  16499. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  16500. break;
  16501. case value_t::array:
  16502. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  16503. break;
  16504. case value_t::binary:
  16505. JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
  16506. break;
  16507. case value_t::null:
  16508. *this = nullptr;
  16509. break;
  16510. case value_t::discarded:
  16511. m_type = value_t::discarded;
  16512. break;
  16513. default: // LCOV_EXCL_LINE
  16514. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  16515. }
  16516. set_parents();
  16517. assert_invariant();
  16518. }
  16519. /*!
  16520. @brief create a container (array or object) from an initializer list
  16521. Creates a JSON value of type array or object from the passed initializer
  16522. list @a init. In case @a type_deduction is `true` (default), the type of
  16523. the JSON value to be created is deducted from the initializer list @a init
  16524. according to the following rules:
  16525. 1. If the list is empty, an empty JSON object value `{}` is created.
  16526. 2. If the list consists of pairs whose first element is a string, a JSON
  16527. object value is created where the first elements of the pairs are
  16528. treated as keys and the second elements are as values.
  16529. 3. In all other cases, an array is created.
  16530. The rules aim to create the best fit between a C++ initializer list and
  16531. JSON values. The rationale is as follows:
  16532. 1. The empty initializer list is written as `{}` which is exactly an empty
  16533. JSON object.
  16534. 2. C++ has no way of describing mapped types other than to list a list of
  16535. pairs. As JSON requires that keys must be of type string, rule 2 is the
  16536. weakest constraint one can pose on initializer lists to interpret them
  16537. as an object.
  16538. 3. In all other cases, the initializer list could not be interpreted as
  16539. JSON object type, so interpreting it as JSON array type is safe.
  16540. With the rules described above, the following JSON values cannot be
  16541. expressed by an initializer list:
  16542. - the empty array (`[]`): use @ref array(initializer_list_t)
  16543. with an empty initializer list in this case
  16544. - arrays whose elements satisfy rule 2: use @ref
  16545. array(initializer_list_t) with the same initializer list
  16546. in this case
  16547. @note When used without parentheses around an empty initializer list, @ref
  16548. basic_json() is called instead of this function, yielding the JSON null
  16549. value.
  16550. @param[in] init initializer list with JSON values
  16551. @param[in] type_deduction internal parameter; when set to `true`, the type
  16552. of the JSON value is deducted from the initializer list @a init; when set
  16553. to `false`, the type provided via @a manual_type is forced. This mode is
  16554. used by the functions @ref array(initializer_list_t) and
  16555. @ref object(initializer_list_t).
  16556. @param[in] manual_type internal parameter; when @a type_deduction is set
  16557. to `false`, the created JSON value will use the provided type (only @ref
  16558. value_t::array and @ref value_t::object are valid); when @a type_deduction
  16559. is set to `true`, this parameter has no effect
  16560. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  16561. `value_t::object`, but @a init contains an element which is not a pair
  16562. whose first element is a string. In this case, the constructor could not
  16563. create an object. If @a type_deduction would have be `true`, an array
  16564. would have been created. See @ref object(initializer_list_t)
  16565. for an example.
  16566. @complexity Linear in the size of the initializer list @a init.
  16567. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16568. changes to any JSON value.
  16569. @liveexample{The example below shows how JSON values are created from
  16570. initializer lists.,basic_json__list_init_t}
  16571. @sa see @ref array(initializer_list_t) -- create a JSON array
  16572. value from an initializer list
  16573. @sa see @ref object(initializer_list_t) -- create a JSON object
  16574. value from an initializer list
  16575. @since version 1.0.0
  16576. */
  16577. basic_json(initializer_list_t init,
  16578. bool type_deduction = true,
  16579. value_t manual_type = value_t::array)
  16580. {
  16581. // check if each element is an array with two elements whose first
  16582. // element is a string
  16583. bool is_an_object = std::all_of(init.begin(), init.end(),
  16584. [](const detail::json_ref<basic_json>& element_ref)
  16585. {
  16586. return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string();
  16587. });
  16588. // adjust type if type deduction is not wanted
  16589. if (!type_deduction)
  16590. {
  16591. // if array is wanted, do not create an object though possible
  16592. if (manual_type == value_t::array)
  16593. {
  16594. is_an_object = false;
  16595. }
  16596. // if object is wanted but impossible, throw an exception
  16597. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object))
  16598. {
  16599. JSON_THROW(type_error::create(301, "cannot create object from initializer list", basic_json()));
  16600. }
  16601. }
  16602. if (is_an_object)
  16603. {
  16604. // the initializer list is a list of pairs -> create object
  16605. m_type = value_t::object;
  16606. m_value = value_t::object;
  16607. for (auto& element_ref : init)
  16608. {
  16609. auto element = element_ref.moved_or_copied();
  16610. m_value.object->emplace(
  16611. std::move(*((*element.m_value.array)[0].m_value.string)),
  16612. std::move((*element.m_value.array)[1]));
  16613. }
  16614. }
  16615. else
  16616. {
  16617. // the initializer list describes an array -> create array
  16618. m_type = value_t::array;
  16619. m_value.array = create<array_t>(init.begin(), init.end());
  16620. }
  16621. set_parents();
  16622. assert_invariant();
  16623. }
  16624. /*!
  16625. @brief explicitly create a binary array (without subtype)
  16626. Creates a JSON binary array value from a given binary container. Binary
  16627. values are part of various binary formats, such as CBOR, MessagePack, and
  16628. BSON. This constructor is used to create a value for serialization to those
  16629. formats.
  16630. @note Note, this function exists because of the difficulty in correctly
  16631. specifying the correct template overload in the standard value ctor, as both
  16632. JSON arrays and JSON binary arrays are backed with some form of a
  16633. `std::vector`. Because JSON binary arrays are a non-standard extension it
  16634. was decided that it would be best to prevent automatic initialization of a
  16635. binary array type, for backwards compatibility and so it does not happen on
  16636. accident.
  16637. @param[in] init container containing bytes to use as binary type
  16638. @return JSON binary array value
  16639. @complexity Linear in the size of @a init.
  16640. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16641. changes to any JSON value.
  16642. @since version 3.8.0
  16643. */
  16644. JSON_HEDLEY_WARN_UNUSED_RESULT
  16645. static basic_json binary(const typename binary_t::container_type& init)
  16646. {
  16647. auto res = basic_json();
  16648. res.m_type = value_t::binary;
  16649. res.m_value = init;
  16650. return res;
  16651. }
  16652. /*!
  16653. @brief explicitly create a binary array (with subtype)
  16654. Creates a JSON binary array value from a given binary container. Binary
  16655. values are part of various binary formats, such as CBOR, MessagePack, and
  16656. BSON. This constructor is used to create a value for serialization to those
  16657. formats.
  16658. @note Note, this function exists because of the difficulty in correctly
  16659. specifying the correct template overload in the standard value ctor, as both
  16660. JSON arrays and JSON binary arrays are backed with some form of a
  16661. `std::vector`. Because JSON binary arrays are a non-standard extension it
  16662. was decided that it would be best to prevent automatic initialization of a
  16663. binary array type, for backwards compatibility and so it does not happen on
  16664. accident.
  16665. @param[in] init container containing bytes to use as binary type
  16666. @param[in] subtype subtype to use in MessagePack and BSON
  16667. @return JSON binary array value
  16668. @complexity Linear in the size of @a init.
  16669. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16670. changes to any JSON value.
  16671. @since version 3.8.0
  16672. */
  16673. JSON_HEDLEY_WARN_UNUSED_RESULT
  16674. static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype)
  16675. {
  16676. auto res = basic_json();
  16677. res.m_type = value_t::binary;
  16678. res.m_value = binary_t(init, subtype);
  16679. return res;
  16680. }
  16681. /// @copydoc binary(const typename binary_t::container_type&)
  16682. JSON_HEDLEY_WARN_UNUSED_RESULT
  16683. static basic_json binary(typename binary_t::container_type&& init)
  16684. {
  16685. auto res = basic_json();
  16686. res.m_type = value_t::binary;
  16687. res.m_value = std::move(init);
  16688. return res;
  16689. }
  16690. /// @copydoc binary(const typename binary_t::container_type&, typename binary_t::subtype_type)
  16691. JSON_HEDLEY_WARN_UNUSED_RESULT
  16692. static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype)
  16693. {
  16694. auto res = basic_json();
  16695. res.m_type = value_t::binary;
  16696. res.m_value = binary_t(std::move(init), subtype);
  16697. return res;
  16698. }
  16699. /*!
  16700. @brief explicitly create an array from an initializer list
  16701. Creates a JSON array value from a given initializer list. That is, given a
  16702. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  16703. initializer list is empty, the empty array `[]` is created.
  16704. @note This function is only needed to express two edge cases that cannot
  16705. be realized with the initializer list constructor (@ref
  16706. basic_json(initializer_list_t, bool, value_t)). These cases
  16707. are:
  16708. 1. creating an array whose elements are all pairs whose first element is a
  16709. string -- in this case, the initializer list constructor would create an
  16710. object, taking the first elements as keys
  16711. 2. creating an empty array -- passing the empty initializer list to the
  16712. initializer list constructor yields an empty object
  16713. @param[in] init initializer list with JSON values to create an array from
  16714. (optional)
  16715. @return JSON array value
  16716. @complexity Linear in the size of @a init.
  16717. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16718. changes to any JSON value.
  16719. @liveexample{The following code shows an example for the `array`
  16720. function.,array}
  16721. @sa see @ref basic_json(initializer_list_t, bool, value_t) --
  16722. create a JSON value from an initializer list
  16723. @sa see @ref object(initializer_list_t) -- create a JSON object
  16724. value from an initializer list
  16725. @since version 1.0.0
  16726. */
  16727. JSON_HEDLEY_WARN_UNUSED_RESULT
  16728. static basic_json array(initializer_list_t init = {})
  16729. {
  16730. return basic_json(init, false, value_t::array);
  16731. }
  16732. /*!
  16733. @brief explicitly create an object from an initializer list
  16734. Creates a JSON object value from a given initializer list. The initializer
  16735. lists elements must be pairs, and their first elements must be strings. If
  16736. the initializer list is empty, the empty object `{}` is created.
  16737. @note This function is only added for symmetry reasons. In contrast to the
  16738. related function @ref array(initializer_list_t), there are
  16739. no cases which can only be expressed by this function. That is, any
  16740. initializer list @a init can also be passed to the initializer list
  16741. constructor @ref basic_json(initializer_list_t, bool, value_t).
  16742. @param[in] init initializer list to create an object from (optional)
  16743. @return JSON object value
  16744. @throw type_error.301 if @a init is not a list of pairs whose first
  16745. elements are strings. In this case, no object can be created. When such a
  16746. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  16747. an array would have been created from the passed initializer list @a init.
  16748. See example below.
  16749. @complexity Linear in the size of @a init.
  16750. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16751. changes to any JSON value.
  16752. @liveexample{The following code shows an example for the `object`
  16753. function.,object}
  16754. @sa see @ref basic_json(initializer_list_t, bool, value_t) --
  16755. create a JSON value from an initializer list
  16756. @sa see @ref array(initializer_list_t) -- create a JSON array
  16757. value from an initializer list
  16758. @since version 1.0.0
  16759. */
  16760. JSON_HEDLEY_WARN_UNUSED_RESULT
  16761. static basic_json object(initializer_list_t init = {})
  16762. {
  16763. return basic_json(init, false, value_t::object);
  16764. }
  16765. /*!
  16766. @brief construct an array with count copies of given value
  16767. Constructs a JSON array value by creating @a cnt copies of a passed value.
  16768. In case @a cnt is `0`, an empty array is created.
  16769. @param[in] cnt the number of JSON copies of @a val to create
  16770. @param[in] val the JSON value to copy
  16771. @post `std::distance(begin(),end()) == cnt` holds.
  16772. @complexity Linear in @a cnt.
  16773. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16774. changes to any JSON value.
  16775. @liveexample{The following code shows examples for the @ref
  16776. basic_json(size_type\, const basic_json&)
  16777. constructor.,basic_json__size_type_basic_json}
  16778. @since version 1.0.0
  16779. */
  16780. basic_json(size_type cnt, const basic_json& val)
  16781. : m_type(value_t::array)
  16782. {
  16783. m_value.array = create<array_t>(cnt, val);
  16784. set_parents();
  16785. assert_invariant();
  16786. }
  16787. /*!
  16788. @brief construct a JSON container given an iterator range
  16789. Constructs the JSON value with the contents of the range `[first, last)`.
  16790. The semantics depends on the different types a JSON value can have:
  16791. - In case of a null type, invalid_iterator.206 is thrown.
  16792. - In case of other primitive types (number, boolean, or string), @a first
  16793. must be `begin()` and @a last must be `end()`. In this case, the value is
  16794. copied. Otherwise, invalid_iterator.204 is thrown.
  16795. - In case of structured types (array, object), the constructor behaves as
  16796. similar versions for `std::vector` or `std::map`; that is, a JSON array
  16797. or object is constructed from the values in the range.
  16798. @tparam InputIT an input iterator type (@ref iterator or @ref
  16799. const_iterator)
  16800. @param[in] first begin of the range to copy from (included)
  16801. @param[in] last end of the range to copy from (excluded)
  16802. @pre Iterators @a first and @a last must be initialized. **This
  16803. precondition is enforced with an assertion (see warning).** If
  16804. assertions are switched off, a violation of this precondition yields
  16805. undefined behavior.
  16806. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  16807. checked efficiently. Only certain edge cases are detected; see the
  16808. description of the exceptions below. A violation of this precondition
  16809. yields undefined behavior.
  16810. @warning A precondition is enforced with a runtime assertion that will
  16811. result in calling `std::abort` if this precondition is not met.
  16812. Assertions can be disabled by defining `NDEBUG` at compile time.
  16813. See https://en.cppreference.com/w/cpp/error/assert for more
  16814. information.
  16815. @throw invalid_iterator.201 if iterators @a first and @a last are not
  16816. compatible (i.e., do not belong to the same JSON value). In this case,
  16817. the range `[first, last)` is undefined.
  16818. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  16819. primitive type (number, boolean, or string), but @a first does not point
  16820. to the first element any more. In this case, the range `[first, last)` is
  16821. undefined. See example code below.
  16822. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  16823. null value. In this case, the range `[first, last)` is undefined.
  16824. @complexity Linear in distance between @a first and @a last.
  16825. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16826. changes to any JSON value.
  16827. @liveexample{The example below shows several ways to create JSON values by
  16828. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  16829. @since version 1.0.0
  16830. */
  16831. template < class InputIT, typename std::enable_if <
  16832. std::is_same<InputIT, typename basic_json_t::iterator>::value ||
  16833. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int >::type = 0 >
  16834. basic_json(InputIT first, InputIT last)
  16835. {
  16836. JSON_ASSERT(first.m_object != nullptr);
  16837. JSON_ASSERT(last.m_object != nullptr);
  16838. // make sure iterator fits the current value
  16839. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16840. {
  16841. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", basic_json()));
  16842. }
  16843. // copy type from first iterator
  16844. m_type = first.m_object->m_type;
  16845. // check if iterator range is complete for primitive values
  16846. switch (m_type)
  16847. {
  16848. case value_t::boolean:
  16849. case value_t::number_float:
  16850. case value_t::number_integer:
  16851. case value_t::number_unsigned:
  16852. case value_t::string:
  16853. {
  16854. if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin()
  16855. || !last.m_it.primitive_iterator.is_end()))
  16856. {
  16857. JSON_THROW(invalid_iterator::create(204, "iterators out of range", *first.m_object));
  16858. }
  16859. break;
  16860. }
  16861. case value_t::null:
  16862. case value_t::object:
  16863. case value_t::array:
  16864. case value_t::binary:
  16865. case value_t::discarded:
  16866. default:
  16867. break;
  16868. }
  16869. switch (m_type)
  16870. {
  16871. case value_t::number_integer:
  16872. {
  16873. m_value.number_integer = first.m_object->m_value.number_integer;
  16874. break;
  16875. }
  16876. case value_t::number_unsigned:
  16877. {
  16878. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  16879. break;
  16880. }
  16881. case value_t::number_float:
  16882. {
  16883. m_value.number_float = first.m_object->m_value.number_float;
  16884. break;
  16885. }
  16886. case value_t::boolean:
  16887. {
  16888. m_value.boolean = first.m_object->m_value.boolean;
  16889. break;
  16890. }
  16891. case value_t::string:
  16892. {
  16893. m_value = *first.m_object->m_value.string;
  16894. break;
  16895. }
  16896. case value_t::object:
  16897. {
  16898. m_value.object = create<object_t>(first.m_it.object_iterator,
  16899. last.m_it.object_iterator);
  16900. break;
  16901. }
  16902. case value_t::array:
  16903. {
  16904. m_value.array = create<array_t>(first.m_it.array_iterator,
  16905. last.m_it.array_iterator);
  16906. break;
  16907. }
  16908. case value_t::binary:
  16909. {
  16910. m_value = *first.m_object->m_value.binary;
  16911. break;
  16912. }
  16913. case value_t::null:
  16914. case value_t::discarded:
  16915. default:
  16916. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()), *first.m_object));
  16917. }
  16918. set_parents();
  16919. assert_invariant();
  16920. }
  16921. ///////////////////////////////////////
  16922. // other constructors and destructor //
  16923. ///////////////////////////////////////
  16924. template<typename JsonRef,
  16925. detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
  16926. std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
  16927. basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
  16928. /*!
  16929. @brief copy constructor
  16930. Creates a copy of a given JSON value.
  16931. @param[in] other the JSON value to copy
  16932. @post `*this == other`
  16933. @complexity Linear in the size of @a other.
  16934. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16935. changes to any JSON value.
  16936. @requirement This function helps `basic_json` satisfying the
  16937. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16938. requirements:
  16939. - The complexity is linear.
  16940. - As postcondition, it holds: `other == basic_json(other)`.
  16941. @liveexample{The following code shows an example for the copy
  16942. constructor.,basic_json__basic_json}
  16943. @since version 1.0.0
  16944. */
  16945. basic_json(const basic_json& other)
  16946. : m_type(other.m_type)
  16947. {
  16948. // check of passed value is valid
  16949. other.assert_invariant();
  16950. switch (m_type)
  16951. {
  16952. case value_t::object:
  16953. {
  16954. m_value = *other.m_value.object;
  16955. break;
  16956. }
  16957. case value_t::array:
  16958. {
  16959. m_value = *other.m_value.array;
  16960. break;
  16961. }
  16962. case value_t::string:
  16963. {
  16964. m_value = *other.m_value.string;
  16965. break;
  16966. }
  16967. case value_t::boolean:
  16968. {
  16969. m_value = other.m_value.boolean;
  16970. break;
  16971. }
  16972. case value_t::number_integer:
  16973. {
  16974. m_value = other.m_value.number_integer;
  16975. break;
  16976. }
  16977. case value_t::number_unsigned:
  16978. {
  16979. m_value = other.m_value.number_unsigned;
  16980. break;
  16981. }
  16982. case value_t::number_float:
  16983. {
  16984. m_value = other.m_value.number_float;
  16985. break;
  16986. }
  16987. case value_t::binary:
  16988. {
  16989. m_value = *other.m_value.binary;
  16990. break;
  16991. }
  16992. case value_t::null:
  16993. case value_t::discarded:
  16994. default:
  16995. break;
  16996. }
  16997. set_parents();
  16998. assert_invariant();
  16999. }
  17000. /*!
  17001. @brief move constructor
  17002. Move constructor. Constructs a JSON value with the contents of the given
  17003. value @a other using move semantics. It "steals" the resources from @a
  17004. other and leaves it as JSON null value.
  17005. @param[in,out] other value to move to this object
  17006. @post `*this` has the same value as @a other before the call.
  17007. @post @a other is a JSON null value.
  17008. @complexity Constant.
  17009. @exceptionsafety No-throw guarantee: this constructor never throws
  17010. exceptions.
  17011. @requirement This function helps `basic_json` satisfying the
  17012. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  17013. requirements.
  17014. @liveexample{The code below shows the move constructor explicitly called
  17015. via std::move.,basic_json__moveconstructor}
  17016. @since version 1.0.0
  17017. */
  17018. basic_json(basic_json&& other) noexcept
  17019. : m_type(std::move(other.m_type)),
  17020. m_value(std::move(other.m_value))
  17021. {
  17022. // check that passed value is valid
  17023. other.assert_invariant(false);
  17024. // invalidate payload
  17025. other.m_type = value_t::null;
  17026. other.m_value = {};
  17027. set_parents();
  17028. assert_invariant();
  17029. }
  17030. /*!
  17031. @brief copy assignment
  17032. Copy assignment operator. Copies a JSON value via the "copy and swap"
  17033. strategy: It is expressed in terms of the copy constructor, destructor,
  17034. and the `swap()` member function.
  17035. @param[in] other value to copy from
  17036. @complexity Linear.
  17037. @requirement This function helps `basic_json` satisfying the
  17038. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17039. requirements:
  17040. - The complexity is linear.
  17041. @liveexample{The code below shows and example for the copy assignment. It
  17042. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  17043. copy of `a` (which is the null value after the swap) is
  17044. destroyed.,basic_json__copyassignment}
  17045. @since version 1.0.0
  17046. */
  17047. basic_json& operator=(basic_json other) noexcept (
  17048. std::is_nothrow_move_constructible<value_t>::value&&
  17049. std::is_nothrow_move_assignable<value_t>::value&&
  17050. std::is_nothrow_move_constructible<json_value>::value&&
  17051. std::is_nothrow_move_assignable<json_value>::value
  17052. )
  17053. {
  17054. // check that passed value is valid
  17055. other.assert_invariant();
  17056. using std::swap;
  17057. swap(m_type, other.m_type);
  17058. swap(m_value, other.m_value);
  17059. set_parents();
  17060. assert_invariant();
  17061. return *this;
  17062. }
  17063. /*!
  17064. @brief destructor
  17065. Destroys the JSON value and frees all allocated memory.
  17066. @complexity Linear.
  17067. @requirement This function helps `basic_json` satisfying the
  17068. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17069. requirements:
  17070. - The complexity is linear.
  17071. - All stored elements are destroyed and all memory is freed.
  17072. @since version 1.0.0
  17073. */
  17074. ~basic_json() noexcept
  17075. {
  17076. assert_invariant(false);
  17077. m_value.destroy(m_type);
  17078. }
  17079. /// @}
  17080. public:
  17081. ///////////////////////
  17082. // object inspection //
  17083. ///////////////////////
  17084. /// @name object inspection
  17085. /// Functions to inspect the type of a JSON value.
  17086. /// @{
  17087. /*!
  17088. @brief serialization
  17089. Serialization function for JSON values. The function tries to mimic
  17090. Python's `json.dumps()` function, and currently supports its @a indent
  17091. and @a ensure_ascii parameters.
  17092. @param[in] indent If indent is nonnegative, then array elements and object
  17093. members will be pretty-printed with that indent level. An indent level of
  17094. `0` will only insert newlines. `-1` (the default) selects the most compact
  17095. representation.
  17096. @param[in] indent_char The character to use for indentation if @a indent is
  17097. greater than `0`. The default is ` ` (space).
  17098. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  17099. in the output are escaped with `\uXXXX` sequences, and the result consists
  17100. of ASCII characters only.
  17101. @param[in] error_handler how to react on decoding errors; there are three
  17102. possible values: `strict` (throws and exception in case a decoding error
  17103. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  17104. and `ignore` (ignore invalid UTF-8 sequences during serialization; all
  17105. bytes are copied to the output unchanged).
  17106. @return string containing the serialization of the JSON value
  17107. @throw type_error.316 if a string stored inside the JSON value is not
  17108. UTF-8 encoded and @a error_handler is set to strict
  17109. @note Binary values are serialized as object containing two keys:
  17110. - "bytes": an array of bytes as integers
  17111. - "subtype": the subtype as integer or "null" if the binary has no subtype
  17112. @complexity Linear.
  17113. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17114. changes in the JSON value.
  17115. @liveexample{The following example shows the effect of different @a indent\,
  17116. @a indent_char\, and @a ensure_ascii parameters to the result of the
  17117. serialization.,dump}
  17118. @see https://docs.python.org/2/library/json.html#json.dump
  17119. @since version 1.0.0; indentation character @a indent_char, option
  17120. @a ensure_ascii and exceptions added in version 3.0.0; error
  17121. handlers added in version 3.4.0; serialization of binary values added
  17122. in version 3.8.0.
  17123. */
  17124. string_t dump(const int indent = -1,
  17125. const char indent_char = ' ',
  17126. const bool ensure_ascii = false,
  17127. const error_handler_t error_handler = error_handler_t::strict) const
  17128. {
  17129. string_t result;
  17130. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  17131. if (indent >= 0)
  17132. {
  17133. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  17134. }
  17135. else
  17136. {
  17137. s.dump(*this, false, ensure_ascii, 0);
  17138. }
  17139. return result;
  17140. }
  17141. /*!
  17142. @brief return the type of the JSON value (explicit)
  17143. Return the type of the JSON value as a value from the @ref value_t
  17144. enumeration.
  17145. @return the type of the JSON value
  17146. Value type | return value
  17147. ------------------------- | -------------------------
  17148. null | value_t::null
  17149. boolean | value_t::boolean
  17150. string | value_t::string
  17151. number (integer) | value_t::number_integer
  17152. number (unsigned integer) | value_t::number_unsigned
  17153. number (floating-point) | value_t::number_float
  17154. object | value_t::object
  17155. array | value_t::array
  17156. binary | value_t::binary
  17157. discarded | value_t::discarded
  17158. @complexity Constant.
  17159. @exceptionsafety No-throw guarantee: this member function never throws
  17160. exceptions.
  17161. @liveexample{The following code exemplifies `type()` for all JSON
  17162. types.,type}
  17163. @sa see @ref operator value_t() -- return the type of the JSON value (implicit)
  17164. @sa see @ref type_name() -- return the type as string
  17165. @since version 1.0.0
  17166. */
  17167. constexpr value_t type() const noexcept
  17168. {
  17169. return m_type;
  17170. }
  17171. /*!
  17172. @brief return whether type is primitive
  17173. This function returns true if and only if the JSON type is primitive
  17174. (string, number, boolean, or null).
  17175. @return `true` if type is primitive (string, number, boolean, or null),
  17176. `false` otherwise.
  17177. @complexity Constant.
  17178. @exceptionsafety No-throw guarantee: this member function never throws
  17179. exceptions.
  17180. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  17181. types.,is_primitive}
  17182. @sa see @ref is_structured() -- returns whether JSON value is structured
  17183. @sa see @ref is_null() -- returns whether JSON value is `null`
  17184. @sa see @ref is_string() -- returns whether JSON value is a string
  17185. @sa see @ref is_boolean() -- returns whether JSON value is a boolean
  17186. @sa see @ref is_number() -- returns whether JSON value is a number
  17187. @sa see @ref is_binary() -- returns whether JSON value is a binary array
  17188. @since version 1.0.0
  17189. */
  17190. constexpr bool is_primitive() const noexcept
  17191. {
  17192. return is_null() || is_string() || is_boolean() || is_number() || is_binary();
  17193. }
  17194. /*!
  17195. @brief return whether type is structured
  17196. This function returns true if and only if the JSON type is structured
  17197. (array or object).
  17198. @return `true` if type is structured (array or object), `false` otherwise.
  17199. @complexity Constant.
  17200. @exceptionsafety No-throw guarantee: this member function never throws
  17201. exceptions.
  17202. @liveexample{The following code exemplifies `is_structured()` for all JSON
  17203. types.,is_structured}
  17204. @sa see @ref is_primitive() -- returns whether value is primitive
  17205. @sa see @ref is_array() -- returns whether value is an array
  17206. @sa see @ref is_object() -- returns whether value is an object
  17207. @since version 1.0.0
  17208. */
  17209. constexpr bool is_structured() const noexcept
  17210. {
  17211. return is_array() || is_object();
  17212. }
  17213. /*!
  17214. @brief return whether value is null
  17215. This function returns true if and only if the JSON value is null.
  17216. @return `true` if type is null, `false` otherwise.
  17217. @complexity Constant.
  17218. @exceptionsafety No-throw guarantee: this member function never throws
  17219. exceptions.
  17220. @liveexample{The following code exemplifies `is_null()` for all JSON
  17221. types.,is_null}
  17222. @since version 1.0.0
  17223. */
  17224. constexpr bool is_null() const noexcept
  17225. {
  17226. return m_type == value_t::null;
  17227. }
  17228. /*!
  17229. @brief return whether value is a boolean
  17230. This function returns true if and only if the JSON value is a boolean.
  17231. @return `true` if type is boolean, `false` otherwise.
  17232. @complexity Constant.
  17233. @exceptionsafety No-throw guarantee: this member function never throws
  17234. exceptions.
  17235. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  17236. types.,is_boolean}
  17237. @since version 1.0.0
  17238. */
  17239. constexpr bool is_boolean() const noexcept
  17240. {
  17241. return m_type == value_t::boolean;
  17242. }
  17243. /*!
  17244. @brief return whether value is a number
  17245. This function returns true if and only if the JSON value is a number. This
  17246. includes both integer (signed and unsigned) and floating-point values.
  17247. @return `true` if type is number (regardless whether integer, unsigned
  17248. integer or floating-type), `false` otherwise.
  17249. @complexity Constant.
  17250. @exceptionsafety No-throw guarantee: this member function never throws
  17251. exceptions.
  17252. @liveexample{The following code exemplifies `is_number()` for all JSON
  17253. types.,is_number}
  17254. @sa see @ref is_number_integer() -- check if value is an integer or unsigned
  17255. integer number
  17256. @sa see @ref is_number_unsigned() -- check if value is an unsigned integer
  17257. number
  17258. @sa see @ref is_number_float() -- check if value is a floating-point number
  17259. @since version 1.0.0
  17260. */
  17261. constexpr bool is_number() const noexcept
  17262. {
  17263. return is_number_integer() || is_number_float();
  17264. }
  17265. /*!
  17266. @brief return whether value is an integer number
  17267. This function returns true if and only if the JSON value is a signed or
  17268. unsigned integer number. This excludes floating-point values.
  17269. @return `true` if type is an integer or unsigned integer number, `false`
  17270. otherwise.
  17271. @complexity Constant.
  17272. @exceptionsafety No-throw guarantee: this member function never throws
  17273. exceptions.
  17274. @liveexample{The following code exemplifies `is_number_integer()` for all
  17275. JSON types.,is_number_integer}
  17276. @sa see @ref is_number() -- check if value is a number
  17277. @sa see @ref is_number_unsigned() -- check if value is an unsigned integer
  17278. number
  17279. @sa see @ref is_number_float() -- check if value is a floating-point number
  17280. @since version 1.0.0
  17281. */
  17282. constexpr bool is_number_integer() const noexcept
  17283. {
  17284. return m_type == value_t::number_integer || m_type == value_t::number_unsigned;
  17285. }
  17286. /*!
  17287. @brief return whether value is an unsigned integer number
  17288. This function returns true if and only if the JSON value is an unsigned
  17289. integer number. This excludes floating-point and signed integer values.
  17290. @return `true` if type is an unsigned integer number, `false` otherwise.
  17291. @complexity Constant.
  17292. @exceptionsafety No-throw guarantee: this member function never throws
  17293. exceptions.
  17294. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  17295. JSON types.,is_number_unsigned}
  17296. @sa see @ref is_number() -- check if value is a number
  17297. @sa see @ref is_number_integer() -- check if value is an integer or unsigned
  17298. integer number
  17299. @sa see @ref is_number_float() -- check if value is a floating-point number
  17300. @since version 2.0.0
  17301. */
  17302. constexpr bool is_number_unsigned() const noexcept
  17303. {
  17304. return m_type == value_t::number_unsigned;
  17305. }
  17306. /*!
  17307. @brief return whether value is a floating-point number
  17308. This function returns true if and only if the JSON value is a
  17309. floating-point number. This excludes signed and unsigned integer values.
  17310. @return `true` if type is a floating-point number, `false` otherwise.
  17311. @complexity Constant.
  17312. @exceptionsafety No-throw guarantee: this member function never throws
  17313. exceptions.
  17314. @liveexample{The following code exemplifies `is_number_float()` for all
  17315. JSON types.,is_number_float}
  17316. @sa see @ref is_number() -- check if value is number
  17317. @sa see @ref is_number_integer() -- check if value is an integer number
  17318. @sa see @ref is_number_unsigned() -- check if value is an unsigned integer
  17319. number
  17320. @since version 1.0.0
  17321. */
  17322. constexpr bool is_number_float() const noexcept
  17323. {
  17324. return m_type == value_t::number_float;
  17325. }
  17326. /*!
  17327. @brief return whether value is an object
  17328. This function returns true if and only if the JSON value is an object.
  17329. @return `true` if type is object, `false` otherwise.
  17330. @complexity Constant.
  17331. @exceptionsafety No-throw guarantee: this member function never throws
  17332. exceptions.
  17333. @liveexample{The following code exemplifies `is_object()` for all JSON
  17334. types.,is_object}
  17335. @since version 1.0.0
  17336. */
  17337. constexpr bool is_object() const noexcept
  17338. {
  17339. return m_type == value_t::object;
  17340. }
  17341. /*!
  17342. @brief return whether value is an array
  17343. This function returns true if and only if the JSON value is an array.
  17344. @return `true` if type is array, `false` otherwise.
  17345. @complexity Constant.
  17346. @exceptionsafety No-throw guarantee: this member function never throws
  17347. exceptions.
  17348. @liveexample{The following code exemplifies `is_array()` for all JSON
  17349. types.,is_array}
  17350. @since version 1.0.0
  17351. */
  17352. constexpr bool is_array() const noexcept
  17353. {
  17354. return m_type == value_t::array;
  17355. }
  17356. /*!
  17357. @brief return whether value is a string
  17358. This function returns true if and only if the JSON value is a string.
  17359. @return `true` if type is string, `false` otherwise.
  17360. @complexity Constant.
  17361. @exceptionsafety No-throw guarantee: this member function never throws
  17362. exceptions.
  17363. @liveexample{The following code exemplifies `is_string()` for all JSON
  17364. types.,is_string}
  17365. @since version 1.0.0
  17366. */
  17367. constexpr bool is_string() const noexcept
  17368. {
  17369. return m_type == value_t::string;
  17370. }
  17371. /*!
  17372. @brief return whether value is a binary array
  17373. This function returns true if and only if the JSON value is a binary array.
  17374. @return `true` if type is binary array, `false` otherwise.
  17375. @complexity Constant.
  17376. @exceptionsafety No-throw guarantee: this member function never throws
  17377. exceptions.
  17378. @liveexample{The following code exemplifies `is_binary()` for all JSON
  17379. types.,is_binary}
  17380. @since version 3.8.0
  17381. */
  17382. constexpr bool is_binary() const noexcept
  17383. {
  17384. return m_type == value_t::binary;
  17385. }
  17386. /*!
  17387. @brief return whether value is discarded
  17388. This function returns true if and only if the JSON value was discarded
  17389. during parsing with a callback function (see @ref parser_callback_t).
  17390. @note This function will always be `false` for JSON values after parsing.
  17391. That is, discarded values can only occur during parsing, but will be
  17392. removed when inside a structured value or replaced by null in other cases.
  17393. @return `true` if type is discarded, `false` otherwise.
  17394. @complexity Constant.
  17395. @exceptionsafety No-throw guarantee: this member function never throws
  17396. exceptions.
  17397. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  17398. types.,is_discarded}
  17399. @since version 1.0.0
  17400. */
  17401. constexpr bool is_discarded() const noexcept
  17402. {
  17403. return m_type == value_t::discarded;
  17404. }
  17405. /*!
  17406. @brief return the type of the JSON value (implicit)
  17407. Implicitly return the type of the JSON value as a value from the @ref
  17408. value_t enumeration.
  17409. @return the type of the JSON value
  17410. @complexity Constant.
  17411. @exceptionsafety No-throw guarantee: this member function never throws
  17412. exceptions.
  17413. @liveexample{The following code exemplifies the @ref value_t operator for
  17414. all JSON types.,operator__value_t}
  17415. @sa see @ref type() -- return the type of the JSON value (explicit)
  17416. @sa see @ref type_name() -- return the type as string
  17417. @since version 1.0.0
  17418. */
  17419. constexpr operator value_t() const noexcept
  17420. {
  17421. return m_type;
  17422. }
  17423. /// @}
  17424. private:
  17425. //////////////////
  17426. // value access //
  17427. //////////////////
  17428. /// get a boolean (explicit)
  17429. boolean_t get_impl(boolean_t* /*unused*/) const
  17430. {
  17431. if (JSON_HEDLEY_LIKELY(is_boolean()))
  17432. {
  17433. return m_value.boolean;
  17434. }
  17435. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()), *this));
  17436. }
  17437. /// get a pointer to the value (object)
  17438. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  17439. {
  17440. return is_object() ? m_value.object : nullptr;
  17441. }
  17442. /// get a pointer to the value (object)
  17443. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  17444. {
  17445. return is_object() ? m_value.object : nullptr;
  17446. }
  17447. /// get a pointer to the value (array)
  17448. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  17449. {
  17450. return is_array() ? m_value.array : nullptr;
  17451. }
  17452. /// get a pointer to the value (array)
  17453. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  17454. {
  17455. return is_array() ? m_value.array : nullptr;
  17456. }
  17457. /// get a pointer to the value (string)
  17458. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  17459. {
  17460. return is_string() ? m_value.string : nullptr;
  17461. }
  17462. /// get a pointer to the value (string)
  17463. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  17464. {
  17465. return is_string() ? m_value.string : nullptr;
  17466. }
  17467. /// get a pointer to the value (boolean)
  17468. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  17469. {
  17470. return is_boolean() ? &m_value.boolean : nullptr;
  17471. }
  17472. /// get a pointer to the value (boolean)
  17473. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  17474. {
  17475. return is_boolean() ? &m_value.boolean : nullptr;
  17476. }
  17477. /// get a pointer to the value (integer number)
  17478. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  17479. {
  17480. return is_number_integer() ? &m_value.number_integer : nullptr;
  17481. }
  17482. /// get a pointer to the value (integer number)
  17483. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  17484. {
  17485. return is_number_integer() ? &m_value.number_integer : nullptr;
  17486. }
  17487. /// get a pointer to the value (unsigned number)
  17488. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  17489. {
  17490. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  17491. }
  17492. /// get a pointer to the value (unsigned number)
  17493. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  17494. {
  17495. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  17496. }
  17497. /// get a pointer to the value (floating-point number)
  17498. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  17499. {
  17500. return is_number_float() ? &m_value.number_float : nullptr;
  17501. }
  17502. /// get a pointer to the value (floating-point number)
  17503. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  17504. {
  17505. return is_number_float() ? &m_value.number_float : nullptr;
  17506. }
  17507. /// get a pointer to the value (binary)
  17508. binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
  17509. {
  17510. return is_binary() ? m_value.binary : nullptr;
  17511. }
  17512. /// get a pointer to the value (binary)
  17513. constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
  17514. {
  17515. return is_binary() ? m_value.binary : nullptr;
  17516. }
  17517. /*!
  17518. @brief helper function to implement get_ref()
  17519. This function helps to implement get_ref() without code duplication for
  17520. const and non-const overloads
  17521. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  17522. @throw type_error.303 if ReferenceType does not match underlying value
  17523. type of the current JSON
  17524. */
  17525. template<typename ReferenceType, typename ThisType>
  17526. static ReferenceType get_ref_impl(ThisType& obj)
  17527. {
  17528. // delegate the call to get_ptr<>()
  17529. auto* ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  17530. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  17531. {
  17532. return *ptr;
  17533. }
  17534. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()), obj));
  17535. }
  17536. public:
  17537. /// @name value access
  17538. /// Direct access to the stored value of a JSON value.
  17539. /// @{
  17540. /*!
  17541. @brief get a pointer value (implicit)
  17542. Implicit pointer access to the internally stored JSON value. No copies are
  17543. made.
  17544. @warning Writing data to the pointee of the result yields an undefined
  17545. state.
  17546. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  17547. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  17548. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  17549. assertion.
  17550. @return pointer to the internally stored JSON value if the requested
  17551. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  17552. @complexity Constant.
  17553. @liveexample{The example below shows how pointers to internal values of a
  17554. JSON value can be requested. Note that no type conversions are made and a
  17555. `nullptr` is returned if the value and the requested pointer type does not
  17556. match.,get_ptr}
  17557. @since version 1.0.0
  17558. */
  17559. template<typename PointerType, typename std::enable_if<
  17560. std::is_pointer<PointerType>::value, int>::type = 0>
  17561. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  17562. {
  17563. // delegate the call to get_impl_ptr<>()
  17564. return get_impl_ptr(static_cast<PointerType>(nullptr));
  17565. }
  17566. /*!
  17567. @brief get a pointer value (implicit)
  17568. @copydoc get_ptr()
  17569. */
  17570. template < typename PointerType, typename std::enable_if <
  17571. std::is_pointer<PointerType>::value&&
  17572. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int >::type = 0 >
  17573. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  17574. {
  17575. // delegate the call to get_impl_ptr<>() const
  17576. return get_impl_ptr(static_cast<PointerType>(nullptr));
  17577. }
  17578. private:
  17579. /*!
  17580. @brief get a value (explicit)
  17581. Explicit type conversion between the JSON value and a compatible value
  17582. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  17583. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  17584. The value is converted by calling the @ref json_serializer<ValueType>
  17585. `from_json()` method.
  17586. The function is equivalent to executing
  17587. @code {.cpp}
  17588. ValueType ret;
  17589. JSONSerializer<ValueType>::from_json(*this, ret);
  17590. return ret;
  17591. @endcode
  17592. This overloads is chosen if:
  17593. - @a ValueType is not @ref basic_json,
  17594. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  17595. `void from_json(const basic_json&, ValueType&)`, and
  17596. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  17597. the form `ValueType from_json(const basic_json&)`
  17598. @tparam ValueType the returned value type
  17599. @return copy of the JSON value, converted to @a ValueType
  17600. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  17601. @liveexample{The example below shows several conversions from JSON values
  17602. to other types. There a few things to note: (1) Floating-point numbers can
  17603. be converted to integers\, (2) A JSON array can be converted to a standard
  17604. `std::vector<short>`\, (3) A JSON object can be converted to C++
  17605. associative containers such as `std::unordered_map<std::string\,
  17606. json>`.,get__ValueType_const}
  17607. @since version 2.1.0
  17608. */
  17609. template < typename ValueType,
  17610. detail::enable_if_t <
  17611. detail::is_default_constructible<ValueType>::value&&
  17612. detail::has_from_json<basic_json_t, ValueType>::value,
  17613. int > = 0 >
  17614. ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept(
  17615. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  17616. {
  17617. ValueType ret{};
  17618. JSONSerializer<ValueType>::from_json(*this, ret);
  17619. return ret;
  17620. }
  17621. /*!
  17622. @brief get a value (explicit); special case
  17623. Explicit type conversion between the JSON value and a compatible value
  17624. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  17625. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  17626. The value is converted by calling the @ref json_serializer<ValueType>
  17627. `from_json()` method.
  17628. The function is equivalent to executing
  17629. @code {.cpp}
  17630. return JSONSerializer<ValueType>::from_json(*this);
  17631. @endcode
  17632. This overloads is chosen if:
  17633. - @a ValueType is not @ref basic_json and
  17634. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  17635. `ValueType from_json(const basic_json&)`
  17636. @note If @ref json_serializer<ValueType> has both overloads of
  17637. `from_json()`, this one is chosen.
  17638. @tparam ValueType the returned value type
  17639. @return copy of the JSON value, converted to @a ValueType
  17640. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  17641. @since version 2.1.0
  17642. */
  17643. template < typename ValueType,
  17644. detail::enable_if_t <
  17645. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  17646. int > = 0 >
  17647. ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept(
  17648. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  17649. {
  17650. return JSONSerializer<ValueType>::from_json(*this);
  17651. }
  17652. /*!
  17653. @brief get special-case overload
  17654. This overloads converts the current @ref basic_json in a different
  17655. @ref basic_json type
  17656. @tparam BasicJsonType == @ref basic_json
  17657. @return a copy of *this, converted into @a BasicJsonType
  17658. @complexity Depending on the implementation of the called `from_json()`
  17659. method.
  17660. @since version 3.2.0
  17661. */
  17662. template < typename BasicJsonType,
  17663. detail::enable_if_t <
  17664. detail::is_basic_json<BasicJsonType>::value,
  17665. int > = 0 >
  17666. BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const
  17667. {
  17668. return *this;
  17669. }
  17670. /*!
  17671. @brief get special-case overload
  17672. This overloads avoids a lot of template boilerplate, it can be seen as the
  17673. identity method
  17674. @tparam BasicJsonType == @ref basic_json
  17675. @return a copy of *this
  17676. @complexity Constant.
  17677. @since version 2.1.0
  17678. */
  17679. template<typename BasicJsonType,
  17680. detail::enable_if_t<
  17681. std::is_same<BasicJsonType, basic_json_t>::value,
  17682. int> = 0>
  17683. basic_json get_impl(detail::priority_tag<3> /*unused*/) const
  17684. {
  17685. return *this;
  17686. }
  17687. /*!
  17688. @brief get a pointer value (explicit)
  17689. @copydoc get()
  17690. */
  17691. template<typename PointerType,
  17692. detail::enable_if_t<
  17693. std::is_pointer<PointerType>::value,
  17694. int> = 0>
  17695. constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept
  17696. -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  17697. {
  17698. // delegate the call to get_ptr
  17699. return get_ptr<PointerType>();
  17700. }
  17701. public:
  17702. /*!
  17703. @brief get a (pointer) value (explicit)
  17704. Performs explicit type conversion between the JSON value and a compatible value if required.
  17705. - If the requested type is a pointer to the internally stored JSON value that pointer is returned.
  17706. No copies are made.
  17707. - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible
  17708. from the current @ref basic_json.
  17709. - Otherwise the value is converted by calling the @ref json_serializer<ValueType> `from_json()`
  17710. method.
  17711. @tparam ValueTypeCV the provided value type
  17712. @tparam ValueType the returned value type
  17713. @return copy of the JSON value, converted to @tparam ValueType if necessary
  17714. @throw what @ref json_serializer<ValueType> `from_json()` method throws if conversion is required
  17715. @since version 2.1.0
  17716. */
  17717. template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>>
  17718. #if defined(JSON_HAS_CPP_14)
  17719. constexpr
  17720. #endif
  17721. auto get() const noexcept(
  17722. noexcept(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {})))
  17723. -> decltype(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {}))
  17724. {
  17725. // we cannot static_assert on ValueTypeCV being non-const, because
  17726. // there is support for get<const basic_json_t>(), which is why we
  17727. // still need the uncvref
  17728. static_assert(!std::is_reference<ValueTypeCV>::value,
  17729. "get() cannot be used with reference types, you might want to use get_ref()");
  17730. return get_impl<ValueType>(detail::priority_tag<4> {});
  17731. }
  17732. /*!
  17733. @brief get a pointer value (explicit)
  17734. Explicit pointer access to the internally stored JSON value. No copies are
  17735. made.
  17736. @warning The pointer becomes invalid if the underlying JSON object
  17737. changes.
  17738. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  17739. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  17740. @ref number_unsigned_t, or @ref number_float_t.
  17741. @return pointer to the internally stored JSON value if the requested
  17742. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  17743. @complexity Constant.
  17744. @liveexample{The example below shows how pointers to internal values of a
  17745. JSON value can be requested. Note that no type conversions are made and a
  17746. `nullptr` is returned if the value and the requested pointer type does not
  17747. match.,get__PointerType}
  17748. @sa see @ref get_ptr() for explicit pointer-member access
  17749. @since version 1.0.0
  17750. */
  17751. template<typename PointerType, typename std::enable_if<
  17752. std::is_pointer<PointerType>::value, int>::type = 0>
  17753. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  17754. {
  17755. // delegate the call to get_ptr
  17756. return get_ptr<PointerType>();
  17757. }
  17758. /*!
  17759. @brief get a value (explicit)
  17760. Explicit type conversion between the JSON value and a compatible value.
  17761. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  17762. `from_json()` method.
  17763. The function is equivalent to executing
  17764. @code {.cpp}
  17765. ValueType v;
  17766. JSONSerializer<ValueType>::from_json(*this, v);
  17767. @endcode
  17768. This overloads is chosen if:
  17769. - @a ValueType is not @ref basic_json,
  17770. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  17771. `void from_json(const basic_json&, ValueType&)`, and
  17772. @tparam ValueType the input parameter type.
  17773. @return the input parameter, allowing chaining calls.
  17774. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  17775. @liveexample{The example below shows several conversions from JSON values
  17776. to other types. There a few things to note: (1) Floating-point numbers can
  17777. be converted to integers\, (2) A JSON array can be converted to a standard
  17778. `std::vector<short>`\, (3) A JSON object can be converted to C++
  17779. associative containers such as `std::unordered_map<std::string\,
  17780. json>`.,get_to}
  17781. @since version 3.3.0
  17782. */
  17783. template < typename ValueType,
  17784. detail::enable_if_t <
  17785. !detail::is_basic_json<ValueType>::value&&
  17786. detail::has_from_json<basic_json_t, ValueType>::value,
  17787. int > = 0 >
  17788. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  17789. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  17790. {
  17791. JSONSerializer<ValueType>::from_json(*this, v);
  17792. return v;
  17793. }
  17794. // specialization to allow to call get_to with a basic_json value
  17795. // see https://github.com/nlohmann/json/issues/2175
  17796. template<typename ValueType,
  17797. detail::enable_if_t <
  17798. detail::is_basic_json<ValueType>::value,
  17799. int> = 0>
  17800. ValueType & get_to(ValueType& v) const
  17801. {
  17802. v = *this;
  17803. return v;
  17804. }
  17805. template <
  17806. typename T, std::size_t N,
  17807. typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  17808. detail::enable_if_t <
  17809. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  17810. Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  17811. noexcept(noexcept(JSONSerializer<Array>::from_json(
  17812. std::declval<const basic_json_t&>(), v)))
  17813. {
  17814. JSONSerializer<Array>::from_json(*this, v);
  17815. return v;
  17816. }
  17817. /*!
  17818. @brief get a reference value (implicit)
  17819. Implicit reference access to the internally stored JSON value. No copies
  17820. are made.
  17821. @warning Writing data to the referee of the result yields an undefined
  17822. state.
  17823. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  17824. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  17825. @ref number_float_t. Enforced by static assertion.
  17826. @return reference to the internally stored JSON value if the requested
  17827. reference type @a ReferenceType fits to the JSON value; throws
  17828. type_error.303 otherwise
  17829. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  17830. with the stored JSON value; see example below
  17831. @complexity Constant.
  17832. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  17833. @since version 1.1.0
  17834. */
  17835. template<typename ReferenceType, typename std::enable_if<
  17836. std::is_reference<ReferenceType>::value, int>::type = 0>
  17837. ReferenceType get_ref()
  17838. {
  17839. // delegate call to get_ref_impl
  17840. return get_ref_impl<ReferenceType>(*this);
  17841. }
  17842. /*!
  17843. @brief get a reference value (implicit)
  17844. @copydoc get_ref()
  17845. */
  17846. template < typename ReferenceType, typename std::enable_if <
  17847. std::is_reference<ReferenceType>::value&&
  17848. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int >::type = 0 >
  17849. ReferenceType get_ref() const
  17850. {
  17851. // delegate call to get_ref_impl
  17852. return get_ref_impl<ReferenceType>(*this);
  17853. }
  17854. /*!
  17855. @brief get a value (implicit)
  17856. Implicit type conversion between the JSON value and a compatible value.
  17857. The call is realized by calling @ref get() const.
  17858. @tparam ValueType non-pointer type compatible to the JSON value, for
  17859. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  17860. `std::vector` types for JSON arrays. The character type of @ref string_t
  17861. as well as an initializer list of this type is excluded to avoid
  17862. ambiguities as these types implicitly convert to `std::string`.
  17863. @return copy of the JSON value, converted to type @a ValueType
  17864. @throw type_error.302 in case passed type @a ValueType is incompatible
  17865. to the JSON value type (e.g., the JSON value is of type boolean, but a
  17866. string is requested); see example below
  17867. @complexity Linear in the size of the JSON value.
  17868. @liveexample{The example below shows several conversions from JSON values
  17869. to other types. There a few things to note: (1) Floating-point numbers can
  17870. be converted to integers\, (2) A JSON array can be converted to a standard
  17871. `std::vector<short>`\, (3) A JSON object can be converted to C++
  17872. associative containers such as `std::unordered_map<std::string\,
  17873. json>`.,operator__ValueType}
  17874. @since version 1.0.0
  17875. */
  17876. template < typename ValueType, typename std::enable_if <
  17877. detail::conjunction <
  17878. detail::negation<std::is_pointer<ValueType>>,
  17879. detail::negation<std::is_same<ValueType, detail::json_ref<basic_json>>>,
  17880. detail::negation<std::is_same<ValueType, typename string_t::value_type>>,
  17881. detail::negation<detail::is_basic_json<ValueType>>,
  17882. detail::negation<std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>>,
  17883. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914))
  17884. detail::negation<std::is_same<ValueType, std::string_view>>,
  17885. #endif
  17886. detail::is_detected_lazy<detail::get_template_function, const basic_json_t&, ValueType>
  17887. >::value, int >::type = 0 >
  17888. JSON_EXPLICIT operator ValueType() const
  17889. {
  17890. // delegate the call to get<>() const
  17891. return get<ValueType>();
  17892. }
  17893. /*!
  17894. @return reference to the binary value
  17895. @throw type_error.302 if the value is not binary
  17896. @sa see @ref is_binary() to check if the value is binary
  17897. @since version 3.8.0
  17898. */
  17899. binary_t& get_binary()
  17900. {
  17901. if (!is_binary())
  17902. {
  17903. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this));
  17904. }
  17905. return *get_ptr<binary_t*>();
  17906. }
  17907. /// @copydoc get_binary()
  17908. const binary_t& get_binary() const
  17909. {
  17910. if (!is_binary())
  17911. {
  17912. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this));
  17913. }
  17914. return *get_ptr<const binary_t*>();
  17915. }
  17916. /// @}
  17917. ////////////////////
  17918. // element access //
  17919. ////////////////////
  17920. /// @name element access
  17921. /// Access to the JSON value.
  17922. /// @{
  17923. /*!
  17924. @brief access specified array element with bounds checking
  17925. Returns a reference to the element at specified location @a idx, with
  17926. bounds checking.
  17927. @param[in] idx index of the element to access
  17928. @return reference to the element at index @a idx
  17929. @throw type_error.304 if the JSON value is not an array; in this case,
  17930. calling `at` with an index makes no sense. See example below.
  17931. @throw out_of_range.401 if the index @a idx is out of range of the array;
  17932. that is, `idx >= size()`. See example below.
  17933. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17934. changes in the JSON value.
  17935. @complexity Constant.
  17936. @since version 1.0.0
  17937. @liveexample{The example below shows how array elements can be read and
  17938. written using `at()`. It also demonstrates the different exceptions that
  17939. can be thrown.,at__size_type}
  17940. */
  17941. reference at(size_type idx)
  17942. {
  17943. // at only works for arrays
  17944. if (JSON_HEDLEY_LIKELY(is_array()))
  17945. {
  17946. JSON_TRY
  17947. {
  17948. return set_parent(m_value.array->at(idx));
  17949. }
  17950. JSON_CATCH (std::out_of_range&)
  17951. {
  17952. // create better exception explanation
  17953. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
  17954. }
  17955. }
  17956. else
  17957. {
  17958. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  17959. }
  17960. }
  17961. /*!
  17962. @brief access specified array element with bounds checking
  17963. Returns a const reference to the element at specified location @a idx,
  17964. with bounds checking.
  17965. @param[in] idx index of the element to access
  17966. @return const reference to the element at index @a idx
  17967. @throw type_error.304 if the JSON value is not an array; in this case,
  17968. calling `at` with an index makes no sense. See example below.
  17969. @throw out_of_range.401 if the index @a idx is out of range of the array;
  17970. that is, `idx >= size()`. See example below.
  17971. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17972. changes in the JSON value.
  17973. @complexity Constant.
  17974. @since version 1.0.0
  17975. @liveexample{The example below shows how array elements can be read using
  17976. `at()`. It also demonstrates the different exceptions that can be thrown.,
  17977. at__size_type_const}
  17978. */
  17979. const_reference at(size_type idx) const
  17980. {
  17981. // at only works for arrays
  17982. if (JSON_HEDLEY_LIKELY(is_array()))
  17983. {
  17984. JSON_TRY
  17985. {
  17986. return m_value.array->at(idx);
  17987. }
  17988. JSON_CATCH (std::out_of_range&)
  17989. {
  17990. // create better exception explanation
  17991. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
  17992. }
  17993. }
  17994. else
  17995. {
  17996. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  17997. }
  17998. }
  17999. /*!
  18000. @brief access specified object element with bounds checking
  18001. Returns a reference to the element at with specified key @a key, with
  18002. bounds checking.
  18003. @param[in] key key of the element to access
  18004. @return reference to the element at key @a key
  18005. @throw type_error.304 if the JSON value is not an object; in this case,
  18006. calling `at` with a key makes no sense. See example below.
  18007. @throw out_of_range.403 if the key @a key is is not stored in the object;
  18008. that is, `find(key) == end()`. See example below.
  18009. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18010. changes in the JSON value.
  18011. @complexity Logarithmic in the size of the container.
  18012. @sa see @ref operator[](const typename object_t::key_type&) for unchecked
  18013. access by reference
  18014. @sa see @ref value() for access by value with a default value
  18015. @since version 1.0.0
  18016. @liveexample{The example below shows how object elements can be read and
  18017. written using `at()`. It also demonstrates the different exceptions that
  18018. can be thrown.,at__object_t_key_type}
  18019. */
  18020. reference at(const typename object_t::key_type& key)
  18021. {
  18022. // at only works for objects
  18023. if (JSON_HEDLEY_LIKELY(is_object()))
  18024. {
  18025. JSON_TRY
  18026. {
  18027. return set_parent(m_value.object->at(key));
  18028. }
  18029. JSON_CATCH (std::out_of_range&)
  18030. {
  18031. // create better exception explanation
  18032. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this));
  18033. }
  18034. }
  18035. else
  18036. {
  18037. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  18038. }
  18039. }
  18040. /*!
  18041. @brief access specified object element with bounds checking
  18042. Returns a const reference to the element at with specified key @a key,
  18043. with bounds checking.
  18044. @param[in] key key of the element to access
  18045. @return const reference to the element at key @a key
  18046. @throw type_error.304 if the JSON value is not an object; in this case,
  18047. calling `at` with a key makes no sense. See example below.
  18048. @throw out_of_range.403 if the key @a key is is not stored in the object;
  18049. that is, `find(key) == end()`. See example below.
  18050. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18051. changes in the JSON value.
  18052. @complexity Logarithmic in the size of the container.
  18053. @sa see @ref operator[](const typename object_t::key_type&) for unchecked
  18054. access by reference
  18055. @sa see @ref value() for access by value with a default value
  18056. @since version 1.0.0
  18057. @liveexample{The example below shows how object elements can be read using
  18058. `at()`. It also demonstrates the different exceptions that can be thrown.,
  18059. at__object_t_key_type_const}
  18060. */
  18061. const_reference at(const typename object_t::key_type& key) const
  18062. {
  18063. // at only works for objects
  18064. if (JSON_HEDLEY_LIKELY(is_object()))
  18065. {
  18066. JSON_TRY
  18067. {
  18068. return m_value.object->at(key);
  18069. }
  18070. JSON_CATCH (std::out_of_range&)
  18071. {
  18072. // create better exception explanation
  18073. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this));
  18074. }
  18075. }
  18076. else
  18077. {
  18078. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
  18079. }
  18080. }
  18081. /*!
  18082. @brief access specified array element
  18083. Returns a reference to the element at specified location @a idx.
  18084. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  18085. then the array is silently filled up with `null` values to make `idx` a
  18086. valid reference to the last stored element.
  18087. @param[in] idx index of the element to access
  18088. @return reference to the element at index @a idx
  18089. @throw type_error.305 if the JSON value is not an array or null; in that
  18090. cases, using the [] operator with an index makes no sense.
  18091. @complexity Constant if @a idx is in the range of the array. Otherwise
  18092. linear in `idx - size()`.
  18093. @liveexample{The example below shows how array elements can be read and
  18094. written using `[]` operator. Note the addition of `null`
  18095. values.,operatorarray__size_type}
  18096. @since version 1.0.0
  18097. */
  18098. reference operator[](size_type idx)
  18099. {
  18100. // implicitly convert null value to an empty array
  18101. if (is_null())
  18102. {
  18103. m_type = value_t::array;
  18104. m_value.array = create<array_t>();
  18105. assert_invariant();
  18106. }
  18107. // operator[] only works for arrays
  18108. if (JSON_HEDLEY_LIKELY(is_array()))
  18109. {
  18110. // fill up array with null values if given idx is outside range
  18111. if (idx >= m_value.array->size())
  18112. {
  18113. #if JSON_DIAGNOSTICS
  18114. // remember array size before resizing
  18115. const auto previous_size = m_value.array->size();
  18116. #endif
  18117. m_value.array->resize(idx + 1);
  18118. #if JSON_DIAGNOSTICS
  18119. // set parent for values added above
  18120. set_parents(begin() + static_cast<typename iterator::difference_type>(previous_size), static_cast<typename iterator::difference_type>(idx + 1 - previous_size));
  18121. #endif
  18122. }
  18123. return m_value.array->operator[](idx);
  18124. }
  18125. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this));
  18126. }
  18127. /*!
  18128. @brief access specified array element
  18129. Returns a const reference to the element at specified location @a idx.
  18130. @param[in] idx index of the element to access
  18131. @return const reference to the element at index @a idx
  18132. @throw type_error.305 if the JSON value is not an array; in that case,
  18133. using the [] operator with an index makes no sense.
  18134. @complexity Constant.
  18135. @liveexample{The example below shows how array elements can be read using
  18136. the `[]` operator.,operatorarray__size_type_const}
  18137. @since version 1.0.0
  18138. */
  18139. const_reference operator[](size_type idx) const
  18140. {
  18141. // const operator[] only works for arrays
  18142. if (JSON_HEDLEY_LIKELY(is_array()))
  18143. {
  18144. return m_value.array->operator[](idx);
  18145. }
  18146. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this));
  18147. }
  18148. /*!
  18149. @brief access specified object element
  18150. Returns a reference to the element at with specified key @a key.
  18151. @note If @a key is not found in the object, then it is silently added to
  18152. the object and filled with a `null` value to make `key` a valid reference.
  18153. In case the value was `null` before, it is converted to an object.
  18154. @param[in] key key of the element to access
  18155. @return reference to the element at key @a key
  18156. @throw type_error.305 if the JSON value is not an object or null; in that
  18157. cases, using the [] operator with a key makes no sense.
  18158. @complexity Logarithmic in the size of the container.
  18159. @liveexample{The example below shows how object elements can be read and
  18160. written using the `[]` operator.,operatorarray__key_type}
  18161. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18162. with range checking
  18163. @sa see @ref value() for access by value with a default value
  18164. @since version 1.0.0
  18165. */
  18166. reference operator[](const typename object_t::key_type& key)
  18167. {
  18168. // implicitly convert null value to an empty object
  18169. if (is_null())
  18170. {
  18171. m_type = value_t::object;
  18172. m_value.object = create<object_t>();
  18173. assert_invariant();
  18174. }
  18175. // operator[] only works for objects
  18176. if (JSON_HEDLEY_LIKELY(is_object()))
  18177. {
  18178. return set_parent(m_value.object->operator[](key));
  18179. }
  18180. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  18181. }
  18182. /*!
  18183. @brief read-only access specified object element
  18184. Returns a const reference to the element at with specified key @a key. No
  18185. bounds checking is performed.
  18186. @warning If the element with key @a key does not exist, the behavior is
  18187. undefined.
  18188. @param[in] key key of the element to access
  18189. @return const reference to the element at key @a key
  18190. @pre The element with key @a key must exist. **This precondition is
  18191. enforced with an assertion.**
  18192. @throw type_error.305 if the JSON value is not an object; in that case,
  18193. using the [] operator with a key makes no sense.
  18194. @complexity Logarithmic in the size of the container.
  18195. @liveexample{The example below shows how object elements can be read using
  18196. the `[]` operator.,operatorarray__key_type_const}
  18197. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18198. with range checking
  18199. @sa see @ref value() for access by value with a default value
  18200. @since version 1.0.0
  18201. */
  18202. const_reference operator[](const typename object_t::key_type& key) const
  18203. {
  18204. // const operator[] only works for objects
  18205. if (JSON_HEDLEY_LIKELY(is_object()))
  18206. {
  18207. JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
  18208. return m_value.object->find(key)->second;
  18209. }
  18210. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  18211. }
  18212. /*!
  18213. @brief access specified object element
  18214. Returns a reference to the element at with specified key @a key.
  18215. @note If @a key is not found in the object, then it is silently added to
  18216. the object and filled with a `null` value to make `key` a valid reference.
  18217. In case the value was `null` before, it is converted to an object.
  18218. @param[in] key key of the element to access
  18219. @return reference to the element at key @a key
  18220. @throw type_error.305 if the JSON value is not an object or null; in that
  18221. cases, using the [] operator with a key makes no sense.
  18222. @complexity Logarithmic in the size of the container.
  18223. @liveexample{The example below shows how object elements can be read and
  18224. written using the `[]` operator.,operatorarray__key_type}
  18225. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18226. with range checking
  18227. @sa see @ref value() for access by value with a default value
  18228. @since version 1.1.0
  18229. */
  18230. template<typename T>
  18231. JSON_HEDLEY_NON_NULL(2)
  18232. reference operator[](T* key)
  18233. {
  18234. // implicitly convert null to object
  18235. if (is_null())
  18236. {
  18237. m_type = value_t::object;
  18238. m_value = value_t::object;
  18239. assert_invariant();
  18240. }
  18241. // at only works for objects
  18242. if (JSON_HEDLEY_LIKELY(is_object()))
  18243. {
  18244. return set_parent(m_value.object->operator[](key));
  18245. }
  18246. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  18247. }
  18248. /*!
  18249. @brief read-only access specified object element
  18250. Returns a const reference to the element at with specified key @a key. No
  18251. bounds checking is performed.
  18252. @warning If the element with key @a key does not exist, the behavior is
  18253. undefined.
  18254. @param[in] key key of the element to access
  18255. @return const reference to the element at key @a key
  18256. @pre The element with key @a key must exist. **This precondition is
  18257. enforced with an assertion.**
  18258. @throw type_error.305 if the JSON value is not an object; in that case,
  18259. using the [] operator with a key makes no sense.
  18260. @complexity Logarithmic in the size of the container.
  18261. @liveexample{The example below shows how object elements can be read using
  18262. the `[]` operator.,operatorarray__key_type_const}
  18263. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18264. with range checking
  18265. @sa see @ref value() for access by value with a default value
  18266. @since version 1.1.0
  18267. */
  18268. template<typename T>
  18269. JSON_HEDLEY_NON_NULL(2)
  18270. const_reference operator[](T* key) const
  18271. {
  18272. // at only works for objects
  18273. if (JSON_HEDLEY_LIKELY(is_object()))
  18274. {
  18275. JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
  18276. return m_value.object->find(key)->second;
  18277. }
  18278. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
  18279. }
  18280. /*!
  18281. @brief access specified object element with default value
  18282. Returns either a copy of an object's element at the specified key @a key
  18283. or a given default value if no element with key @a key exists.
  18284. The function is basically equivalent to executing
  18285. @code {.cpp}
  18286. try {
  18287. return at(key);
  18288. } catch(out_of_range) {
  18289. return default_value;
  18290. }
  18291. @endcode
  18292. @note Unlike @ref at(const typename object_t::key_type&), this function
  18293. does not throw if the given key @a key was not found.
  18294. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  18295. function does not implicitly add an element to the position defined by @a
  18296. key. This function is furthermore also applicable to const objects.
  18297. @param[in] key key of the element to access
  18298. @param[in] default_value the value to return if @a key is not found
  18299. @tparam ValueType type compatible to JSON values, for instance `int` for
  18300. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  18301. JSON arrays. Note the type of the expected value at @a key and the default
  18302. value @a default_value must be compatible.
  18303. @return copy of the element at key @a key or @a default_value if @a key
  18304. is not found
  18305. @throw type_error.302 if @a default_value does not match the type of the
  18306. value at @a key
  18307. @throw type_error.306 if the JSON value is not an object; in that case,
  18308. using `value()` with a key makes no sense.
  18309. @complexity Logarithmic in the size of the container.
  18310. @liveexample{The example below shows how object elements can be queried
  18311. with a default value.,basic_json__value}
  18312. @sa see @ref at(const typename object_t::key_type&) for access by reference
  18313. with range checking
  18314. @sa see @ref operator[](const typename object_t::key_type&) for unchecked
  18315. access by reference
  18316. @since version 1.0.0
  18317. */
  18318. // using std::is_convertible in a std::enable_if will fail when using explicit conversions
  18319. template < class ValueType, typename std::enable_if <
  18320. detail::is_getable<basic_json_t, ValueType>::value
  18321. && !std::is_same<value_t, ValueType>::value, int >::type = 0 >
  18322. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  18323. {
  18324. // at only works for objects
  18325. if (JSON_HEDLEY_LIKELY(is_object()))
  18326. {
  18327. // if key is found, return value and given default value otherwise
  18328. const auto it = find(key);
  18329. if (it != end())
  18330. {
  18331. return it->template get<ValueType>();
  18332. }
  18333. return default_value;
  18334. }
  18335. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this));
  18336. }
  18337. /*!
  18338. @brief overload for a default value of type const char*
  18339. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  18340. */
  18341. string_t value(const typename object_t::key_type& key, const char* default_value) const
  18342. {
  18343. return value(key, string_t(default_value));
  18344. }
  18345. /*!
  18346. @brief access specified object element via JSON Pointer with default value
  18347. Returns either a copy of an object's element at the specified key @a key
  18348. or a given default value if no element with key @a key exists.
  18349. The function is basically equivalent to executing
  18350. @code {.cpp}
  18351. try {
  18352. return at(ptr);
  18353. } catch(out_of_range) {
  18354. return default_value;
  18355. }
  18356. @endcode
  18357. @note Unlike @ref at(const json_pointer&), this function does not throw
  18358. if the given key @a key was not found.
  18359. @param[in] ptr a JSON pointer to the element to access
  18360. @param[in] default_value the value to return if @a ptr found no value
  18361. @tparam ValueType type compatible to JSON values, for instance `int` for
  18362. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  18363. JSON arrays. Note the type of the expected value at @a key and the default
  18364. value @a default_value must be compatible.
  18365. @return copy of the element at key @a key or @a default_value if @a key
  18366. is not found
  18367. @throw type_error.302 if @a default_value does not match the type of the
  18368. value at @a ptr
  18369. @throw type_error.306 if the JSON value is not an object; in that case,
  18370. using `value()` with a key makes no sense.
  18371. @complexity Logarithmic in the size of the container.
  18372. @liveexample{The example below shows how object elements can be queried
  18373. with a default value.,basic_json__value_ptr}
  18374. @sa see @ref operator[](const json_pointer&) for unchecked access by reference
  18375. @since version 2.0.2
  18376. */
  18377. template<class ValueType, typename std::enable_if<
  18378. detail::is_getable<basic_json_t, ValueType>::value, int>::type = 0>
  18379. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  18380. {
  18381. // at only works for objects
  18382. if (JSON_HEDLEY_LIKELY(is_object()))
  18383. {
  18384. // if pointer resolves a value, return it or use default value
  18385. JSON_TRY
  18386. {
  18387. return ptr.get_checked(this).template get<ValueType>();
  18388. }
  18389. JSON_INTERNAL_CATCH (out_of_range&)
  18390. {
  18391. return default_value;
  18392. }
  18393. }
  18394. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this));
  18395. }
  18396. /*!
  18397. @brief overload for a default value of type const char*
  18398. @copydoc basic_json::value(const json_pointer&, ValueType) const
  18399. */
  18400. JSON_HEDLEY_NON_NULL(3)
  18401. string_t value(const json_pointer& ptr, const char* default_value) const
  18402. {
  18403. return value(ptr, string_t(default_value));
  18404. }
  18405. /*!
  18406. @brief access the first element
  18407. Returns a reference to the first element in the container. For a JSON
  18408. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  18409. @return In case of a structured type (array or object), a reference to the
  18410. first element is returned. In case of number, string, boolean, or binary
  18411. values, a reference to the value is returned.
  18412. @complexity Constant.
  18413. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  18414. or an empty array or object (undefined behavior, **guarded by
  18415. assertions**).
  18416. @post The JSON value remains unchanged.
  18417. @throw invalid_iterator.214 when called on `null` value
  18418. @liveexample{The following code shows an example for `front()`.,front}
  18419. @sa see @ref back() -- access the last element
  18420. @since version 1.0.0
  18421. */
  18422. reference front()
  18423. {
  18424. return *begin();
  18425. }
  18426. /*!
  18427. @copydoc basic_json::front()
  18428. */
  18429. const_reference front() const
  18430. {
  18431. return *cbegin();
  18432. }
  18433. /*!
  18434. @brief access the last element
  18435. Returns a reference to the last element in the container. For a JSON
  18436. container `c`, the expression `c.back()` is equivalent to
  18437. @code {.cpp}
  18438. auto tmp = c.end();
  18439. --tmp;
  18440. return *tmp;
  18441. @endcode
  18442. @return In case of a structured type (array or object), a reference to the
  18443. last element is returned. In case of number, string, boolean, or binary
  18444. values, a reference to the value is returned.
  18445. @complexity Constant.
  18446. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  18447. or an empty array or object (undefined behavior, **guarded by
  18448. assertions**).
  18449. @post The JSON value remains unchanged.
  18450. @throw invalid_iterator.214 when called on a `null` value. See example
  18451. below.
  18452. @liveexample{The following code shows an example for `back()`.,back}
  18453. @sa see @ref front() -- access the first element
  18454. @since version 1.0.0
  18455. */
  18456. reference back()
  18457. {
  18458. auto tmp = end();
  18459. --tmp;
  18460. return *tmp;
  18461. }
  18462. /*!
  18463. @copydoc basic_json::back()
  18464. */
  18465. const_reference back() const
  18466. {
  18467. auto tmp = cend();
  18468. --tmp;
  18469. return *tmp;
  18470. }
  18471. /*!
  18472. @brief remove element given an iterator
  18473. Removes the element specified by iterator @a pos. The iterator @a pos must
  18474. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  18475. but is not dereferenceable) cannot be used as a value for @a pos.
  18476. If called on a primitive type other than `null`, the resulting JSON value
  18477. will be `null`.
  18478. @param[in] pos iterator to the element to remove
  18479. @return Iterator following the last removed element. If the iterator @a
  18480. pos refers to the last element, the `end()` iterator is returned.
  18481. @tparam IteratorType an @ref iterator or @ref const_iterator
  18482. @post Invalidates iterators and references at or after the point of the
  18483. erase, including the `end()` iterator.
  18484. @throw type_error.307 if called on a `null` value; example: `"cannot use
  18485. erase() with null"`
  18486. @throw invalid_iterator.202 if called on an iterator which does not belong
  18487. to the current JSON value; example: `"iterator does not fit current
  18488. value"`
  18489. @throw invalid_iterator.205 if called on a primitive type with invalid
  18490. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  18491. out of range"`
  18492. @complexity The complexity depends on the type:
  18493. - objects: amortized constant
  18494. - arrays: linear in distance between @a pos and the end of the container
  18495. - strings and binary: linear in the length of the member
  18496. - other types: constant
  18497. @liveexample{The example shows the result of `erase()` for different JSON
  18498. types.,erase__IteratorType}
  18499. @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in
  18500. the given range
  18501. @sa see @ref erase(const typename object_t::key_type&) -- removes the element
  18502. from an object at the given key
  18503. @sa see @ref erase(const size_type) -- removes the element from an array at
  18504. the given index
  18505. @since version 1.0.0
  18506. */
  18507. template < class IteratorType, typename std::enable_if <
  18508. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  18509. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
  18510. = 0 >
  18511. IteratorType erase(IteratorType pos)
  18512. {
  18513. // make sure iterator fits the current value
  18514. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  18515. {
  18516. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  18517. }
  18518. IteratorType result = end();
  18519. switch (m_type)
  18520. {
  18521. case value_t::boolean:
  18522. case value_t::number_float:
  18523. case value_t::number_integer:
  18524. case value_t::number_unsigned:
  18525. case value_t::string:
  18526. case value_t::binary:
  18527. {
  18528. if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin()))
  18529. {
  18530. JSON_THROW(invalid_iterator::create(205, "iterator out of range", *this));
  18531. }
  18532. if (is_string())
  18533. {
  18534. AllocatorType<string_t> alloc;
  18535. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  18536. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  18537. m_value.string = nullptr;
  18538. }
  18539. else if (is_binary())
  18540. {
  18541. AllocatorType<binary_t> alloc;
  18542. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  18543. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  18544. m_value.binary = nullptr;
  18545. }
  18546. m_type = value_t::null;
  18547. assert_invariant();
  18548. break;
  18549. }
  18550. case value_t::object:
  18551. {
  18552. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  18553. break;
  18554. }
  18555. case value_t::array:
  18556. {
  18557. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  18558. break;
  18559. }
  18560. case value_t::null:
  18561. case value_t::discarded:
  18562. default:
  18563. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  18564. }
  18565. return result;
  18566. }
  18567. /*!
  18568. @brief remove elements given an iterator range
  18569. Removes the element specified by the range `[first; last)`. The iterator
  18570. @a first does not need to be dereferenceable if `first == last`: erasing
  18571. an empty range is a no-op.
  18572. If called on a primitive type other than `null`, the resulting JSON value
  18573. will be `null`.
  18574. @param[in] first iterator to the beginning of the range to remove
  18575. @param[in] last iterator past the end of the range to remove
  18576. @return Iterator following the last removed element. If the iterator @a
  18577. second refers to the last element, the `end()` iterator is returned.
  18578. @tparam IteratorType an @ref iterator or @ref const_iterator
  18579. @post Invalidates iterators and references at or after the point of the
  18580. erase, including the `end()` iterator.
  18581. @throw type_error.307 if called on a `null` value; example: `"cannot use
  18582. erase() with null"`
  18583. @throw invalid_iterator.203 if called on iterators which does not belong
  18584. to the current JSON value; example: `"iterators do not fit current value"`
  18585. @throw invalid_iterator.204 if called on a primitive type with invalid
  18586. iterators (i.e., if `first != begin()` and `last != end()`); example:
  18587. `"iterators out of range"`
  18588. @complexity The complexity depends on the type:
  18589. - objects: `log(size()) + std::distance(first, last)`
  18590. - arrays: linear in the distance between @a first and @a last, plus linear
  18591. in the distance between @a last and end of the container
  18592. - strings and binary: linear in the length of the member
  18593. - other types: constant
  18594. @liveexample{The example shows the result of `erase()` for different JSON
  18595. types.,erase__IteratorType_IteratorType}
  18596. @sa see @ref erase(IteratorType) -- removes the element at a given position
  18597. @sa see @ref erase(const typename object_t::key_type&) -- removes the element
  18598. from an object at the given key
  18599. @sa see @ref erase(const size_type) -- removes the element from an array at
  18600. the given index
  18601. @since version 1.0.0
  18602. */
  18603. template < class IteratorType, typename std::enable_if <
  18604. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  18605. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
  18606. = 0 >
  18607. IteratorType erase(IteratorType first, IteratorType last)
  18608. {
  18609. // make sure iterator fits the current value
  18610. if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object))
  18611. {
  18612. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", *this));
  18613. }
  18614. IteratorType result = end();
  18615. switch (m_type)
  18616. {
  18617. case value_t::boolean:
  18618. case value_t::number_float:
  18619. case value_t::number_integer:
  18620. case value_t::number_unsigned:
  18621. case value_t::string:
  18622. case value_t::binary:
  18623. {
  18624. if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin()
  18625. || !last.m_it.primitive_iterator.is_end()))
  18626. {
  18627. JSON_THROW(invalid_iterator::create(204, "iterators out of range", *this));
  18628. }
  18629. if (is_string())
  18630. {
  18631. AllocatorType<string_t> alloc;
  18632. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  18633. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  18634. m_value.string = nullptr;
  18635. }
  18636. else if (is_binary())
  18637. {
  18638. AllocatorType<binary_t> alloc;
  18639. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  18640. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  18641. m_value.binary = nullptr;
  18642. }
  18643. m_type = value_t::null;
  18644. assert_invariant();
  18645. break;
  18646. }
  18647. case value_t::object:
  18648. {
  18649. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  18650. last.m_it.object_iterator);
  18651. break;
  18652. }
  18653. case value_t::array:
  18654. {
  18655. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  18656. last.m_it.array_iterator);
  18657. break;
  18658. }
  18659. case value_t::null:
  18660. case value_t::discarded:
  18661. default:
  18662. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  18663. }
  18664. return result;
  18665. }
  18666. /*!
  18667. @brief remove element from a JSON object given a key
  18668. Removes elements from a JSON object with the key value @a key.
  18669. @param[in] key value of the elements to remove
  18670. @return Number of elements removed. If @a ObjectType is the default
  18671. `std::map` type, the return value will always be `0` (@a key was not
  18672. found) or `1` (@a key was found).
  18673. @post References and iterators to the erased elements are invalidated.
  18674. Other references and iterators are not affected.
  18675. @throw type_error.307 when called on a type other than JSON object;
  18676. example: `"cannot use erase() with null"`
  18677. @complexity `log(size()) + count(key)`
  18678. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  18679. @sa see @ref erase(IteratorType) -- removes the element at a given position
  18680. @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in
  18681. the given range
  18682. @sa see @ref erase(const size_type) -- removes the element from an array at
  18683. the given index
  18684. @since version 1.0.0
  18685. */
  18686. size_type erase(const typename object_t::key_type& key)
  18687. {
  18688. // this erase only works for objects
  18689. if (JSON_HEDLEY_LIKELY(is_object()))
  18690. {
  18691. return m_value.object->erase(key);
  18692. }
  18693. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  18694. }
  18695. /*!
  18696. @brief remove element from a JSON array given an index
  18697. Removes element from a JSON array at the index @a idx.
  18698. @param[in] idx index of the element to remove
  18699. @throw type_error.307 when called on a type other than JSON object;
  18700. example: `"cannot use erase() with null"`
  18701. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  18702. is out of range"`
  18703. @complexity Linear in distance between @a idx and the end of the container.
  18704. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  18705. @sa see @ref erase(IteratorType) -- removes the element at a given position
  18706. @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in
  18707. the given range
  18708. @sa see @ref erase(const typename object_t::key_type&) -- removes the element
  18709. from an object at the given key
  18710. @since version 1.0.0
  18711. */
  18712. void erase(const size_type idx)
  18713. {
  18714. // this erase only works for arrays
  18715. if (JSON_HEDLEY_LIKELY(is_array()))
  18716. {
  18717. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  18718. {
  18719. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
  18720. }
  18721. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  18722. }
  18723. else
  18724. {
  18725. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
  18726. }
  18727. }
  18728. /// @}
  18729. ////////////
  18730. // lookup //
  18731. ////////////
  18732. /// @name lookup
  18733. /// @{
  18734. /*!
  18735. @brief find an element in a JSON object
  18736. Finds an element in a JSON object with key equivalent to @a key. If the
  18737. element is not found or the JSON value is not an object, end() is
  18738. returned.
  18739. @note This method always returns @ref end() when executed on a JSON type
  18740. that is not an object.
  18741. @param[in] key key value of the element to search for.
  18742. @return Iterator to an element with key equivalent to @a key. If no such
  18743. element is found or the JSON value is not an object, past-the-end (see
  18744. @ref end()) iterator is returned.
  18745. @complexity Logarithmic in the size of the JSON object.
  18746. @liveexample{The example shows how `find()` is used.,find__key_type}
  18747. @sa see @ref contains(KeyT&&) const -- checks whether a key exists
  18748. @since version 1.0.0
  18749. */
  18750. template<typename KeyT>
  18751. iterator find(KeyT&& key)
  18752. {
  18753. auto result = end();
  18754. if (is_object())
  18755. {
  18756. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  18757. }
  18758. return result;
  18759. }
  18760. /*!
  18761. @brief find an element in a JSON object
  18762. @copydoc find(KeyT&&)
  18763. */
  18764. template<typename KeyT>
  18765. const_iterator find(KeyT&& key) const
  18766. {
  18767. auto result = cend();
  18768. if (is_object())
  18769. {
  18770. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  18771. }
  18772. return result;
  18773. }
  18774. /*!
  18775. @brief returns the number of occurrences of a key in a JSON object
  18776. Returns the number of elements with key @a key. If ObjectType is the
  18777. default `std::map` type, the return value will always be `0` (@a key was
  18778. not found) or `1` (@a key was found).
  18779. @note This method always returns `0` when executed on a JSON type that is
  18780. not an object.
  18781. @param[in] key key value of the element to count
  18782. @return Number of elements with key @a key. If the JSON value is not an
  18783. object, the return value will be `0`.
  18784. @complexity Logarithmic in the size of the JSON object.
  18785. @liveexample{The example shows how `count()` is used.,count}
  18786. @since version 1.0.0
  18787. */
  18788. template<typename KeyT>
  18789. size_type count(KeyT&& key) const
  18790. {
  18791. // return 0 for all nonobject types
  18792. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  18793. }
  18794. /*!
  18795. @brief check the existence of an element in a JSON object
  18796. Check whether an element exists in a JSON object with key equivalent to
  18797. @a key. If the element is not found or the JSON value is not an object,
  18798. false is returned.
  18799. @note This method always returns false when executed on a JSON type
  18800. that is not an object.
  18801. @param[in] key key value to check its existence.
  18802. @return true if an element with specified @a key exists. If no such
  18803. element with such key is found or the JSON value is not an object,
  18804. false is returned.
  18805. @complexity Logarithmic in the size of the JSON object.
  18806. @liveexample{The following code shows an example for `contains()`.,contains}
  18807. @sa see @ref find(KeyT&&) -- returns an iterator to an object element
  18808. @sa see @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  18809. @since version 3.6.0
  18810. */
  18811. template < typename KeyT, typename std::enable_if <
  18812. !std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int >::type = 0 >
  18813. bool contains(KeyT && key) const
  18814. {
  18815. return is_object() && m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  18816. }
  18817. /*!
  18818. @brief check the existence of an element in a JSON object given a JSON pointer
  18819. Check whether the given JSON pointer @a ptr can be resolved in the current
  18820. JSON value.
  18821. @note This method can be executed on any JSON value type.
  18822. @param[in] ptr JSON pointer to check its existence.
  18823. @return true if the JSON pointer can be resolved to a stored value, false
  18824. otherwise.
  18825. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  18826. @throw parse_error.106 if an array index begins with '0'
  18827. @throw parse_error.109 if an array index was not a number
  18828. @complexity Logarithmic in the size of the JSON object.
  18829. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  18830. @sa see @ref contains(KeyT &&) const -- checks the existence of a key
  18831. @since version 3.7.0
  18832. */
  18833. bool contains(const json_pointer& ptr) const
  18834. {
  18835. return ptr.contains(this);
  18836. }
  18837. /// @}
  18838. ///////////////
  18839. // iterators //
  18840. ///////////////
  18841. /// @name iterators
  18842. /// @{
  18843. /*!
  18844. @brief returns an iterator to the first element
  18845. Returns an iterator to the first element.
  18846. @image html range-begin-end.svg "Illustration from cppreference.com"
  18847. @return iterator to the first element
  18848. @complexity Constant.
  18849. @requirement This function helps `basic_json` satisfying the
  18850. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18851. requirements:
  18852. - The complexity is constant.
  18853. @liveexample{The following code shows an example for `begin()`.,begin}
  18854. @sa see @ref cbegin() -- returns a const iterator to the beginning
  18855. @sa see @ref end() -- returns an iterator to the end
  18856. @sa see @ref cend() -- returns a const iterator to the end
  18857. @since version 1.0.0
  18858. */
  18859. iterator begin() noexcept
  18860. {
  18861. iterator result(this);
  18862. result.set_begin();
  18863. return result;
  18864. }
  18865. /*!
  18866. @copydoc basic_json::cbegin()
  18867. */
  18868. const_iterator begin() const noexcept
  18869. {
  18870. return cbegin();
  18871. }
  18872. /*!
  18873. @brief returns a const iterator to the first element
  18874. Returns a const iterator to the first element.
  18875. @image html range-begin-end.svg "Illustration from cppreference.com"
  18876. @return const iterator to the first element
  18877. @complexity Constant.
  18878. @requirement This function helps `basic_json` satisfying the
  18879. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18880. requirements:
  18881. - The complexity is constant.
  18882. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  18883. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  18884. @sa see @ref begin() -- returns an iterator to the beginning
  18885. @sa see @ref end() -- returns an iterator to the end
  18886. @sa see @ref cend() -- returns a const iterator to the end
  18887. @since version 1.0.0
  18888. */
  18889. const_iterator cbegin() const noexcept
  18890. {
  18891. const_iterator result(this);
  18892. result.set_begin();
  18893. return result;
  18894. }
  18895. /*!
  18896. @brief returns an iterator to one past the last element
  18897. Returns an iterator to one past the last element.
  18898. @image html range-begin-end.svg "Illustration from cppreference.com"
  18899. @return iterator one past the last element
  18900. @complexity Constant.
  18901. @requirement This function helps `basic_json` satisfying the
  18902. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18903. requirements:
  18904. - The complexity is constant.
  18905. @liveexample{The following code shows an example for `end()`.,end}
  18906. @sa see @ref cend() -- returns a const iterator to the end
  18907. @sa see @ref begin() -- returns an iterator to the beginning
  18908. @sa see @ref cbegin() -- returns a const iterator to the beginning
  18909. @since version 1.0.0
  18910. */
  18911. iterator end() noexcept
  18912. {
  18913. iterator result(this);
  18914. result.set_end();
  18915. return result;
  18916. }
  18917. /*!
  18918. @copydoc basic_json::cend()
  18919. */
  18920. const_iterator end() const noexcept
  18921. {
  18922. return cend();
  18923. }
  18924. /*!
  18925. @brief returns a const iterator to one past the last element
  18926. Returns a const iterator to one past the last element.
  18927. @image html range-begin-end.svg "Illustration from cppreference.com"
  18928. @return const iterator one past the last element
  18929. @complexity Constant.
  18930. @requirement This function helps `basic_json` satisfying the
  18931. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  18932. requirements:
  18933. - The complexity is constant.
  18934. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  18935. @liveexample{The following code shows an example for `cend()`.,cend}
  18936. @sa see @ref end() -- returns an iterator to the end
  18937. @sa see @ref begin() -- returns an iterator to the beginning
  18938. @sa see @ref cbegin() -- returns a const iterator to the beginning
  18939. @since version 1.0.0
  18940. */
  18941. const_iterator cend() const noexcept
  18942. {
  18943. const_iterator result(this);
  18944. result.set_end();
  18945. return result;
  18946. }
  18947. /*!
  18948. @brief returns an iterator to the reverse-beginning
  18949. Returns an iterator to the reverse-beginning; that is, the last element.
  18950. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  18951. @complexity Constant.
  18952. @requirement This function helps `basic_json` satisfying the
  18953. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  18954. requirements:
  18955. - The complexity is constant.
  18956. - Has the semantics of `reverse_iterator(end())`.
  18957. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  18958. @sa see @ref crbegin() -- returns a const reverse iterator to the beginning
  18959. @sa see @ref rend() -- returns a reverse iterator to the end
  18960. @sa see @ref crend() -- returns a const reverse iterator to the end
  18961. @since version 1.0.0
  18962. */
  18963. reverse_iterator rbegin() noexcept
  18964. {
  18965. return reverse_iterator(end());
  18966. }
  18967. /*!
  18968. @copydoc basic_json::crbegin()
  18969. */
  18970. const_reverse_iterator rbegin() const noexcept
  18971. {
  18972. return crbegin();
  18973. }
  18974. /*!
  18975. @brief returns an iterator to the reverse-end
  18976. Returns an iterator to the reverse-end; that is, one before the first
  18977. element.
  18978. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  18979. @complexity Constant.
  18980. @requirement This function helps `basic_json` satisfying the
  18981. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  18982. requirements:
  18983. - The complexity is constant.
  18984. - Has the semantics of `reverse_iterator(begin())`.
  18985. @liveexample{The following code shows an example for `rend()`.,rend}
  18986. @sa see @ref crend() -- returns a const reverse iterator to the end
  18987. @sa see @ref rbegin() -- returns a reverse iterator to the beginning
  18988. @sa see @ref crbegin() -- returns a const reverse iterator to the beginning
  18989. @since version 1.0.0
  18990. */
  18991. reverse_iterator rend() noexcept
  18992. {
  18993. return reverse_iterator(begin());
  18994. }
  18995. /*!
  18996. @copydoc basic_json::crend()
  18997. */
  18998. const_reverse_iterator rend() const noexcept
  18999. {
  19000. return crend();
  19001. }
  19002. /*!
  19003. @brief returns a const reverse iterator to the last element
  19004. Returns a const iterator to the reverse-beginning; that is, the last
  19005. element.
  19006. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  19007. @complexity Constant.
  19008. @requirement This function helps `basic_json` satisfying the
  19009. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  19010. requirements:
  19011. - The complexity is constant.
  19012. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  19013. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  19014. @sa see @ref rbegin() -- returns a reverse iterator to the beginning
  19015. @sa see @ref rend() -- returns a reverse iterator to the end
  19016. @sa see @ref crend() -- returns a const reverse iterator to the end
  19017. @since version 1.0.0
  19018. */
  19019. const_reverse_iterator crbegin() const noexcept
  19020. {
  19021. return const_reverse_iterator(cend());
  19022. }
  19023. /*!
  19024. @brief returns a const reverse iterator to one before the first
  19025. Returns a const reverse iterator to the reverse-end; that is, one before
  19026. the first element.
  19027. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  19028. @complexity Constant.
  19029. @requirement This function helps `basic_json` satisfying the
  19030. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  19031. requirements:
  19032. - The complexity is constant.
  19033. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  19034. @liveexample{The following code shows an example for `crend()`.,crend}
  19035. @sa see @ref rend() -- returns a reverse iterator to the end
  19036. @sa see @ref rbegin() -- returns a reverse iterator to the beginning
  19037. @sa see @ref crbegin() -- returns a const reverse iterator to the beginning
  19038. @since version 1.0.0
  19039. */
  19040. const_reverse_iterator crend() const noexcept
  19041. {
  19042. return const_reverse_iterator(cbegin());
  19043. }
  19044. public:
  19045. /*!
  19046. @brief wrapper to access iterator member functions in range-based for
  19047. This function allows to access @ref iterator::key() and @ref
  19048. iterator::value() during range-based for loops. In these loops, a
  19049. reference to the JSON values is returned, so there is no access to the
  19050. underlying iterator.
  19051. For loop without iterator_wrapper:
  19052. @code{cpp}
  19053. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  19054. {
  19055. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  19056. }
  19057. @endcode
  19058. Range-based for loop without iterator proxy:
  19059. @code{cpp}
  19060. for (auto it : j_object)
  19061. {
  19062. // "it" is of type json::reference and has no key() member
  19063. std::cout << "value: " << it << '\n';
  19064. }
  19065. @endcode
  19066. Range-based for loop with iterator proxy:
  19067. @code{cpp}
  19068. for (auto it : json::iterator_wrapper(j_object))
  19069. {
  19070. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  19071. }
  19072. @endcode
  19073. @note When iterating over an array, `key()` will return the index of the
  19074. element as string (see example).
  19075. @param[in] ref reference to a JSON value
  19076. @return iteration proxy object wrapping @a ref with an interface to use in
  19077. range-based for loops
  19078. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  19079. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  19080. changes in the JSON value.
  19081. @complexity Constant.
  19082. @note The name of this function is not yet final and may change in the
  19083. future.
  19084. @deprecated This stream operator is deprecated and will be removed in
  19085. future 4.0.0 of the library. Please use @ref items() instead;
  19086. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  19087. */
  19088. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  19089. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  19090. {
  19091. return ref.items();
  19092. }
  19093. /*!
  19094. @copydoc iterator_wrapper(reference)
  19095. */
  19096. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  19097. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  19098. {
  19099. return ref.items();
  19100. }
  19101. /*!
  19102. @brief helper to access iterator member functions in range-based for
  19103. This function allows to access @ref iterator::key() and @ref
  19104. iterator::value() during range-based for loops. In these loops, a
  19105. reference to the JSON values is returned, so there is no access to the
  19106. underlying iterator.
  19107. For loop without `items()` function:
  19108. @code{cpp}
  19109. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  19110. {
  19111. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  19112. }
  19113. @endcode
  19114. Range-based for loop without `items()` function:
  19115. @code{cpp}
  19116. for (auto it : j_object)
  19117. {
  19118. // "it" is of type json::reference and has no key() member
  19119. std::cout << "value: " << it << '\n';
  19120. }
  19121. @endcode
  19122. Range-based for loop with `items()` function:
  19123. @code{cpp}
  19124. for (auto& el : j_object.items())
  19125. {
  19126. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  19127. }
  19128. @endcode
  19129. The `items()` function also allows to use
  19130. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  19131. (C++17):
  19132. @code{cpp}
  19133. for (auto& [key, val] : j_object.items())
  19134. {
  19135. std::cout << "key: " << key << ", value:" << val << '\n';
  19136. }
  19137. @endcode
  19138. @note When iterating over an array, `key()` will return the index of the
  19139. element as string (see example). For primitive types (e.g., numbers),
  19140. `key()` returns an empty string.
  19141. @warning Using `items()` on temporary objects is dangerous. Make sure the
  19142. object's lifetime exeeds the iteration. See
  19143. <https://github.com/nlohmann/json/issues/2040> for more
  19144. information.
  19145. @return iteration proxy object wrapping @a ref with an interface to use in
  19146. range-based for loops
  19147. @liveexample{The following code shows how the function is used.,items}
  19148. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  19149. changes in the JSON value.
  19150. @complexity Constant.
  19151. @since version 3.1.0, structured bindings support since 3.5.0.
  19152. */
  19153. iteration_proxy<iterator> items() noexcept
  19154. {
  19155. return iteration_proxy<iterator>(*this);
  19156. }
  19157. /*!
  19158. @copydoc items()
  19159. */
  19160. iteration_proxy<const_iterator> items() const noexcept
  19161. {
  19162. return iteration_proxy<const_iterator>(*this);
  19163. }
  19164. /// @}
  19165. //////////////
  19166. // capacity //
  19167. //////////////
  19168. /// @name capacity
  19169. /// @{
  19170. /*!
  19171. @brief checks whether the container is empty.
  19172. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  19173. @return The return value depends on the different types and is
  19174. defined as follows:
  19175. Value type | return value
  19176. ----------- | -------------
  19177. null | `true`
  19178. boolean | `false`
  19179. string | `false`
  19180. number | `false`
  19181. binary | `false`
  19182. object | result of function `object_t::empty()`
  19183. array | result of function `array_t::empty()`
  19184. @liveexample{The following code uses `empty()` to check if a JSON
  19185. object contains any elements.,empty}
  19186. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  19187. the Container concept; that is, their `empty()` functions have constant
  19188. complexity.
  19189. @iterators No changes.
  19190. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19191. @note This function does not return whether a string stored as JSON value
  19192. is empty - it returns whether the JSON container itself is empty which is
  19193. false in the case of a string.
  19194. @requirement This function helps `basic_json` satisfying the
  19195. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  19196. requirements:
  19197. - The complexity is constant.
  19198. - Has the semantics of `begin() == end()`.
  19199. @sa see @ref size() -- returns the number of elements
  19200. @since version 1.0.0
  19201. */
  19202. bool empty() const noexcept
  19203. {
  19204. switch (m_type)
  19205. {
  19206. case value_t::null:
  19207. {
  19208. // null values are empty
  19209. return true;
  19210. }
  19211. case value_t::array:
  19212. {
  19213. // delegate call to array_t::empty()
  19214. return m_value.array->empty();
  19215. }
  19216. case value_t::object:
  19217. {
  19218. // delegate call to object_t::empty()
  19219. return m_value.object->empty();
  19220. }
  19221. case value_t::string:
  19222. case value_t::boolean:
  19223. case value_t::number_integer:
  19224. case value_t::number_unsigned:
  19225. case value_t::number_float:
  19226. case value_t::binary:
  19227. case value_t::discarded:
  19228. default:
  19229. {
  19230. // all other types are nonempty
  19231. return false;
  19232. }
  19233. }
  19234. }
  19235. /*!
  19236. @brief returns the number of elements
  19237. Returns the number of elements in a JSON value.
  19238. @return The return value depends on the different types and is
  19239. defined as follows:
  19240. Value type | return value
  19241. ----------- | -------------
  19242. null | `0`
  19243. boolean | `1`
  19244. string | `1`
  19245. number | `1`
  19246. binary | `1`
  19247. object | result of function object_t::size()
  19248. array | result of function array_t::size()
  19249. @liveexample{The following code calls `size()` on the different value
  19250. types.,size}
  19251. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  19252. the Container concept; that is, their size() functions have constant
  19253. complexity.
  19254. @iterators No changes.
  19255. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19256. @note This function does not return the length of a string stored as JSON
  19257. value - it returns the number of elements in the JSON value which is 1 in
  19258. the case of a string.
  19259. @requirement This function helps `basic_json` satisfying the
  19260. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  19261. requirements:
  19262. - The complexity is constant.
  19263. - Has the semantics of `std::distance(begin(), end())`.
  19264. @sa see @ref empty() -- checks whether the container is empty
  19265. @sa see @ref max_size() -- returns the maximal number of elements
  19266. @since version 1.0.0
  19267. */
  19268. size_type size() const noexcept
  19269. {
  19270. switch (m_type)
  19271. {
  19272. case value_t::null:
  19273. {
  19274. // null values are empty
  19275. return 0;
  19276. }
  19277. case value_t::array:
  19278. {
  19279. // delegate call to array_t::size()
  19280. return m_value.array->size();
  19281. }
  19282. case value_t::object:
  19283. {
  19284. // delegate call to object_t::size()
  19285. return m_value.object->size();
  19286. }
  19287. case value_t::string:
  19288. case value_t::boolean:
  19289. case value_t::number_integer:
  19290. case value_t::number_unsigned:
  19291. case value_t::number_float:
  19292. case value_t::binary:
  19293. case value_t::discarded:
  19294. default:
  19295. {
  19296. // all other types have size 1
  19297. return 1;
  19298. }
  19299. }
  19300. }
  19301. /*!
  19302. @brief returns the maximum possible number of elements
  19303. Returns the maximum number of elements a JSON value is able to hold due to
  19304. system or library implementation limitations, i.e. `std::distance(begin(),
  19305. end())` for the JSON value.
  19306. @return The return value depends on the different types and is
  19307. defined as follows:
  19308. Value type | return value
  19309. ----------- | -------------
  19310. null | `0` (same as `size()`)
  19311. boolean | `1` (same as `size()`)
  19312. string | `1` (same as `size()`)
  19313. number | `1` (same as `size()`)
  19314. binary | `1` (same as `size()`)
  19315. object | result of function `object_t::max_size()`
  19316. array | result of function `array_t::max_size()`
  19317. @liveexample{The following code calls `max_size()` on the different value
  19318. types. Note the output is implementation specific.,max_size}
  19319. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  19320. the Container concept; that is, their `max_size()` functions have constant
  19321. complexity.
  19322. @iterators No changes.
  19323. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19324. @requirement This function helps `basic_json` satisfying the
  19325. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  19326. requirements:
  19327. - The complexity is constant.
  19328. - Has the semantics of returning `b.size()` where `b` is the largest
  19329. possible JSON value.
  19330. @sa see @ref size() -- returns the number of elements
  19331. @since version 1.0.0
  19332. */
  19333. size_type max_size() const noexcept
  19334. {
  19335. switch (m_type)
  19336. {
  19337. case value_t::array:
  19338. {
  19339. // delegate call to array_t::max_size()
  19340. return m_value.array->max_size();
  19341. }
  19342. case value_t::object:
  19343. {
  19344. // delegate call to object_t::max_size()
  19345. return m_value.object->max_size();
  19346. }
  19347. case value_t::null:
  19348. case value_t::string:
  19349. case value_t::boolean:
  19350. case value_t::number_integer:
  19351. case value_t::number_unsigned:
  19352. case value_t::number_float:
  19353. case value_t::binary:
  19354. case value_t::discarded:
  19355. default:
  19356. {
  19357. // all other types have max_size() == size()
  19358. return size();
  19359. }
  19360. }
  19361. }
  19362. /// @}
  19363. ///////////////
  19364. // modifiers //
  19365. ///////////////
  19366. /// @name modifiers
  19367. /// @{
  19368. /*!
  19369. @brief clears the contents
  19370. Clears the content of a JSON value and resets it to the default value as
  19371. if @ref basic_json(value_t) would have been called with the current value
  19372. type from @ref type():
  19373. Value type | initial value
  19374. ----------- | -------------
  19375. null | `null`
  19376. boolean | `false`
  19377. string | `""`
  19378. number | `0`
  19379. binary | An empty byte vector
  19380. object | `{}`
  19381. array | `[]`
  19382. @post Has the same effect as calling
  19383. @code {.cpp}
  19384. *this = basic_json(type());
  19385. @endcode
  19386. @liveexample{The example below shows the effect of `clear()` to different
  19387. JSON types.,clear}
  19388. @complexity Linear in the size of the JSON value.
  19389. @iterators All iterators, pointers and references related to this container
  19390. are invalidated.
  19391. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19392. @sa see @ref basic_json(value_t) -- constructor that creates an object with the
  19393. same value than calling `clear()`
  19394. @since version 1.0.0
  19395. */
  19396. void clear() noexcept
  19397. {
  19398. switch (m_type)
  19399. {
  19400. case value_t::number_integer:
  19401. {
  19402. m_value.number_integer = 0;
  19403. break;
  19404. }
  19405. case value_t::number_unsigned:
  19406. {
  19407. m_value.number_unsigned = 0;
  19408. break;
  19409. }
  19410. case value_t::number_float:
  19411. {
  19412. m_value.number_float = 0.0;
  19413. break;
  19414. }
  19415. case value_t::boolean:
  19416. {
  19417. m_value.boolean = false;
  19418. break;
  19419. }
  19420. case value_t::string:
  19421. {
  19422. m_value.string->clear();
  19423. break;
  19424. }
  19425. case value_t::binary:
  19426. {
  19427. m_value.binary->clear();
  19428. break;
  19429. }
  19430. case value_t::array:
  19431. {
  19432. m_value.array->clear();
  19433. break;
  19434. }
  19435. case value_t::object:
  19436. {
  19437. m_value.object->clear();
  19438. break;
  19439. }
  19440. case value_t::null:
  19441. case value_t::discarded:
  19442. default:
  19443. break;
  19444. }
  19445. }
  19446. /*!
  19447. @brief add an object to an array
  19448. Appends the given element @a val to the end of the JSON value. If the
  19449. function is called on a JSON null value, an empty array is created before
  19450. appending @a val.
  19451. @param[in] val the value to add to the JSON array
  19452. @throw type_error.308 when called on a type other than JSON array or
  19453. null; example: `"cannot use push_back() with number"`
  19454. @complexity Amortized constant.
  19455. @liveexample{The example shows how `push_back()` and `+=` can be used to
  19456. add elements to a JSON array. Note how the `null` value was silently
  19457. converted to a JSON array.,push_back}
  19458. @since version 1.0.0
  19459. */
  19460. void push_back(basic_json&& val)
  19461. {
  19462. // push_back only works for null objects or arrays
  19463. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  19464. {
  19465. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
  19466. }
  19467. // transform null object into an array
  19468. if (is_null())
  19469. {
  19470. m_type = value_t::array;
  19471. m_value = value_t::array;
  19472. assert_invariant();
  19473. }
  19474. // add element to array (move semantics)
  19475. const auto old_capacity = m_value.array->capacity();
  19476. m_value.array->push_back(std::move(val));
  19477. set_parent(m_value.array->back(), old_capacity);
  19478. // if val is moved from, basic_json move constructor marks it null so we do not call the destructor
  19479. }
  19480. /*!
  19481. @brief add an object to an array
  19482. @copydoc push_back(basic_json&&)
  19483. */
  19484. reference operator+=(basic_json&& val)
  19485. {
  19486. push_back(std::move(val));
  19487. return *this;
  19488. }
  19489. /*!
  19490. @brief add an object to an array
  19491. @copydoc push_back(basic_json&&)
  19492. */
  19493. void push_back(const basic_json& val)
  19494. {
  19495. // push_back only works for null objects or arrays
  19496. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  19497. {
  19498. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
  19499. }
  19500. // transform null object into an array
  19501. if (is_null())
  19502. {
  19503. m_type = value_t::array;
  19504. m_value = value_t::array;
  19505. assert_invariant();
  19506. }
  19507. // add element to array
  19508. const auto old_capacity = m_value.array->capacity();
  19509. m_value.array->push_back(val);
  19510. set_parent(m_value.array->back(), old_capacity);
  19511. }
  19512. /*!
  19513. @brief add an object to an array
  19514. @copydoc push_back(basic_json&&)
  19515. */
  19516. reference operator+=(const basic_json& val)
  19517. {
  19518. push_back(val);
  19519. return *this;
  19520. }
  19521. /*!
  19522. @brief add an object to an object
  19523. Inserts the given element @a val to the JSON object. If the function is
  19524. called on a JSON null value, an empty object is created before inserting
  19525. @a val.
  19526. @param[in] val the value to add to the JSON object
  19527. @throw type_error.308 when called on a type other than JSON object or
  19528. null; example: `"cannot use push_back() with number"`
  19529. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  19530. @liveexample{The example shows how `push_back()` and `+=` can be used to
  19531. add elements to a JSON object. Note how the `null` value was silently
  19532. converted to a JSON object.,push_back__object_t__value}
  19533. @since version 1.0.0
  19534. */
  19535. void push_back(const typename object_t::value_type& val)
  19536. {
  19537. // push_back only works for null objects or objects
  19538. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  19539. {
  19540. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
  19541. }
  19542. // transform null object into an object
  19543. if (is_null())
  19544. {
  19545. m_type = value_t::object;
  19546. m_value = value_t::object;
  19547. assert_invariant();
  19548. }
  19549. // add element to object
  19550. auto res = m_value.object->insert(val);
  19551. set_parent(res.first->second);
  19552. }
  19553. /*!
  19554. @brief add an object to an object
  19555. @copydoc push_back(const typename object_t::value_type&)
  19556. */
  19557. reference operator+=(const typename object_t::value_type& val)
  19558. {
  19559. push_back(val);
  19560. return *this;
  19561. }
  19562. /*!
  19563. @brief add an object to an object
  19564. This function allows to use `push_back` with an initializer list. In case
  19565. 1. the current value is an object,
  19566. 2. the initializer list @a init contains only two elements, and
  19567. 3. the first element of @a init is a string,
  19568. @a init is converted into an object element and added using
  19569. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  19570. is converted to a JSON value and added using @ref push_back(basic_json&&).
  19571. @param[in] init an initializer list
  19572. @complexity Linear in the size of the initializer list @a init.
  19573. @note This function is required to resolve an ambiguous overload error,
  19574. because pairs like `{"key", "value"}` can be both interpreted as
  19575. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  19576. https://github.com/nlohmann/json/issues/235 for more information.
  19577. @liveexample{The example shows how initializer lists are treated as
  19578. objects when possible.,push_back__initializer_list}
  19579. */
  19580. void push_back(initializer_list_t init)
  19581. {
  19582. if (is_object() && init.size() == 2 && (*init.begin())->is_string())
  19583. {
  19584. basic_json&& key = init.begin()->moved_or_copied();
  19585. push_back(typename object_t::value_type(
  19586. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  19587. }
  19588. else
  19589. {
  19590. push_back(basic_json(init));
  19591. }
  19592. }
  19593. /*!
  19594. @brief add an object to an object
  19595. @copydoc push_back(initializer_list_t)
  19596. */
  19597. reference operator+=(initializer_list_t init)
  19598. {
  19599. push_back(init);
  19600. return *this;
  19601. }
  19602. /*!
  19603. @brief add an object to an array
  19604. Creates a JSON value from the passed parameters @a args to the end of the
  19605. JSON value. If the function is called on a JSON null value, an empty array
  19606. is created before appending the value created from @a args.
  19607. @param[in] args arguments to forward to a constructor of @ref basic_json
  19608. @tparam Args compatible types to create a @ref basic_json object
  19609. @return reference to the inserted element
  19610. @throw type_error.311 when called on a type other than JSON array or
  19611. null; example: `"cannot use emplace_back() with number"`
  19612. @complexity Amortized constant.
  19613. @liveexample{The example shows how `push_back()` can be used to add
  19614. elements to a JSON array. Note how the `null` value was silently converted
  19615. to a JSON array.,emplace_back}
  19616. @since version 2.0.8, returns reference since 3.7.0
  19617. */
  19618. template<class... Args>
  19619. reference emplace_back(Args&& ... args)
  19620. {
  19621. // emplace_back only works for null objects or arrays
  19622. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  19623. {
  19624. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()), *this));
  19625. }
  19626. // transform null object into an array
  19627. if (is_null())
  19628. {
  19629. m_type = value_t::array;
  19630. m_value = value_t::array;
  19631. assert_invariant();
  19632. }
  19633. // add element to array (perfect forwarding)
  19634. const auto old_capacity = m_value.array->capacity();
  19635. m_value.array->emplace_back(std::forward<Args>(args)...);
  19636. return set_parent(m_value.array->back(), old_capacity);
  19637. }
  19638. /*!
  19639. @brief add an object to an object if key does not exist
  19640. Inserts a new element into a JSON object constructed in-place with the
  19641. given @a args if there is no element with the key in the container. If the
  19642. function is called on a JSON null value, an empty object is created before
  19643. appending the value created from @a args.
  19644. @param[in] args arguments to forward to a constructor of @ref basic_json
  19645. @tparam Args compatible types to create a @ref basic_json object
  19646. @return a pair consisting of an iterator to the inserted element, or the
  19647. already-existing element if no insertion happened, and a bool
  19648. denoting whether the insertion took place.
  19649. @throw type_error.311 when called on a type other than JSON object or
  19650. null; example: `"cannot use emplace() with number"`
  19651. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  19652. @liveexample{The example shows how `emplace()` can be used to add elements
  19653. to a JSON object. Note how the `null` value was silently converted to a
  19654. JSON object. Further note how no value is added if there was already one
  19655. value stored with the same key.,emplace}
  19656. @since version 2.0.8
  19657. */
  19658. template<class... Args>
  19659. std::pair<iterator, bool> emplace(Args&& ... args)
  19660. {
  19661. // emplace only works for null objects or arrays
  19662. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  19663. {
  19664. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()), *this));
  19665. }
  19666. // transform null object into an object
  19667. if (is_null())
  19668. {
  19669. m_type = value_t::object;
  19670. m_value = value_t::object;
  19671. assert_invariant();
  19672. }
  19673. // add element to array (perfect forwarding)
  19674. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  19675. set_parent(res.first->second);
  19676. // create result iterator and set iterator to the result of emplace
  19677. auto it = begin();
  19678. it.m_it.object_iterator = res.first;
  19679. // return pair of iterator and boolean
  19680. return {it, res.second};
  19681. }
  19682. /// Helper for insertion of an iterator
  19683. /// @note: This uses std::distance to support GCC 4.8,
  19684. /// see https://github.com/nlohmann/json/pull/1257
  19685. template<typename... Args>
  19686. iterator insert_iterator(const_iterator pos, Args&& ... args)
  19687. {
  19688. iterator result(this);
  19689. JSON_ASSERT(m_value.array != nullptr);
  19690. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  19691. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  19692. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  19693. // This could have been written as:
  19694. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  19695. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  19696. set_parents();
  19697. return result;
  19698. }
  19699. /*!
  19700. @brief inserts element
  19701. Inserts element @a val before iterator @a pos.
  19702. @param[in] pos iterator before which the content will be inserted; may be
  19703. the end() iterator
  19704. @param[in] val element to insert
  19705. @return iterator pointing to the inserted @a val.
  19706. @throw type_error.309 if called on JSON values other than arrays;
  19707. example: `"cannot use insert() with string"`
  19708. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  19709. example: `"iterator does not fit current value"`
  19710. @complexity Constant plus linear in the distance between @a pos and end of
  19711. the container.
  19712. @liveexample{The example shows how `insert()` is used.,insert}
  19713. @since version 1.0.0
  19714. */
  19715. iterator insert(const_iterator pos, const basic_json& val)
  19716. {
  19717. // insert only works for arrays
  19718. if (JSON_HEDLEY_LIKELY(is_array()))
  19719. {
  19720. // check if iterator pos fits to this JSON value
  19721. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  19722. {
  19723. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  19724. }
  19725. // insert to array and return iterator
  19726. return insert_iterator(pos, val);
  19727. }
  19728. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19729. }
  19730. /*!
  19731. @brief inserts element
  19732. @copydoc insert(const_iterator, const basic_json&)
  19733. */
  19734. iterator insert(const_iterator pos, basic_json&& val)
  19735. {
  19736. return insert(pos, val);
  19737. }
  19738. /*!
  19739. @brief inserts elements
  19740. Inserts @a cnt copies of @a val before iterator @a pos.
  19741. @param[in] pos iterator before which the content will be inserted; may be
  19742. the end() iterator
  19743. @param[in] cnt number of copies of @a val to insert
  19744. @param[in] val element to insert
  19745. @return iterator pointing to the first element inserted, or @a pos if
  19746. `cnt==0`
  19747. @throw type_error.309 if called on JSON values other than arrays; example:
  19748. `"cannot use insert() with string"`
  19749. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  19750. example: `"iterator does not fit current value"`
  19751. @complexity Linear in @a cnt plus linear in the distance between @a pos
  19752. and end of the container.
  19753. @liveexample{The example shows how `insert()` is used.,insert__count}
  19754. @since version 1.0.0
  19755. */
  19756. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  19757. {
  19758. // insert only works for arrays
  19759. if (JSON_HEDLEY_LIKELY(is_array()))
  19760. {
  19761. // check if iterator pos fits to this JSON value
  19762. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  19763. {
  19764. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  19765. }
  19766. // insert to array and return iterator
  19767. return insert_iterator(pos, cnt, val);
  19768. }
  19769. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19770. }
  19771. /*!
  19772. @brief inserts elements
  19773. Inserts elements from range `[first, last)` before iterator @a pos.
  19774. @param[in] pos iterator before which the content will be inserted; may be
  19775. the end() iterator
  19776. @param[in] first begin of the range of elements to insert
  19777. @param[in] last end of the range of elements to insert
  19778. @throw type_error.309 if called on JSON values other than arrays; example:
  19779. `"cannot use insert() with string"`
  19780. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  19781. example: `"iterator does not fit current value"`
  19782. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  19783. same JSON value; example: `"iterators do not fit"`
  19784. @throw invalid_iterator.211 if @a first or @a last are iterators into
  19785. container for which insert is called; example: `"passed iterators may not
  19786. belong to container"`
  19787. @return iterator pointing to the first element inserted, or @a pos if
  19788. `first==last`
  19789. @complexity Linear in `std::distance(first, last)` plus linear in the
  19790. distance between @a pos and end of the container.
  19791. @liveexample{The example shows how `insert()` is used.,insert__range}
  19792. @since version 1.0.0
  19793. */
  19794. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  19795. {
  19796. // insert only works for arrays
  19797. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  19798. {
  19799. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19800. }
  19801. // check if iterator pos fits to this JSON value
  19802. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  19803. {
  19804. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  19805. }
  19806. // check if range iterators belong to the same JSON object
  19807. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  19808. {
  19809. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
  19810. }
  19811. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  19812. {
  19813. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", *this));
  19814. }
  19815. // insert to array and return iterator
  19816. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  19817. }
  19818. /*!
  19819. @brief inserts elements
  19820. Inserts elements from initializer list @a ilist before iterator @a pos.
  19821. @param[in] pos iterator before which the content will be inserted; may be
  19822. the end() iterator
  19823. @param[in] ilist initializer list to insert the values from
  19824. @throw type_error.309 if called on JSON values other than arrays; example:
  19825. `"cannot use insert() with string"`
  19826. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  19827. example: `"iterator does not fit current value"`
  19828. @return iterator pointing to the first element inserted, or @a pos if
  19829. `ilist` is empty
  19830. @complexity Linear in `ilist.size()` plus linear in the distance between
  19831. @a pos and end of the container.
  19832. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  19833. @since version 1.0.0
  19834. */
  19835. iterator insert(const_iterator pos, initializer_list_t ilist)
  19836. {
  19837. // insert only works for arrays
  19838. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  19839. {
  19840. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19841. }
  19842. // check if iterator pos fits to this JSON value
  19843. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  19844. {
  19845. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
  19846. }
  19847. // insert to array and return iterator
  19848. return insert_iterator(pos, ilist.begin(), ilist.end());
  19849. }
  19850. /*!
  19851. @brief inserts elements
  19852. Inserts elements from range `[first, last)`.
  19853. @param[in] first begin of the range of elements to insert
  19854. @param[in] last end of the range of elements to insert
  19855. @throw type_error.309 if called on JSON values other than objects; example:
  19856. `"cannot use insert() with string"`
  19857. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  19858. point to an object; example: `"iterators first and last must point to
  19859. objects"`
  19860. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  19861. same JSON value; example: `"iterators do not fit"`
  19862. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  19863. of elements to insert.
  19864. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  19865. @since version 3.0.0
  19866. */
  19867. void insert(const_iterator first, const_iterator last)
  19868. {
  19869. // insert only works for objects
  19870. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  19871. {
  19872. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
  19873. }
  19874. // check if range iterators belong to the same JSON object
  19875. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  19876. {
  19877. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
  19878. }
  19879. // passed iterators must belong to objects
  19880. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
  19881. {
  19882. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this));
  19883. }
  19884. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  19885. }
  19886. /*!
  19887. @brief updates a JSON object from another object, overwriting existing keys
  19888. Inserts all values from JSON object @a j and overwrites existing keys.
  19889. @param[in] j JSON object to read values from
  19890. @throw type_error.312 if called on JSON values other than objects; example:
  19891. `"cannot use update() with string"`
  19892. @complexity O(N*log(size() + N)), where N is the number of elements to
  19893. insert.
  19894. @liveexample{The example shows how `update()` is used.,update}
  19895. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  19896. @since version 3.0.0
  19897. */
  19898. void update(const_reference j)
  19899. {
  19900. // implicitly convert null value to an empty object
  19901. if (is_null())
  19902. {
  19903. m_type = value_t::object;
  19904. m_value.object = create<object_t>();
  19905. assert_invariant();
  19906. }
  19907. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  19908. {
  19909. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this));
  19910. }
  19911. if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
  19912. {
  19913. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name()), *this));
  19914. }
  19915. for (auto it = j.cbegin(); it != j.cend(); ++it)
  19916. {
  19917. m_value.object->operator[](it.key()) = it.value();
  19918. #if JSON_DIAGNOSTICS
  19919. m_value.object->operator[](it.key()).m_parent = this;
  19920. #endif
  19921. }
  19922. }
  19923. /*!
  19924. @brief updates a JSON object from another object, overwriting existing keys
  19925. Inserts all values from from range `[first, last)` and overwrites existing
  19926. keys.
  19927. @param[in] first begin of the range of elements to insert
  19928. @param[in] last end of the range of elements to insert
  19929. @throw type_error.312 if called on JSON values other than objects; example:
  19930. `"cannot use update() with string"`
  19931. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  19932. point to an object; example: `"iterators first and last must point to
  19933. objects"`
  19934. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  19935. same JSON value; example: `"iterators do not fit"`
  19936. @complexity O(N*log(size() + N)), where N is the number of elements to
  19937. insert.
  19938. @liveexample{The example shows how `update()` is used__range.,update}
  19939. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  19940. @since version 3.0.0
  19941. */
  19942. void update(const_iterator first, const_iterator last)
  19943. {
  19944. // implicitly convert null value to an empty object
  19945. if (is_null())
  19946. {
  19947. m_type = value_t::object;
  19948. m_value.object = create<object_t>();
  19949. assert_invariant();
  19950. }
  19951. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  19952. {
  19953. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this));
  19954. }
  19955. // check if range iterators belong to the same JSON object
  19956. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  19957. {
  19958. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
  19959. }
  19960. // passed iterators must belong to objects
  19961. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()
  19962. || !last.m_object->is_object()))
  19963. {
  19964. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this));
  19965. }
  19966. for (auto it = first; it != last; ++it)
  19967. {
  19968. m_value.object->operator[](it.key()) = it.value();
  19969. #if JSON_DIAGNOSTICS
  19970. m_value.object->operator[](it.key()).m_parent = this;
  19971. #endif
  19972. }
  19973. }
  19974. /*!
  19975. @brief exchanges the values
  19976. Exchanges the contents of the JSON value with those of @a other. Does not
  19977. invoke any move, copy, or swap operations on individual elements. All
  19978. iterators and references remain valid. The past-the-end iterator is
  19979. invalidated.
  19980. @param[in,out] other JSON value to exchange the contents with
  19981. @complexity Constant.
  19982. @liveexample{The example below shows how JSON values can be swapped with
  19983. `swap()`.,swap__reference}
  19984. @since version 1.0.0
  19985. */
  19986. void swap(reference other) noexcept (
  19987. std::is_nothrow_move_constructible<value_t>::value&&
  19988. std::is_nothrow_move_assignable<value_t>::value&&
  19989. std::is_nothrow_move_constructible<json_value>::value&&
  19990. std::is_nothrow_move_assignable<json_value>::value
  19991. )
  19992. {
  19993. std::swap(m_type, other.m_type);
  19994. std::swap(m_value, other.m_value);
  19995. set_parents();
  19996. other.set_parents();
  19997. assert_invariant();
  19998. }
  19999. /*!
  20000. @brief exchanges the values
  20001. Exchanges the contents of the JSON value from @a left with those of @a right. Does not
  20002. invoke any move, copy, or swap operations on individual elements. All
  20003. iterators and references remain valid. The past-the-end iterator is
  20004. invalidated. implemented as a friend function callable via ADL.
  20005. @param[in,out] left JSON value to exchange the contents with
  20006. @param[in,out] right JSON value to exchange the contents with
  20007. @complexity Constant.
  20008. @liveexample{The example below shows how JSON values can be swapped with
  20009. `swap()`.,swap__reference}
  20010. @since version 1.0.0
  20011. */
  20012. friend void swap(reference left, reference right) noexcept (
  20013. std::is_nothrow_move_constructible<value_t>::value&&
  20014. std::is_nothrow_move_assignable<value_t>::value&&
  20015. std::is_nothrow_move_constructible<json_value>::value&&
  20016. std::is_nothrow_move_assignable<json_value>::value
  20017. )
  20018. {
  20019. left.swap(right);
  20020. }
  20021. /*!
  20022. @brief exchanges the values
  20023. Exchanges the contents of a JSON array with those of @a other. Does not
  20024. invoke any move, copy, or swap operations on individual elements. All
  20025. iterators and references remain valid. The past-the-end iterator is
  20026. invalidated.
  20027. @param[in,out] other array to exchange the contents with
  20028. @throw type_error.310 when JSON value is not an array; example: `"cannot
  20029. use swap() with string"`
  20030. @complexity Constant.
  20031. @liveexample{The example below shows how arrays can be swapped with
  20032. `swap()`.,swap__array_t}
  20033. @since version 1.0.0
  20034. */
  20035. void swap(array_t& other) // NOLINT(bugprone-exception-escape)
  20036. {
  20037. // swap only works for arrays
  20038. if (JSON_HEDLEY_LIKELY(is_array()))
  20039. {
  20040. std::swap(*(m_value.array), other);
  20041. }
  20042. else
  20043. {
  20044. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20045. }
  20046. }
  20047. /*!
  20048. @brief exchanges the values
  20049. Exchanges the contents of a JSON object with those of @a other. Does not
  20050. invoke any move, copy, or swap operations on individual elements. All
  20051. iterators and references remain valid. The past-the-end iterator is
  20052. invalidated.
  20053. @param[in,out] other object to exchange the contents with
  20054. @throw type_error.310 when JSON value is not an object; example:
  20055. `"cannot use swap() with string"`
  20056. @complexity Constant.
  20057. @liveexample{The example below shows how objects can be swapped with
  20058. `swap()`.,swap__object_t}
  20059. @since version 1.0.0
  20060. */
  20061. void swap(object_t& other) // NOLINT(bugprone-exception-escape)
  20062. {
  20063. // swap only works for objects
  20064. if (JSON_HEDLEY_LIKELY(is_object()))
  20065. {
  20066. std::swap(*(m_value.object), other);
  20067. }
  20068. else
  20069. {
  20070. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20071. }
  20072. }
  20073. /*!
  20074. @brief exchanges the values
  20075. Exchanges the contents of a JSON string with those of @a other. Does not
  20076. invoke any move, copy, or swap operations on individual elements. All
  20077. iterators and references remain valid. The past-the-end iterator is
  20078. invalidated.
  20079. @param[in,out] other string to exchange the contents with
  20080. @throw type_error.310 when JSON value is not a string; example: `"cannot
  20081. use swap() with boolean"`
  20082. @complexity Constant.
  20083. @liveexample{The example below shows how strings can be swapped with
  20084. `swap()`.,swap__string_t}
  20085. @since version 1.0.0
  20086. */
  20087. void swap(string_t& other) // NOLINT(bugprone-exception-escape)
  20088. {
  20089. // swap only works for strings
  20090. if (JSON_HEDLEY_LIKELY(is_string()))
  20091. {
  20092. std::swap(*(m_value.string), other);
  20093. }
  20094. else
  20095. {
  20096. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20097. }
  20098. }
  20099. /*!
  20100. @brief exchanges the values
  20101. Exchanges the contents of a JSON string with those of @a other. Does not
  20102. invoke any move, copy, or swap operations on individual elements. All
  20103. iterators and references remain valid. The past-the-end iterator is
  20104. invalidated.
  20105. @param[in,out] other binary to exchange the contents with
  20106. @throw type_error.310 when JSON value is not a string; example: `"cannot
  20107. use swap() with boolean"`
  20108. @complexity Constant.
  20109. @liveexample{The example below shows how strings can be swapped with
  20110. `swap()`.,swap__binary_t}
  20111. @since version 3.8.0
  20112. */
  20113. void swap(binary_t& other) // NOLINT(bugprone-exception-escape)
  20114. {
  20115. // swap only works for strings
  20116. if (JSON_HEDLEY_LIKELY(is_binary()))
  20117. {
  20118. std::swap(*(m_value.binary), other);
  20119. }
  20120. else
  20121. {
  20122. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20123. }
  20124. }
  20125. /// @copydoc swap(binary_t&)
  20126. void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape)
  20127. {
  20128. // swap only works for strings
  20129. if (JSON_HEDLEY_LIKELY(is_binary()))
  20130. {
  20131. std::swap(*(m_value.binary), other);
  20132. }
  20133. else
  20134. {
  20135. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
  20136. }
  20137. }
  20138. /// @}
  20139. public:
  20140. //////////////////////////////////////////
  20141. // lexicographical comparison operators //
  20142. //////////////////////////////////////////
  20143. /// @name lexicographical comparison operators
  20144. /// @{
  20145. /*!
  20146. @brief comparison: equal
  20147. Compares two JSON values for equality according to the following rules:
  20148. - Two JSON values are equal if (1) they are from the same type and (2)
  20149. their stored values are the same according to their respective
  20150. `operator==`.
  20151. - Integer and floating-point numbers are automatically converted before
  20152. comparison. Note that two NaN values are always treated as unequal.
  20153. - Two JSON null values are equal.
  20154. @note Floating-point inside JSON values numbers are compared with
  20155. `json::number_float_t::operator==` which is `double::operator==` by
  20156. default. To compare floating-point while respecting an epsilon, an alternative
  20157. [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39)
  20158. could be used, for instance
  20159. @code {.cpp}
  20160. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  20161. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  20162. {
  20163. return std::abs(a - b) <= epsilon;
  20164. }
  20165. @endcode
  20166. Or you can self-defined operator equal function like this:
  20167. @code {.cpp}
  20168. bool my_equal(const_reference lhs, const_reference rhs) {
  20169. const auto lhs_type lhs.type();
  20170. const auto rhs_type rhs.type();
  20171. if (lhs_type == rhs_type) {
  20172. switch(lhs_type)
  20173. // self_defined case
  20174. case value_t::number_float:
  20175. return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();
  20176. // other cases remain the same with the original
  20177. ...
  20178. }
  20179. ...
  20180. }
  20181. @endcode
  20182. @note NaN values never compare equal to themselves or to other NaN values.
  20183. @param[in] lhs first JSON value to consider
  20184. @param[in] rhs second JSON value to consider
  20185. @return whether the values @a lhs and @a rhs are equal
  20186. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20187. @complexity Linear.
  20188. @liveexample{The example demonstrates comparing several JSON
  20189. types.,operator__equal}
  20190. @since version 1.0.0
  20191. */
  20192. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  20193. {
  20194. #ifdef __GNUC__
  20195. #pragma GCC diagnostic push
  20196. #pragma GCC diagnostic ignored "-Wfloat-equal"
  20197. #endif
  20198. const auto lhs_type = lhs.type();
  20199. const auto rhs_type = rhs.type();
  20200. if (lhs_type == rhs_type)
  20201. {
  20202. switch (lhs_type)
  20203. {
  20204. case value_t::array:
  20205. return *lhs.m_value.array == *rhs.m_value.array;
  20206. case value_t::object:
  20207. return *lhs.m_value.object == *rhs.m_value.object;
  20208. case value_t::null:
  20209. return true;
  20210. case value_t::string:
  20211. return *lhs.m_value.string == *rhs.m_value.string;
  20212. case value_t::boolean:
  20213. return lhs.m_value.boolean == rhs.m_value.boolean;
  20214. case value_t::number_integer:
  20215. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  20216. case value_t::number_unsigned:
  20217. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  20218. case value_t::number_float:
  20219. return lhs.m_value.number_float == rhs.m_value.number_float;
  20220. case value_t::binary:
  20221. return *lhs.m_value.binary == *rhs.m_value.binary;
  20222. case value_t::discarded:
  20223. default:
  20224. return false;
  20225. }
  20226. }
  20227. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
  20228. {
  20229. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  20230. }
  20231. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
  20232. {
  20233. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  20234. }
  20235. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
  20236. {
  20237. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  20238. }
  20239. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
  20240. {
  20241. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  20242. }
  20243. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
  20244. {
  20245. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  20246. }
  20247. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
  20248. {
  20249. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  20250. }
  20251. return false;
  20252. #ifdef __GNUC__
  20253. #pragma GCC diagnostic pop
  20254. #endif
  20255. }
  20256. /*!
  20257. @brief comparison: equal
  20258. @copydoc operator==(const_reference, const_reference)
  20259. */
  20260. template<typename ScalarType, typename std::enable_if<
  20261. std::is_scalar<ScalarType>::value, int>::type = 0>
  20262. friend bool operator==(const_reference lhs, ScalarType rhs) noexcept
  20263. {
  20264. return lhs == basic_json(rhs);
  20265. }
  20266. /*!
  20267. @brief comparison: equal
  20268. @copydoc operator==(const_reference, const_reference)
  20269. */
  20270. template<typename ScalarType, typename std::enable_if<
  20271. std::is_scalar<ScalarType>::value, int>::type = 0>
  20272. friend bool operator==(ScalarType lhs, const_reference rhs) noexcept
  20273. {
  20274. return basic_json(lhs) == rhs;
  20275. }
  20276. /*!
  20277. @brief comparison: not equal
  20278. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  20279. @param[in] lhs first JSON value to consider
  20280. @param[in] rhs second JSON value to consider
  20281. @return whether the values @a lhs and @a rhs are not equal
  20282. @complexity Linear.
  20283. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20284. @liveexample{The example demonstrates comparing several JSON
  20285. types.,operator__notequal}
  20286. @since version 1.0.0
  20287. */
  20288. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  20289. {
  20290. return !(lhs == rhs);
  20291. }
  20292. /*!
  20293. @brief comparison: not equal
  20294. @copydoc operator!=(const_reference, const_reference)
  20295. */
  20296. template<typename ScalarType, typename std::enable_if<
  20297. std::is_scalar<ScalarType>::value, int>::type = 0>
  20298. friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept
  20299. {
  20300. return lhs != basic_json(rhs);
  20301. }
  20302. /*!
  20303. @brief comparison: not equal
  20304. @copydoc operator!=(const_reference, const_reference)
  20305. */
  20306. template<typename ScalarType, typename std::enable_if<
  20307. std::is_scalar<ScalarType>::value, int>::type = 0>
  20308. friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept
  20309. {
  20310. return basic_json(lhs) != rhs;
  20311. }
  20312. /*!
  20313. @brief comparison: less than
  20314. Compares whether one JSON value @a lhs is less than another JSON value @a
  20315. rhs according to the following rules:
  20316. - If @a lhs and @a rhs have the same type, the values are compared using
  20317. the default `<` operator.
  20318. - Integer and floating-point numbers are automatically converted before
  20319. comparison
  20320. - In case @a lhs and @a rhs have different types, the values are ignored
  20321. and the order of the types is considered, see
  20322. @ref operator<(const value_t, const value_t).
  20323. @param[in] lhs first JSON value to consider
  20324. @param[in] rhs second JSON value to consider
  20325. @return whether @a lhs is less than @a rhs
  20326. @complexity Linear.
  20327. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20328. @liveexample{The example demonstrates comparing several JSON
  20329. types.,operator__less}
  20330. @since version 1.0.0
  20331. */
  20332. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  20333. {
  20334. const auto lhs_type = lhs.type();
  20335. const auto rhs_type = rhs.type();
  20336. if (lhs_type == rhs_type)
  20337. {
  20338. switch (lhs_type)
  20339. {
  20340. case value_t::array:
  20341. // note parentheses are necessary, see
  20342. // https://github.com/nlohmann/json/issues/1530
  20343. return (*lhs.m_value.array) < (*rhs.m_value.array);
  20344. case value_t::object:
  20345. return (*lhs.m_value.object) < (*rhs.m_value.object);
  20346. case value_t::null:
  20347. return false;
  20348. case value_t::string:
  20349. return (*lhs.m_value.string) < (*rhs.m_value.string);
  20350. case value_t::boolean:
  20351. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  20352. case value_t::number_integer:
  20353. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  20354. case value_t::number_unsigned:
  20355. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  20356. case value_t::number_float:
  20357. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  20358. case value_t::binary:
  20359. return (*lhs.m_value.binary) < (*rhs.m_value.binary);
  20360. case value_t::discarded:
  20361. default:
  20362. return false;
  20363. }
  20364. }
  20365. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
  20366. {
  20367. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  20368. }
  20369. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
  20370. {
  20371. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  20372. }
  20373. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
  20374. {
  20375. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  20376. }
  20377. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
  20378. {
  20379. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  20380. }
  20381. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
  20382. {
  20383. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  20384. }
  20385. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
  20386. {
  20387. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  20388. }
  20389. // We only reach this line if we cannot compare values. In that case,
  20390. // we compare types. Note we have to call the operator explicitly,
  20391. // because MSVC has problems otherwise.
  20392. return operator<(lhs_type, rhs_type);
  20393. }
  20394. /*!
  20395. @brief comparison: less than
  20396. @copydoc operator<(const_reference, const_reference)
  20397. */
  20398. template<typename ScalarType, typename std::enable_if<
  20399. std::is_scalar<ScalarType>::value, int>::type = 0>
  20400. friend bool operator<(const_reference lhs, ScalarType rhs) noexcept
  20401. {
  20402. return lhs < basic_json(rhs);
  20403. }
  20404. /*!
  20405. @brief comparison: less than
  20406. @copydoc operator<(const_reference, const_reference)
  20407. */
  20408. template<typename ScalarType, typename std::enable_if<
  20409. std::is_scalar<ScalarType>::value, int>::type = 0>
  20410. friend bool operator<(ScalarType lhs, const_reference rhs) noexcept
  20411. {
  20412. return basic_json(lhs) < rhs;
  20413. }
  20414. /*!
  20415. @brief comparison: less than or equal
  20416. Compares whether one JSON value @a lhs is less than or equal to another
  20417. JSON value by calculating `not (rhs < lhs)`.
  20418. @param[in] lhs first JSON value to consider
  20419. @param[in] rhs second JSON value to consider
  20420. @return whether @a lhs is less than or equal to @a rhs
  20421. @complexity Linear.
  20422. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20423. @liveexample{The example demonstrates comparing several JSON
  20424. types.,operator__greater}
  20425. @since version 1.0.0
  20426. */
  20427. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  20428. {
  20429. return !(rhs < lhs);
  20430. }
  20431. /*!
  20432. @brief comparison: less than or equal
  20433. @copydoc operator<=(const_reference, const_reference)
  20434. */
  20435. template<typename ScalarType, typename std::enable_if<
  20436. std::is_scalar<ScalarType>::value, int>::type = 0>
  20437. friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept
  20438. {
  20439. return lhs <= basic_json(rhs);
  20440. }
  20441. /*!
  20442. @brief comparison: less than or equal
  20443. @copydoc operator<=(const_reference, const_reference)
  20444. */
  20445. template<typename ScalarType, typename std::enable_if<
  20446. std::is_scalar<ScalarType>::value, int>::type = 0>
  20447. friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept
  20448. {
  20449. return basic_json(lhs) <= rhs;
  20450. }
  20451. /*!
  20452. @brief comparison: greater than
  20453. Compares whether one JSON value @a lhs is greater than another
  20454. JSON value by calculating `not (lhs <= rhs)`.
  20455. @param[in] lhs first JSON value to consider
  20456. @param[in] rhs second JSON value to consider
  20457. @return whether @a lhs is greater than to @a rhs
  20458. @complexity Linear.
  20459. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20460. @liveexample{The example demonstrates comparing several JSON
  20461. types.,operator__lessequal}
  20462. @since version 1.0.0
  20463. */
  20464. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  20465. {
  20466. return !(lhs <= rhs);
  20467. }
  20468. /*!
  20469. @brief comparison: greater than
  20470. @copydoc operator>(const_reference, const_reference)
  20471. */
  20472. template<typename ScalarType, typename std::enable_if<
  20473. std::is_scalar<ScalarType>::value, int>::type = 0>
  20474. friend bool operator>(const_reference lhs, ScalarType rhs) noexcept
  20475. {
  20476. return lhs > basic_json(rhs);
  20477. }
  20478. /*!
  20479. @brief comparison: greater than
  20480. @copydoc operator>(const_reference, const_reference)
  20481. */
  20482. template<typename ScalarType, typename std::enable_if<
  20483. std::is_scalar<ScalarType>::value, int>::type = 0>
  20484. friend bool operator>(ScalarType lhs, const_reference rhs) noexcept
  20485. {
  20486. return basic_json(lhs) > rhs;
  20487. }
  20488. /*!
  20489. @brief comparison: greater than or equal
  20490. Compares whether one JSON value @a lhs is greater than or equal to another
  20491. JSON value by calculating `not (lhs < rhs)`.
  20492. @param[in] lhs first JSON value to consider
  20493. @param[in] rhs second JSON value to consider
  20494. @return whether @a lhs is greater than or equal to @a rhs
  20495. @complexity Linear.
  20496. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20497. @liveexample{The example demonstrates comparing several JSON
  20498. types.,operator__greaterequal}
  20499. @since version 1.0.0
  20500. */
  20501. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  20502. {
  20503. return !(lhs < rhs);
  20504. }
  20505. /*!
  20506. @brief comparison: greater than or equal
  20507. @copydoc operator>=(const_reference, const_reference)
  20508. */
  20509. template<typename ScalarType, typename std::enable_if<
  20510. std::is_scalar<ScalarType>::value, int>::type = 0>
  20511. friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept
  20512. {
  20513. return lhs >= basic_json(rhs);
  20514. }
  20515. /*!
  20516. @brief comparison: greater than or equal
  20517. @copydoc operator>=(const_reference, const_reference)
  20518. */
  20519. template<typename ScalarType, typename std::enable_if<
  20520. std::is_scalar<ScalarType>::value, int>::type = 0>
  20521. friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept
  20522. {
  20523. return basic_json(lhs) >= rhs;
  20524. }
  20525. /// @}
  20526. ///////////////////
  20527. // serialization //
  20528. ///////////////////
  20529. /// @name serialization
  20530. /// @{
  20531. #ifndef JSON_NO_IO
  20532. /*!
  20533. @brief serialize to stream
  20534. Serialize the given JSON value @a j to the output stream @a o. The JSON
  20535. value will be serialized using the @ref dump member function.
  20536. - The indentation of the output can be controlled with the member variable
  20537. `width` of the output stream @a o. For instance, using the manipulator
  20538. `std::setw(4)` on @a o sets the indentation level to `4` and the
  20539. serialization result is the same as calling `dump(4)`.
  20540. - The indentation character can be controlled with the member variable
  20541. `fill` of the output stream @a o. For instance, the manipulator
  20542. `std::setfill('\\t')` sets indentation to use a tab character rather than
  20543. the default space character.
  20544. @param[in,out] o stream to serialize to
  20545. @param[in] j JSON value to serialize
  20546. @return the stream @a o
  20547. @throw type_error.316 if a string stored inside the JSON value is not
  20548. UTF-8 encoded
  20549. @complexity Linear.
  20550. @liveexample{The example below shows the serialization with different
  20551. parameters to `width` to adjust the indentation level.,operator_serialize}
  20552. @since version 1.0.0; indentation character added in version 3.0.0
  20553. */
  20554. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  20555. {
  20556. // read width member and use it as indentation parameter if nonzero
  20557. const bool pretty_print = o.width() > 0;
  20558. const auto indentation = pretty_print ? o.width() : 0;
  20559. // reset width to 0 for subsequent calls to this stream
  20560. o.width(0);
  20561. // do the actual serialization
  20562. serializer s(detail::output_adapter<char>(o), o.fill());
  20563. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  20564. return o;
  20565. }
  20566. /*!
  20567. @brief serialize to stream
  20568. @deprecated This stream operator is deprecated and will be removed in
  20569. future 4.0.0 of the library. Please use
  20570. @ref operator<<(std::ostream&, const basic_json&)
  20571. instead; that is, replace calls like `j >> o;` with `o << j;`.
  20572. @since version 1.0.0; deprecated since version 3.0.0
  20573. */
  20574. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&))
  20575. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  20576. {
  20577. return o << j;
  20578. }
  20579. #endif // JSON_NO_IO
  20580. /// @}
  20581. /////////////////////
  20582. // deserialization //
  20583. /////////////////////
  20584. /// @name deserialization
  20585. /// @{
  20586. /*!
  20587. @brief deserialize from a compatible input
  20588. @tparam InputType A compatible input, for instance
  20589. - an std::istream object
  20590. - a FILE pointer
  20591. - a C-style array of characters
  20592. - a pointer to a null-terminated string of single byte characters
  20593. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  20594. iterators.
  20595. @param[in] i input to read from
  20596. @param[in] cb a parser callback function of type @ref parser_callback_t
  20597. which is used to control the deserialization by filtering unwanted values
  20598. (optional)
  20599. @param[in] allow_exceptions whether to throw exceptions in case of a
  20600. parse error (optional, true by default)
  20601. @param[in] ignore_comments whether comments should be ignored and treated
  20602. like whitespace (true) or yield a parse error (true); (optional, false by
  20603. default)
  20604. @return deserialized JSON value; in case of a parse error and
  20605. @a allow_exceptions set to `false`, the return value will be
  20606. value_t::discarded.
  20607. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  20608. of input; expected string literal""`
  20609. @throw parse_error.102 if to_unicode fails or surrogate error
  20610. @throw parse_error.103 if to_unicode fails
  20611. @complexity Linear in the length of the input. The parser is a predictive
  20612. LL(1) parser. The complexity can be higher if the parser callback function
  20613. @a cb or reading from the input @a i has a super-linear complexity.
  20614. @note A UTF-8 byte order mark is silently ignored.
  20615. @liveexample{The example below demonstrates the `parse()` function reading
  20616. from an array.,parse__array__parser_callback_t}
  20617. @liveexample{The example below demonstrates the `parse()` function with
  20618. and without callback function.,parse__string__parser_callback_t}
  20619. @liveexample{The example below demonstrates the `parse()` function with
  20620. and without callback function.,parse__istream__parser_callback_t}
  20621. @liveexample{The example below demonstrates the `parse()` function reading
  20622. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  20623. @since version 2.0.3 (contiguous containers); version 3.9.0 allowed to
  20624. ignore comments.
  20625. */
  20626. template<typename InputType>
  20627. JSON_HEDLEY_WARN_UNUSED_RESULT
  20628. static basic_json parse(InputType&& i,
  20629. const parser_callback_t cb = nullptr,
  20630. const bool allow_exceptions = true,
  20631. const bool ignore_comments = false)
  20632. {
  20633. basic_json result;
  20634. parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions, ignore_comments).parse(true, result);
  20635. return result;
  20636. }
  20637. /*!
  20638. @brief deserialize from a pair of character iterators
  20639. The value_type of the iterator must be a integral type with size of 1, 2 or
  20640. 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
  20641. @param[in] first iterator to start of character range
  20642. @param[in] last iterator to end of character range
  20643. @param[in] cb a parser callback function of type @ref parser_callback_t
  20644. which is used to control the deserialization by filtering unwanted values
  20645. (optional)
  20646. @param[in] allow_exceptions whether to throw exceptions in case of a
  20647. parse error (optional, true by default)
  20648. @param[in] ignore_comments whether comments should be ignored and treated
  20649. like whitespace (true) or yield a parse error (true); (optional, false by
  20650. default)
  20651. @return deserialized JSON value; in case of a parse error and
  20652. @a allow_exceptions set to `false`, the return value will be
  20653. value_t::discarded.
  20654. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  20655. of input; expected string literal""`
  20656. @throw parse_error.102 if to_unicode fails or surrogate error
  20657. @throw parse_error.103 if to_unicode fails
  20658. */
  20659. template<typename IteratorType>
  20660. JSON_HEDLEY_WARN_UNUSED_RESULT
  20661. static basic_json parse(IteratorType first,
  20662. IteratorType last,
  20663. const parser_callback_t cb = nullptr,
  20664. const bool allow_exceptions = true,
  20665. const bool ignore_comments = false)
  20666. {
  20667. basic_json result;
  20668. parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result);
  20669. return result;
  20670. }
  20671. JSON_HEDLEY_WARN_UNUSED_RESULT
  20672. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len))
  20673. static basic_json parse(detail::span_input_adapter&& i,
  20674. const parser_callback_t cb = nullptr,
  20675. const bool allow_exceptions = true,
  20676. const bool ignore_comments = false)
  20677. {
  20678. basic_json result;
  20679. parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result);
  20680. return result;
  20681. }
  20682. /*!
  20683. @brief check if the input is valid JSON
  20684. Unlike the @ref parse(InputType&&, const parser_callback_t,const bool)
  20685. function, this function neither throws an exception in case of invalid JSON
  20686. input (i.e., a parse error) nor creates diagnostic information.
  20687. @tparam InputType A compatible input, for instance
  20688. - an std::istream object
  20689. - a FILE pointer
  20690. - a C-style array of characters
  20691. - a pointer to a null-terminated string of single byte characters
  20692. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  20693. iterators.
  20694. @param[in] i input to read from
  20695. @param[in] ignore_comments whether comments should be ignored and treated
  20696. like whitespace (true) or yield a parse error (true); (optional, false by
  20697. default)
  20698. @return Whether the input read from @a i is valid JSON.
  20699. @complexity Linear in the length of the input. The parser is a predictive
  20700. LL(1) parser.
  20701. @note A UTF-8 byte order mark is silently ignored.
  20702. @liveexample{The example below demonstrates the `accept()` function reading
  20703. from a string.,accept__string}
  20704. */
  20705. template<typename InputType>
  20706. static bool accept(InputType&& i,
  20707. const bool ignore_comments = false)
  20708. {
  20709. return parser(detail::input_adapter(std::forward<InputType>(i)), nullptr, false, ignore_comments).accept(true);
  20710. }
  20711. template<typename IteratorType>
  20712. static bool accept(IteratorType first, IteratorType last,
  20713. const bool ignore_comments = false)
  20714. {
  20715. return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true);
  20716. }
  20717. JSON_HEDLEY_WARN_UNUSED_RESULT
  20718. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len))
  20719. static bool accept(detail::span_input_adapter&& i,
  20720. const bool ignore_comments = false)
  20721. {
  20722. return parser(i.get(), nullptr, false, ignore_comments).accept(true);
  20723. }
  20724. /*!
  20725. @brief generate SAX events
  20726. The SAX event lister must follow the interface of @ref json_sax.
  20727. This function reads from a compatible input. Examples are:
  20728. - an std::istream object
  20729. - a FILE pointer
  20730. - a C-style array of characters
  20731. - a pointer to a null-terminated string of single byte characters
  20732. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  20733. iterators.
  20734. @param[in] i input to read from
  20735. @param[in,out] sax SAX event listener
  20736. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  20737. @param[in] strict whether the input has to be consumed completely
  20738. @param[in] ignore_comments whether comments should be ignored and treated
  20739. like whitespace (true) or yield a parse error (true); (optional, false by
  20740. default); only applies to the JSON file format.
  20741. @return return value of the last processed SAX event
  20742. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  20743. of input; expected string literal""`
  20744. @throw parse_error.102 if to_unicode fails or surrogate error
  20745. @throw parse_error.103 if to_unicode fails
  20746. @complexity Linear in the length of the input. The parser is a predictive
  20747. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  20748. a super-linear complexity.
  20749. @note A UTF-8 byte order mark is silently ignored.
  20750. @liveexample{The example below demonstrates the `sax_parse()` function
  20751. reading from string and processing the events with a user-defined SAX
  20752. event consumer.,sax_parse}
  20753. @since version 3.2.0
  20754. */
  20755. template <typename InputType, typename SAX>
  20756. JSON_HEDLEY_NON_NULL(2)
  20757. static bool sax_parse(InputType&& i, SAX* sax,
  20758. input_format_t format = input_format_t::json,
  20759. const bool strict = true,
  20760. const bool ignore_comments = false)
  20761. {
  20762. auto ia = detail::input_adapter(std::forward<InputType>(i));
  20763. return format == input_format_t::json
  20764. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  20765. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  20766. }
  20767. template<class IteratorType, class SAX>
  20768. JSON_HEDLEY_NON_NULL(3)
  20769. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax,
  20770. input_format_t format = input_format_t::json,
  20771. const bool strict = true,
  20772. const bool ignore_comments = false)
  20773. {
  20774. auto ia = detail::input_adapter(std::move(first), std::move(last));
  20775. return format == input_format_t::json
  20776. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  20777. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  20778. }
  20779. template <typename SAX>
  20780. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...))
  20781. JSON_HEDLEY_NON_NULL(2)
  20782. static bool sax_parse(detail::span_input_adapter&& i, SAX* sax,
  20783. input_format_t format = input_format_t::json,
  20784. const bool strict = true,
  20785. const bool ignore_comments = false)
  20786. {
  20787. auto ia = i.get();
  20788. return format == input_format_t::json
  20789. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  20790. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  20791. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  20792. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  20793. }
  20794. #ifndef JSON_NO_IO
  20795. /*!
  20796. @brief deserialize from stream
  20797. @deprecated This stream operator is deprecated and will be removed in
  20798. version 4.0.0 of the library. Please use
  20799. @ref operator>>(std::istream&, basic_json&)
  20800. instead; that is, replace calls like `j << i;` with `i >> j;`.
  20801. @since version 1.0.0; deprecated since version 3.0.0
  20802. */
  20803. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&))
  20804. friend std::istream& operator<<(basic_json& j, std::istream& i)
  20805. {
  20806. return operator>>(i, j);
  20807. }
  20808. /*!
  20809. @brief deserialize from stream
  20810. Deserializes an input stream to a JSON value.
  20811. @param[in,out] i input stream to read a serialized JSON value from
  20812. @param[in,out] j JSON value to write the deserialized input to
  20813. @throw parse_error.101 in case of an unexpected token
  20814. @throw parse_error.102 if to_unicode fails or surrogate error
  20815. @throw parse_error.103 if to_unicode fails
  20816. @complexity Linear in the length of the input. The parser is a predictive
  20817. LL(1) parser.
  20818. @note A UTF-8 byte order mark is silently ignored.
  20819. @liveexample{The example below shows how a JSON value is constructed by
  20820. reading a serialization from a stream.,operator_deserialize}
  20821. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  20822. parser callback function to filter values while parsing
  20823. @since version 1.0.0
  20824. */
  20825. friend std::istream& operator>>(std::istream& i, basic_json& j)
  20826. {
  20827. parser(detail::input_adapter(i)).parse(false, j);
  20828. return i;
  20829. }
  20830. #endif // JSON_NO_IO
  20831. /// @}
  20832. ///////////////////////////
  20833. // convenience functions //
  20834. ///////////////////////////
  20835. /*!
  20836. @brief return the type as string
  20837. Returns the type name as string to be used in error messages - usually to
  20838. indicate that a function was called on a wrong JSON type.
  20839. @return a string representation of a the @a m_type member:
  20840. Value type | return value
  20841. ----------- | -------------
  20842. null | `"null"`
  20843. boolean | `"boolean"`
  20844. string | `"string"`
  20845. number | `"number"` (for all number types)
  20846. object | `"object"`
  20847. array | `"array"`
  20848. binary | `"binary"`
  20849. discarded | `"discarded"`
  20850. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  20851. @complexity Constant.
  20852. @liveexample{The following code exemplifies `type_name()` for all JSON
  20853. types.,type_name}
  20854. @sa see @ref type() -- return the type of the JSON value
  20855. @sa see @ref operator value_t() -- return the type of the JSON value (implicit)
  20856. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  20857. since 3.0.0
  20858. */
  20859. JSON_HEDLEY_RETURNS_NON_NULL
  20860. const char* type_name() const noexcept
  20861. {
  20862. {
  20863. switch (m_type)
  20864. {
  20865. case value_t::null:
  20866. return "null";
  20867. case value_t::object:
  20868. return "object";
  20869. case value_t::array:
  20870. return "array";
  20871. case value_t::string:
  20872. return "string";
  20873. case value_t::boolean:
  20874. return "boolean";
  20875. case value_t::binary:
  20876. return "binary";
  20877. case value_t::discarded:
  20878. return "discarded";
  20879. case value_t::number_integer:
  20880. case value_t::number_unsigned:
  20881. case value_t::number_float:
  20882. default:
  20883. return "number";
  20884. }
  20885. }
  20886. }
  20887. JSON_PRIVATE_UNLESS_TESTED:
  20888. //////////////////////
  20889. // member variables //
  20890. //////////////////////
  20891. /// the type of the current element
  20892. value_t m_type = value_t::null;
  20893. /// the value of the current element
  20894. json_value m_value = {};
  20895. #if JSON_DIAGNOSTICS
  20896. /// a pointer to a parent value (for debugging purposes)
  20897. basic_json* m_parent = nullptr;
  20898. #endif
  20899. //////////////////////////////////////////
  20900. // binary serialization/deserialization //
  20901. //////////////////////////////////////////
  20902. /// @name binary serialization/deserialization support
  20903. /// @{
  20904. public:
  20905. /*!
  20906. @brief create a CBOR serialization of a given JSON value
  20907. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  20908. Binary Object Representation) serialization format. CBOR is a binary
  20909. serialization format which aims to be more compact than JSON itself, yet
  20910. more efficient to parse.
  20911. The library uses the following mapping from JSON values types to
  20912. CBOR types according to the CBOR specification (RFC 7049):
  20913. JSON value type | value/range | CBOR type | first byte
  20914. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  20915. null | `null` | Null | 0xF6
  20916. boolean | `true` | True | 0xF5
  20917. boolean | `false` | False | 0xF4
  20918. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  20919. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  20920. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  20921. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  20922. number_integer | -24..-1 | Negative integer | 0x20..0x37
  20923. number_integer | 0..23 | Integer | 0x00..0x17
  20924. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  20925. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  20926. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  20927. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  20928. number_unsigned | 0..23 | Integer | 0x00..0x17
  20929. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  20930. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  20931. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  20932. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  20933. number_float | *any value representable by a float* | Single-Precision Float | 0xFA
  20934. number_float | *any value NOT representable by a float* | Double-Precision Float | 0xFB
  20935. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  20936. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  20937. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  20938. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  20939. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  20940. array | *size*: 0..23 | array | 0x80..0x97
  20941. array | *size*: 23..255 | array (1 byte follow) | 0x98
  20942. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  20943. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  20944. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  20945. object | *size*: 0..23 | map | 0xA0..0xB7
  20946. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  20947. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  20948. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  20949. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  20950. binary | *size*: 0..23 | byte string | 0x40..0x57
  20951. binary | *size*: 23..255 | byte string (1 byte follow) | 0x58
  20952. binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59
  20953. binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A
  20954. binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B
  20955. Binary values with subtype are mapped to tagged values (0xD8..0xDB)
  20956. depending on the subtype, followed by a byte string, see "binary" cells
  20957. in the table above.
  20958. @note The mapping is **complete** in the sense that any JSON value type
  20959. can be converted to a CBOR value.
  20960. @note If NaN or Infinity are stored inside a JSON number, they are
  20961. serialized properly. This behavior differs from the @ref dump()
  20962. function which serializes NaN or Infinity to `null`.
  20963. @note The following CBOR types are not used in the conversion:
  20964. - UTF-8 strings terminated by "break" (0x7F)
  20965. - arrays terminated by "break" (0x9F)
  20966. - maps terminated by "break" (0xBF)
  20967. - byte strings terminated by "break" (0x5F)
  20968. - date/time (0xC0..0xC1)
  20969. - bignum (0xC2..0xC3)
  20970. - decimal fraction (0xC4)
  20971. - bigfloat (0xC5)
  20972. - expected conversions (0xD5..0xD7)
  20973. - simple values (0xE0..0xF3, 0xF8)
  20974. - undefined (0xF7)
  20975. - half-precision floats (0xF9)
  20976. - break (0xFF)
  20977. @param[in] j JSON value to serialize
  20978. @return CBOR serialization as byte vector
  20979. @complexity Linear in the size of the JSON value @a j.
  20980. @liveexample{The example shows the serialization of a JSON value to a byte
  20981. vector in CBOR format.,to_cbor}
  20982. @sa http://cbor.io
  20983. @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the
  20984. analogous deserialization
  20985. @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format
  20986. @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the
  20987. related UBJSON format
  20988. @since version 2.0.9; compact representation of floating-point numbers
  20989. since version 3.8.0
  20990. */
  20991. static std::vector<std::uint8_t> to_cbor(const basic_json& j)
  20992. {
  20993. std::vector<std::uint8_t> result;
  20994. to_cbor(j, result);
  20995. return result;
  20996. }
  20997. static void to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  20998. {
  20999. binary_writer<std::uint8_t>(o).write_cbor(j);
  21000. }
  21001. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  21002. {
  21003. binary_writer<char>(o).write_cbor(j);
  21004. }
  21005. /*!
  21006. @brief create a MessagePack serialization of a given JSON value
  21007. Serializes a given JSON value @a j to a byte vector using the MessagePack
  21008. serialization format. MessagePack is a binary serialization format which
  21009. aims to be more compact than JSON itself, yet more efficient to parse.
  21010. The library uses the following mapping from JSON values types to
  21011. MessagePack types according to the MessagePack specification:
  21012. JSON value type | value/range | MessagePack type | first byte
  21013. --------------- | --------------------------------- | ---------------- | ----------
  21014. null | `null` | nil | 0xC0
  21015. boolean | `true` | true | 0xC3
  21016. boolean | `false` | false | 0xC2
  21017. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  21018. number_integer | -2147483648..-32769 | int32 | 0xD2
  21019. number_integer | -32768..-129 | int16 | 0xD1
  21020. number_integer | -128..-33 | int8 | 0xD0
  21021. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  21022. number_integer | 0..127 | positive fixint | 0x00..0x7F
  21023. number_integer | 128..255 | uint 8 | 0xCC
  21024. number_integer | 256..65535 | uint 16 | 0xCD
  21025. number_integer | 65536..4294967295 | uint 32 | 0xCE
  21026. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  21027. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  21028. number_unsigned | 128..255 | uint 8 | 0xCC
  21029. number_unsigned | 256..65535 | uint 16 | 0xCD
  21030. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  21031. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  21032. number_float | *any value representable by a float* | float 32 | 0xCA
  21033. number_float | *any value NOT representable by a float* | float 64 | 0xCB
  21034. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  21035. string | *length*: 32..255 | str 8 | 0xD9
  21036. string | *length*: 256..65535 | str 16 | 0xDA
  21037. string | *length*: 65536..4294967295 | str 32 | 0xDB
  21038. array | *size*: 0..15 | fixarray | 0x90..0x9F
  21039. array | *size*: 16..65535 | array 16 | 0xDC
  21040. array | *size*: 65536..4294967295 | array 32 | 0xDD
  21041. object | *size*: 0..15 | fix map | 0x80..0x8F
  21042. object | *size*: 16..65535 | map 16 | 0xDE
  21043. object | *size*: 65536..4294967295 | map 32 | 0xDF
  21044. binary | *size*: 0..255 | bin 8 | 0xC4
  21045. binary | *size*: 256..65535 | bin 16 | 0xC5
  21046. binary | *size*: 65536..4294967295 | bin 32 | 0xC6
  21047. @note The mapping is **complete** in the sense that any JSON value type
  21048. can be converted to a MessagePack value.
  21049. @note The following values can **not** be converted to a MessagePack value:
  21050. - strings with more than 4294967295 bytes
  21051. - byte strings with more than 4294967295 bytes
  21052. - arrays with more than 4294967295 elements
  21053. - objects with more than 4294967295 elements
  21054. @note Any MessagePack output created @ref to_msgpack can be successfully
  21055. parsed by @ref from_msgpack.
  21056. @note If NaN or Infinity are stored inside a JSON number, they are
  21057. serialized properly. This behavior differs from the @ref dump()
  21058. function which serializes NaN or Infinity to `null`.
  21059. @param[in] j JSON value to serialize
  21060. @return MessagePack serialization as byte vector
  21061. @complexity Linear in the size of the JSON value @a j.
  21062. @liveexample{The example shows the serialization of a JSON value to a byte
  21063. vector in MessagePack format.,to_msgpack}
  21064. @sa http://msgpack.org
  21065. @sa see @ref from_msgpack for the analogous deserialization
  21066. @sa see @ref to_cbor(const basic_json& for the related CBOR format
  21067. @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the
  21068. related UBJSON format
  21069. @since version 2.0.9
  21070. */
  21071. static std::vector<std::uint8_t> to_msgpack(const basic_json& j)
  21072. {
  21073. std::vector<std::uint8_t> result;
  21074. to_msgpack(j, result);
  21075. return result;
  21076. }
  21077. static void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  21078. {
  21079. binary_writer<std::uint8_t>(o).write_msgpack(j);
  21080. }
  21081. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  21082. {
  21083. binary_writer<char>(o).write_msgpack(j);
  21084. }
  21085. /*!
  21086. @brief create a UBJSON serialization of a given JSON value
  21087. Serializes a given JSON value @a j to a byte vector using the UBJSON
  21088. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  21089. than JSON itself, yet more efficient to parse.
  21090. The library uses the following mapping from JSON values types to
  21091. UBJSON types according to the UBJSON specification:
  21092. JSON value type | value/range | UBJSON type | marker
  21093. --------------- | --------------------------------- | ----------- | ------
  21094. null | `null` | null | `Z`
  21095. boolean | `true` | true | `T`
  21096. boolean | `false` | false | `F`
  21097. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  21098. number_integer | -2147483648..-32769 | int32 | `l`
  21099. number_integer | -32768..-129 | int16 | `I`
  21100. number_integer | -128..127 | int8 | `i`
  21101. number_integer | 128..255 | uint8 | `U`
  21102. number_integer | 256..32767 | int16 | `I`
  21103. number_integer | 32768..2147483647 | int32 | `l`
  21104. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  21105. number_unsigned | 0..127 | int8 | `i`
  21106. number_unsigned | 128..255 | uint8 | `U`
  21107. number_unsigned | 256..32767 | int16 | `I`
  21108. number_unsigned | 32768..2147483647 | int32 | `l`
  21109. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  21110. number_unsigned | 2147483649..18446744073709551615 | high-precision | `H`
  21111. number_float | *any value* | float64 | `D`
  21112. string | *with shortest length indicator* | string | `S`
  21113. array | *see notes on optimized format* | array | `[`
  21114. object | *see notes on optimized format* | map | `{`
  21115. @note The mapping is **complete** in the sense that any JSON value type
  21116. can be converted to a UBJSON value.
  21117. @note The following values can **not** be converted to a UBJSON value:
  21118. - strings with more than 9223372036854775807 bytes (theoretical)
  21119. @note The following markers are not used in the conversion:
  21120. - `Z`: no-op values are not created.
  21121. - `C`: single-byte strings are serialized with `S` markers.
  21122. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  21123. by @ref from_ubjson.
  21124. @note If NaN or Infinity are stored inside a JSON number, they are
  21125. serialized properly. This behavior differs from the @ref dump()
  21126. function which serializes NaN or Infinity to `null`.
  21127. @note The optimized formats for containers are supported: Parameter
  21128. @a use_size adds size information to the beginning of a container and
  21129. removes the closing marker. Parameter @a use_type further checks
  21130. whether all elements of a container have the same type and adds the
  21131. type marker to the beginning of the container. The @a use_type
  21132. parameter must only be used together with @a use_size = true. Note
  21133. that @a use_size = true alone may result in larger representations -
  21134. the benefit of this parameter is that the receiving side is
  21135. immediately informed on the number of elements of the container.
  21136. @note If the JSON data contains the binary type, the value stored is a list
  21137. of integers, as suggested by the UBJSON documentation. In particular,
  21138. this means that serialization and the deserialization of a JSON
  21139. containing binary values into UBJSON and back will result in a
  21140. different JSON object.
  21141. @param[in] j JSON value to serialize
  21142. @param[in] use_size whether to add size annotations to container types
  21143. @param[in] use_type whether to add type annotations to container types
  21144. (must be combined with @a use_size = true)
  21145. @return UBJSON serialization as byte vector
  21146. @complexity Linear in the size of the JSON value @a j.
  21147. @liveexample{The example shows the serialization of a JSON value to a byte
  21148. vector in UBJSON format.,to_ubjson}
  21149. @sa http://ubjson.org
  21150. @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the
  21151. analogous deserialization
  21152. @sa see @ref to_cbor(const basic_json& for the related CBOR format
  21153. @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format
  21154. @since version 3.1.0
  21155. */
  21156. static std::vector<std::uint8_t> to_ubjson(const basic_json& j,
  21157. const bool use_size = false,
  21158. const bool use_type = false)
  21159. {
  21160. std::vector<std::uint8_t> result;
  21161. to_ubjson(j, result, use_size, use_type);
  21162. return result;
  21163. }
  21164. static void to_ubjson(const basic_json& j, detail::output_adapter<std::uint8_t> o,
  21165. const bool use_size = false, const bool use_type = false)
  21166. {
  21167. binary_writer<std::uint8_t>(o).write_ubjson(j, use_size, use_type);
  21168. }
  21169. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  21170. const bool use_size = false, const bool use_type = false)
  21171. {
  21172. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  21173. }
  21174. /*!
  21175. @brief Serializes the given JSON object `j` to BSON and returns a vector
  21176. containing the corresponding BSON-representation.
  21177. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  21178. stored as a single entity (a so-called document).
  21179. The library uses the following mapping from JSON values types to BSON types:
  21180. JSON value type | value/range | BSON type | marker
  21181. --------------- | --------------------------------- | ----------- | ------
  21182. null | `null` | null | 0x0A
  21183. boolean | `true`, `false` | boolean | 0x08
  21184. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  21185. number_integer | -2147483648..2147483647 | int32 | 0x10
  21186. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  21187. number_unsigned | 0..2147483647 | int32 | 0x10
  21188. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  21189. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  21190. number_float | *any value* | double | 0x01
  21191. string | *any value* | string | 0x02
  21192. array | *any value* | document | 0x04
  21193. object | *any value* | document | 0x03
  21194. binary | *any value* | binary | 0x05
  21195. @warning The mapping is **incomplete**, since only JSON-objects (and things
  21196. contained therein) can be serialized to BSON.
  21197. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  21198. and the keys may not contain U+0000, since they are serialized a
  21199. zero-terminated c-strings.
  21200. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  21201. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  21202. @throw type_error.317 if `!j.is_object()`
  21203. @pre The input `j` is required to be an object: `j.is_object() == true`.
  21204. @note Any BSON output created via @ref to_bson can be successfully parsed
  21205. by @ref from_bson.
  21206. @param[in] j JSON value to serialize
  21207. @return BSON serialization as byte vector
  21208. @complexity Linear in the size of the JSON value @a j.
  21209. @liveexample{The example shows the serialization of a JSON value to a byte
  21210. vector in BSON format.,to_bson}
  21211. @sa http://bsonspec.org/spec.html
  21212. @sa see @ref from_bson(detail::input_adapter&&, const bool strict) for the
  21213. analogous deserialization
  21214. @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the
  21215. related UBJSON format
  21216. @sa see @ref to_cbor(const basic_json&) for the related CBOR format
  21217. @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format
  21218. */
  21219. static std::vector<std::uint8_t> to_bson(const basic_json& j)
  21220. {
  21221. std::vector<std::uint8_t> result;
  21222. to_bson(j, result);
  21223. return result;
  21224. }
  21225. /*!
  21226. @brief Serializes the given JSON object `j` to BSON and forwards the
  21227. corresponding BSON-representation to the given output_adapter `o`.
  21228. @param j The JSON object to convert to BSON.
  21229. @param o The output adapter that receives the binary BSON representation.
  21230. @pre The input `j` shall be an object: `j.is_object() == true`
  21231. @sa see @ref to_bson(const basic_json&)
  21232. */
  21233. static void to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  21234. {
  21235. binary_writer<std::uint8_t>(o).write_bson(j);
  21236. }
  21237. /*!
  21238. @copydoc to_bson(const basic_json&, detail::output_adapter<std::uint8_t>)
  21239. */
  21240. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  21241. {
  21242. binary_writer<char>(o).write_bson(j);
  21243. }
  21244. /*!
  21245. @brief create a JSON value from an input in CBOR format
  21246. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  21247. Binary Object Representation) serialization format.
  21248. The library maps CBOR types to JSON value types as follows:
  21249. CBOR type | JSON value type | first byte
  21250. ---------------------- | --------------- | ----------
  21251. Integer | number_unsigned | 0x00..0x17
  21252. Unsigned integer | number_unsigned | 0x18
  21253. Unsigned integer | number_unsigned | 0x19
  21254. Unsigned integer | number_unsigned | 0x1A
  21255. Unsigned integer | number_unsigned | 0x1B
  21256. Negative integer | number_integer | 0x20..0x37
  21257. Negative integer | number_integer | 0x38
  21258. Negative integer | number_integer | 0x39
  21259. Negative integer | number_integer | 0x3A
  21260. Negative integer | number_integer | 0x3B
  21261. Byte string | binary | 0x40..0x57
  21262. Byte string | binary | 0x58
  21263. Byte string | binary | 0x59
  21264. Byte string | binary | 0x5A
  21265. Byte string | binary | 0x5B
  21266. UTF-8 string | string | 0x60..0x77
  21267. UTF-8 string | string | 0x78
  21268. UTF-8 string | string | 0x79
  21269. UTF-8 string | string | 0x7A
  21270. UTF-8 string | string | 0x7B
  21271. UTF-8 string | string | 0x7F
  21272. array | array | 0x80..0x97
  21273. array | array | 0x98
  21274. array | array | 0x99
  21275. array | array | 0x9A
  21276. array | array | 0x9B
  21277. array | array | 0x9F
  21278. map | object | 0xA0..0xB7
  21279. map | object | 0xB8
  21280. map | object | 0xB9
  21281. map | object | 0xBA
  21282. map | object | 0xBB
  21283. map | object | 0xBF
  21284. False | `false` | 0xF4
  21285. True | `true` | 0xF5
  21286. Null | `null` | 0xF6
  21287. Half-Precision Float | number_float | 0xF9
  21288. Single-Precision Float | number_float | 0xFA
  21289. Double-Precision Float | number_float | 0xFB
  21290. @warning The mapping is **incomplete** in the sense that not all CBOR
  21291. types can be converted to a JSON value. The following CBOR types
  21292. are not supported and will yield parse errors (parse_error.112):
  21293. - date/time (0xC0..0xC1)
  21294. - bignum (0xC2..0xC3)
  21295. - decimal fraction (0xC4)
  21296. - bigfloat (0xC5)
  21297. - expected conversions (0xD5..0xD7)
  21298. - simple values (0xE0..0xF3, 0xF8)
  21299. - undefined (0xF7)
  21300. @warning CBOR allows map keys of any type, whereas JSON only allows
  21301. strings as keys in object values. Therefore, CBOR maps with keys
  21302. other than UTF-8 strings are rejected (parse_error.113).
  21303. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  21304. @ref from_cbor.
  21305. @param[in] i an input in CBOR format convertible to an input adapter
  21306. @param[in] strict whether to expect the input to be consumed until EOF
  21307. (true by default)
  21308. @param[in] allow_exceptions whether to throw exceptions in case of a
  21309. parse error (optional, true by default)
  21310. @param[in] tag_handler how to treat CBOR tags (optional, error by default)
  21311. @return deserialized JSON value; in case of a parse error and
  21312. @a allow_exceptions set to `false`, the return value will be
  21313. value_t::discarded.
  21314. @throw parse_error.110 if the given input ends prematurely or the end of
  21315. file was not reached when @a strict was set to true
  21316. @throw parse_error.112 if unsupported features from CBOR were
  21317. used in the given input @a v or if the input is not valid CBOR
  21318. @throw parse_error.113 if a string was expected as map key, but not found
  21319. @complexity Linear in the size of the input @a i.
  21320. @liveexample{The example shows the deserialization of a byte vector in CBOR
  21321. format to a JSON value.,from_cbor}
  21322. @sa http://cbor.io
  21323. @sa see @ref to_cbor(const basic_json&) for the analogous serialization
  21324. @sa see @ref from_msgpack(InputType&&, const bool, const bool) for the
  21325. related MessagePack format
  21326. @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the
  21327. related UBJSON format
  21328. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  21329. consume input adapters, removed start_index parameter, and added
  21330. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  21331. since 3.2.0; added @a tag_handler parameter since 3.9.0.
  21332. */
  21333. template<typename InputType>
  21334. JSON_HEDLEY_WARN_UNUSED_RESULT
  21335. static basic_json from_cbor(InputType&& i,
  21336. const bool strict = true,
  21337. const bool allow_exceptions = true,
  21338. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  21339. {
  21340. basic_json result;
  21341. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21342. auto ia = detail::input_adapter(std::forward<InputType>(i));
  21343. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  21344. return res ? result : basic_json(value_t::discarded);
  21345. }
  21346. /*!
  21347. @copydoc from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t)
  21348. */
  21349. template<typename IteratorType>
  21350. JSON_HEDLEY_WARN_UNUSED_RESULT
  21351. static basic_json from_cbor(IteratorType first, IteratorType last,
  21352. const bool strict = true,
  21353. const bool allow_exceptions = true,
  21354. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  21355. {
  21356. basic_json result;
  21357. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21358. auto ia = detail::input_adapter(std::move(first), std::move(last));
  21359. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  21360. return res ? result : basic_json(value_t::discarded);
  21361. }
  21362. template<typename T>
  21363. JSON_HEDLEY_WARN_UNUSED_RESULT
  21364. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  21365. static basic_json from_cbor(const T* ptr, std::size_t len,
  21366. const bool strict = true,
  21367. const bool allow_exceptions = true,
  21368. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  21369. {
  21370. return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler);
  21371. }
  21372. JSON_HEDLEY_WARN_UNUSED_RESULT
  21373. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  21374. static basic_json from_cbor(detail::span_input_adapter&& i,
  21375. const bool strict = true,
  21376. const bool allow_exceptions = true,
  21377. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  21378. {
  21379. basic_json result;
  21380. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21381. auto ia = i.get();
  21382. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  21383. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  21384. return res ? result : basic_json(value_t::discarded);
  21385. }
  21386. /*!
  21387. @brief create a JSON value from an input in MessagePack format
  21388. Deserializes a given input @a i to a JSON value using the MessagePack
  21389. serialization format.
  21390. The library maps MessagePack types to JSON value types as follows:
  21391. MessagePack type | JSON value type | first byte
  21392. ---------------- | --------------- | ----------
  21393. positive fixint | number_unsigned | 0x00..0x7F
  21394. fixmap | object | 0x80..0x8F
  21395. fixarray | array | 0x90..0x9F
  21396. fixstr | string | 0xA0..0xBF
  21397. nil | `null` | 0xC0
  21398. false | `false` | 0xC2
  21399. true | `true` | 0xC3
  21400. float 32 | number_float | 0xCA
  21401. float 64 | number_float | 0xCB
  21402. uint 8 | number_unsigned | 0xCC
  21403. uint 16 | number_unsigned | 0xCD
  21404. uint 32 | number_unsigned | 0xCE
  21405. uint 64 | number_unsigned | 0xCF
  21406. int 8 | number_integer | 0xD0
  21407. int 16 | number_integer | 0xD1
  21408. int 32 | number_integer | 0xD2
  21409. int 64 | number_integer | 0xD3
  21410. str 8 | string | 0xD9
  21411. str 16 | string | 0xDA
  21412. str 32 | string | 0xDB
  21413. array 16 | array | 0xDC
  21414. array 32 | array | 0xDD
  21415. map 16 | object | 0xDE
  21416. map 32 | object | 0xDF
  21417. bin 8 | binary | 0xC4
  21418. bin 16 | binary | 0xC5
  21419. bin 32 | binary | 0xC6
  21420. ext 8 | binary | 0xC7
  21421. ext 16 | binary | 0xC8
  21422. ext 32 | binary | 0xC9
  21423. fixext 1 | binary | 0xD4
  21424. fixext 2 | binary | 0xD5
  21425. fixext 4 | binary | 0xD6
  21426. fixext 8 | binary | 0xD7
  21427. fixext 16 | binary | 0xD8
  21428. negative fixint | number_integer | 0xE0-0xFF
  21429. @note Any MessagePack output created @ref to_msgpack can be successfully
  21430. parsed by @ref from_msgpack.
  21431. @param[in] i an input in MessagePack format convertible to an input
  21432. adapter
  21433. @param[in] strict whether to expect the input to be consumed until EOF
  21434. (true by default)
  21435. @param[in] allow_exceptions whether to throw exceptions in case of a
  21436. parse error (optional, true by default)
  21437. @return deserialized JSON value; in case of a parse error and
  21438. @a allow_exceptions set to `false`, the return value will be
  21439. value_t::discarded.
  21440. @throw parse_error.110 if the given input ends prematurely or the end of
  21441. file was not reached when @a strict was set to true
  21442. @throw parse_error.112 if unsupported features from MessagePack were
  21443. used in the given input @a i or if the input is not valid MessagePack
  21444. @throw parse_error.113 if a string was expected as map key, but not found
  21445. @complexity Linear in the size of the input @a i.
  21446. @liveexample{The example shows the deserialization of a byte vector in
  21447. MessagePack format to a JSON value.,from_msgpack}
  21448. @sa http://msgpack.org
  21449. @sa see @ref to_msgpack(const basic_json&) for the analogous serialization
  21450. @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the
  21451. related CBOR format
  21452. @sa see @ref from_ubjson(InputType&&, const bool, const bool) for
  21453. the related UBJSON format
  21454. @sa see @ref from_bson(InputType&&, const bool, const bool) for
  21455. the related BSON format
  21456. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  21457. consume input adapters, removed start_index parameter, and added
  21458. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  21459. since 3.2.0
  21460. */
  21461. template<typename InputType>
  21462. JSON_HEDLEY_WARN_UNUSED_RESULT
  21463. static basic_json from_msgpack(InputType&& i,
  21464. const bool strict = true,
  21465. const bool allow_exceptions = true)
  21466. {
  21467. basic_json result;
  21468. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21469. auto ia = detail::input_adapter(std::forward<InputType>(i));
  21470. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  21471. return res ? result : basic_json(value_t::discarded);
  21472. }
  21473. /*!
  21474. @copydoc from_msgpack(InputType&&, const bool, const bool)
  21475. */
  21476. template<typename IteratorType>
  21477. JSON_HEDLEY_WARN_UNUSED_RESULT
  21478. static basic_json from_msgpack(IteratorType first, IteratorType last,
  21479. const bool strict = true,
  21480. const bool allow_exceptions = true)
  21481. {
  21482. basic_json result;
  21483. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21484. auto ia = detail::input_adapter(std::move(first), std::move(last));
  21485. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  21486. return res ? result : basic_json(value_t::discarded);
  21487. }
  21488. template<typename T>
  21489. JSON_HEDLEY_WARN_UNUSED_RESULT
  21490. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  21491. static basic_json from_msgpack(const T* ptr, std::size_t len,
  21492. const bool strict = true,
  21493. const bool allow_exceptions = true)
  21494. {
  21495. return from_msgpack(ptr, ptr + len, strict, allow_exceptions);
  21496. }
  21497. JSON_HEDLEY_WARN_UNUSED_RESULT
  21498. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  21499. static basic_json from_msgpack(detail::span_input_adapter&& i,
  21500. const bool strict = true,
  21501. const bool allow_exceptions = true)
  21502. {
  21503. basic_json result;
  21504. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21505. auto ia = i.get();
  21506. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  21507. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  21508. return res ? result : basic_json(value_t::discarded);
  21509. }
  21510. /*!
  21511. @brief create a JSON value from an input in UBJSON format
  21512. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  21513. Binary JSON) serialization format.
  21514. The library maps UBJSON types to JSON value types as follows:
  21515. UBJSON type | JSON value type | marker
  21516. ----------- | --------------------------------------- | ------
  21517. no-op | *no value, next value is read* | `N`
  21518. null | `null` | `Z`
  21519. false | `false` | `F`
  21520. true | `true` | `T`
  21521. float32 | number_float | `d`
  21522. float64 | number_float | `D`
  21523. uint8 | number_unsigned | `U`
  21524. int8 | number_integer | `i`
  21525. int16 | number_integer | `I`
  21526. int32 | number_integer | `l`
  21527. int64 | number_integer | `L`
  21528. high-precision number | number_integer, number_unsigned, or number_float - depends on number string | 'H'
  21529. string | string | `S`
  21530. char | string | `C`
  21531. array | array (optimized values are supported) | `[`
  21532. object | object (optimized values are supported) | `{`
  21533. @note The mapping is **complete** in the sense that any UBJSON value can
  21534. be converted to a JSON value.
  21535. @param[in] i an input in UBJSON format convertible to an input adapter
  21536. @param[in] strict whether to expect the input to be consumed until EOF
  21537. (true by default)
  21538. @param[in] allow_exceptions whether to throw exceptions in case of a
  21539. parse error (optional, true by default)
  21540. @return deserialized JSON value; in case of a parse error and
  21541. @a allow_exceptions set to `false`, the return value will be
  21542. value_t::discarded.
  21543. @throw parse_error.110 if the given input ends prematurely or the end of
  21544. file was not reached when @a strict was set to true
  21545. @throw parse_error.112 if a parse error occurs
  21546. @throw parse_error.113 if a string could not be parsed successfully
  21547. @complexity Linear in the size of the input @a i.
  21548. @liveexample{The example shows the deserialization of a byte vector in
  21549. UBJSON format to a JSON value.,from_ubjson}
  21550. @sa http://ubjson.org
  21551. @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the
  21552. analogous serialization
  21553. @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the
  21554. related CBOR format
  21555. @sa see @ref from_msgpack(InputType&&, const bool, const bool) for
  21556. the related MessagePack format
  21557. @sa see @ref from_bson(InputType&&, const bool, const bool) for
  21558. the related BSON format
  21559. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  21560. */
  21561. template<typename InputType>
  21562. JSON_HEDLEY_WARN_UNUSED_RESULT
  21563. static basic_json from_ubjson(InputType&& i,
  21564. const bool strict = true,
  21565. const bool allow_exceptions = true)
  21566. {
  21567. basic_json result;
  21568. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21569. auto ia = detail::input_adapter(std::forward<InputType>(i));
  21570. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  21571. return res ? result : basic_json(value_t::discarded);
  21572. }
  21573. /*!
  21574. @copydoc from_ubjson(InputType&&, const bool, const bool)
  21575. */
  21576. template<typename IteratorType>
  21577. JSON_HEDLEY_WARN_UNUSED_RESULT
  21578. static basic_json from_ubjson(IteratorType first, IteratorType last,
  21579. const bool strict = true,
  21580. const bool allow_exceptions = true)
  21581. {
  21582. basic_json result;
  21583. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21584. auto ia = detail::input_adapter(std::move(first), std::move(last));
  21585. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  21586. return res ? result : basic_json(value_t::discarded);
  21587. }
  21588. template<typename T>
  21589. JSON_HEDLEY_WARN_UNUSED_RESULT
  21590. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  21591. static basic_json from_ubjson(const T* ptr, std::size_t len,
  21592. const bool strict = true,
  21593. const bool allow_exceptions = true)
  21594. {
  21595. return from_ubjson(ptr, ptr + len, strict, allow_exceptions);
  21596. }
  21597. JSON_HEDLEY_WARN_UNUSED_RESULT
  21598. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  21599. static basic_json from_ubjson(detail::span_input_adapter&& i,
  21600. const bool strict = true,
  21601. const bool allow_exceptions = true)
  21602. {
  21603. basic_json result;
  21604. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21605. auto ia = i.get();
  21606. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  21607. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  21608. return res ? result : basic_json(value_t::discarded);
  21609. }
  21610. /*!
  21611. @brief Create a JSON value from an input in BSON format
  21612. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  21613. serialization format.
  21614. The library maps BSON record types to JSON value types as follows:
  21615. BSON type | BSON marker byte | JSON value type
  21616. --------------- | ---------------- | ---------------------------
  21617. double | 0x01 | number_float
  21618. string | 0x02 | string
  21619. document | 0x03 | object
  21620. array | 0x04 | array
  21621. binary | 0x05 | binary
  21622. undefined | 0x06 | still unsupported
  21623. ObjectId | 0x07 | still unsupported
  21624. boolean | 0x08 | boolean
  21625. UTC Date-Time | 0x09 | still unsupported
  21626. null | 0x0A | null
  21627. Regular Expr. | 0x0B | still unsupported
  21628. DB Pointer | 0x0C | still unsupported
  21629. JavaScript Code | 0x0D | still unsupported
  21630. Symbol | 0x0E | still unsupported
  21631. JavaScript Code | 0x0F | still unsupported
  21632. int32 | 0x10 | number_integer
  21633. Timestamp | 0x11 | still unsupported
  21634. 128-bit decimal float | 0x13 | still unsupported
  21635. Max Key | 0x7F | still unsupported
  21636. Min Key | 0xFF | still unsupported
  21637. @warning The mapping is **incomplete**. The unsupported mappings
  21638. are indicated in the table above.
  21639. @param[in] i an input in BSON format convertible to an input adapter
  21640. @param[in] strict whether to expect the input to be consumed until EOF
  21641. (true by default)
  21642. @param[in] allow_exceptions whether to throw exceptions in case of a
  21643. parse error (optional, true by default)
  21644. @return deserialized JSON value; in case of a parse error and
  21645. @a allow_exceptions set to `false`, the return value will be
  21646. value_t::discarded.
  21647. @throw parse_error.114 if an unsupported BSON record type is encountered
  21648. @complexity Linear in the size of the input @a i.
  21649. @liveexample{The example shows the deserialization of a byte vector in
  21650. BSON format to a JSON value.,from_bson}
  21651. @sa http://bsonspec.org/spec.html
  21652. @sa see @ref to_bson(const basic_json&) for the analogous serialization
  21653. @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the
  21654. related CBOR format
  21655. @sa see @ref from_msgpack(InputType&&, const bool, const bool) for
  21656. the related MessagePack format
  21657. @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the
  21658. related UBJSON format
  21659. */
  21660. template<typename InputType>
  21661. JSON_HEDLEY_WARN_UNUSED_RESULT
  21662. static basic_json from_bson(InputType&& i,
  21663. const bool strict = true,
  21664. const bool allow_exceptions = true)
  21665. {
  21666. basic_json result;
  21667. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21668. auto ia = detail::input_adapter(std::forward<InputType>(i));
  21669. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  21670. return res ? result : basic_json(value_t::discarded);
  21671. }
  21672. /*!
  21673. @copydoc from_bson(InputType&&, const bool, const bool)
  21674. */
  21675. template<typename IteratorType>
  21676. JSON_HEDLEY_WARN_UNUSED_RESULT
  21677. static basic_json from_bson(IteratorType first, IteratorType last,
  21678. const bool strict = true,
  21679. const bool allow_exceptions = true)
  21680. {
  21681. basic_json result;
  21682. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21683. auto ia = detail::input_adapter(std::move(first), std::move(last));
  21684. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  21685. return res ? result : basic_json(value_t::discarded);
  21686. }
  21687. template<typename T>
  21688. JSON_HEDLEY_WARN_UNUSED_RESULT
  21689. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  21690. static basic_json from_bson(const T* ptr, std::size_t len,
  21691. const bool strict = true,
  21692. const bool allow_exceptions = true)
  21693. {
  21694. return from_bson(ptr, ptr + len, strict, allow_exceptions);
  21695. }
  21696. JSON_HEDLEY_WARN_UNUSED_RESULT
  21697. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  21698. static basic_json from_bson(detail::span_input_adapter&& i,
  21699. const bool strict = true,
  21700. const bool allow_exceptions = true)
  21701. {
  21702. basic_json result;
  21703. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  21704. auto ia = i.get();
  21705. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  21706. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  21707. return res ? result : basic_json(value_t::discarded);
  21708. }
  21709. /// @}
  21710. //////////////////////////
  21711. // JSON Pointer support //
  21712. //////////////////////////
  21713. /// @name JSON Pointer functions
  21714. /// @{
  21715. /*!
  21716. @brief access specified element via JSON Pointer
  21717. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  21718. No bound checking is performed. Similar to @ref operator[](const typename
  21719. object_t::key_type&), `null` values are created in arrays and objects if
  21720. necessary.
  21721. In particular:
  21722. - If the JSON pointer points to an object key that does not exist, it
  21723. is created an filled with a `null` value before a reference to it
  21724. is returned.
  21725. - If the JSON pointer points to an array index that does not exist, it
  21726. is created an filled with a `null` value before a reference to it
  21727. is returned. All indices between the current maximum and the given
  21728. index are also filled with `null`.
  21729. - The special value `-` is treated as a synonym for the index past the
  21730. end.
  21731. @param[in] ptr a JSON pointer
  21732. @return reference to the element pointed to by @a ptr
  21733. @complexity Constant.
  21734. @throw parse_error.106 if an array index begins with '0'
  21735. @throw parse_error.109 if an array index was not a number
  21736. @throw out_of_range.404 if the JSON pointer can not be resolved
  21737. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  21738. @since version 2.0.0
  21739. */
  21740. reference operator[](const json_pointer& ptr)
  21741. {
  21742. return ptr.get_unchecked(this);
  21743. }
  21744. /*!
  21745. @brief access specified element via JSON Pointer
  21746. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  21747. No bound checking is performed. The function does not change the JSON
  21748. value; no `null` values are created. In particular, the special value
  21749. `-` yields an exception.
  21750. @param[in] ptr JSON pointer to the desired element
  21751. @return const reference to the element pointed to by @a ptr
  21752. @complexity Constant.
  21753. @throw parse_error.106 if an array index begins with '0'
  21754. @throw parse_error.109 if an array index was not a number
  21755. @throw out_of_range.402 if the array index '-' is used
  21756. @throw out_of_range.404 if the JSON pointer can not be resolved
  21757. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  21758. @since version 2.0.0
  21759. */
  21760. const_reference operator[](const json_pointer& ptr) const
  21761. {
  21762. return ptr.get_unchecked(this);
  21763. }
  21764. /*!
  21765. @brief access specified element via JSON Pointer
  21766. Returns a reference to the element at with specified JSON pointer @a ptr,
  21767. with bounds checking.
  21768. @param[in] ptr JSON pointer to the desired element
  21769. @return reference to the element pointed to by @a ptr
  21770. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  21771. begins with '0'. See example below.
  21772. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  21773. is not a number. See example below.
  21774. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  21775. is out of range. See example below.
  21776. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  21777. pointer @a ptr. As `at` provides checked access (and no elements are
  21778. implicitly inserted), the index '-' is always invalid. See example below.
  21779. @throw out_of_range.403 if the JSON pointer describes a key of an object
  21780. which cannot be found. See example below.
  21781. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  21782. See example below.
  21783. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  21784. changes in the JSON value.
  21785. @complexity Constant.
  21786. @since version 2.0.0
  21787. @liveexample{The behavior is shown in the example.,at_json_pointer}
  21788. */
  21789. reference at(const json_pointer& ptr)
  21790. {
  21791. return ptr.get_checked(this);
  21792. }
  21793. /*!
  21794. @brief access specified element via JSON Pointer
  21795. Returns a const reference to the element at with specified JSON pointer @a
  21796. ptr, with bounds checking.
  21797. @param[in] ptr JSON pointer to the desired element
  21798. @return reference to the element pointed to by @a ptr
  21799. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  21800. begins with '0'. See example below.
  21801. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  21802. is not a number. See example below.
  21803. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  21804. is out of range. See example below.
  21805. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  21806. pointer @a ptr. As `at` provides checked access (and no elements are
  21807. implicitly inserted), the index '-' is always invalid. See example below.
  21808. @throw out_of_range.403 if the JSON pointer describes a key of an object
  21809. which cannot be found. See example below.
  21810. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  21811. See example below.
  21812. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  21813. changes in the JSON value.
  21814. @complexity Constant.
  21815. @since version 2.0.0
  21816. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  21817. */
  21818. const_reference at(const json_pointer& ptr) const
  21819. {
  21820. return ptr.get_checked(this);
  21821. }
  21822. /*!
  21823. @brief return flattened JSON value
  21824. The function creates a JSON object whose keys are JSON pointers (see [RFC
  21825. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  21826. primitive. The original JSON value can be restored using the @ref
  21827. unflatten() function.
  21828. @return an object that maps JSON pointers to primitive values
  21829. @note Empty objects and arrays are flattened to `null` and will not be
  21830. reconstructed correctly by the @ref unflatten() function.
  21831. @complexity Linear in the size the JSON value.
  21832. @liveexample{The following code shows how a JSON object is flattened to an
  21833. object whose keys consist of JSON pointers.,flatten}
  21834. @sa see @ref unflatten() for the reverse function
  21835. @since version 2.0.0
  21836. */
  21837. basic_json flatten() const
  21838. {
  21839. basic_json result(value_t::object);
  21840. json_pointer::flatten("", *this, result);
  21841. return result;
  21842. }
  21843. /*!
  21844. @brief unflatten a previously flattened JSON value
  21845. The function restores the arbitrary nesting of a JSON value that has been
  21846. flattened before using the @ref flatten() function. The JSON value must
  21847. meet certain constraints:
  21848. 1. The value must be an object.
  21849. 2. The keys must be JSON pointers (see
  21850. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  21851. 3. The mapped values must be primitive JSON types.
  21852. @return the original JSON from a flattened version
  21853. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  21854. values and can not unflattened to their original type. Apart from
  21855. this example, for a JSON value `j`, the following is always true:
  21856. `j == j.flatten().unflatten()`.
  21857. @complexity Linear in the size the JSON value.
  21858. @throw type_error.314 if value is not an object
  21859. @throw type_error.315 if object values are not primitive
  21860. @liveexample{The following code shows how a flattened JSON object is
  21861. unflattened into the original nested JSON object.,unflatten}
  21862. @sa see @ref flatten() for the reverse function
  21863. @since version 2.0.0
  21864. */
  21865. basic_json unflatten() const
  21866. {
  21867. return json_pointer::unflatten(*this);
  21868. }
  21869. /// @}
  21870. //////////////////////////
  21871. // JSON Patch functions //
  21872. //////////////////////////
  21873. /// @name JSON Patch functions
  21874. /// @{
  21875. /*!
  21876. @brief applies a JSON patch
  21877. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  21878. expressing a sequence of operations to apply to a JSON) document. With
  21879. this function, a JSON Patch is applied to the current JSON value by
  21880. executing all operations from the patch.
  21881. @param[in] json_patch JSON patch document
  21882. @return patched document
  21883. @note The application of a patch is atomic: Either all operations succeed
  21884. and the patched document is returned or an exception is thrown. In
  21885. any case, the original value is not changed: the patch is applied
  21886. to a copy of the value.
  21887. @throw parse_error.104 if the JSON patch does not consist of an array of
  21888. objects
  21889. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  21890. attributes are missing); example: `"operation add must have member path"`
  21891. @throw out_of_range.401 if an array index is out of range.
  21892. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  21893. resolved successfully in the current JSON value; example: `"key baz not
  21894. found"`
  21895. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  21896. "move")
  21897. @throw other_error.501 if "test" operation was unsuccessful
  21898. @complexity Linear in the size of the JSON value and the length of the
  21899. JSON patch. As usually only a fraction of the JSON value is affected by
  21900. the patch, the complexity can usually be neglected.
  21901. @liveexample{The following code shows how a JSON patch is applied to a
  21902. value.,patch}
  21903. @sa see @ref diff -- create a JSON patch by comparing two JSON values
  21904. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  21905. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  21906. @since version 2.0.0
  21907. */
  21908. basic_json patch(const basic_json& json_patch) const
  21909. {
  21910. // make a working copy to apply the patch to
  21911. basic_json result = *this;
  21912. // the valid JSON Patch operations
  21913. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  21914. const auto get_op = [](const std::string & op)
  21915. {
  21916. if (op == "add")
  21917. {
  21918. return patch_operations::add;
  21919. }
  21920. if (op == "remove")
  21921. {
  21922. return patch_operations::remove;
  21923. }
  21924. if (op == "replace")
  21925. {
  21926. return patch_operations::replace;
  21927. }
  21928. if (op == "move")
  21929. {
  21930. return patch_operations::move;
  21931. }
  21932. if (op == "copy")
  21933. {
  21934. return patch_operations::copy;
  21935. }
  21936. if (op == "test")
  21937. {
  21938. return patch_operations::test;
  21939. }
  21940. return patch_operations::invalid;
  21941. };
  21942. // wrapper for "add" operation; add value at ptr
  21943. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  21944. {
  21945. // adding to the root of the target document means replacing it
  21946. if (ptr.empty())
  21947. {
  21948. result = val;
  21949. return;
  21950. }
  21951. // make sure the top element of the pointer exists
  21952. json_pointer top_pointer = ptr.top();
  21953. if (top_pointer != ptr)
  21954. {
  21955. result.at(top_pointer);
  21956. }
  21957. // get reference to parent of JSON pointer ptr
  21958. const auto last_path = ptr.back();
  21959. ptr.pop_back();
  21960. basic_json& parent = result[ptr];
  21961. switch (parent.m_type)
  21962. {
  21963. case value_t::null:
  21964. case value_t::object:
  21965. {
  21966. // use operator[] to add value
  21967. parent[last_path] = val;
  21968. break;
  21969. }
  21970. case value_t::array:
  21971. {
  21972. if (last_path == "-")
  21973. {
  21974. // special case: append to back
  21975. parent.push_back(val);
  21976. }
  21977. else
  21978. {
  21979. const auto idx = json_pointer::array_index(last_path);
  21980. if (JSON_HEDLEY_UNLIKELY(idx > parent.size()))
  21981. {
  21982. // avoid undefined behavior
  21983. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", parent));
  21984. }
  21985. // default case: insert add offset
  21986. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  21987. }
  21988. break;
  21989. }
  21990. // if there exists a parent it cannot be primitive
  21991. case value_t::string: // LCOV_EXCL_LINE
  21992. case value_t::boolean: // LCOV_EXCL_LINE
  21993. case value_t::number_integer: // LCOV_EXCL_LINE
  21994. case value_t::number_unsigned: // LCOV_EXCL_LINE
  21995. case value_t::number_float: // LCOV_EXCL_LINE
  21996. case value_t::binary: // LCOV_EXCL_LINE
  21997. case value_t::discarded: // LCOV_EXCL_LINE
  21998. default: // LCOV_EXCL_LINE
  21999. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  22000. }
  22001. };
  22002. // wrapper for "remove" operation; remove value at ptr
  22003. const auto operation_remove = [this, &result](json_pointer & ptr)
  22004. {
  22005. // get reference to parent of JSON pointer ptr
  22006. const auto last_path = ptr.back();
  22007. ptr.pop_back();
  22008. basic_json& parent = result.at(ptr);
  22009. // remove child
  22010. if (parent.is_object())
  22011. {
  22012. // perform range check
  22013. auto it = parent.find(last_path);
  22014. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  22015. {
  22016. parent.erase(it);
  22017. }
  22018. else
  22019. {
  22020. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found", *this));
  22021. }
  22022. }
  22023. else if (parent.is_array())
  22024. {
  22025. // note erase performs range check
  22026. parent.erase(json_pointer::array_index(last_path));
  22027. }
  22028. };
  22029. // type check: top level value must be an array
  22030. if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array()))
  22031. {
  22032. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", json_patch));
  22033. }
  22034. // iterate and apply the operations
  22035. for (const auto& val : json_patch)
  22036. {
  22037. // wrapper to get a value for an operation
  22038. const auto get_value = [&val](const std::string & op,
  22039. const std::string & member,
  22040. bool string_type) -> basic_json &
  22041. {
  22042. // find value
  22043. auto it = val.m_value.object->find(member);
  22044. // context-sensitive error message
  22045. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  22046. // check if desired value is present
  22047. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  22048. {
  22049. // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
  22050. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'", val));
  22051. }
  22052. // check if result is of type string
  22053. if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string()))
  22054. {
  22055. // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
  22056. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'", val));
  22057. }
  22058. // no error: return value
  22059. return it->second;
  22060. };
  22061. // type check: every element of the array must be an object
  22062. if (JSON_HEDLEY_UNLIKELY(!val.is_object()))
  22063. {
  22064. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", val));
  22065. }
  22066. // collect mandatory members
  22067. const auto op = get_value("op", "op", true).template get<std::string>();
  22068. const auto path = get_value(op, "path", true).template get<std::string>();
  22069. json_pointer ptr(path);
  22070. switch (get_op(op))
  22071. {
  22072. case patch_operations::add:
  22073. {
  22074. operation_add(ptr, get_value("add", "value", false));
  22075. break;
  22076. }
  22077. case patch_operations::remove:
  22078. {
  22079. operation_remove(ptr);
  22080. break;
  22081. }
  22082. case patch_operations::replace:
  22083. {
  22084. // the "path" location must exist - use at()
  22085. result.at(ptr) = get_value("replace", "value", false);
  22086. break;
  22087. }
  22088. case patch_operations::move:
  22089. {
  22090. const auto from_path = get_value("move", "from", true).template get<std::string>();
  22091. json_pointer from_ptr(from_path);
  22092. // the "from" location must exist - use at()
  22093. basic_json v = result.at(from_ptr);
  22094. // The move operation is functionally identical to a
  22095. // "remove" operation on the "from" location, followed
  22096. // immediately by an "add" operation at the target
  22097. // location with the value that was just removed.
  22098. operation_remove(from_ptr);
  22099. operation_add(ptr, v);
  22100. break;
  22101. }
  22102. case patch_operations::copy:
  22103. {
  22104. const auto from_path = get_value("copy", "from", true).template get<std::string>();
  22105. const json_pointer from_ptr(from_path);
  22106. // the "from" location must exist - use at()
  22107. basic_json v = result.at(from_ptr);
  22108. // The copy is functionally identical to an "add"
  22109. // operation at the target location using the value
  22110. // specified in the "from" member.
  22111. operation_add(ptr, v);
  22112. break;
  22113. }
  22114. case patch_operations::test:
  22115. {
  22116. bool success = false;
  22117. JSON_TRY
  22118. {
  22119. // check if "value" matches the one at "path"
  22120. // the "path" location must exist - use at()
  22121. success = (result.at(ptr) == get_value("test", "value", false));
  22122. }
  22123. JSON_INTERNAL_CATCH (out_of_range&)
  22124. {
  22125. // ignore out of range errors: success remains false
  22126. }
  22127. // throw an exception if test fails
  22128. if (JSON_HEDLEY_UNLIKELY(!success))
  22129. {
  22130. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump(), val));
  22131. }
  22132. break;
  22133. }
  22134. case patch_operations::invalid:
  22135. default:
  22136. {
  22137. // op must be "add", "remove", "replace", "move", "copy", or
  22138. // "test"
  22139. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid", val));
  22140. }
  22141. }
  22142. }
  22143. return result;
  22144. }
  22145. /*!
  22146. @brief creates a diff as a JSON patch
  22147. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  22148. be changed into the value @a target by calling @ref patch function.
  22149. @invariant For two JSON values @a source and @a target, the following code
  22150. yields always `true`:
  22151. @code {.cpp}
  22152. source.patch(diff(source, target)) == target;
  22153. @endcode
  22154. @note Currently, only `remove`, `add`, and `replace` operations are
  22155. generated.
  22156. @param[in] source JSON value to compare from
  22157. @param[in] target JSON value to compare against
  22158. @param[in] path helper value to create JSON pointers
  22159. @return a JSON patch to convert the @a source to @a target
  22160. @complexity Linear in the lengths of @a source and @a target.
  22161. @liveexample{The following code shows how a JSON patch is created as a
  22162. diff for two JSON values.,diff}
  22163. @sa see @ref patch -- apply a JSON patch
  22164. @sa see @ref merge_patch -- apply a JSON Merge Patch
  22165. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  22166. @since version 2.0.0
  22167. */
  22168. JSON_HEDLEY_WARN_UNUSED_RESULT
  22169. static basic_json diff(const basic_json& source, const basic_json& target,
  22170. const std::string& path = "")
  22171. {
  22172. // the patch
  22173. basic_json result(value_t::array);
  22174. // if the values are the same, return empty patch
  22175. if (source == target)
  22176. {
  22177. return result;
  22178. }
  22179. if (source.type() != target.type())
  22180. {
  22181. // different types: replace value
  22182. result.push_back(
  22183. {
  22184. {"op", "replace"}, {"path", path}, {"value", target}
  22185. });
  22186. return result;
  22187. }
  22188. switch (source.type())
  22189. {
  22190. case value_t::array:
  22191. {
  22192. // first pass: traverse common elements
  22193. std::size_t i = 0;
  22194. while (i < source.size() && i < target.size())
  22195. {
  22196. // recursive call to compare array values at index i
  22197. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  22198. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  22199. ++i;
  22200. }
  22201. // i now reached the end of at least one array
  22202. // in a second pass, traverse the remaining elements
  22203. // remove my remaining elements
  22204. const auto end_index = static_cast<difference_type>(result.size());
  22205. while (i < source.size())
  22206. {
  22207. // add operations in reverse order to avoid invalid
  22208. // indices
  22209. result.insert(result.begin() + end_index, object(
  22210. {
  22211. {"op", "remove"},
  22212. {"path", path + "/" + std::to_string(i)}
  22213. }));
  22214. ++i;
  22215. }
  22216. // add other remaining elements
  22217. while (i < target.size())
  22218. {
  22219. result.push_back(
  22220. {
  22221. {"op", "add"},
  22222. {"path", path + "/-"},
  22223. {"value", target[i]}
  22224. });
  22225. ++i;
  22226. }
  22227. break;
  22228. }
  22229. case value_t::object:
  22230. {
  22231. // first pass: traverse this object's elements
  22232. for (auto it = source.cbegin(); it != source.cend(); ++it)
  22233. {
  22234. // escape the key name to be used in a JSON patch
  22235. const auto path_key = path + "/" + detail::escape(it.key());
  22236. if (target.find(it.key()) != target.end())
  22237. {
  22238. // recursive call to compare object values at key it
  22239. auto temp_diff = diff(it.value(), target[it.key()], path_key);
  22240. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  22241. }
  22242. else
  22243. {
  22244. // found a key that is not in o -> remove it
  22245. result.push_back(object(
  22246. {
  22247. {"op", "remove"}, {"path", path_key}
  22248. }));
  22249. }
  22250. }
  22251. // second pass: traverse other object's elements
  22252. for (auto it = target.cbegin(); it != target.cend(); ++it)
  22253. {
  22254. if (source.find(it.key()) == source.end())
  22255. {
  22256. // found a key that is not in this -> add it
  22257. const auto path_key = path + "/" + detail::escape(it.key());
  22258. result.push_back(
  22259. {
  22260. {"op", "add"}, {"path", path_key},
  22261. {"value", it.value()}
  22262. });
  22263. }
  22264. }
  22265. break;
  22266. }
  22267. case value_t::null:
  22268. case value_t::string:
  22269. case value_t::boolean:
  22270. case value_t::number_integer:
  22271. case value_t::number_unsigned:
  22272. case value_t::number_float:
  22273. case value_t::binary:
  22274. case value_t::discarded:
  22275. default:
  22276. {
  22277. // both primitive type: replace value
  22278. result.push_back(
  22279. {
  22280. {"op", "replace"}, {"path", path}, {"value", target}
  22281. });
  22282. break;
  22283. }
  22284. }
  22285. return result;
  22286. }
  22287. /// @}
  22288. ////////////////////////////////
  22289. // JSON Merge Patch functions //
  22290. ////////////////////////////////
  22291. /// @name JSON Merge Patch functions
  22292. /// @{
  22293. /*!
  22294. @brief applies a JSON Merge Patch
  22295. The merge patch format is primarily intended for use with the HTTP PATCH
  22296. method as a means of describing a set of modifications to a target
  22297. resource's content. This function applies a merge patch to the current
  22298. JSON value.
  22299. The function implements the following algorithm from Section 2 of
  22300. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  22301. ```
  22302. define MergePatch(Target, Patch):
  22303. if Patch is an Object:
  22304. if Target is not an Object:
  22305. Target = {} // Ignore the contents and set it to an empty Object
  22306. for each Name/Value pair in Patch:
  22307. if Value is null:
  22308. if Name exists in Target:
  22309. remove the Name/Value pair from Target
  22310. else:
  22311. Target[Name] = MergePatch(Target[Name], Value)
  22312. return Target
  22313. else:
  22314. return Patch
  22315. ```
  22316. Thereby, `Target` is the current object; that is, the patch is applied to
  22317. the current value.
  22318. @param[in] apply_patch the patch to apply
  22319. @complexity Linear in the lengths of @a patch.
  22320. @liveexample{The following code shows how a JSON Merge Patch is applied to
  22321. a JSON document.,merge_patch}
  22322. @sa see @ref patch -- apply a JSON patch
  22323. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  22324. @since version 3.0.0
  22325. */
  22326. void merge_patch(const basic_json& apply_patch)
  22327. {
  22328. if (apply_patch.is_object())
  22329. {
  22330. if (!is_object())
  22331. {
  22332. *this = object();
  22333. }
  22334. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  22335. {
  22336. if (it.value().is_null())
  22337. {
  22338. erase(it.key());
  22339. }
  22340. else
  22341. {
  22342. operator[](it.key()).merge_patch(it.value());
  22343. }
  22344. }
  22345. }
  22346. else
  22347. {
  22348. *this = apply_patch;
  22349. }
  22350. }
  22351. /// @}
  22352. };
  22353. /*!
  22354. @brief user-defined to_string function for JSON values
  22355. This function implements a user-defined to_string for JSON objects.
  22356. @param[in] j a JSON object
  22357. @return a std::string object
  22358. */
  22359. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  22360. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  22361. {
  22362. return j.dump();
  22363. }
  22364. } // namespace nlohmann
  22365. ///////////////////////
  22366. // nonmember support //
  22367. ///////////////////////
  22368. // specialization of std::swap, and std::hash
  22369. namespace std
  22370. {
  22371. /// hash value for JSON objects
  22372. template<>
  22373. struct hash<nlohmann::json>
  22374. {
  22375. /*!
  22376. @brief return a hash value for a JSON object
  22377. @since version 1.0.0
  22378. */
  22379. std::size_t operator()(const nlohmann::json& j) const
  22380. {
  22381. return nlohmann::detail::hash(j);
  22382. }
  22383. };
  22384. /// specialization for std::less<value_t>
  22385. /// @note: do not remove the space after '<',
  22386. /// see https://github.com/nlohmann/json/pull/679
  22387. template<>
  22388. struct less<::nlohmann::detail::value_t>
  22389. {
  22390. /*!
  22391. @brief compare two value_t enum values
  22392. @since version 3.0.0
  22393. */
  22394. bool operator()(nlohmann::detail::value_t lhs,
  22395. nlohmann::detail::value_t rhs) const noexcept
  22396. {
  22397. return nlohmann::detail::operator<(lhs, rhs);
  22398. }
  22399. };
  22400. // C++20 prohibit function specialization in the std namespace.
  22401. #ifndef JSON_HAS_CPP_20
  22402. /*!
  22403. @brief exchanges the values of two JSON objects
  22404. @since version 1.0.0
  22405. */
  22406. template<>
  22407. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name)
  22408. is_nothrow_move_constructible<nlohmann::json>::value&& // NOLINT(misc-redundant-expression)
  22409. is_nothrow_move_assignable<nlohmann::json>::value
  22410. )
  22411. {
  22412. j1.swap(j2);
  22413. }
  22414. #endif
  22415. } // namespace std
  22416. /*!
  22417. @brief user-defined string literal for JSON values
  22418. This operator implements a user-defined string literal for JSON objects. It
  22419. can be used by adding `"_json"` to a string literal and returns a JSON object
  22420. if no parse error occurred.
  22421. @param[in] s a string representation of a JSON object
  22422. @param[in] n the length of string @a s
  22423. @return a JSON object
  22424. @since version 1.0.0
  22425. */
  22426. JSON_HEDLEY_NON_NULL(1)
  22427. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  22428. {
  22429. return nlohmann::json::parse(s, s + n);
  22430. }
  22431. /*!
  22432. @brief user-defined string literal for JSON pointer
  22433. This operator implements a user-defined string literal for JSON Pointers. It
  22434. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  22435. object if no parse error occurred.
  22436. @param[in] s a string representation of a JSON Pointer
  22437. @param[in] n the length of string @a s
  22438. @return a JSON pointer object
  22439. @since version 2.0.0
  22440. */
  22441. JSON_HEDLEY_NON_NULL(1)
  22442. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  22443. {
  22444. return nlohmann::json::json_pointer(std::string(s, n));
  22445. }
  22446. // #include <nlohmann/detail/macro_unscope.hpp>
  22447. // restore clang diagnostic settings
  22448. #if defined(__clang__)
  22449. #pragma clang diagnostic pop
  22450. #endif
  22451. // clean up
  22452. #undef JSON_ASSERT
  22453. #undef JSON_INTERNAL_CATCH
  22454. #undef JSON_CATCH
  22455. #undef JSON_THROW
  22456. #undef JSON_TRY
  22457. #undef JSON_PRIVATE_UNLESS_TESTED
  22458. #undef JSON_HAS_CPP_11
  22459. #undef JSON_HAS_CPP_14
  22460. #undef JSON_HAS_CPP_17
  22461. #undef JSON_HAS_CPP_20
  22462. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  22463. #undef NLOHMANN_BASIC_JSON_TPL
  22464. #undef JSON_EXPLICIT
  22465. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  22466. #undef JSON_HEDLEY_ALWAYS_INLINE
  22467. #undef JSON_HEDLEY_ARM_VERSION
  22468. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  22469. #undef JSON_HEDLEY_ARRAY_PARAM
  22470. #undef JSON_HEDLEY_ASSUME
  22471. #undef JSON_HEDLEY_BEGIN_C_DECLS
  22472. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  22473. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  22474. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  22475. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  22476. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  22477. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  22478. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  22479. #undef JSON_HEDLEY_COMPCERT_VERSION
  22480. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  22481. #undef JSON_HEDLEY_CONCAT
  22482. #undef JSON_HEDLEY_CONCAT3
  22483. #undef JSON_HEDLEY_CONCAT3_EX
  22484. #undef JSON_HEDLEY_CONCAT_EX
  22485. #undef JSON_HEDLEY_CONST
  22486. #undef JSON_HEDLEY_CONSTEXPR
  22487. #undef JSON_HEDLEY_CONST_CAST
  22488. #undef JSON_HEDLEY_CPP_CAST
  22489. #undef JSON_HEDLEY_CRAY_VERSION
  22490. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  22491. #undef JSON_HEDLEY_C_DECL
  22492. #undef JSON_HEDLEY_DEPRECATED
  22493. #undef JSON_HEDLEY_DEPRECATED_FOR
  22494. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  22495. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  22496. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  22497. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  22498. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  22499. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
  22500. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  22501. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  22502. #undef JSON_HEDLEY_DMC_VERSION
  22503. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  22504. #undef JSON_HEDLEY_EMPTY_BASES
  22505. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  22506. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  22507. #undef JSON_HEDLEY_END_C_DECLS
  22508. #undef JSON_HEDLEY_FLAGS
  22509. #undef JSON_HEDLEY_FLAGS_CAST
  22510. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  22511. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  22512. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  22513. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  22514. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  22515. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  22516. #undef JSON_HEDLEY_GCC_HAS_WARNING
  22517. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  22518. #undef JSON_HEDLEY_GCC_VERSION
  22519. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  22520. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  22521. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  22522. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  22523. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  22524. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  22525. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  22526. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  22527. #undef JSON_HEDLEY_GNUC_VERSION
  22528. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  22529. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  22530. #undef JSON_HEDLEY_HAS_BUILTIN
  22531. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  22532. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  22533. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  22534. #undef JSON_HEDLEY_HAS_EXTENSION
  22535. #undef JSON_HEDLEY_HAS_FEATURE
  22536. #undef JSON_HEDLEY_HAS_WARNING
  22537. #undef JSON_HEDLEY_IAR_VERSION
  22538. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  22539. #undef JSON_HEDLEY_IBM_VERSION
  22540. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  22541. #undef JSON_HEDLEY_IMPORT
  22542. #undef JSON_HEDLEY_INLINE
  22543. #undef JSON_HEDLEY_INTEL_CL_VERSION
  22544. #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK
  22545. #undef JSON_HEDLEY_INTEL_VERSION
  22546. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  22547. #undef JSON_HEDLEY_IS_CONSTANT
  22548. #undef JSON_HEDLEY_IS_CONSTEXPR_
  22549. #undef JSON_HEDLEY_LIKELY
  22550. #undef JSON_HEDLEY_MALLOC
  22551. #undef JSON_HEDLEY_MCST_LCC_VERSION
  22552. #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK
  22553. #undef JSON_HEDLEY_MESSAGE
  22554. #undef JSON_HEDLEY_MSVC_VERSION
  22555. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  22556. #undef JSON_HEDLEY_NEVER_INLINE
  22557. #undef JSON_HEDLEY_NON_NULL
  22558. #undef JSON_HEDLEY_NO_ESCAPE
  22559. #undef JSON_HEDLEY_NO_RETURN
  22560. #undef JSON_HEDLEY_NO_THROW
  22561. #undef JSON_HEDLEY_NULL
  22562. #undef JSON_HEDLEY_PELLES_VERSION
  22563. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  22564. #undef JSON_HEDLEY_PGI_VERSION
  22565. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  22566. #undef JSON_HEDLEY_PREDICT
  22567. #undef JSON_HEDLEY_PRINTF_FORMAT
  22568. #undef JSON_HEDLEY_PRIVATE
  22569. #undef JSON_HEDLEY_PUBLIC
  22570. #undef JSON_HEDLEY_PURE
  22571. #undef JSON_HEDLEY_REINTERPRET_CAST
  22572. #undef JSON_HEDLEY_REQUIRE
  22573. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  22574. #undef JSON_HEDLEY_REQUIRE_MSG
  22575. #undef JSON_HEDLEY_RESTRICT
  22576. #undef JSON_HEDLEY_RETURNS_NON_NULL
  22577. #undef JSON_HEDLEY_SENTINEL
  22578. #undef JSON_HEDLEY_STATIC_ASSERT
  22579. #undef JSON_HEDLEY_STATIC_CAST
  22580. #undef JSON_HEDLEY_STRINGIFY
  22581. #undef JSON_HEDLEY_STRINGIFY_EX
  22582. #undef JSON_HEDLEY_SUNPRO_VERSION
  22583. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  22584. #undef JSON_HEDLEY_TINYC_VERSION
  22585. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  22586. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  22587. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  22588. #undef JSON_HEDLEY_TI_CL2000_VERSION
  22589. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  22590. #undef JSON_HEDLEY_TI_CL430_VERSION
  22591. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  22592. #undef JSON_HEDLEY_TI_CL6X_VERSION
  22593. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  22594. #undef JSON_HEDLEY_TI_CL7X_VERSION
  22595. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  22596. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  22597. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  22598. #undef JSON_HEDLEY_TI_VERSION
  22599. #undef JSON_HEDLEY_TI_VERSION_CHECK
  22600. #undef JSON_HEDLEY_UNAVAILABLE
  22601. #undef JSON_HEDLEY_UNLIKELY
  22602. #undef JSON_HEDLEY_UNPREDICTABLE
  22603. #undef JSON_HEDLEY_UNREACHABLE
  22604. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  22605. #undef JSON_HEDLEY_VERSION
  22606. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  22607. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  22608. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  22609. #undef JSON_HEDLEY_VERSION_ENCODE
  22610. #undef JSON_HEDLEY_WARNING
  22611. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  22612. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  22613. #undef JSON_HEDLEY_FALL_THROUGH
  22614. #endif // INCLUDE_NLOHMANN_JSON_HPP_