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

22684 lines
782 KiB

  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.7.0
  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 7
  29. #define NLOHMANN_JSON_VERSION_PATCH 0
  30. #include <algorithm> // all_of, find, for_each
  31. #include <cassert> // assert
  32. #include <ciso646> // and, not, or
  33. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  34. #include <functional> // hash, less
  35. #include <initializer_list> // initializer_list
  36. #include <iosfwd> // istream, ostream
  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 <utility>
  45. // #include <nlohmann/detail/conversions/from_json.hpp>
  46. #include <algorithm> // transform
  47. #include <array> // array
  48. #include <ciso646> // and, not
  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 <nlohmann/detail/input/position_t.hpp>
  63. #include <cstddef> // size_t
  64. namespace nlohmann
  65. {
  66. namespace detail
  67. {
  68. /// struct to capture the start position of the current token
  69. struct position_t
  70. {
  71. /// the total number of characters read
  72. std::size_t chars_read_total = 0;
  73. /// the number of characters read in the current line
  74. std::size_t chars_read_current_line = 0;
  75. /// the number of lines read
  76. std::size_t lines_read = 0;
  77. /// conversion to size_t to preserve SAX interface
  78. constexpr operator size_t() const
  79. {
  80. return chars_read_total;
  81. }
  82. };
  83. } // namespace detail
  84. } // namespace nlohmann
  85. // #include <nlohmann/detail/macro_scope.hpp>
  86. #include <utility> // pair
  87. // #include <nlohmann/thirdparty/hedley/hedley.hpp>
  88. /* Hedley - https://nemequ.github.io/hedley
  89. * Created by Evan Nemerson <evan@nemerson.com>
  90. *
  91. * To the extent possible under law, the author(s) have dedicated all
  92. * copyright and related and neighboring rights to this software to
  93. * the public domain worldwide. This software is distributed without
  94. * any warranty.
  95. *
  96. * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
  97. * SPDX-License-Identifier: CC0-1.0
  98. */
  99. #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 9)
  100. #if defined(JSON_HEDLEY_VERSION)
  101. #undef JSON_HEDLEY_VERSION
  102. #endif
  103. #define JSON_HEDLEY_VERSION 9
  104. #if defined(JSON_HEDLEY_STRINGIFY_EX)
  105. #undef JSON_HEDLEY_STRINGIFY_EX
  106. #endif
  107. #define JSON_HEDLEY_STRINGIFY_EX(x) #x
  108. #if defined(JSON_HEDLEY_STRINGIFY)
  109. #undef JSON_HEDLEY_STRINGIFY
  110. #endif
  111. #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
  112. #if defined(JSON_HEDLEY_CONCAT_EX)
  113. #undef JSON_HEDLEY_CONCAT_EX
  114. #endif
  115. #define JSON_HEDLEY_CONCAT_EX(a,b) a##b
  116. #if defined(JSON_HEDLEY_CONCAT)
  117. #undef JSON_HEDLEY_CONCAT
  118. #endif
  119. #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b)
  120. #if defined(JSON_HEDLEY_VERSION_ENCODE)
  121. #undef JSON_HEDLEY_VERSION_ENCODE
  122. #endif
  123. #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
  124. #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
  125. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  126. #endif
  127. #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
  128. #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
  129. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  130. #endif
  131. #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
  132. #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
  133. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  134. #endif
  135. #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
  136. #if defined(JSON_HEDLEY_GNUC_VERSION)
  137. #undef JSON_HEDLEY_GNUC_VERSION
  138. #endif
  139. #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
  140. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
  141. #elif defined(__GNUC__)
  142. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
  143. #endif
  144. #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
  145. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  146. #endif
  147. #if defined(JSON_HEDLEY_GNUC_VERSION)
  148. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  149. #else
  150. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
  151. #endif
  152. #if defined(JSON_HEDLEY_MSVC_VERSION)
  153. #undef JSON_HEDLEY_MSVC_VERSION
  154. #endif
  155. #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000)
  156. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
  157. #elif defined(_MSC_FULL_VER)
  158. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
  159. #elif defined(_MSC_VER)
  160. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
  161. #endif
  162. #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
  163. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  164. #endif
  165. #if !defined(_MSC_VER)
  166. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
  167. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  168. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
  169. #elif defined(_MSC_VER) && (_MSC_VER >= 1200)
  170. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
  171. #else
  172. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
  173. #endif
  174. #if defined(JSON_HEDLEY_INTEL_VERSION)
  175. #undef JSON_HEDLEY_INTEL_VERSION
  176. #endif
  177. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE)
  178. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
  179. #elif defined(__INTEL_COMPILER)
  180. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
  181. #endif
  182. #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
  183. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  184. #endif
  185. #if defined(JSON_HEDLEY_INTEL_VERSION)
  186. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  187. #else
  188. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
  189. #endif
  190. #if defined(JSON_HEDLEY_PGI_VERSION)
  191. #undef JSON_HEDLEY_PGI_VERSION
  192. #endif
  193. #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
  194. #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
  195. #endif
  196. #if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
  197. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  198. #endif
  199. #if defined(JSON_HEDLEY_PGI_VERSION)
  200. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  201. #else
  202. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
  203. #endif
  204. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  205. #undef JSON_HEDLEY_SUNPRO_VERSION
  206. #endif
  207. #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
  208. #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)
  209. #elif defined(__SUNPRO_C)
  210. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
  211. #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
  212. #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)
  213. #elif defined(__SUNPRO_CC)
  214. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
  215. #endif
  216. #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
  217. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  218. #endif
  219. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  220. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  221. #else
  222. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
  223. #endif
  224. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  225. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  226. #endif
  227. #if defined(__EMSCRIPTEN__)
  228. #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
  229. #endif
  230. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
  231. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  232. #endif
  233. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  234. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  235. #else
  236. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
  237. #endif
  238. #if defined(JSON_HEDLEY_ARM_VERSION)
  239. #undef JSON_HEDLEY_ARM_VERSION
  240. #endif
  241. #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
  242. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
  243. #elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
  244. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
  245. #endif
  246. #if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
  247. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  248. #endif
  249. #if defined(JSON_HEDLEY_ARM_VERSION)
  250. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  251. #else
  252. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
  253. #endif
  254. #if defined(JSON_HEDLEY_IBM_VERSION)
  255. #undef JSON_HEDLEY_IBM_VERSION
  256. #endif
  257. #if defined(__ibmxl__)
  258. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
  259. #elif defined(__xlC__) && defined(__xlC_ver__)
  260. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
  261. #elif defined(__xlC__)
  262. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
  263. #endif
  264. #if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
  265. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  266. #endif
  267. #if defined(JSON_HEDLEY_IBM_VERSION)
  268. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  269. #else
  270. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
  271. #endif
  272. #if defined(JSON_HEDLEY_TI_VERSION)
  273. #undef JSON_HEDLEY_TI_VERSION
  274. #endif
  275. #if defined(__TI_COMPILER_VERSION__)
  276. #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  277. #endif
  278. #if defined(JSON_HEDLEY_TI_VERSION_CHECK)
  279. #undef JSON_HEDLEY_TI_VERSION_CHECK
  280. #endif
  281. #if defined(JSON_HEDLEY_TI_VERSION)
  282. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  283. #else
  284. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
  285. #endif
  286. #if defined(JSON_HEDLEY_CRAY_VERSION)
  287. #undef JSON_HEDLEY_CRAY_VERSION
  288. #endif
  289. #if defined(_CRAYC)
  290. #if defined(_RELEASE_PATCHLEVEL)
  291. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
  292. #else
  293. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
  294. #endif
  295. #endif
  296. #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
  297. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  298. #endif
  299. #if defined(JSON_HEDLEY_CRAY_VERSION)
  300. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  301. #else
  302. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
  303. #endif
  304. #if defined(JSON_HEDLEY_IAR_VERSION)
  305. #undef JSON_HEDLEY_IAR_VERSION
  306. #endif
  307. #if defined(__IAR_SYSTEMS_ICC__)
  308. #if __VER__ > 1000
  309. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
  310. #else
  311. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(VER / 100, __VER__ % 100, 0)
  312. #endif
  313. #endif
  314. #if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
  315. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  316. #endif
  317. #if defined(JSON_HEDLEY_IAR_VERSION)
  318. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  319. #else
  320. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
  321. #endif
  322. #if defined(JSON_HEDLEY_TINYC_VERSION)
  323. #undef JSON_HEDLEY_TINYC_VERSION
  324. #endif
  325. #if defined(__TINYC__)
  326. #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
  327. #endif
  328. #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
  329. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  330. #endif
  331. #if defined(JSON_HEDLEY_TINYC_VERSION)
  332. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  333. #else
  334. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
  335. #endif
  336. #if defined(JSON_HEDLEY_DMC_VERSION)
  337. #undef JSON_HEDLEY_DMC_VERSION
  338. #endif
  339. #if defined(__DMC__)
  340. #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
  341. #endif
  342. #if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
  343. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  344. #endif
  345. #if defined(JSON_HEDLEY_DMC_VERSION)
  346. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  347. #else
  348. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
  349. #endif
  350. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  351. #undef JSON_HEDLEY_COMPCERT_VERSION
  352. #endif
  353. #if defined(__COMPCERT_VERSION__)
  354. #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
  355. #endif
  356. #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
  357. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  358. #endif
  359. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  360. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  361. #else
  362. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
  363. #endif
  364. #if defined(JSON_HEDLEY_PELLES_VERSION)
  365. #undef JSON_HEDLEY_PELLES_VERSION
  366. #endif
  367. #if defined(__POCC__)
  368. #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
  369. #endif
  370. #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
  371. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  372. #endif
  373. #if defined(JSON_HEDLEY_PELLES_VERSION)
  374. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  375. #else
  376. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
  377. #endif
  378. #if defined(JSON_HEDLEY_GCC_VERSION)
  379. #undef JSON_HEDLEY_GCC_VERSION
  380. #endif
  381. #if \
  382. defined(JSON_HEDLEY_GNUC_VERSION) && \
  383. !defined(__clang__) && \
  384. !defined(JSON_HEDLEY_INTEL_VERSION) && \
  385. !defined(JSON_HEDLEY_PGI_VERSION) && \
  386. !defined(JSON_HEDLEY_ARM_VERSION) && \
  387. !defined(JSON_HEDLEY_TI_VERSION) && \
  388. !defined(__COMPCERT__)
  389. #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
  390. #endif
  391. #if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
  392. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  393. #endif
  394. #if defined(JSON_HEDLEY_GCC_VERSION)
  395. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  396. #else
  397. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
  398. #endif
  399. #if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
  400. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  401. #endif
  402. #if defined(__has_attribute)
  403. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
  404. #else
  405. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
  406. #endif
  407. #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
  408. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  409. #endif
  410. #if defined(__has_attribute)
  411. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  412. #else
  413. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  414. #endif
  415. #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
  416. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  417. #endif
  418. #if defined(__has_attribute)
  419. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  420. #else
  421. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  422. #endif
  423. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
  424. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  425. #endif
  426. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  427. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
  428. #else
  429. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
  430. #endif
  431. #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
  432. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  433. #endif
  434. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  435. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  436. #else
  437. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  438. #endif
  439. #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
  440. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  441. #endif
  442. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  443. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  444. #else
  445. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  446. #endif
  447. #if defined(JSON_HEDLEY_HAS_BUILTIN)
  448. #undef JSON_HEDLEY_HAS_BUILTIN
  449. #endif
  450. #if defined(__has_builtin)
  451. #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
  452. #else
  453. #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
  454. #endif
  455. #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
  456. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  457. #endif
  458. #if defined(__has_builtin)
  459. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  460. #else
  461. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  462. #endif
  463. #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
  464. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  465. #endif
  466. #if defined(__has_builtin)
  467. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  468. #else
  469. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  470. #endif
  471. #if defined(JSON_HEDLEY_HAS_FEATURE)
  472. #undef JSON_HEDLEY_HAS_FEATURE
  473. #endif
  474. #if defined(__has_feature)
  475. #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
  476. #else
  477. #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
  478. #endif
  479. #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
  480. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  481. #endif
  482. #if defined(__has_feature)
  483. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  484. #else
  485. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  486. #endif
  487. #if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
  488. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  489. #endif
  490. #if defined(__has_feature)
  491. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  492. #else
  493. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  494. #endif
  495. #if defined(JSON_HEDLEY_HAS_EXTENSION)
  496. #undef JSON_HEDLEY_HAS_EXTENSION
  497. #endif
  498. #if defined(__has_extension)
  499. #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
  500. #else
  501. #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
  502. #endif
  503. #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
  504. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  505. #endif
  506. #if defined(__has_extension)
  507. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  508. #else
  509. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  510. #endif
  511. #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
  512. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  513. #endif
  514. #if defined(__has_extension)
  515. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  516. #else
  517. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  518. #endif
  519. #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
  520. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  521. #endif
  522. #if defined(__has_declspec_attribute)
  523. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
  524. #else
  525. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
  526. #endif
  527. #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
  528. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  529. #endif
  530. #if defined(__has_declspec_attribute)
  531. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  532. #else
  533. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  534. #endif
  535. #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
  536. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  537. #endif
  538. #if defined(__has_declspec_attribute)
  539. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  540. #else
  541. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  542. #endif
  543. #if defined(JSON_HEDLEY_HAS_WARNING)
  544. #undef JSON_HEDLEY_HAS_WARNING
  545. #endif
  546. #if defined(__has_warning)
  547. #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
  548. #else
  549. #define JSON_HEDLEY_HAS_WARNING(warning) (0)
  550. #endif
  551. #if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
  552. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  553. #endif
  554. #if defined(__has_warning)
  555. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  556. #else
  557. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  558. #endif
  559. #if defined(JSON_HEDLEY_GCC_HAS_WARNING)
  560. #undef JSON_HEDLEY_GCC_HAS_WARNING
  561. #endif
  562. #if defined(__has_warning)
  563. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  564. #else
  565. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  566. #endif
  567. #if \
  568. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  569. defined(__clang__) || \
  570. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  571. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  572. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  573. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  574. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  575. JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) || \
  576. JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
  577. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
  578. JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
  579. (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
  580. #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
  581. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  582. #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
  583. #else
  584. #define JSON_HEDLEY_PRAGMA(value)
  585. #endif
  586. #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
  587. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  588. #endif
  589. #if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
  590. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  591. #endif
  592. #if defined(__clang__)
  593. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
  594. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
  595. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  596. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  597. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  598. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  599. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
  600. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
  601. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  602. #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
  603. #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
  604. #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
  605. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
  606. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
  607. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,1,0)
  608. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
  609. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
  610. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  611. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  612. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  613. #else
  614. #define JSON_HEDLEY_DIAGNOSTIC_PUSH
  615. #define JSON_HEDLEY_DIAGNOSTIC_POP
  616. #endif
  617. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
  618. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  619. #endif
  620. #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
  621. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
  622. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  623. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
  624. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  625. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  626. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  627. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  628. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  629. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
  630. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  631. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
  632. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
  633. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
  634. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
  635. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
  636. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  637. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
  638. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  639. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
  640. #else
  641. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  642. #endif
  643. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
  644. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  645. #endif
  646. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  647. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
  648. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  649. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
  650. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  651. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
  652. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  653. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
  654. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  655. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
  656. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  657. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  658. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  659. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
  660. #else
  661. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  662. #endif
  663. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
  664. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  665. #endif
  666. #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
  667. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
  668. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  669. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
  670. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
  671. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
  672. #else
  673. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  674. #endif
  675. #if defined(JSON_HEDLEY_DEPRECATED)
  676. #undef JSON_HEDLEY_DEPRECATED
  677. #endif
  678. #if defined(JSON_HEDLEY_DEPRECATED_FOR)
  679. #undef JSON_HEDLEY_DEPRECATED_FOR
  680. #endif
  681. #if defined(__cplusplus) && (__cplusplus >= 201402L)
  682. #define JSON_HEDLEY_DEPRECATED(since) [[deprecated("Since " #since)]]
  683. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) [[deprecated("Since " #since "; use " #replacement)]]
  684. #elif \
  685. JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) || \
  686. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  687. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  688. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  689. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
  690. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  691. JSON_HEDLEY_TI_VERSION_CHECK(8,3,0)
  692. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
  693. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
  694. #elif \
  695. JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
  696. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  697. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  698. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  699. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  700. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
  701. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
  702. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0)
  703. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
  704. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
  705. #elif \
  706. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  707. JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0)
  708. #define JSON_HEDLEY_DEPRECATED(since) _declspec(deprecated)
  709. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
  710. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  711. #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
  712. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
  713. #else
  714. #define JSON_HEDLEY_DEPRECATED(since)
  715. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
  716. #endif
  717. #if defined(JSON_HEDLEY_UNAVAILABLE)
  718. #undef JSON_HEDLEY_UNAVAILABLE
  719. #endif
  720. #if \
  721. JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
  722. JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
  723. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  724. #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
  725. #else
  726. #define JSON_HEDLEY_UNAVAILABLE(available_since)
  727. #endif
  728. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
  729. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  730. #endif
  731. #if defined(__cplusplus) && (__cplusplus >= 201703L)
  732. #define JSON_HEDLEY_WARN_UNUSED_RESULT [[nodiscard]]
  733. #elif \
  734. JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
  735. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  736. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  737. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  738. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  739. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  740. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  741. #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
  742. #elif defined(_Check_return_) /* SAL */
  743. #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
  744. #else
  745. #define JSON_HEDLEY_WARN_UNUSED_RESULT
  746. #endif
  747. #if defined(JSON_HEDLEY_SENTINEL)
  748. #undef JSON_HEDLEY_SENTINEL
  749. #endif
  750. #if \
  751. JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
  752. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  753. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  754. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0)
  755. #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
  756. #else
  757. #define JSON_HEDLEY_SENTINEL(position)
  758. #endif
  759. #if defined(JSON_HEDLEY_NO_RETURN)
  760. #undef JSON_HEDLEY_NO_RETURN
  761. #endif
  762. #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  763. #define JSON_HEDLEY_NO_RETURN __noreturn
  764. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  765. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  766. #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
  767. #define JSON_HEDLEY_NO_RETURN _Noreturn
  768. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  769. #define JSON_HEDLEY_NO_RETURN [[noreturn]]
  770. #elif \
  771. JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
  772. JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
  773. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  774. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  775. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  776. JSON_HEDLEY_TI_VERSION_CHECK(18,0,0) || \
  777. (JSON_HEDLEY_TI_VERSION_CHECK(17,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  778. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  779. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  780. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  781. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  782. #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
  783. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  784. #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
  785. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  786. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  787. #else
  788. #define JSON_HEDLEY_NO_RETURN
  789. #endif
  790. #if defined(JSON_HEDLEY_UNREACHABLE)
  791. #undef JSON_HEDLEY_UNREACHABLE
  792. #endif
  793. #if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  794. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  795. #endif
  796. #if \
  797. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
  798. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  799. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  800. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
  801. #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
  802. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  803. #define JSON_HEDLEY_UNREACHABLE() __assume(0)
  804. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0)
  805. #if defined(__cplusplus)
  806. #define JSON_HEDLEY_UNREACHABLE() std::_nassert(0)
  807. #else
  808. #define JSON_HEDLEY_UNREACHABLE() _nassert(0)
  809. #endif
  810. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return value
  811. #elif defined(EXIT_FAILURE)
  812. #define JSON_HEDLEY_UNREACHABLE() abort()
  813. #else
  814. #define JSON_HEDLEY_UNREACHABLE()
  815. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return value
  816. #endif
  817. #if !defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  818. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
  819. #endif
  820. #if defined(JSON_HEDLEY_ASSUME)
  821. #undef JSON_HEDLEY_ASSUME
  822. #endif
  823. #if \
  824. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  825. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  826. #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
  827. #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
  828. #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
  829. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0)
  830. #if defined(__cplusplus)
  831. #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
  832. #else
  833. #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
  834. #endif
  835. #elif \
  836. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && !defined(JSON_HEDLEY_ARM_VERSION)) || \
  837. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  838. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  839. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
  840. #define JSON_HEDLEY_ASSUME(expr) ((void) ((expr) ? 1 : (__builtin_unreachable(), 1)))
  841. #else
  842. #define JSON_HEDLEY_ASSUME(expr) ((void) (expr))
  843. #endif
  844. JSON_HEDLEY_DIAGNOSTIC_PUSH
  845. #if \
  846. JSON_HEDLEY_HAS_WARNING("-Wvariadic-macros") || \
  847. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0)
  848. #if defined(__clang__)
  849. #pragma clang diagnostic ignored "-Wvariadic-macros"
  850. #elif defined(JSON_HEDLEY_GCC_VERSION)
  851. #pragma GCC diagnostic ignored "-Wvariadic-macros"
  852. #endif
  853. #endif
  854. #if defined(JSON_HEDLEY_NON_NULL)
  855. #undef JSON_HEDLEY_NON_NULL
  856. #endif
  857. #if \
  858. JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
  859. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  860. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  861. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  862. #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
  863. #else
  864. #define JSON_HEDLEY_NON_NULL(...)
  865. #endif
  866. JSON_HEDLEY_DIAGNOSTIC_POP
  867. #if defined(JSON_HEDLEY_PRINTF_FORMAT)
  868. #undef JSON_HEDLEY_PRINTF_FORMAT
  869. #endif
  870. #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
  871. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
  872. #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
  873. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
  874. #elif \
  875. JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
  876. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  877. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  878. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  879. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  880. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  881. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  882. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
  883. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
  884. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
  885. #else
  886. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
  887. #endif
  888. #if defined(JSON_HEDLEY_CONSTEXPR)
  889. #undef JSON_HEDLEY_CONSTEXPR
  890. #endif
  891. #if defined(__cplusplus)
  892. #if __cplusplus >= 201103L
  893. #define JSON_HEDLEY_CONSTEXPR constexpr
  894. #endif
  895. #endif
  896. #if !defined(JSON_HEDLEY_CONSTEXPR)
  897. #define JSON_HEDLEY_CONSTEXPR
  898. #endif
  899. #if defined(JSON_HEDLEY_PREDICT)
  900. #undef JSON_HEDLEY_PREDICT
  901. #endif
  902. #if defined(JSON_HEDLEY_LIKELY)
  903. #undef JSON_HEDLEY_LIKELY
  904. #endif
  905. #if defined(JSON_HEDLEY_UNLIKELY)
  906. #undef JSON_HEDLEY_UNLIKELY
  907. #endif
  908. #if defined(JSON_HEDLEY_UNPREDICTABLE)
  909. #undef JSON_HEDLEY_UNPREDICTABLE
  910. #endif
  911. #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
  912. #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable(!!(expr))
  913. #endif
  914. #if \
  915. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) || \
  916. JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0)
  917. # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability(expr, value, probability)
  918. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1, probability)
  919. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0, probability)
  920. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  921. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  922. #if !defined(JSON_HEDLEY_BUILTIN_UNPREDICTABLE)
  923. #define JSON_HEDLEY_BUILTIN_UNPREDICTABLE(expr) __builtin_expect_with_probability(!!(expr), 1, 0.5)
  924. #endif
  925. #elif \
  926. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) || \
  927. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  928. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  929. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  930. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  931. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  932. JSON_HEDLEY_TI_VERSION_CHECK(6,1,0) || \
  933. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27)
  934. # define JSON_HEDLEY_PREDICT(expr, expected, probability) \
  935. (((probability) >= 0.9) ? __builtin_expect(!!(expr), (expected)) : (((void) (expected)), !!(expr)))
  936. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
  937. (__extension__ ({ \
  938. JSON_HEDLEY_CONSTEXPR double hedley_probability_ = (probability); \
  939. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
  940. }))
  941. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
  942. (__extension__ ({ \
  943. JSON_HEDLEY_CONSTEXPR double hedley_probability_ = (probability); \
  944. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
  945. }))
  946. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  947. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  948. #else
  949. # define JSON_HEDLEY_PREDICT(expr, expected, probability) (((void) (expected)), !!(expr))
  950. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
  951. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
  952. # define JSON_HEDLEY_LIKELY(expr) (!!(expr))
  953. # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
  954. #endif
  955. #if !defined(JSON_HEDLEY_UNPREDICTABLE)
  956. #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
  957. #endif
  958. #if defined(JSON_HEDLEY_MALLOC)
  959. #undef JSON_HEDLEY_MALLOC
  960. #endif
  961. #if \
  962. JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
  963. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  964. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  965. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  966. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  967. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  968. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  969. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  970. #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
  971. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0)
  972. #define JSON_HEDLEY_MALLOC __declspec(restrict)
  973. #else
  974. #define JSON_HEDLEY_MALLOC
  975. #endif
  976. #if defined(JSON_HEDLEY_PURE)
  977. #undef JSON_HEDLEY_PURE
  978. #endif
  979. #if \
  980. JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
  981. JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
  982. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  983. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  984. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  985. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  986. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  987. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  988. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  989. #define JSON_HEDLEY_PURE __attribute__((__pure__))
  990. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  991. #define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
  992. #else
  993. #define JSON_HEDLEY_PURE
  994. #endif
  995. #if defined(JSON_HEDLEY_CONST)
  996. #undef JSON_HEDLEY_CONST
  997. #endif
  998. #if \
  999. JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
  1000. JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
  1001. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1002. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1003. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1004. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1005. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1006. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1007. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1008. #define JSON_HEDLEY_CONST __attribute__((__const__))
  1009. #else
  1010. #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
  1011. #endif
  1012. #if defined(JSON_HEDLEY_RESTRICT)
  1013. #undef JSON_HEDLEY_RESTRICT
  1014. #endif
  1015. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
  1016. #define JSON_HEDLEY_RESTRICT restrict
  1017. #elif \
  1018. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1019. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1020. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1021. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1022. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1023. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1024. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1025. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
  1026. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  1027. defined(__clang__)
  1028. #define JSON_HEDLEY_RESTRICT __restrict
  1029. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
  1030. #define JSON_HEDLEY_RESTRICT _Restrict
  1031. #else
  1032. #define JSON_HEDLEY_RESTRICT
  1033. #endif
  1034. #if defined(JSON_HEDLEY_INLINE)
  1035. #undef JSON_HEDLEY_INLINE
  1036. #endif
  1037. #if \
  1038. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  1039. (defined(__cplusplus) && (__cplusplus >= 199711L))
  1040. #define JSON_HEDLEY_INLINE inline
  1041. #elif \
  1042. defined(JSON_HEDLEY_GCC_VERSION) || \
  1043. JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
  1044. #define JSON_HEDLEY_INLINE __inline__
  1045. #elif \
  1046. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1047. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1048. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  1049. #define JSON_HEDLEY_INLINE __inline
  1050. #else
  1051. #define JSON_HEDLEY_INLINE
  1052. #endif
  1053. #if defined(JSON_HEDLEY_ALWAYS_INLINE)
  1054. #undef JSON_HEDLEY_ALWAYS_INLINE
  1055. #endif
  1056. #if \
  1057. JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
  1058. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1059. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1060. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1061. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1062. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1063. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1064. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1065. #define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
  1066. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0)
  1067. #define JSON_HEDLEY_ALWAYS_INLINE __forceinline
  1068. #elif JSON_HEDLEY_TI_VERSION_CHECK(7,0,0) && defined(__cplusplus)
  1069. #define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
  1070. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1071. #define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
  1072. #else
  1073. #define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
  1074. #endif
  1075. #if defined(JSON_HEDLEY_NEVER_INLINE)
  1076. #undef JSON_HEDLEY_NEVER_INLINE
  1077. #endif
  1078. #if \
  1079. JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
  1080. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1081. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1082. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1083. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1084. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1085. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1086. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1087. #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
  1088. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  1089. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1090. #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
  1091. #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
  1092. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1093. #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
  1094. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1095. #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
  1096. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1097. #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
  1098. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1099. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1100. #else
  1101. #define JSON_HEDLEY_NEVER_INLINE
  1102. #endif
  1103. #if defined(JSON_HEDLEY_PRIVATE)
  1104. #undef JSON_HEDLEY_PRIVATE
  1105. #endif
  1106. #if defined(JSON_HEDLEY_PUBLIC)
  1107. #undef JSON_HEDLEY_PUBLIC
  1108. #endif
  1109. #if defined(JSON_HEDLEY_IMPORT)
  1110. #undef JSON_HEDLEY_IMPORT
  1111. #endif
  1112. #if defined(_WIN32) || defined(__CYGWIN__)
  1113. #define JSON_HEDLEY_PRIVATE
  1114. #define JSON_HEDLEY_PUBLIC __declspec(dllexport)
  1115. #define JSON_HEDLEY_IMPORT __declspec(dllimport)
  1116. #else
  1117. #if \
  1118. JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
  1119. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1120. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1121. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1122. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1123. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1124. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1125. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_EABI__) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1126. #define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
  1127. #define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default")))
  1128. #else
  1129. #define JSON_HEDLEY_PRIVATE
  1130. #define JSON_HEDLEY_PUBLIC
  1131. #endif
  1132. #define JSON_HEDLEY_IMPORT extern
  1133. #endif
  1134. #if defined(JSON_HEDLEY_NO_THROW)
  1135. #undef JSON_HEDLEY_NO_THROW
  1136. #endif
  1137. #if \
  1138. JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
  1139. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1140. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1141. #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
  1142. #elif \
  1143. JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
  1144. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1145. #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
  1146. #else
  1147. #define JSON_HEDLEY_NO_THROW
  1148. #endif
  1149. #if defined(JSON_HEDLEY_FALL_THROUGH)
  1150. #undef JSON_HEDLEY_FALL_THROUGH
  1151. #endif
  1152. #if \
  1153. defined(__cplusplus) && \
  1154. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
  1155. !defined(JSON_HEDLEY_PGI_VERSION)
  1156. #if \
  1157. (__cplusplus >= 201703L) || \
  1158. ((__cplusplus >= 201103L) && JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough))
  1159. #define JSON_HEDLEY_FALL_THROUGH [[fallthrough]]
  1160. #elif (__cplusplus >= 201103L) && JSON_HEDLEY_HAS_CPP_ATTRIBUTE(clang::fallthrough)
  1161. #define JSON_HEDLEY_FALL_THROUGH [[clang::fallthrough]]
  1162. #elif (__cplusplus >= 201103L) && JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0)
  1163. #define JSON_HEDLEY_FALL_THROUGH [[gnu::fallthrough]]
  1164. #endif
  1165. #endif
  1166. #if !defined(JSON_HEDLEY_FALL_THROUGH)
  1167. #if JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(fallthrough,7,0,0) && !defined(JSON_HEDLEY_PGI_VERSION)
  1168. #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
  1169. #elif defined(__fallthrough) /* SAL */
  1170. #define JSON_HEDLEY_FALL_THROUGH __fallthrough
  1171. #else
  1172. #define JSON_HEDLEY_FALL_THROUGH
  1173. #endif
  1174. #endif
  1175. #if defined(JSON_HEDLEY_RETURNS_NON_NULL)
  1176. #undef JSON_HEDLEY_RETURNS_NON_NULL
  1177. #endif
  1178. #if \
  1179. JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
  1180. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0)
  1181. #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
  1182. #elif defined(_Ret_notnull_) /* SAL */
  1183. #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
  1184. #else
  1185. #define JSON_HEDLEY_RETURNS_NON_NULL
  1186. #endif
  1187. #if defined(JSON_HEDLEY_ARRAY_PARAM)
  1188. #undef JSON_HEDLEY_ARRAY_PARAM
  1189. #endif
  1190. #if \
  1191. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
  1192. !defined(__STDC_NO_VLA__) && \
  1193. !defined(__cplusplus) && \
  1194. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1195. !defined(JSON_HEDLEY_TINYC_VERSION)
  1196. #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
  1197. #else
  1198. #define JSON_HEDLEY_ARRAY_PARAM(name)
  1199. #endif
  1200. #if defined(JSON_HEDLEY_IS_CONSTANT)
  1201. #undef JSON_HEDLEY_IS_CONSTANT
  1202. #endif
  1203. #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
  1204. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  1205. #endif
  1206. /* Note the double-underscore. For internal use only; no API
  1207. * guarantees! */
  1208. #if defined(JSON_HEDLEY__IS_CONSTEXPR)
  1209. #undef JSON_HEDLEY__IS_CONSTEXPR
  1210. #endif
  1211. #if \
  1212. JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
  1213. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1214. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1215. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
  1216. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1217. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1218. JSON_HEDLEY_TI_VERSION_CHECK(6,1,0) || \
  1219. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) || \
  1220. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
  1221. #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
  1222. #endif
  1223. #if !defined(__cplusplus)
  1224. # if \
  1225. JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
  1226. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1227. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1228. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1229. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1230. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1231. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
  1232. #if defined(__INTPTR_TYPE__)
  1233. #define JSON_HEDLEY__IS_CONSTEXPR(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
  1234. #else
  1235. #include <stdint.h>
  1236. #define JSON_HEDLEY__IS_CONSTEXPR(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
  1237. #endif
  1238. # elif \
  1239. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(JSON_HEDLEY_SUNPRO_VERSION) && !defined(JSON_HEDLEY_PGI_VERSION)) || \
  1240. JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) || \
  1241. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1242. JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
  1243. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1244. JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
  1245. #if defined(__INTPTR_TYPE__)
  1246. #define JSON_HEDLEY__IS_CONSTEXPR(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
  1247. #else
  1248. #include <stdint.h>
  1249. #define JSON_HEDLEY__IS_CONSTEXPR(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
  1250. #endif
  1251. # elif \
  1252. defined(JSON_HEDLEY_GCC_VERSION) || \
  1253. defined(JSON_HEDLEY_INTEL_VERSION) || \
  1254. defined(JSON_HEDLEY_TINYC_VERSION) || \
  1255. defined(JSON_HEDLEY_TI_VERSION) || \
  1256. defined(__clang__)
  1257. # define JSON_HEDLEY__IS_CONSTEXPR(expr) ( \
  1258. sizeof(void) != \
  1259. sizeof(*( \
  1260. 1 ? \
  1261. ((void*) ((expr) * 0L) ) : \
  1262. ((struct { char v[sizeof(void) * 2]; } *) 1) \
  1263. ) \
  1264. ) \
  1265. )
  1266. # endif
  1267. #endif
  1268. #if defined(JSON_HEDLEY__IS_CONSTEXPR)
  1269. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1270. #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY__IS_CONSTEXPR(expr)
  1271. #endif
  1272. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY__IS_CONSTEXPR(expr) ? (expr) : (-1))
  1273. #else
  1274. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1275. #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
  1276. #endif
  1277. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
  1278. #endif
  1279. #if defined(JSON_HEDLEY_BEGIN_C_DECLS)
  1280. #undef JSON_HEDLEY_BEGIN_C_DECLS
  1281. #endif
  1282. #if defined(JSON_HEDLEY_END_C_DECLS)
  1283. #undef JSON_HEDLEY_END_C_DECLS
  1284. #endif
  1285. #if defined(JSON_HEDLEY_C_DECL)
  1286. #undef JSON_HEDLEY_C_DECL
  1287. #endif
  1288. #if defined(__cplusplus)
  1289. #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
  1290. #define JSON_HEDLEY_END_C_DECLS }
  1291. #define JSON_HEDLEY_C_DECL extern "C"
  1292. #else
  1293. #define JSON_HEDLEY_BEGIN_C_DECLS
  1294. #define JSON_HEDLEY_END_C_DECLS
  1295. #define JSON_HEDLEY_C_DECL
  1296. #endif
  1297. #if defined(JSON_HEDLEY_STATIC_ASSERT)
  1298. #undef JSON_HEDLEY_STATIC_ASSERT
  1299. #endif
  1300. #if \
  1301. !defined(__cplusplus) && ( \
  1302. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
  1303. JSON_HEDLEY_HAS_FEATURE(c_static_assert) || \
  1304. JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
  1305. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1306. defined(_Static_assert) \
  1307. )
  1308. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
  1309. #elif \
  1310. (defined(__cplusplus) && (__cplusplus >= 201703L)) || \
  1311. JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \
  1312. (defined(__cplusplus) && JSON_HEDLEY_TI_VERSION_CHECK(8,3,0))
  1313. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) static_assert(expr, message)
  1314. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  1315. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) static_assert(expr)
  1316. #else
  1317. # define JSON_HEDLEY_STATIC_ASSERT(expr, message)
  1318. #endif
  1319. #if defined(JSON_HEDLEY_CONST_CAST)
  1320. #undef JSON_HEDLEY_CONST_CAST
  1321. #endif
  1322. #if defined(__cplusplus)
  1323. # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
  1324. #elif \
  1325. JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
  1326. JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
  1327. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1328. # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
  1329. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1330. JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
  1331. ((T) (expr)); \
  1332. JSON_HEDLEY_DIAGNOSTIC_POP \
  1333. }))
  1334. #else
  1335. # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
  1336. #endif
  1337. #if defined(JSON_HEDLEY_REINTERPRET_CAST)
  1338. #undef JSON_HEDLEY_REINTERPRET_CAST
  1339. #endif
  1340. #if defined(__cplusplus)
  1341. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
  1342. #else
  1343. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (*((T*) &(expr)))
  1344. #endif
  1345. #if defined(JSON_HEDLEY_STATIC_CAST)
  1346. #undef JSON_HEDLEY_STATIC_CAST
  1347. #endif
  1348. #if defined(__cplusplus)
  1349. #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
  1350. #else
  1351. #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
  1352. #endif
  1353. #if defined(JSON_HEDLEY_CPP_CAST)
  1354. #undef JSON_HEDLEY_CPP_CAST
  1355. #endif
  1356. #if defined(__cplusplus)
  1357. #define JSON_HEDLEY_CPP_CAST(T, expr) static_cast<T>(expr)
  1358. #else
  1359. #define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
  1360. #endif
  1361. #if defined(JSON_HEDLEY_MESSAGE)
  1362. #undef JSON_HEDLEY_MESSAGE
  1363. #endif
  1364. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1365. # define JSON_HEDLEY_MESSAGE(msg) \
  1366. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1367. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1368. JSON_HEDLEY_PRAGMA(message msg) \
  1369. JSON_HEDLEY_DIAGNOSTIC_POP
  1370. #elif \
  1371. JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
  1372. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1373. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
  1374. #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
  1375. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
  1376. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1377. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1378. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
  1379. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1380. #else
  1381. # define JSON_HEDLEY_MESSAGE(msg)
  1382. #endif
  1383. #if defined(JSON_HEDLEY_WARNING)
  1384. #undef JSON_HEDLEY_WARNING
  1385. #endif
  1386. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1387. # define JSON_HEDLEY_WARNING(msg) \
  1388. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1389. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1390. JSON_HEDLEY_PRAGMA(clang warning msg) \
  1391. JSON_HEDLEY_DIAGNOSTIC_POP
  1392. #elif \
  1393. JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
  1394. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0)
  1395. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
  1396. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  1397. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1398. #else
  1399. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
  1400. #endif
  1401. #if defined(JSON_HEDLEY_REQUIRE_MSG)
  1402. #undef JSON_HEDLEY_REQUIRE_MSG
  1403. #endif
  1404. #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
  1405. # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
  1406. # define JSON_HEDLEY_REQUIRE_MSG(expr, msg) \
  1407. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1408. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1409. __attribute__((__diagnose_if__(!(expr), msg, "error"))) \
  1410. JSON_HEDLEY_DIAGNOSTIC_POP
  1411. # else
  1412. # define JSON_HEDLEY_REQUIRE_MSG(expr, msg) __attribute__((__diagnose_if__(!(expr), msg, "error")))
  1413. # endif
  1414. #else
  1415. # define JSON_HEDLEY_REQUIRE_MSG(expr, msg)
  1416. #endif
  1417. #if defined(JSON_HEDLEY_REQUIRE)
  1418. #undef JSON_HEDLEY_REQUIRE
  1419. #endif
  1420. #define JSON_HEDLEY_REQUIRE(expr) JSON_HEDLEY_REQUIRE_MSG(expr, #expr)
  1421. #if defined(JSON_HEDLEY_FLAGS)
  1422. #undef JSON_HEDLEY_FLAGS
  1423. #endif
  1424. #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum)
  1425. #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
  1426. #endif
  1427. #if defined(JSON_HEDLEY_FLAGS_CAST)
  1428. #undef JSON_HEDLEY_FLAGS_CAST
  1429. #endif
  1430. #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
  1431. # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
  1432. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1433. _Pragma("warning(disable:188)") \
  1434. ((T) (expr)); \
  1435. JSON_HEDLEY_DIAGNOSTIC_POP \
  1436. }))
  1437. #else
  1438. # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
  1439. #endif
  1440. /* Remaining macros are deprecated. */
  1441. #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
  1442. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  1443. #endif
  1444. #if defined(__clang__)
  1445. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
  1446. #else
  1447. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  1448. #endif
  1449. #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
  1450. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  1451. #endif
  1452. #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  1453. #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
  1454. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  1455. #endif
  1456. #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
  1457. #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
  1458. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  1459. #endif
  1460. #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
  1461. #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
  1462. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  1463. #endif
  1464. #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
  1465. #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
  1466. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  1467. #endif
  1468. #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
  1469. #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
  1470. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  1471. #endif
  1472. #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
  1473. #if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
  1474. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  1475. #endif
  1476. #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
  1477. #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
  1478. // This file contains all internal macro definitions
  1479. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  1480. // exclude unsupported compilers
  1481. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  1482. #if defined(__clang__)
  1483. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  1484. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  1485. #endif
  1486. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  1487. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  1488. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  1489. #endif
  1490. #endif
  1491. #endif
  1492. // C++ language standard detection
  1493. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  1494. #define JSON_HAS_CPP_17
  1495. #define JSON_HAS_CPP_14
  1496. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  1497. #define JSON_HAS_CPP_14
  1498. #endif
  1499. // disable float-equal warnings on GCC/clang
  1500. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  1501. #pragma GCC diagnostic push
  1502. #pragma GCC diagnostic ignored "-Wfloat-equal"
  1503. #endif
  1504. // disable documentation warnings on clang
  1505. #if defined(__clang__)
  1506. #pragma GCC diagnostic push
  1507. #pragma GCC diagnostic ignored "-Wdocumentation"
  1508. #endif
  1509. // allow to disable exceptions
  1510. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  1511. #define JSON_THROW(exception) throw exception
  1512. #define JSON_TRY try
  1513. #define JSON_CATCH(exception) catch(exception)
  1514. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  1515. #else
  1516. #include <cstdlib>
  1517. #define JSON_THROW(exception) std::abort()
  1518. #define JSON_TRY if(true)
  1519. #define JSON_CATCH(exception) if(false)
  1520. #define JSON_INTERNAL_CATCH(exception) if(false)
  1521. #endif
  1522. // override exception macros
  1523. #if defined(JSON_THROW_USER)
  1524. #undef JSON_THROW
  1525. #define JSON_THROW JSON_THROW_USER
  1526. #endif
  1527. #if defined(JSON_TRY_USER)
  1528. #undef JSON_TRY
  1529. #define JSON_TRY JSON_TRY_USER
  1530. #endif
  1531. #if defined(JSON_CATCH_USER)
  1532. #undef JSON_CATCH
  1533. #define JSON_CATCH JSON_CATCH_USER
  1534. #undef JSON_INTERNAL_CATCH
  1535. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  1536. #endif
  1537. #if defined(JSON_INTERNAL_CATCH_USER)
  1538. #undef JSON_INTERNAL_CATCH
  1539. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  1540. #endif
  1541. /*!
  1542. @brief macro to briefly define a mapping between an enum and JSON
  1543. @def NLOHMANN_JSON_SERIALIZE_ENUM
  1544. @since version 3.4.0
  1545. */
  1546. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  1547. template<typename BasicJsonType> \
  1548. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  1549. { \
  1550. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1551. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1552. auto it = std::find_if(std::begin(m), std::end(m), \
  1553. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1554. { \
  1555. return ej_pair.first == e; \
  1556. }); \
  1557. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  1558. } \
  1559. template<typename BasicJsonType> \
  1560. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  1561. { \
  1562. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1563. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1564. auto it = std::find_if(std::begin(m), std::end(m), \
  1565. [j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1566. { \
  1567. return ej_pair.second == j; \
  1568. }); \
  1569. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  1570. }
  1571. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  1572. // may be removed in the future once the class is split.
  1573. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  1574. template<template<typename, typename, typename...> class ObjectType, \
  1575. template<typename, typename...> class ArrayType, \
  1576. class StringType, class BooleanType, class NumberIntegerType, \
  1577. class NumberUnsignedType, class NumberFloatType, \
  1578. template<typename> class AllocatorType, \
  1579. template<typename, typename = void> class JSONSerializer>
  1580. #define NLOHMANN_BASIC_JSON_TPL \
  1581. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  1582. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  1583. AllocatorType, JSONSerializer>
  1584. namespace nlohmann
  1585. {
  1586. namespace detail
  1587. {
  1588. ////////////////
  1589. // exceptions //
  1590. ////////////////
  1591. /*!
  1592. @brief general exception of the @ref basic_json class
  1593. This class is an extension of `std::exception` objects with a member @a id for
  1594. exception ids. It is used as the base class for all exceptions thrown by the
  1595. @ref basic_json class. This class can hence be used as "wildcard" to catch
  1596. exceptions.
  1597. Subclasses:
  1598. - @ref parse_error for exceptions indicating a parse error
  1599. - @ref invalid_iterator for exceptions indicating errors with iterators
  1600. - @ref type_error for exceptions indicating executing a member function with
  1601. a wrong type
  1602. - @ref out_of_range for exceptions indicating access out of the defined range
  1603. - @ref other_error for exceptions indicating other library errors
  1604. @internal
  1605. @note To have nothrow-copy-constructible exceptions, we internally use
  1606. `std::runtime_error` which can cope with arbitrary-length error messages.
  1607. Intermediate strings are built with static functions and then passed to
  1608. the actual constructor.
  1609. @endinternal
  1610. @liveexample{The following code shows how arbitrary library exceptions can be
  1611. caught.,exception}
  1612. @since version 3.0.0
  1613. */
  1614. class exception : public std::exception
  1615. {
  1616. public:
  1617. /// returns the explanatory string
  1618. JSON_HEDLEY_RETURNS_NON_NULL
  1619. const char* what() const noexcept override
  1620. {
  1621. return m.what();
  1622. }
  1623. /// the id of the exception
  1624. const int id;
  1625. protected:
  1626. JSON_HEDLEY_NON_NULL(3)
  1627. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  1628. static std::string name(const std::string& ename, int id_)
  1629. {
  1630. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  1631. }
  1632. private:
  1633. /// an exception object as storage for error messages
  1634. std::runtime_error m;
  1635. };
  1636. /*!
  1637. @brief exception indicating a parse error
  1638. This exception is thrown by the library when a parse error occurs. Parse errors
  1639. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  1640. as when using JSON Patch.
  1641. Member @a byte holds the byte index of the last read character in the input
  1642. file.
  1643. Exceptions have ids 1xx.
  1644. name / id | example message | description
  1645. ------------------------------ | --------------- | -------------------------
  1646. 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.
  1647. 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.
  1648. 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.
  1649. 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.
  1650. 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.
  1651. 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`.
  1652. 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.
  1653. 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.
  1654. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  1655. 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.
  1656. 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.
  1657. 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.
  1658. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  1659. @note For an input with n bytes, 1 is the index of the first character and n+1
  1660. is the index of the terminating null byte or the end of file. This also
  1661. holds true when reading a byte vector (CBOR or MessagePack).
  1662. @liveexample{The following code shows how a `parse_error` exception can be
  1663. caught.,parse_error}
  1664. @sa - @ref exception for the base class of the library exceptions
  1665. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1666. @sa - @ref type_error for exceptions indicating executing a member function with
  1667. a wrong type
  1668. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1669. @sa - @ref other_error for exceptions indicating other library errors
  1670. @since version 3.0.0
  1671. */
  1672. class parse_error : public exception
  1673. {
  1674. public:
  1675. /*!
  1676. @brief create a parse error exception
  1677. @param[in] id_ the id of the exception
  1678. @param[in] pos the position where the error occurred (or with
  1679. chars_read_total=0 if the position cannot be
  1680. determined)
  1681. @param[in] what_arg the explanatory string
  1682. @return parse_error object
  1683. */
  1684. static parse_error create(int id_, const position_t& pos, const std::string& what_arg)
  1685. {
  1686. std::string w = exception::name("parse_error", id_) + "parse error" +
  1687. position_string(pos) + ": " + what_arg;
  1688. return parse_error(id_, pos.chars_read_total, w.c_str());
  1689. }
  1690. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  1691. {
  1692. std::string w = exception::name("parse_error", id_) + "parse error" +
  1693. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  1694. ": " + what_arg;
  1695. return parse_error(id_, byte_, w.c_str());
  1696. }
  1697. /*!
  1698. @brief byte index of the parse error
  1699. The byte index of the last read character in the input file.
  1700. @note For an input with n bytes, 1 is the index of the first character and
  1701. n+1 is the index of the terminating null byte or the end of file.
  1702. This also holds true when reading a byte vector (CBOR or MessagePack).
  1703. */
  1704. const std::size_t byte;
  1705. private:
  1706. parse_error(int id_, std::size_t byte_, const char* what_arg)
  1707. : exception(id_, what_arg), byte(byte_) {}
  1708. static std::string position_string(const position_t& pos)
  1709. {
  1710. return " at line " + std::to_string(pos.lines_read + 1) +
  1711. ", column " + std::to_string(pos.chars_read_current_line);
  1712. }
  1713. };
  1714. /*!
  1715. @brief exception indicating errors with iterators
  1716. This exception is thrown if iterators passed to a library function do not match
  1717. the expected semantics.
  1718. Exceptions have ids 2xx.
  1719. name / id | example message | description
  1720. ----------------------------------- | --------------- | -------------------------
  1721. 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.
  1722. 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.
  1723. 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.
  1724. 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.
  1725. 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.
  1726. 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.
  1727. 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.
  1728. 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.
  1729. 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.
  1730. 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.
  1731. 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.
  1732. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  1733. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  1734. 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().
  1735. @liveexample{The following code shows how an `invalid_iterator` exception can be
  1736. caught.,invalid_iterator}
  1737. @sa - @ref exception for the base class of the library exceptions
  1738. @sa - @ref parse_error for exceptions indicating a parse error
  1739. @sa - @ref type_error for exceptions indicating executing a member function with
  1740. a wrong type
  1741. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1742. @sa - @ref other_error for exceptions indicating other library errors
  1743. @since version 3.0.0
  1744. */
  1745. class invalid_iterator : public exception
  1746. {
  1747. public:
  1748. static invalid_iterator create(int id_, const std::string& what_arg)
  1749. {
  1750. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  1751. return invalid_iterator(id_, w.c_str());
  1752. }
  1753. private:
  1754. JSON_HEDLEY_NON_NULL(3)
  1755. invalid_iterator(int id_, const char* what_arg)
  1756. : exception(id_, what_arg) {}
  1757. };
  1758. /*!
  1759. @brief exception indicating executing a member function with a wrong type
  1760. This exception is thrown in case of a type error; that is, a library function is
  1761. executed on a JSON value whose type does not match the expected semantics.
  1762. Exceptions have ids 3xx.
  1763. name / id | example message | description
  1764. ----------------------------- | --------------- | -------------------------
  1765. 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.
  1766. 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.
  1767. 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 &.
  1768. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  1769. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  1770. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  1771. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  1772. 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.
  1773. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  1774. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  1775. 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.
  1776. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  1777. 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.
  1778. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  1779. 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.
  1780. 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. |
  1781. 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) |
  1782. @liveexample{The following code shows how a `type_error` exception can be
  1783. caught.,type_error}
  1784. @sa - @ref exception for the base class of the library exceptions
  1785. @sa - @ref parse_error for exceptions indicating a parse error
  1786. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1787. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1788. @sa - @ref other_error for exceptions indicating other library errors
  1789. @since version 3.0.0
  1790. */
  1791. class type_error : public exception
  1792. {
  1793. public:
  1794. static type_error create(int id_, const std::string& what_arg)
  1795. {
  1796. std::string w = exception::name("type_error", id_) + what_arg;
  1797. return type_error(id_, w.c_str());
  1798. }
  1799. private:
  1800. JSON_HEDLEY_NON_NULL(3)
  1801. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  1802. };
  1803. /*!
  1804. @brief exception indicating access out of the defined range
  1805. This exception is thrown in case a library function is called on an input
  1806. parameter that exceeds the expected range, for instance in case of array
  1807. indices or nonexisting object keys.
  1808. Exceptions have ids 4xx.
  1809. name / id | example message | description
  1810. ------------------------------- | --------------- | -------------------------
  1811. 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.
  1812. 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.
  1813. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  1814. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  1815. 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.
  1816. 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.
  1817. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. |
  1818. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  1819. 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 |
  1820. @liveexample{The following code shows how an `out_of_range` exception can be
  1821. caught.,out_of_range}
  1822. @sa - @ref exception for the base class of the library exceptions
  1823. @sa - @ref parse_error for exceptions indicating a parse error
  1824. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1825. @sa - @ref type_error for exceptions indicating executing a member function with
  1826. a wrong type
  1827. @sa - @ref other_error for exceptions indicating other library errors
  1828. @since version 3.0.0
  1829. */
  1830. class out_of_range : public exception
  1831. {
  1832. public:
  1833. static out_of_range create(int id_, const std::string& what_arg)
  1834. {
  1835. std::string w = exception::name("out_of_range", id_) + what_arg;
  1836. return out_of_range(id_, w.c_str());
  1837. }
  1838. private:
  1839. JSON_HEDLEY_NON_NULL(3)
  1840. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  1841. };
  1842. /*!
  1843. @brief exception indicating other library errors
  1844. This exception is thrown in case of errors that cannot be classified with the
  1845. other exception types.
  1846. Exceptions have ids 5xx.
  1847. name / id | example message | description
  1848. ------------------------------ | --------------- | -------------------------
  1849. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  1850. @sa - @ref exception for the base class of the library exceptions
  1851. @sa - @ref parse_error for exceptions indicating a parse error
  1852. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1853. @sa - @ref type_error for exceptions indicating executing a member function with
  1854. a wrong type
  1855. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1856. @liveexample{The following code shows how an `other_error` exception can be
  1857. caught.,other_error}
  1858. @since version 3.0.0
  1859. */
  1860. class other_error : public exception
  1861. {
  1862. public:
  1863. static other_error create(int id_, const std::string& what_arg)
  1864. {
  1865. std::string w = exception::name("other_error", id_) + what_arg;
  1866. return other_error(id_, w.c_str());
  1867. }
  1868. private:
  1869. JSON_HEDLEY_NON_NULL(3)
  1870. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  1871. };
  1872. } // namespace detail
  1873. } // namespace nlohmann
  1874. // #include <nlohmann/detail/macro_scope.hpp>
  1875. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1876. #include <ciso646> // not
  1877. #include <cstddef> // size_t
  1878. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  1879. namespace nlohmann
  1880. {
  1881. namespace detail
  1882. {
  1883. // alias templates to reduce boilerplate
  1884. template<bool B, typename T = void>
  1885. using enable_if_t = typename std::enable_if<B, T>::type;
  1886. template<typename T>
  1887. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  1888. // implementation of C++14 index_sequence and affiliates
  1889. // source: https://stackoverflow.com/a/32223343
  1890. template<std::size_t... Ints>
  1891. struct index_sequence
  1892. {
  1893. using type = index_sequence;
  1894. using value_type = std::size_t;
  1895. static constexpr std::size_t size() noexcept
  1896. {
  1897. return sizeof...(Ints);
  1898. }
  1899. };
  1900. template<class Sequence1, class Sequence2>
  1901. struct merge_and_renumber;
  1902. template<std::size_t... I1, std::size_t... I2>
  1903. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  1904. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  1905. template<std::size_t N>
  1906. struct make_index_sequence
  1907. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  1908. typename make_index_sequence < N - N / 2 >::type > {};
  1909. template<> struct make_index_sequence<0> : index_sequence<> {};
  1910. template<> struct make_index_sequence<1> : index_sequence<0> {};
  1911. template<typename... Ts>
  1912. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  1913. // dispatch utility (taken from ranges-v3)
  1914. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  1915. template<> struct priority_tag<0> {};
  1916. // taken from ranges-v3
  1917. template<typename T>
  1918. struct static_const
  1919. {
  1920. static constexpr T value{};
  1921. };
  1922. template<typename T>
  1923. constexpr T static_const<T>::value;
  1924. } // namespace detail
  1925. } // namespace nlohmann
  1926. // #include <nlohmann/detail/meta/type_traits.hpp>
  1927. #include <ciso646> // not
  1928. #include <limits> // numeric_limits
  1929. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  1930. #include <utility> // declval
  1931. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  1932. #include <iterator> // random_access_iterator_tag
  1933. // #include <nlohmann/detail/meta/void_t.hpp>
  1934. namespace nlohmann
  1935. {
  1936. namespace detail
  1937. {
  1938. template <typename ...Ts> struct make_void
  1939. {
  1940. using type = void;
  1941. };
  1942. template <typename ...Ts> using void_t = typename make_void<Ts...>::type;
  1943. } // namespace detail
  1944. } // namespace nlohmann
  1945. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1946. namespace nlohmann
  1947. {
  1948. namespace detail
  1949. {
  1950. template <typename It, typename = void>
  1951. struct iterator_types {};
  1952. template <typename It>
  1953. struct iterator_types <
  1954. It,
  1955. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  1956. typename It::reference, typename It::iterator_category >>
  1957. {
  1958. using difference_type = typename It::difference_type;
  1959. using value_type = typename It::value_type;
  1960. using pointer = typename It::pointer;
  1961. using reference = typename It::reference;
  1962. using iterator_category = typename It::iterator_category;
  1963. };
  1964. // This is required as some compilers implement std::iterator_traits in a way that
  1965. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  1966. template <typename T, typename = void>
  1967. struct iterator_traits
  1968. {
  1969. };
  1970. template <typename T>
  1971. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  1972. : iterator_types<T>
  1973. {
  1974. };
  1975. template <typename T>
  1976. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  1977. {
  1978. using iterator_category = std::random_access_iterator_tag;
  1979. using value_type = T;
  1980. using difference_type = ptrdiff_t;
  1981. using pointer = T*;
  1982. using reference = T&;
  1983. };
  1984. } // namespace detail
  1985. } // namespace nlohmann
  1986. // #include <nlohmann/detail/macro_scope.hpp>
  1987. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1988. // #include <nlohmann/detail/meta/detected.hpp>
  1989. #include <type_traits>
  1990. // #include <nlohmann/detail/meta/void_t.hpp>
  1991. // http://en.cppreference.com/w/cpp/experimental/is_detected
  1992. namespace nlohmann
  1993. {
  1994. namespace detail
  1995. {
  1996. struct nonesuch
  1997. {
  1998. nonesuch() = delete;
  1999. ~nonesuch() = delete;
  2000. nonesuch(nonesuch const&) = delete;
  2001. nonesuch(nonesuch const&&) = delete;
  2002. void operator=(nonesuch const&) = delete;
  2003. void operator=(nonesuch&&) = delete;
  2004. };
  2005. template <class Default,
  2006. class AlwaysVoid,
  2007. template <class...> class Op,
  2008. class... Args>
  2009. struct detector
  2010. {
  2011. using value_t = std::false_type;
  2012. using type = Default;
  2013. };
  2014. template <class Default, template <class...> class Op, class... Args>
  2015. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  2016. {
  2017. using value_t = std::true_type;
  2018. using type = Op<Args...>;
  2019. };
  2020. template <template <class...> class Op, class... Args>
  2021. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  2022. template <template <class...> class Op, class... Args>
  2023. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  2024. template <class Default, template <class...> class Op, class... Args>
  2025. using detected_or = detector<Default, void, Op, Args...>;
  2026. template <class Default, template <class...> class Op, class... Args>
  2027. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  2028. template <class Expected, template <class...> class Op, class... Args>
  2029. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  2030. template <class To, template <class...> class Op, class... Args>
  2031. using is_detected_convertible =
  2032. std::is_convertible<detected_t<Op, Args...>, To>;
  2033. } // namespace detail
  2034. } // namespace nlohmann
  2035. // #include <nlohmann/json_fwd.hpp>
  2036. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2037. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2038. #include <cstdint> // int64_t, uint64_t
  2039. #include <map> // map
  2040. #include <memory> // allocator
  2041. #include <string> // string
  2042. #include <vector> // vector
  2043. /*!
  2044. @brief namespace for Niels Lohmann
  2045. @see https://github.com/nlohmann
  2046. @since version 1.0.0
  2047. */
  2048. namespace nlohmann
  2049. {
  2050. /*!
  2051. @brief default JSONSerializer template argument
  2052. This serializer ignores the template arguments and uses ADL
  2053. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  2054. for serialization.
  2055. */
  2056. template<typename T = void, typename SFINAE = void>
  2057. struct adl_serializer;
  2058. template<template<typename U, typename V, typename... Args> class ObjectType =
  2059. std::map,
  2060. template<typename U, typename... Args> class ArrayType = std::vector,
  2061. class StringType = std::string, class BooleanType = bool,
  2062. class NumberIntegerType = std::int64_t,
  2063. class NumberUnsignedType = std::uint64_t,
  2064. class NumberFloatType = double,
  2065. template<typename U> class AllocatorType = std::allocator,
  2066. template<typename T, typename SFINAE = void> class JSONSerializer =
  2067. adl_serializer>
  2068. class basic_json;
  2069. /*!
  2070. @brief JSON Pointer
  2071. A JSON pointer defines a string syntax for identifying a specific value
  2072. within a JSON document. It can be used with functions `at` and
  2073. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  2074. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  2075. @since version 2.0.0
  2076. */
  2077. template<typename BasicJsonType>
  2078. class json_pointer;
  2079. /*!
  2080. @brief default JSON class
  2081. This type is the default specialization of the @ref basic_json class which
  2082. uses the standard template types.
  2083. @since version 1.0.0
  2084. */
  2085. using json = basic_json<>;
  2086. } // namespace nlohmann
  2087. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2088. namespace nlohmann
  2089. {
  2090. /*!
  2091. @brief detail namespace with internal helper functions
  2092. This namespace collects functions that should not be exposed,
  2093. implementations of some @ref basic_json methods, and meta-programming helpers.
  2094. @since version 2.1.0
  2095. */
  2096. namespace detail
  2097. {
  2098. /////////////
  2099. // helpers //
  2100. /////////////
  2101. // Note to maintainers:
  2102. //
  2103. // Every trait in this file expects a non CV-qualified type.
  2104. // The only exceptions are in the 'aliases for detected' section
  2105. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  2106. //
  2107. // In this case, T has to be properly CV-qualified to constraint the function arguments
  2108. // (e.g. to_json(BasicJsonType&, const T&))
  2109. template<typename> struct is_basic_json : std::false_type {};
  2110. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  2111. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  2112. //////////////////////////
  2113. // aliases for detected //
  2114. //////////////////////////
  2115. template <typename T>
  2116. using mapped_type_t = typename T::mapped_type;
  2117. template <typename T>
  2118. using key_type_t = typename T::key_type;
  2119. template <typename T>
  2120. using value_type_t = typename T::value_type;
  2121. template <typename T>
  2122. using difference_type_t = typename T::difference_type;
  2123. template <typename T>
  2124. using pointer_t = typename T::pointer;
  2125. template <typename T>
  2126. using reference_t = typename T::reference;
  2127. template <typename T>
  2128. using iterator_category_t = typename T::iterator_category;
  2129. template <typename T>
  2130. using iterator_t = typename T::iterator;
  2131. template <typename T, typename... Args>
  2132. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  2133. template <typename T, typename... Args>
  2134. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  2135. template <typename T, typename U>
  2136. using get_template_function = decltype(std::declval<T>().template get<U>());
  2137. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  2138. template <typename BasicJsonType, typename T, typename = void>
  2139. struct has_from_json : std::false_type {};
  2140. template <typename BasicJsonType, typename T>
  2141. struct has_from_json<BasicJsonType, T,
  2142. enable_if_t<not is_basic_json<T>::value>>
  2143. {
  2144. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2145. static constexpr bool value =
  2146. is_detected_exact<void, from_json_function, serializer,
  2147. const BasicJsonType&, T&>::value;
  2148. };
  2149. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  2150. // this overload is used for non-default-constructible user-defined-types
  2151. template <typename BasicJsonType, typename T, typename = void>
  2152. struct has_non_default_from_json : std::false_type {};
  2153. template<typename BasicJsonType, typename T>
  2154. struct has_non_default_from_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  2155. {
  2156. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2157. static constexpr bool value =
  2158. is_detected_exact<T, from_json_function, serializer,
  2159. const BasicJsonType&>::value;
  2160. };
  2161. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  2162. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  2163. template <typename BasicJsonType, typename T, typename = void>
  2164. struct has_to_json : std::false_type {};
  2165. template <typename BasicJsonType, typename T>
  2166. struct has_to_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  2167. {
  2168. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2169. static constexpr bool value =
  2170. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  2171. T>::value;
  2172. };
  2173. ///////////////////
  2174. // is_ functions //
  2175. ///////////////////
  2176. template <typename T, typename = void>
  2177. struct is_iterator_traits : std::false_type {};
  2178. template <typename T>
  2179. struct is_iterator_traits<iterator_traits<T>>
  2180. {
  2181. private:
  2182. using traits = iterator_traits<T>;
  2183. public:
  2184. static constexpr auto value =
  2185. is_detected<value_type_t, traits>::value &&
  2186. is_detected<difference_type_t, traits>::value &&
  2187. is_detected<pointer_t, traits>::value &&
  2188. is_detected<iterator_category_t, traits>::value &&
  2189. is_detected<reference_t, traits>::value;
  2190. };
  2191. // source: https://stackoverflow.com/a/37193089/4116453
  2192. template <typename T, typename = void>
  2193. struct is_complete_type : std::false_type {};
  2194. template <typename T>
  2195. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  2196. template <typename BasicJsonType, typename CompatibleObjectType,
  2197. typename = void>
  2198. struct is_compatible_object_type_impl : std::false_type {};
  2199. template <typename BasicJsonType, typename CompatibleObjectType>
  2200. struct is_compatible_object_type_impl <
  2201. BasicJsonType, CompatibleObjectType,
  2202. enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value and
  2203. is_detected<key_type_t, CompatibleObjectType>::value >>
  2204. {
  2205. using object_t = typename BasicJsonType::object_t;
  2206. // macOS's is_constructible does not play well with nonesuch...
  2207. static constexpr bool value =
  2208. std::is_constructible<typename object_t::key_type,
  2209. typename CompatibleObjectType::key_type>::value and
  2210. std::is_constructible<typename object_t::mapped_type,
  2211. typename CompatibleObjectType::mapped_type>::value;
  2212. };
  2213. template <typename BasicJsonType, typename CompatibleObjectType>
  2214. struct is_compatible_object_type
  2215. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  2216. template <typename BasicJsonType, typename ConstructibleObjectType,
  2217. typename = void>
  2218. struct is_constructible_object_type_impl : std::false_type {};
  2219. template <typename BasicJsonType, typename ConstructibleObjectType>
  2220. struct is_constructible_object_type_impl <
  2221. BasicJsonType, ConstructibleObjectType,
  2222. enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value and
  2223. is_detected<key_type_t, ConstructibleObjectType>::value >>
  2224. {
  2225. using object_t = typename BasicJsonType::object_t;
  2226. static constexpr bool value =
  2227. (std::is_default_constructible<ConstructibleObjectType>::value and
  2228. (std::is_move_assignable<ConstructibleObjectType>::value or
  2229. std::is_copy_assignable<ConstructibleObjectType>::value) and
  2230. (std::is_constructible<typename ConstructibleObjectType::key_type,
  2231. typename object_t::key_type>::value and
  2232. std::is_same <
  2233. typename object_t::mapped_type,
  2234. typename ConstructibleObjectType::mapped_type >::value)) or
  2235. (has_from_json<BasicJsonType,
  2236. typename ConstructibleObjectType::mapped_type>::value or
  2237. has_non_default_from_json <
  2238. BasicJsonType,
  2239. typename ConstructibleObjectType::mapped_type >::value);
  2240. };
  2241. template <typename BasicJsonType, typename ConstructibleObjectType>
  2242. struct is_constructible_object_type
  2243. : is_constructible_object_type_impl<BasicJsonType,
  2244. ConstructibleObjectType> {};
  2245. template <typename BasicJsonType, typename CompatibleStringType,
  2246. typename = void>
  2247. struct is_compatible_string_type_impl : std::false_type {};
  2248. template <typename BasicJsonType, typename CompatibleStringType>
  2249. struct is_compatible_string_type_impl <
  2250. BasicJsonType, CompatibleStringType,
  2251. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2252. value_type_t, CompatibleStringType>::value >>
  2253. {
  2254. static constexpr auto value =
  2255. std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  2256. };
  2257. template <typename BasicJsonType, typename ConstructibleStringType>
  2258. struct is_compatible_string_type
  2259. : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2260. template <typename BasicJsonType, typename ConstructibleStringType,
  2261. typename = void>
  2262. struct is_constructible_string_type_impl : std::false_type {};
  2263. template <typename BasicJsonType, typename ConstructibleStringType>
  2264. struct is_constructible_string_type_impl <
  2265. BasicJsonType, ConstructibleStringType,
  2266. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2267. value_type_t, ConstructibleStringType>::value >>
  2268. {
  2269. static constexpr auto value =
  2270. std::is_constructible<ConstructibleStringType,
  2271. typename BasicJsonType::string_t>::value;
  2272. };
  2273. template <typename BasicJsonType, typename ConstructibleStringType>
  2274. struct is_constructible_string_type
  2275. : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2276. template <typename BasicJsonType, typename CompatibleArrayType, typename = void>
  2277. struct is_compatible_array_type_impl : std::false_type {};
  2278. template <typename BasicJsonType, typename CompatibleArrayType>
  2279. struct is_compatible_array_type_impl <
  2280. BasicJsonType, CompatibleArrayType,
  2281. enable_if_t<is_detected<value_type_t, CompatibleArrayType>::value and
  2282. is_detected<iterator_t, CompatibleArrayType>::value and
  2283. // This is needed because json_reverse_iterator has a ::iterator type...
  2284. // Therefore it is detected as a CompatibleArrayType.
  2285. // The real fix would be to have an Iterable concept.
  2286. not is_iterator_traits<
  2287. iterator_traits<CompatibleArrayType>>::value >>
  2288. {
  2289. static constexpr bool value =
  2290. std::is_constructible<BasicJsonType,
  2291. typename CompatibleArrayType::value_type>::value;
  2292. };
  2293. template <typename BasicJsonType, typename CompatibleArrayType>
  2294. struct is_compatible_array_type
  2295. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  2296. template <typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  2297. struct is_constructible_array_type_impl : std::false_type {};
  2298. template <typename BasicJsonType, typename ConstructibleArrayType>
  2299. struct is_constructible_array_type_impl <
  2300. BasicJsonType, ConstructibleArrayType,
  2301. enable_if_t<std::is_same<ConstructibleArrayType,
  2302. typename BasicJsonType::value_type>::value >>
  2303. : std::true_type {};
  2304. template <typename BasicJsonType, typename ConstructibleArrayType>
  2305. struct is_constructible_array_type_impl <
  2306. BasicJsonType, ConstructibleArrayType,
  2307. enable_if_t<not std::is_same<ConstructibleArrayType,
  2308. typename BasicJsonType::value_type>::value and
  2309. std::is_default_constructible<ConstructibleArrayType>::value and
  2310. (std::is_move_assignable<ConstructibleArrayType>::value or
  2311. std::is_copy_assignable<ConstructibleArrayType>::value) and
  2312. is_detected<value_type_t, ConstructibleArrayType>::value and
  2313. is_detected<iterator_t, ConstructibleArrayType>::value and
  2314. is_complete_type<
  2315. detected_t<value_type_t, ConstructibleArrayType>>::value >>
  2316. {
  2317. static constexpr bool value =
  2318. // This is needed because json_reverse_iterator has a ::iterator type,
  2319. // furthermore, std::back_insert_iterator (and other iterators) have a
  2320. // base class `iterator`... Therefore it is detected as a
  2321. // ConstructibleArrayType. The real fix would be to have an Iterable
  2322. // concept.
  2323. not is_iterator_traits<iterator_traits<ConstructibleArrayType>>::value and
  2324. (std::is_same<typename ConstructibleArrayType::value_type,
  2325. typename BasicJsonType::array_t::value_type>::value or
  2326. has_from_json<BasicJsonType,
  2327. typename ConstructibleArrayType::value_type>::value or
  2328. has_non_default_from_json <
  2329. BasicJsonType, typename ConstructibleArrayType::value_type >::value);
  2330. };
  2331. template <typename BasicJsonType, typename ConstructibleArrayType>
  2332. struct is_constructible_array_type
  2333. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  2334. template <typename RealIntegerType, typename CompatibleNumberIntegerType,
  2335. typename = void>
  2336. struct is_compatible_integer_type_impl : std::false_type {};
  2337. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  2338. struct is_compatible_integer_type_impl <
  2339. RealIntegerType, CompatibleNumberIntegerType,
  2340. enable_if_t<std::is_integral<RealIntegerType>::value and
  2341. std::is_integral<CompatibleNumberIntegerType>::value and
  2342. not std::is_same<bool, CompatibleNumberIntegerType>::value >>
  2343. {
  2344. // is there an assert somewhere on overflows?
  2345. using RealLimits = std::numeric_limits<RealIntegerType>;
  2346. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  2347. static constexpr auto value =
  2348. std::is_constructible<RealIntegerType,
  2349. CompatibleNumberIntegerType>::value and
  2350. CompatibleLimits::is_integer and
  2351. RealLimits::is_signed == CompatibleLimits::is_signed;
  2352. };
  2353. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  2354. struct is_compatible_integer_type
  2355. : is_compatible_integer_type_impl<RealIntegerType,
  2356. CompatibleNumberIntegerType> {};
  2357. template <typename BasicJsonType, typename CompatibleType, typename = void>
  2358. struct is_compatible_type_impl: std::false_type {};
  2359. template <typename BasicJsonType, typename CompatibleType>
  2360. struct is_compatible_type_impl <
  2361. BasicJsonType, CompatibleType,
  2362. enable_if_t<is_complete_type<CompatibleType>::value >>
  2363. {
  2364. static constexpr bool value =
  2365. has_to_json<BasicJsonType, CompatibleType>::value;
  2366. };
  2367. template <typename BasicJsonType, typename CompatibleType>
  2368. struct is_compatible_type
  2369. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  2370. } // namespace detail
  2371. } // namespace nlohmann
  2372. // #include <nlohmann/detail/value_t.hpp>
  2373. #include <array> // array
  2374. #include <ciso646> // and
  2375. #include <cstddef> // size_t
  2376. #include <cstdint> // uint8_t
  2377. #include <string> // string
  2378. namespace nlohmann
  2379. {
  2380. namespace detail
  2381. {
  2382. ///////////////////////////
  2383. // JSON type enumeration //
  2384. ///////////////////////////
  2385. /*!
  2386. @brief the JSON type enumeration
  2387. This enumeration collects the different JSON types. It is internally used to
  2388. distinguish the stored values, and the functions @ref basic_json::is_null(),
  2389. @ref basic_json::is_object(), @ref basic_json::is_array(),
  2390. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  2391. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  2392. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  2393. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  2394. @ref basic_json::is_structured() rely on it.
  2395. @note There are three enumeration entries (number_integer, number_unsigned, and
  2396. number_float), because the library distinguishes these three types for numbers:
  2397. @ref basic_json::number_unsigned_t is used for unsigned integers,
  2398. @ref basic_json::number_integer_t is used for signed integers, and
  2399. @ref basic_json::number_float_t is used for floating-point numbers or to
  2400. approximate integers which do not fit in the limits of their respective type.
  2401. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  2402. value with the default value for a given type
  2403. @since version 1.0.0
  2404. */
  2405. enum class value_t : std::uint8_t
  2406. {
  2407. null, ///< null value
  2408. object, ///< object (unordered set of name/value pairs)
  2409. array, ///< array (ordered collection of values)
  2410. string, ///< string value
  2411. boolean, ///< boolean value
  2412. number_integer, ///< number value (signed integer)
  2413. number_unsigned, ///< number value (unsigned integer)
  2414. number_float, ///< number value (floating-point)
  2415. discarded ///< discarded by the the parser callback function
  2416. };
  2417. /*!
  2418. @brief comparison operator for JSON types
  2419. Returns an ordering that is similar to Python:
  2420. - order: null < boolean < number < object < array < string
  2421. - furthermore, each type is not smaller than itself
  2422. - discarded values are not comparable
  2423. @since version 1.0.0
  2424. */
  2425. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  2426. {
  2427. static constexpr std::array<std::uint8_t, 8> order = {{
  2428. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  2429. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
  2430. }
  2431. };
  2432. const auto l_index = static_cast<std::size_t>(lhs);
  2433. const auto r_index = static_cast<std::size_t>(rhs);
  2434. return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
  2435. }
  2436. } // namespace detail
  2437. } // namespace nlohmann
  2438. namespace nlohmann
  2439. {
  2440. namespace detail
  2441. {
  2442. template<typename BasicJsonType>
  2443. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  2444. {
  2445. if (JSON_HEDLEY_UNLIKELY(not j.is_null()))
  2446. {
  2447. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
  2448. }
  2449. n = nullptr;
  2450. }
  2451. // overloads for basic_json template parameters
  2452. template<typename BasicJsonType, typename ArithmeticType,
  2453. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  2454. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  2455. int> = 0>
  2456. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  2457. {
  2458. switch (static_cast<value_t>(j))
  2459. {
  2460. case value_t::number_unsigned:
  2461. {
  2462. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  2463. break;
  2464. }
  2465. case value_t::number_integer:
  2466. {
  2467. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  2468. break;
  2469. }
  2470. case value_t::number_float:
  2471. {
  2472. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  2473. break;
  2474. }
  2475. default:
  2476. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  2477. }
  2478. }
  2479. template<typename BasicJsonType>
  2480. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  2481. {
  2482. if (JSON_HEDLEY_UNLIKELY(not j.is_boolean()))
  2483. {
  2484. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  2485. }
  2486. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  2487. }
  2488. template<typename BasicJsonType>
  2489. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  2490. {
  2491. if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
  2492. {
  2493. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2494. }
  2495. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2496. }
  2497. template <
  2498. typename BasicJsonType, typename ConstructibleStringType,
  2499. enable_if_t <
  2500. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value and
  2501. not std::is_same<typename BasicJsonType::string_t,
  2502. ConstructibleStringType>::value,
  2503. int > = 0 >
  2504. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  2505. {
  2506. if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
  2507. {
  2508. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2509. }
  2510. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2511. }
  2512. template<typename BasicJsonType>
  2513. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  2514. {
  2515. get_arithmetic_value(j, val);
  2516. }
  2517. template<typename BasicJsonType>
  2518. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  2519. {
  2520. get_arithmetic_value(j, val);
  2521. }
  2522. template<typename BasicJsonType>
  2523. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  2524. {
  2525. get_arithmetic_value(j, val);
  2526. }
  2527. template<typename BasicJsonType, typename EnumType,
  2528. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  2529. void from_json(const BasicJsonType& j, EnumType& e)
  2530. {
  2531. typename std::underlying_type<EnumType>::type val;
  2532. get_arithmetic_value(j, val);
  2533. e = static_cast<EnumType>(val);
  2534. }
  2535. // forward_list doesn't have an insert method
  2536. template<typename BasicJsonType, typename T, typename Allocator,
  2537. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  2538. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  2539. {
  2540. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2541. {
  2542. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2543. }
  2544. l.clear();
  2545. std::transform(j.rbegin(), j.rend(),
  2546. std::front_inserter(l), [](const BasicJsonType & i)
  2547. {
  2548. return i.template get<T>();
  2549. });
  2550. }
  2551. // valarray doesn't have an insert method
  2552. template<typename BasicJsonType, typename T,
  2553. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  2554. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  2555. {
  2556. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2557. {
  2558. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2559. }
  2560. l.resize(j.size());
  2561. std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
  2562. }
  2563. template <typename BasicJsonType, typename T, std::size_t N>
  2564. auto from_json(const BasicJsonType& j, T (&arr)[N])
  2565. -> decltype(j.template get<T>(), void())
  2566. {
  2567. for (std::size_t i = 0; i < N; ++i)
  2568. {
  2569. arr[i] = j.at(i).template get<T>();
  2570. }
  2571. }
  2572. template<typename BasicJsonType>
  2573. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  2574. {
  2575. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  2576. }
  2577. template <typename BasicJsonType, typename T, std::size_t N>
  2578. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  2579. priority_tag<2> /*unused*/)
  2580. -> decltype(j.template get<T>(), void())
  2581. {
  2582. for (std::size_t i = 0; i < N; ++i)
  2583. {
  2584. arr[i] = j.at(i).template get<T>();
  2585. }
  2586. }
  2587. template<typename BasicJsonType, typename ConstructibleArrayType>
  2588. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  2589. -> decltype(
  2590. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  2591. j.template get<typename ConstructibleArrayType::value_type>(),
  2592. void())
  2593. {
  2594. using std::end;
  2595. ConstructibleArrayType ret;
  2596. ret.reserve(j.size());
  2597. std::transform(j.begin(), j.end(),
  2598. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  2599. {
  2600. // get<BasicJsonType>() returns *this, this won't call a from_json
  2601. // method when value_type is BasicJsonType
  2602. return i.template get<typename ConstructibleArrayType::value_type>();
  2603. });
  2604. arr = std::move(ret);
  2605. }
  2606. template <typename BasicJsonType, typename ConstructibleArrayType>
  2607. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  2608. priority_tag<0> /*unused*/)
  2609. {
  2610. using std::end;
  2611. ConstructibleArrayType ret;
  2612. std::transform(
  2613. j.begin(), j.end(), std::inserter(ret, end(ret)),
  2614. [](const BasicJsonType & i)
  2615. {
  2616. // get<BasicJsonType>() returns *this, this won't call a from_json
  2617. // method when value_type is BasicJsonType
  2618. return i.template get<typename ConstructibleArrayType::value_type>();
  2619. });
  2620. arr = std::move(ret);
  2621. }
  2622. template <typename BasicJsonType, typename ConstructibleArrayType,
  2623. enable_if_t <
  2624. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value and
  2625. not is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value and
  2626. not is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value and
  2627. not is_basic_json<ConstructibleArrayType>::value,
  2628. int > = 0 >
  2629. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  2630. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  2631. j.template get<typename ConstructibleArrayType::value_type>(),
  2632. void())
  2633. {
  2634. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2635. {
  2636. JSON_THROW(type_error::create(302, "type must be array, but is " +
  2637. std::string(j.type_name())));
  2638. }
  2639. from_json_array_impl(j, arr, priority_tag<3> {});
  2640. }
  2641. template<typename BasicJsonType, typename ConstructibleObjectType,
  2642. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  2643. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  2644. {
  2645. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  2646. {
  2647. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  2648. }
  2649. ConstructibleObjectType ret;
  2650. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  2651. using value_type = typename ConstructibleObjectType::value_type;
  2652. std::transform(
  2653. inner_object->begin(), inner_object->end(),
  2654. std::inserter(ret, ret.begin()),
  2655. [](typename BasicJsonType::object_t::value_type const & p)
  2656. {
  2657. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  2658. });
  2659. obj = std::move(ret);
  2660. }
  2661. // overload for arithmetic types, not chosen for basic_json template arguments
  2662. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  2663. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  2664. // an arithmetic type?
  2665. template<typename BasicJsonType, typename ArithmeticType,
  2666. enable_if_t <
  2667. std::is_arithmetic<ArithmeticType>::value and
  2668. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  2669. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  2670. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  2671. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  2672. int> = 0>
  2673. void from_json(const BasicJsonType& j, ArithmeticType& val)
  2674. {
  2675. switch (static_cast<value_t>(j))
  2676. {
  2677. case value_t::number_unsigned:
  2678. {
  2679. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  2680. break;
  2681. }
  2682. case value_t::number_integer:
  2683. {
  2684. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  2685. break;
  2686. }
  2687. case value_t::number_float:
  2688. {
  2689. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  2690. break;
  2691. }
  2692. case value_t::boolean:
  2693. {
  2694. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  2695. break;
  2696. }
  2697. default:
  2698. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  2699. }
  2700. }
  2701. template<typename BasicJsonType, typename A1, typename A2>
  2702. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  2703. {
  2704. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  2705. }
  2706. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  2707. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/)
  2708. {
  2709. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  2710. }
  2711. template<typename BasicJsonType, typename... Args>
  2712. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  2713. {
  2714. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  2715. }
  2716. template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  2717. typename = enable_if_t<not std::is_constructible<
  2718. typename BasicJsonType::string_t, Key>::value>>
  2719. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  2720. {
  2721. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2722. {
  2723. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2724. }
  2725. m.clear();
  2726. for (const auto& p : j)
  2727. {
  2728. if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
  2729. {
  2730. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  2731. }
  2732. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  2733. }
  2734. }
  2735. template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  2736. typename = enable_if_t<not std::is_constructible<
  2737. typename BasicJsonType::string_t, Key>::value>>
  2738. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  2739. {
  2740. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2741. {
  2742. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2743. }
  2744. m.clear();
  2745. for (const auto& p : j)
  2746. {
  2747. if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
  2748. {
  2749. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  2750. }
  2751. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  2752. }
  2753. }
  2754. struct from_json_fn
  2755. {
  2756. template<typename BasicJsonType, typename T>
  2757. auto operator()(const BasicJsonType& j, T& val) const
  2758. noexcept(noexcept(from_json(j, val)))
  2759. -> decltype(from_json(j, val), void())
  2760. {
  2761. return from_json(j, val);
  2762. }
  2763. };
  2764. } // namespace detail
  2765. /// namespace to hold default `from_json` function
  2766. /// to see why this is required:
  2767. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  2768. namespace
  2769. {
  2770. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  2771. } // namespace
  2772. } // namespace nlohmann
  2773. // #include <nlohmann/detail/conversions/to_json.hpp>
  2774. #include <algorithm> // copy
  2775. #include <ciso646> // or, and, not
  2776. #include <iterator> // begin, end
  2777. #include <string> // string
  2778. #include <tuple> // tuple, get
  2779. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  2780. #include <utility> // move, forward, declval, pair
  2781. #include <valarray> // valarray
  2782. #include <vector> // vector
  2783. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  2784. #include <cstddef> // size_t
  2785. #include <iterator> // input_iterator_tag
  2786. #include <string> // string, to_string
  2787. #include <tuple> // tuple_size, get, tuple_element
  2788. // #include <nlohmann/detail/meta/type_traits.hpp>
  2789. // #include <nlohmann/detail/value_t.hpp>
  2790. namespace nlohmann
  2791. {
  2792. namespace detail
  2793. {
  2794. template <typename IteratorType> class iteration_proxy_value
  2795. {
  2796. public:
  2797. using difference_type = std::ptrdiff_t;
  2798. using value_type = iteration_proxy_value;
  2799. using pointer = value_type * ;
  2800. using reference = value_type & ;
  2801. using iterator_category = std::input_iterator_tag;
  2802. private:
  2803. /// the iterator
  2804. IteratorType anchor;
  2805. /// an index for arrays (used to create key names)
  2806. std::size_t array_index = 0;
  2807. /// last stringified array index
  2808. mutable std::size_t array_index_last = 0;
  2809. /// a string representation of the array index
  2810. mutable std::string array_index_str = "0";
  2811. /// an empty string (to return a reference for primitive values)
  2812. const std::string empty_str = "";
  2813. public:
  2814. explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {}
  2815. /// dereference operator (needed for range-based for)
  2816. iteration_proxy_value& operator*()
  2817. {
  2818. return *this;
  2819. }
  2820. /// increment operator (needed for range-based for)
  2821. iteration_proxy_value& operator++()
  2822. {
  2823. ++anchor;
  2824. ++array_index;
  2825. return *this;
  2826. }
  2827. /// equality operator (needed for InputIterator)
  2828. bool operator==(const iteration_proxy_value& o) const
  2829. {
  2830. return anchor == o.anchor;
  2831. }
  2832. /// inequality operator (needed for range-based for)
  2833. bool operator!=(const iteration_proxy_value& o) const
  2834. {
  2835. return anchor != o.anchor;
  2836. }
  2837. /// return key of the iterator
  2838. const std::string& key() const
  2839. {
  2840. assert(anchor.m_object != nullptr);
  2841. switch (anchor.m_object->type())
  2842. {
  2843. // use integer array index as key
  2844. case value_t::array:
  2845. {
  2846. if (array_index != array_index_last)
  2847. {
  2848. array_index_str = std::to_string(array_index);
  2849. array_index_last = array_index;
  2850. }
  2851. return array_index_str;
  2852. }
  2853. // use key from the object
  2854. case value_t::object:
  2855. return anchor.key();
  2856. // use an empty key for all primitive types
  2857. default:
  2858. return empty_str;
  2859. }
  2860. }
  2861. /// return value of the iterator
  2862. typename IteratorType::reference value() const
  2863. {
  2864. return anchor.value();
  2865. }
  2866. };
  2867. /// proxy class for the items() function
  2868. template<typename IteratorType> class iteration_proxy
  2869. {
  2870. private:
  2871. /// the container to iterate
  2872. typename IteratorType::reference container;
  2873. public:
  2874. /// construct iteration proxy from a container
  2875. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  2876. : container(cont) {}
  2877. /// return iterator begin (needed for range-based for)
  2878. iteration_proxy_value<IteratorType> begin() noexcept
  2879. {
  2880. return iteration_proxy_value<IteratorType>(container.begin());
  2881. }
  2882. /// return iterator end (needed for range-based for)
  2883. iteration_proxy_value<IteratorType> end() noexcept
  2884. {
  2885. return iteration_proxy_value<IteratorType>(container.end());
  2886. }
  2887. };
  2888. // Structured Bindings Support
  2889. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  2890. // And see https://github.com/nlohmann/json/pull/1391
  2891. template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  2892. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  2893. {
  2894. return i.key();
  2895. }
  2896. // Structured Bindings Support
  2897. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  2898. // And see https://github.com/nlohmann/json/pull/1391
  2899. template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  2900. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  2901. {
  2902. return i.value();
  2903. }
  2904. } // namespace detail
  2905. } // namespace nlohmann
  2906. // The Addition to the STD Namespace is required to add
  2907. // Structured Bindings Support to the iteration_proxy_value class
  2908. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  2909. // And see https://github.com/nlohmann/json/pull/1391
  2910. namespace std
  2911. {
  2912. #if defined(__clang__)
  2913. // Fix: https://github.com/nlohmann/json/issues/1401
  2914. #pragma clang diagnostic push
  2915. #pragma clang diagnostic ignored "-Wmismatched-tags"
  2916. #endif
  2917. template <typename IteratorType>
  2918. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  2919. : public std::integral_constant<std::size_t, 2> {};
  2920. template <std::size_t N, typename IteratorType>
  2921. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  2922. {
  2923. public:
  2924. using type = decltype(
  2925. get<N>(std::declval <
  2926. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  2927. };
  2928. #if defined(__clang__)
  2929. #pragma clang diagnostic pop
  2930. #endif
  2931. } // namespace std
  2932. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2933. // #include <nlohmann/detail/meta/type_traits.hpp>
  2934. // #include <nlohmann/detail/value_t.hpp>
  2935. namespace nlohmann
  2936. {
  2937. namespace detail
  2938. {
  2939. //////////////////
  2940. // constructors //
  2941. //////////////////
  2942. template<value_t> struct external_constructor;
  2943. template<>
  2944. struct external_constructor<value_t::boolean>
  2945. {
  2946. template<typename BasicJsonType>
  2947. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  2948. {
  2949. j.m_type = value_t::boolean;
  2950. j.m_value = b;
  2951. j.assert_invariant();
  2952. }
  2953. };
  2954. template<>
  2955. struct external_constructor<value_t::string>
  2956. {
  2957. template<typename BasicJsonType>
  2958. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  2959. {
  2960. j.m_type = value_t::string;
  2961. j.m_value = s;
  2962. j.assert_invariant();
  2963. }
  2964. template<typename BasicJsonType>
  2965. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  2966. {
  2967. j.m_type = value_t::string;
  2968. j.m_value = std::move(s);
  2969. j.assert_invariant();
  2970. }
  2971. template<typename BasicJsonType, typename CompatibleStringType,
  2972. enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  2973. int> = 0>
  2974. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  2975. {
  2976. j.m_type = value_t::string;
  2977. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  2978. j.assert_invariant();
  2979. }
  2980. };
  2981. template<>
  2982. struct external_constructor<value_t::number_float>
  2983. {
  2984. template<typename BasicJsonType>
  2985. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  2986. {
  2987. j.m_type = value_t::number_float;
  2988. j.m_value = val;
  2989. j.assert_invariant();
  2990. }
  2991. };
  2992. template<>
  2993. struct external_constructor<value_t::number_unsigned>
  2994. {
  2995. template<typename BasicJsonType>
  2996. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  2997. {
  2998. j.m_type = value_t::number_unsigned;
  2999. j.m_value = val;
  3000. j.assert_invariant();
  3001. }
  3002. };
  3003. template<>
  3004. struct external_constructor<value_t::number_integer>
  3005. {
  3006. template<typename BasicJsonType>
  3007. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  3008. {
  3009. j.m_type = value_t::number_integer;
  3010. j.m_value = val;
  3011. j.assert_invariant();
  3012. }
  3013. };
  3014. template<>
  3015. struct external_constructor<value_t::array>
  3016. {
  3017. template<typename BasicJsonType>
  3018. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  3019. {
  3020. j.m_type = value_t::array;
  3021. j.m_value = arr;
  3022. j.assert_invariant();
  3023. }
  3024. template<typename BasicJsonType>
  3025. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3026. {
  3027. j.m_type = value_t::array;
  3028. j.m_value = std::move(arr);
  3029. j.assert_invariant();
  3030. }
  3031. template<typename BasicJsonType, typename CompatibleArrayType,
  3032. enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  3033. int> = 0>
  3034. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  3035. {
  3036. using std::begin;
  3037. using std::end;
  3038. j.m_type = value_t::array;
  3039. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  3040. j.assert_invariant();
  3041. }
  3042. template<typename BasicJsonType>
  3043. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  3044. {
  3045. j.m_type = value_t::array;
  3046. j.m_value = value_t::array;
  3047. j.m_value.array->reserve(arr.size());
  3048. for (const bool x : arr)
  3049. {
  3050. j.m_value.array->push_back(x);
  3051. }
  3052. j.assert_invariant();
  3053. }
  3054. template<typename BasicJsonType, typename T,
  3055. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3056. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  3057. {
  3058. j.m_type = value_t::array;
  3059. j.m_value = value_t::array;
  3060. j.m_value.array->resize(arr.size());
  3061. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  3062. j.assert_invariant();
  3063. }
  3064. };
  3065. template<>
  3066. struct external_constructor<value_t::object>
  3067. {
  3068. template<typename BasicJsonType>
  3069. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  3070. {
  3071. j.m_type = value_t::object;
  3072. j.m_value = obj;
  3073. j.assert_invariant();
  3074. }
  3075. template<typename BasicJsonType>
  3076. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3077. {
  3078. j.m_type = value_t::object;
  3079. j.m_value = std::move(obj);
  3080. j.assert_invariant();
  3081. }
  3082. template<typename BasicJsonType, typename CompatibleObjectType,
  3083. enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
  3084. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  3085. {
  3086. using std::begin;
  3087. using std::end;
  3088. j.m_type = value_t::object;
  3089. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  3090. j.assert_invariant();
  3091. }
  3092. };
  3093. /////////////
  3094. // to_json //
  3095. /////////////
  3096. template<typename BasicJsonType, typename T,
  3097. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  3098. void to_json(BasicJsonType& j, T b) noexcept
  3099. {
  3100. external_constructor<value_t::boolean>::construct(j, b);
  3101. }
  3102. template<typename BasicJsonType, typename CompatibleString,
  3103. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  3104. void to_json(BasicJsonType& j, const CompatibleString& s)
  3105. {
  3106. external_constructor<value_t::string>::construct(j, s);
  3107. }
  3108. template<typename BasicJsonType>
  3109. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3110. {
  3111. external_constructor<value_t::string>::construct(j, std::move(s));
  3112. }
  3113. template<typename BasicJsonType, typename FloatType,
  3114. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  3115. void to_json(BasicJsonType& j, FloatType val) noexcept
  3116. {
  3117. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  3118. }
  3119. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  3120. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  3121. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  3122. {
  3123. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  3124. }
  3125. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  3126. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  3127. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  3128. {
  3129. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  3130. }
  3131. template<typename BasicJsonType, typename EnumType,
  3132. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3133. void to_json(BasicJsonType& j, EnumType e) noexcept
  3134. {
  3135. using underlying_type = typename std::underlying_type<EnumType>::type;
  3136. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  3137. }
  3138. template<typename BasicJsonType>
  3139. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  3140. {
  3141. external_constructor<value_t::array>::construct(j, e);
  3142. }
  3143. template <typename BasicJsonType, typename CompatibleArrayType,
  3144. enable_if_t<is_compatible_array_type<BasicJsonType,
  3145. CompatibleArrayType>::value and
  3146. not is_compatible_object_type<
  3147. BasicJsonType, CompatibleArrayType>::value and
  3148. not is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value and
  3149. not is_basic_json<CompatibleArrayType>::value,
  3150. int> = 0>
  3151. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  3152. {
  3153. external_constructor<value_t::array>::construct(j, arr);
  3154. }
  3155. template<typename BasicJsonType, typename T,
  3156. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3157. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  3158. {
  3159. external_constructor<value_t::array>::construct(j, std::move(arr));
  3160. }
  3161. template<typename BasicJsonType>
  3162. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3163. {
  3164. external_constructor<value_t::array>::construct(j, std::move(arr));
  3165. }
  3166. template<typename BasicJsonType, typename CompatibleObjectType,
  3167. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value and not is_basic_json<CompatibleObjectType>::value, int> = 0>
  3168. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  3169. {
  3170. external_constructor<value_t::object>::construct(j, obj);
  3171. }
  3172. template<typename BasicJsonType>
  3173. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3174. {
  3175. external_constructor<value_t::object>::construct(j, std::move(obj));
  3176. }
  3177. template <
  3178. typename BasicJsonType, typename T, std::size_t N,
  3179. enable_if_t<not std::is_constructible<typename BasicJsonType::string_t,
  3180. const T(&)[N]>::value,
  3181. int> = 0 >
  3182. void to_json(BasicJsonType& j, const T(&arr)[N])
  3183. {
  3184. external_constructor<value_t::array>::construct(j, arr);
  3185. }
  3186. template<typename BasicJsonType, typename... Args>
  3187. void to_json(BasicJsonType& j, const std::pair<Args...>& p)
  3188. {
  3189. j = { p.first, p.second };
  3190. }
  3191. // for https://github.com/nlohmann/json/pull/1134
  3192. template < typename BasicJsonType, typename T,
  3193. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  3194. void to_json(BasicJsonType& j, const T& b)
  3195. {
  3196. j = { {b.key(), b.value()} };
  3197. }
  3198. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  3199. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  3200. {
  3201. j = { std::get<Idx>(t)... };
  3202. }
  3203. template<typename BasicJsonType, typename... Args>
  3204. void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
  3205. {
  3206. to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  3207. }
  3208. struct to_json_fn
  3209. {
  3210. template<typename BasicJsonType, typename T>
  3211. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  3212. -> decltype(to_json(j, std::forward<T>(val)), void())
  3213. {
  3214. return to_json(j, std::forward<T>(val));
  3215. }
  3216. };
  3217. } // namespace detail
  3218. /// namespace to hold default `to_json` function
  3219. namespace
  3220. {
  3221. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  3222. } // namespace
  3223. } // namespace nlohmann
  3224. namespace nlohmann
  3225. {
  3226. template<typename, typename>
  3227. struct adl_serializer
  3228. {
  3229. /*!
  3230. @brief convert a JSON value to any value type
  3231. This function is usually called by the `get()` function of the
  3232. @ref basic_json class (either explicit or via conversion operators).
  3233. @param[in] j JSON value to read from
  3234. @param[in,out] val value to write to
  3235. */
  3236. template<typename BasicJsonType, typename ValueType>
  3237. static auto from_json(BasicJsonType&& j, ValueType& val) noexcept(
  3238. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  3239. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  3240. {
  3241. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  3242. }
  3243. /*!
  3244. @brief convert any value type to a JSON value
  3245. This function is usually called by the constructors of the @ref basic_json
  3246. class.
  3247. @param[in,out] j JSON value to write to
  3248. @param[in] val value to read from
  3249. */
  3250. template <typename BasicJsonType, typename ValueType>
  3251. static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
  3252. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  3253. -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
  3254. {
  3255. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  3256. }
  3257. };
  3258. } // namespace nlohmann
  3259. // #include <nlohmann/detail/conversions/from_json.hpp>
  3260. // #include <nlohmann/detail/conversions/to_json.hpp>
  3261. // #include <nlohmann/detail/exceptions.hpp>
  3262. // #include <nlohmann/detail/input/binary_reader.hpp>
  3263. #include <algorithm> // generate_n
  3264. #include <array> // array
  3265. #include <cassert> // assert
  3266. #include <cmath> // ldexp
  3267. #include <cstddef> // size_t
  3268. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  3269. #include <cstdio> // snprintf
  3270. #include <cstring> // memcpy
  3271. #include <iterator> // back_inserter
  3272. #include <limits> // numeric_limits
  3273. #include <string> // char_traits, string
  3274. #include <utility> // make_pair, move
  3275. // #include <nlohmann/detail/exceptions.hpp>
  3276. // #include <nlohmann/detail/input/input_adapters.hpp>
  3277. #include <array> // array
  3278. #include <cassert> // assert
  3279. #include <cstddef> // size_t
  3280. #include <cstdio> //FILE *
  3281. #include <cstring> // strlen
  3282. #include <istream> // istream
  3283. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  3284. #include <memory> // shared_ptr, make_shared, addressof
  3285. #include <numeric> // accumulate
  3286. #include <string> // string, char_traits
  3287. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  3288. #include <utility> // pair, declval
  3289. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  3290. // #include <nlohmann/detail/macro_scope.hpp>
  3291. namespace nlohmann
  3292. {
  3293. namespace detail
  3294. {
  3295. /// the supported input formats
  3296. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  3297. ////////////////////
  3298. // input adapters //
  3299. ////////////////////
  3300. /*!
  3301. @brief abstract input adapter interface
  3302. Produces a stream of std::char_traits<char>::int_type characters from a
  3303. std::istream, a buffer, or some other input type. Accepts the return of
  3304. exactly one non-EOF character for future input. The int_type characters
  3305. returned consist of all valid char values as positive values (typically
  3306. unsigned char), plus an EOF value outside that range, specified by the value
  3307. of the function std::char_traits<char>::eof(). This value is typically -1, but
  3308. could be any arbitrary value which is not a valid char value.
  3309. */
  3310. struct input_adapter_protocol
  3311. {
  3312. /// get a character [0,255] or std::char_traits<char>::eof().
  3313. virtual std::char_traits<char>::int_type get_character() = 0;
  3314. virtual ~input_adapter_protocol() = default;
  3315. };
  3316. /// a type to simplify interfaces
  3317. using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
  3318. /*!
  3319. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  3320. buffer. This adapter is a very low level adapter.
  3321. */
  3322. class file_input_adapter : public input_adapter_protocol
  3323. {
  3324. public:
  3325. JSON_HEDLEY_NON_NULL(2)
  3326. explicit file_input_adapter(std::FILE* f) noexcept
  3327. : m_file(f)
  3328. {}
  3329. // make class move-only
  3330. file_input_adapter(const file_input_adapter&) = delete;
  3331. file_input_adapter(file_input_adapter&&) = default;
  3332. file_input_adapter& operator=(const file_input_adapter&) = delete;
  3333. file_input_adapter& operator=(file_input_adapter&&) = default;
  3334. ~file_input_adapter() override = default;
  3335. std::char_traits<char>::int_type get_character() noexcept override
  3336. {
  3337. return std::fgetc(m_file);
  3338. }
  3339. private:
  3340. /// the file pointer to read from
  3341. std::FILE* m_file;
  3342. };
  3343. /*!
  3344. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  3345. beginning of input. Does not support changing the underlying std::streambuf
  3346. in mid-input. Maintains underlying std::istream and std::streambuf to support
  3347. subsequent use of standard std::istream operations to process any input
  3348. characters following those used in parsing the JSON input. Clears the
  3349. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  3350. subsequent call for input from the std::istream.
  3351. */
  3352. class input_stream_adapter : public input_adapter_protocol
  3353. {
  3354. public:
  3355. ~input_stream_adapter() override
  3356. {
  3357. // clear stream flags; we use underlying streambuf I/O, do not
  3358. // maintain ifstream flags, except eof
  3359. is.clear(is.rdstate() & std::ios::eofbit);
  3360. }
  3361. explicit input_stream_adapter(std::istream& i)
  3362. : is(i), sb(*i.rdbuf())
  3363. {}
  3364. // delete because of pointer members
  3365. input_stream_adapter(const input_stream_adapter&) = delete;
  3366. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  3367. input_stream_adapter(input_stream_adapter&&) = delete;
  3368. input_stream_adapter& operator=(input_stream_adapter&&) = delete;
  3369. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  3370. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  3371. // end up as the same value, eg. 0xFFFFFFFF.
  3372. std::char_traits<char>::int_type get_character() override
  3373. {
  3374. auto res = sb.sbumpc();
  3375. // set eof manually, as we don't use the istream interface.
  3376. if (res == EOF)
  3377. {
  3378. is.clear(is.rdstate() | std::ios::eofbit);
  3379. }
  3380. return res;
  3381. }
  3382. private:
  3383. /// the associated input stream
  3384. std::istream& is;
  3385. std::streambuf& sb;
  3386. };
  3387. /// input adapter for buffer input
  3388. class input_buffer_adapter : public input_adapter_protocol
  3389. {
  3390. public:
  3391. JSON_HEDLEY_NON_NULL(2)
  3392. input_buffer_adapter(const char* b, const std::size_t l) noexcept
  3393. : cursor(b), limit(b + l)
  3394. {}
  3395. // delete because of pointer members
  3396. input_buffer_adapter(const input_buffer_adapter&) = delete;
  3397. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  3398. input_buffer_adapter(input_buffer_adapter&&) = delete;
  3399. input_buffer_adapter& operator=(input_buffer_adapter&&) = delete;
  3400. ~input_buffer_adapter() override = default;
  3401. std::char_traits<char>::int_type get_character() noexcept override
  3402. {
  3403. if (JSON_HEDLEY_LIKELY(cursor < limit))
  3404. {
  3405. return std::char_traits<char>::to_int_type(*(cursor++));
  3406. }
  3407. return std::char_traits<char>::eof();
  3408. }
  3409. private:
  3410. /// pointer to the current character
  3411. const char* cursor;
  3412. /// pointer past the last character
  3413. const char* const limit;
  3414. };
  3415. template<typename WideStringType, size_t T>
  3416. struct wide_string_input_helper
  3417. {
  3418. // UTF-32
  3419. static void fill_buffer(const WideStringType& str,
  3420. size_t& current_wchar,
  3421. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  3422. size_t& utf8_bytes_index,
  3423. size_t& utf8_bytes_filled)
  3424. {
  3425. utf8_bytes_index = 0;
  3426. if (current_wchar == str.size())
  3427. {
  3428. utf8_bytes[0] = std::char_traits<char>::eof();
  3429. utf8_bytes_filled = 1;
  3430. }
  3431. else
  3432. {
  3433. // get the current character
  3434. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  3435. // UTF-32 to UTF-8 encoding
  3436. if (wc < 0x80)
  3437. {
  3438. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3439. utf8_bytes_filled = 1;
  3440. }
  3441. else if (wc <= 0x7FF)
  3442. {
  3443. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u) & 0x1Fu));
  3444. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3445. utf8_bytes_filled = 2;
  3446. }
  3447. else if (wc <= 0xFFFF)
  3448. {
  3449. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u) & 0x0Fu));
  3450. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3451. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3452. utf8_bytes_filled = 3;
  3453. }
  3454. else if (wc <= 0x10FFFF)
  3455. {
  3456. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((wc >> 18u) & 0x07u));
  3457. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 12u) & 0x3Fu));
  3458. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3459. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3460. utf8_bytes_filled = 4;
  3461. }
  3462. else
  3463. {
  3464. // unknown character
  3465. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3466. utf8_bytes_filled = 1;
  3467. }
  3468. }
  3469. }
  3470. };
  3471. template<typename WideStringType>
  3472. struct wide_string_input_helper<WideStringType, 2>
  3473. {
  3474. // UTF-16
  3475. static void fill_buffer(const WideStringType& str,
  3476. size_t& current_wchar,
  3477. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  3478. size_t& utf8_bytes_index,
  3479. size_t& utf8_bytes_filled)
  3480. {
  3481. utf8_bytes_index = 0;
  3482. if (current_wchar == str.size())
  3483. {
  3484. utf8_bytes[0] = std::char_traits<char>::eof();
  3485. utf8_bytes_filled = 1;
  3486. }
  3487. else
  3488. {
  3489. // get the current character
  3490. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  3491. // UTF-16 to UTF-8 encoding
  3492. if (wc < 0x80)
  3493. {
  3494. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3495. utf8_bytes_filled = 1;
  3496. }
  3497. else if (wc <= 0x7FF)
  3498. {
  3499. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u)));
  3500. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3501. utf8_bytes_filled = 2;
  3502. }
  3503. else if (0xD800 > wc or wc >= 0xE000)
  3504. {
  3505. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u)));
  3506. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3507. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3508. utf8_bytes_filled = 3;
  3509. }
  3510. else
  3511. {
  3512. if (current_wchar < str.size())
  3513. {
  3514. const auto wc2 = static_cast<unsigned int>(str[current_wchar++]);
  3515. const auto charcode = 0x10000u + (((wc & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  3516. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  3517. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  3518. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  3519. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  3520. utf8_bytes_filled = 4;
  3521. }
  3522. else
  3523. {
  3524. // unknown character
  3525. ++current_wchar;
  3526. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3527. utf8_bytes_filled = 1;
  3528. }
  3529. }
  3530. }
  3531. }
  3532. };
  3533. template<typename WideStringType>
  3534. class wide_string_input_adapter : public input_adapter_protocol
  3535. {
  3536. public:
  3537. explicit wide_string_input_adapter(const WideStringType& w) noexcept
  3538. : str(w)
  3539. {}
  3540. std::char_traits<char>::int_type get_character() noexcept override
  3541. {
  3542. // check if buffer needs to be filled
  3543. if (utf8_bytes_index == utf8_bytes_filled)
  3544. {
  3545. fill_buffer<sizeof(typename WideStringType::value_type)>();
  3546. assert(utf8_bytes_filled > 0);
  3547. assert(utf8_bytes_index == 0);
  3548. }
  3549. // use buffer
  3550. assert(utf8_bytes_filled > 0);
  3551. assert(utf8_bytes_index < utf8_bytes_filled);
  3552. return utf8_bytes[utf8_bytes_index++];
  3553. }
  3554. private:
  3555. template<size_t T>
  3556. void fill_buffer()
  3557. {
  3558. wide_string_input_helper<WideStringType, T>::fill_buffer(str, current_wchar, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  3559. }
  3560. /// the wstring to process
  3561. const WideStringType& str;
  3562. /// index of the current wchar in str
  3563. std::size_t current_wchar = 0;
  3564. /// a buffer for UTF-8 bytes
  3565. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  3566. /// index to the utf8_codes array for the next valid byte
  3567. std::size_t utf8_bytes_index = 0;
  3568. /// number of valid bytes in the utf8_codes array
  3569. std::size_t utf8_bytes_filled = 0;
  3570. };
  3571. class input_adapter
  3572. {
  3573. public:
  3574. // native support
  3575. JSON_HEDLEY_NON_NULL(2)
  3576. input_adapter(std::FILE* file)
  3577. : ia(std::make_shared<file_input_adapter>(file)) {}
  3578. /// input adapter for input stream
  3579. input_adapter(std::istream& i)
  3580. : ia(std::make_shared<input_stream_adapter>(i)) {}
  3581. /// input adapter for input stream
  3582. input_adapter(std::istream&& i)
  3583. : ia(std::make_shared<input_stream_adapter>(i)) {}
  3584. input_adapter(const std::wstring& ws)
  3585. : ia(std::make_shared<wide_string_input_adapter<std::wstring>>(ws)) {}
  3586. input_adapter(const std::u16string& ws)
  3587. : ia(std::make_shared<wide_string_input_adapter<std::u16string>>(ws)) {}
  3588. input_adapter(const std::u32string& ws)
  3589. : ia(std::make_shared<wide_string_input_adapter<std::u32string>>(ws)) {}
  3590. /// input adapter for buffer
  3591. template<typename CharT,
  3592. typename std::enable_if<
  3593. std::is_pointer<CharT>::value and
  3594. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  3595. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  3596. int>::type = 0>
  3597. input_adapter(CharT b, std::size_t l)
  3598. : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
  3599. // derived support
  3600. /// input adapter for string literal
  3601. template<typename CharT,
  3602. typename std::enable_if<
  3603. std::is_pointer<CharT>::value and
  3604. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  3605. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  3606. int>::type = 0>
  3607. input_adapter(CharT b)
  3608. : input_adapter(reinterpret_cast<const char*>(b),
  3609. std::strlen(reinterpret_cast<const char*>(b))) {}
  3610. /// input adapter for iterator range with contiguous storage
  3611. template<class IteratorType,
  3612. typename std::enable_if<
  3613. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  3614. int>::type = 0>
  3615. input_adapter(IteratorType first, IteratorType last)
  3616. {
  3617. #ifndef NDEBUG
  3618. // assertion to check that the iterator range is indeed contiguous,
  3619. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  3620. const auto is_contiguous = std::accumulate(
  3621. first, last, std::pair<bool, int>(true, 0),
  3622. [&first](std::pair<bool, int> res, decltype(*first) val)
  3623. {
  3624. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  3625. return res;
  3626. }).first;
  3627. assert(is_contiguous);
  3628. #endif
  3629. // assertion to check that each element is 1 byte long
  3630. static_assert(
  3631. sizeof(typename iterator_traits<IteratorType>::value_type) == 1,
  3632. "each element in the iterator range must have the size of 1 byte");
  3633. const auto len = static_cast<size_t>(std::distance(first, last));
  3634. if (JSON_HEDLEY_LIKELY(len > 0))
  3635. {
  3636. // there is at least one element: use the address of first
  3637. ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
  3638. }
  3639. else
  3640. {
  3641. // the address of first cannot be used: use nullptr
  3642. ia = std::make_shared<input_buffer_adapter>(nullptr, len);
  3643. }
  3644. }
  3645. /// input adapter for array
  3646. template<class T, std::size_t N>
  3647. input_adapter(T (&array)[N])
  3648. : input_adapter(std::begin(array), std::end(array)) {}
  3649. /// input adapter for contiguous container
  3650. template<class ContiguousContainer, typename
  3651. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  3652. std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  3653. int>::type = 0>
  3654. input_adapter(const ContiguousContainer& c)
  3655. : input_adapter(std::begin(c), std::end(c)) {}
  3656. operator input_adapter_t()
  3657. {
  3658. return ia;
  3659. }
  3660. private:
  3661. /// the actual adapter
  3662. input_adapter_t ia = nullptr;
  3663. };
  3664. } // namespace detail
  3665. } // namespace nlohmann
  3666. // #include <nlohmann/detail/input/json_sax.hpp>
  3667. #include <cassert> // assert
  3668. #include <cstddef>
  3669. #include <string> // string
  3670. #include <utility> // move
  3671. #include <vector> // vector
  3672. // #include <nlohmann/detail/exceptions.hpp>
  3673. // #include <nlohmann/detail/macro_scope.hpp>
  3674. namespace nlohmann
  3675. {
  3676. /*!
  3677. @brief SAX interface
  3678. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  3679. Each function is called in different situations while the input is parsed. The
  3680. boolean return value informs the parser whether to continue processing the
  3681. input.
  3682. */
  3683. template<typename BasicJsonType>
  3684. struct json_sax
  3685. {
  3686. /// type for (signed) integers
  3687. using number_integer_t = typename BasicJsonType::number_integer_t;
  3688. /// type for unsigned integers
  3689. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3690. /// type for floating-point numbers
  3691. using number_float_t = typename BasicJsonType::number_float_t;
  3692. /// type for strings
  3693. using string_t = typename BasicJsonType::string_t;
  3694. /*!
  3695. @brief a null value was read
  3696. @return whether parsing should proceed
  3697. */
  3698. virtual bool null() = 0;
  3699. /*!
  3700. @brief a boolean value was read
  3701. @param[in] val boolean value
  3702. @return whether parsing should proceed
  3703. */
  3704. virtual bool boolean(bool val) = 0;
  3705. /*!
  3706. @brief an integer number was read
  3707. @param[in] val integer value
  3708. @return whether parsing should proceed
  3709. */
  3710. virtual bool number_integer(number_integer_t val) = 0;
  3711. /*!
  3712. @brief an unsigned integer number was read
  3713. @param[in] val unsigned integer value
  3714. @return whether parsing should proceed
  3715. */
  3716. virtual bool number_unsigned(number_unsigned_t val) = 0;
  3717. /*!
  3718. @brief an floating-point number was read
  3719. @param[in] val floating-point value
  3720. @param[in] s raw token value
  3721. @return whether parsing should proceed
  3722. */
  3723. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  3724. /*!
  3725. @brief a string was read
  3726. @param[in] val string value
  3727. @return whether parsing should proceed
  3728. @note It is safe to move the passed string.
  3729. */
  3730. virtual bool string(string_t& val) = 0;
  3731. /*!
  3732. @brief the beginning of an object was read
  3733. @param[in] elements number of object elements or -1 if unknown
  3734. @return whether parsing should proceed
  3735. @note binary formats may report the number of elements
  3736. */
  3737. virtual bool start_object(std::size_t elements) = 0;
  3738. /*!
  3739. @brief an object key was read
  3740. @param[in] val object key
  3741. @return whether parsing should proceed
  3742. @note It is safe to move the passed string.
  3743. */
  3744. virtual bool key(string_t& val) = 0;
  3745. /*!
  3746. @brief the end of an object was read
  3747. @return whether parsing should proceed
  3748. */
  3749. virtual bool end_object() = 0;
  3750. /*!
  3751. @brief the beginning of an array was read
  3752. @param[in] elements number of array elements or -1 if unknown
  3753. @return whether parsing should proceed
  3754. @note binary formats may report the number of elements
  3755. */
  3756. virtual bool start_array(std::size_t elements) = 0;
  3757. /*!
  3758. @brief the end of an array was read
  3759. @return whether parsing should proceed
  3760. */
  3761. virtual bool end_array() = 0;
  3762. /*!
  3763. @brief a parse error occurred
  3764. @param[in] position the position in the input where the error occurs
  3765. @param[in] last_token the last read token
  3766. @param[in] ex an exception object describing the error
  3767. @return whether parsing should proceed (must return false)
  3768. */
  3769. virtual bool parse_error(std::size_t position,
  3770. const std::string& last_token,
  3771. const detail::exception& ex) = 0;
  3772. virtual ~json_sax() = default;
  3773. };
  3774. namespace detail
  3775. {
  3776. /*!
  3777. @brief SAX implementation to create a JSON value from SAX events
  3778. This class implements the @ref json_sax interface and processes the SAX events
  3779. to create a JSON value which makes it basically a DOM parser. The structure or
  3780. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  3781. a pointer to the respective array or object for each recursion depth.
  3782. After successful parsing, the value that is passed by reference to the
  3783. constructor contains the parsed value.
  3784. @tparam BasicJsonType the JSON type
  3785. */
  3786. template<typename BasicJsonType>
  3787. class json_sax_dom_parser
  3788. {
  3789. public:
  3790. using number_integer_t = typename BasicJsonType::number_integer_t;
  3791. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3792. using number_float_t = typename BasicJsonType::number_float_t;
  3793. using string_t = typename BasicJsonType::string_t;
  3794. /*!
  3795. @param[in, out] r reference to a JSON value that is manipulated while
  3796. parsing
  3797. @param[in] allow_exceptions_ whether parse errors yield exceptions
  3798. */
  3799. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  3800. : root(r), allow_exceptions(allow_exceptions_)
  3801. {}
  3802. // make class move-only
  3803. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  3804. json_sax_dom_parser(json_sax_dom_parser&&) = default;
  3805. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  3806. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default;
  3807. ~json_sax_dom_parser() = default;
  3808. bool null()
  3809. {
  3810. handle_value(nullptr);
  3811. return true;
  3812. }
  3813. bool boolean(bool val)
  3814. {
  3815. handle_value(val);
  3816. return true;
  3817. }
  3818. bool number_integer(number_integer_t val)
  3819. {
  3820. handle_value(val);
  3821. return true;
  3822. }
  3823. bool number_unsigned(number_unsigned_t val)
  3824. {
  3825. handle_value(val);
  3826. return true;
  3827. }
  3828. bool number_float(number_float_t val, const string_t& /*unused*/)
  3829. {
  3830. handle_value(val);
  3831. return true;
  3832. }
  3833. bool string(string_t& val)
  3834. {
  3835. handle_value(val);
  3836. return true;
  3837. }
  3838. bool start_object(std::size_t len)
  3839. {
  3840. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  3841. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3842. {
  3843. JSON_THROW(out_of_range::create(408,
  3844. "excessive object size: " + std::to_string(len)));
  3845. }
  3846. return true;
  3847. }
  3848. bool key(string_t& val)
  3849. {
  3850. // add null at given key and store the reference for later
  3851. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  3852. return true;
  3853. }
  3854. bool end_object()
  3855. {
  3856. ref_stack.pop_back();
  3857. return true;
  3858. }
  3859. bool start_array(std::size_t len)
  3860. {
  3861. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  3862. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3863. {
  3864. JSON_THROW(out_of_range::create(408,
  3865. "excessive array size: " + std::to_string(len)));
  3866. }
  3867. return true;
  3868. }
  3869. bool end_array()
  3870. {
  3871. ref_stack.pop_back();
  3872. return true;
  3873. }
  3874. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  3875. const detail::exception& ex)
  3876. {
  3877. errored = true;
  3878. if (allow_exceptions)
  3879. {
  3880. // determine the proper exception type from the id
  3881. switch ((ex.id / 100) % 100)
  3882. {
  3883. case 1:
  3884. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  3885. case 4:
  3886. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  3887. // LCOV_EXCL_START
  3888. case 2:
  3889. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  3890. case 3:
  3891. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  3892. case 5:
  3893. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  3894. default:
  3895. assert(false);
  3896. // LCOV_EXCL_STOP
  3897. }
  3898. }
  3899. return false;
  3900. }
  3901. constexpr bool is_errored() const
  3902. {
  3903. return errored;
  3904. }
  3905. private:
  3906. /*!
  3907. @invariant If the ref stack is empty, then the passed value will be the new
  3908. root.
  3909. @invariant If the ref stack contains a value, then it is an array or an
  3910. object to which we can add elements
  3911. */
  3912. template<typename Value>
  3913. JSON_HEDLEY_RETURNS_NON_NULL
  3914. BasicJsonType* handle_value(Value&& v)
  3915. {
  3916. if (ref_stack.empty())
  3917. {
  3918. root = BasicJsonType(std::forward<Value>(v));
  3919. return &root;
  3920. }
  3921. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  3922. if (ref_stack.back()->is_array())
  3923. {
  3924. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  3925. return &(ref_stack.back()->m_value.array->back());
  3926. }
  3927. assert(ref_stack.back()->is_object());
  3928. assert(object_element);
  3929. *object_element = BasicJsonType(std::forward<Value>(v));
  3930. return object_element;
  3931. }
  3932. /// the parsed JSON value
  3933. BasicJsonType& root;
  3934. /// stack to model hierarchy of values
  3935. std::vector<BasicJsonType*> ref_stack {};
  3936. /// helper to hold the reference for the next object element
  3937. BasicJsonType* object_element = nullptr;
  3938. /// whether a syntax error occurred
  3939. bool errored = false;
  3940. /// whether to throw exceptions in case of errors
  3941. const bool allow_exceptions = true;
  3942. };
  3943. template<typename BasicJsonType>
  3944. class json_sax_dom_callback_parser
  3945. {
  3946. public:
  3947. using number_integer_t = typename BasicJsonType::number_integer_t;
  3948. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3949. using number_float_t = typename BasicJsonType::number_float_t;
  3950. using string_t = typename BasicJsonType::string_t;
  3951. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  3952. using parse_event_t = typename BasicJsonType::parse_event_t;
  3953. json_sax_dom_callback_parser(BasicJsonType& r,
  3954. const parser_callback_t cb,
  3955. const bool allow_exceptions_ = true)
  3956. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  3957. {
  3958. keep_stack.push_back(true);
  3959. }
  3960. // make class move-only
  3961. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  3962. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default;
  3963. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  3964. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default;
  3965. ~json_sax_dom_callback_parser() = default;
  3966. bool null()
  3967. {
  3968. handle_value(nullptr);
  3969. return true;
  3970. }
  3971. bool boolean(bool val)
  3972. {
  3973. handle_value(val);
  3974. return true;
  3975. }
  3976. bool number_integer(number_integer_t val)
  3977. {
  3978. handle_value(val);
  3979. return true;
  3980. }
  3981. bool number_unsigned(number_unsigned_t val)
  3982. {
  3983. handle_value(val);
  3984. return true;
  3985. }
  3986. bool number_float(number_float_t val, const string_t& /*unused*/)
  3987. {
  3988. handle_value(val);
  3989. return true;
  3990. }
  3991. bool string(string_t& val)
  3992. {
  3993. handle_value(val);
  3994. return true;
  3995. }
  3996. bool start_object(std::size_t len)
  3997. {
  3998. // check callback for object start
  3999. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  4000. keep_stack.push_back(keep);
  4001. auto val = handle_value(BasicJsonType::value_t::object, true);
  4002. ref_stack.push_back(val.second);
  4003. // check object limit
  4004. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4005. {
  4006. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len)));
  4007. }
  4008. return true;
  4009. }
  4010. bool key(string_t& val)
  4011. {
  4012. BasicJsonType k = BasicJsonType(val);
  4013. // check callback for key
  4014. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  4015. key_keep_stack.push_back(keep);
  4016. // add discarded value at given key and store the reference for later
  4017. if (keep and ref_stack.back())
  4018. {
  4019. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  4020. }
  4021. return true;
  4022. }
  4023. bool end_object()
  4024. {
  4025. if (ref_stack.back() and not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  4026. {
  4027. // discard object
  4028. *ref_stack.back() = discarded;
  4029. }
  4030. assert(not ref_stack.empty());
  4031. assert(not keep_stack.empty());
  4032. ref_stack.pop_back();
  4033. keep_stack.pop_back();
  4034. if (not ref_stack.empty() and ref_stack.back() and ref_stack.back()->is_object())
  4035. {
  4036. // remove discarded value
  4037. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  4038. {
  4039. if (it->is_discarded())
  4040. {
  4041. ref_stack.back()->erase(it);
  4042. break;
  4043. }
  4044. }
  4045. }
  4046. return true;
  4047. }
  4048. bool start_array(std::size_t len)
  4049. {
  4050. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  4051. keep_stack.push_back(keep);
  4052. auto val = handle_value(BasicJsonType::value_t::array, true);
  4053. ref_stack.push_back(val.second);
  4054. // check array limit
  4055. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4056. {
  4057. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len)));
  4058. }
  4059. return true;
  4060. }
  4061. bool end_array()
  4062. {
  4063. bool keep = true;
  4064. if (ref_stack.back())
  4065. {
  4066. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  4067. if (not keep)
  4068. {
  4069. // discard array
  4070. *ref_stack.back() = discarded;
  4071. }
  4072. }
  4073. assert(not ref_stack.empty());
  4074. assert(not keep_stack.empty());
  4075. ref_stack.pop_back();
  4076. keep_stack.pop_back();
  4077. // remove discarded value
  4078. if (not keep and not ref_stack.empty() and ref_stack.back()->is_array())
  4079. {
  4080. ref_stack.back()->m_value.array->pop_back();
  4081. }
  4082. return true;
  4083. }
  4084. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4085. const detail::exception& ex)
  4086. {
  4087. errored = true;
  4088. if (allow_exceptions)
  4089. {
  4090. // determine the proper exception type from the id
  4091. switch ((ex.id / 100) % 100)
  4092. {
  4093. case 1:
  4094. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  4095. case 4:
  4096. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  4097. // LCOV_EXCL_START
  4098. case 2:
  4099. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  4100. case 3:
  4101. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  4102. case 5:
  4103. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  4104. default:
  4105. assert(false);
  4106. // LCOV_EXCL_STOP
  4107. }
  4108. }
  4109. return false;
  4110. }
  4111. constexpr bool is_errored() const
  4112. {
  4113. return errored;
  4114. }
  4115. private:
  4116. /*!
  4117. @param[in] v value to add to the JSON value we build during parsing
  4118. @param[in] skip_callback whether we should skip calling the callback
  4119. function; this is required after start_array() and
  4120. start_object() SAX events, because otherwise we would call the
  4121. callback function with an empty array or object, respectively.
  4122. @invariant If the ref stack is empty, then the passed value will be the new
  4123. root.
  4124. @invariant If the ref stack contains a value, then it is an array or an
  4125. object to which we can add elements
  4126. @return pair of boolean (whether value should be kept) and pointer (to the
  4127. passed value in the ref_stack hierarchy; nullptr if not kept)
  4128. */
  4129. template<typename Value>
  4130. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  4131. {
  4132. assert(not keep_stack.empty());
  4133. // do not handle this value if we know it would be added to a discarded
  4134. // container
  4135. if (not keep_stack.back())
  4136. {
  4137. return {false, nullptr};
  4138. }
  4139. // create value
  4140. auto value = BasicJsonType(std::forward<Value>(v));
  4141. // check callback
  4142. const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  4143. // do not handle this value if we just learnt it shall be discarded
  4144. if (not keep)
  4145. {
  4146. return {false, nullptr};
  4147. }
  4148. if (ref_stack.empty())
  4149. {
  4150. root = std::move(value);
  4151. return {true, &root};
  4152. }
  4153. // skip this value if we already decided to skip the parent
  4154. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  4155. if (not ref_stack.back())
  4156. {
  4157. return {false, nullptr};
  4158. }
  4159. // we now only expect arrays and objects
  4160. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4161. // array
  4162. if (ref_stack.back()->is_array())
  4163. {
  4164. ref_stack.back()->m_value.array->push_back(std::move(value));
  4165. return {true, &(ref_stack.back()->m_value.array->back())};
  4166. }
  4167. // object
  4168. assert(ref_stack.back()->is_object());
  4169. // check if we should store an element for the current key
  4170. assert(not key_keep_stack.empty());
  4171. const bool store_element = key_keep_stack.back();
  4172. key_keep_stack.pop_back();
  4173. if (not store_element)
  4174. {
  4175. return {false, nullptr};
  4176. }
  4177. assert(object_element);
  4178. *object_element = std::move(value);
  4179. return {true, object_element};
  4180. }
  4181. /// the parsed JSON value
  4182. BasicJsonType& root;
  4183. /// stack to model hierarchy of values
  4184. std::vector<BasicJsonType*> ref_stack {};
  4185. /// stack to manage which values to keep
  4186. std::vector<bool> keep_stack {};
  4187. /// stack to manage which object keys to keep
  4188. std::vector<bool> key_keep_stack {};
  4189. /// helper to hold the reference for the next object element
  4190. BasicJsonType* object_element = nullptr;
  4191. /// whether a syntax error occurred
  4192. bool errored = false;
  4193. /// callback function
  4194. const parser_callback_t callback = nullptr;
  4195. /// whether to throw exceptions in case of errors
  4196. const bool allow_exceptions = true;
  4197. /// a discarded value for the callback
  4198. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  4199. };
  4200. template<typename BasicJsonType>
  4201. class json_sax_acceptor
  4202. {
  4203. public:
  4204. using number_integer_t = typename BasicJsonType::number_integer_t;
  4205. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4206. using number_float_t = typename BasicJsonType::number_float_t;
  4207. using string_t = typename BasicJsonType::string_t;
  4208. bool null()
  4209. {
  4210. return true;
  4211. }
  4212. bool boolean(bool /*unused*/)
  4213. {
  4214. return true;
  4215. }
  4216. bool number_integer(number_integer_t /*unused*/)
  4217. {
  4218. return true;
  4219. }
  4220. bool number_unsigned(number_unsigned_t /*unused*/)
  4221. {
  4222. return true;
  4223. }
  4224. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  4225. {
  4226. return true;
  4227. }
  4228. bool string(string_t& /*unused*/)
  4229. {
  4230. return true;
  4231. }
  4232. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  4233. {
  4234. return true;
  4235. }
  4236. bool key(string_t& /*unused*/)
  4237. {
  4238. return true;
  4239. }
  4240. bool end_object()
  4241. {
  4242. return true;
  4243. }
  4244. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  4245. {
  4246. return true;
  4247. }
  4248. bool end_array()
  4249. {
  4250. return true;
  4251. }
  4252. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  4253. {
  4254. return false;
  4255. }
  4256. };
  4257. } // namespace detail
  4258. } // namespace nlohmann
  4259. // #include <nlohmann/detail/macro_scope.hpp>
  4260. // #include <nlohmann/detail/meta/is_sax.hpp>
  4261. #include <cstdint> // size_t
  4262. #include <utility> // declval
  4263. #include <string> // string
  4264. // #include <nlohmann/detail/meta/detected.hpp>
  4265. // #include <nlohmann/detail/meta/type_traits.hpp>
  4266. namespace nlohmann
  4267. {
  4268. namespace detail
  4269. {
  4270. template <typename T>
  4271. using null_function_t = decltype(std::declval<T&>().null());
  4272. template <typename T>
  4273. using boolean_function_t =
  4274. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  4275. template <typename T, typename Integer>
  4276. using number_integer_function_t =
  4277. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  4278. template <typename T, typename Unsigned>
  4279. using number_unsigned_function_t =
  4280. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  4281. template <typename T, typename Float, typename String>
  4282. using number_float_function_t = decltype(std::declval<T&>().number_float(
  4283. std::declval<Float>(), std::declval<const String&>()));
  4284. template <typename T, typename String>
  4285. using string_function_t =
  4286. decltype(std::declval<T&>().string(std::declval<String&>()));
  4287. template <typename T>
  4288. using start_object_function_t =
  4289. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  4290. template <typename T, typename String>
  4291. using key_function_t =
  4292. decltype(std::declval<T&>().key(std::declval<String&>()));
  4293. template <typename T>
  4294. using end_object_function_t = decltype(std::declval<T&>().end_object());
  4295. template <typename T>
  4296. using start_array_function_t =
  4297. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  4298. template <typename T>
  4299. using end_array_function_t = decltype(std::declval<T&>().end_array());
  4300. template <typename T, typename Exception>
  4301. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  4302. std::declval<std::size_t>(), std::declval<const std::string&>(),
  4303. std::declval<const Exception&>()));
  4304. template <typename SAX, typename BasicJsonType>
  4305. struct is_sax
  4306. {
  4307. private:
  4308. static_assert(is_basic_json<BasicJsonType>::value,
  4309. "BasicJsonType must be of type basic_json<...>");
  4310. using number_integer_t = typename BasicJsonType::number_integer_t;
  4311. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4312. using number_float_t = typename BasicJsonType::number_float_t;
  4313. using string_t = typename BasicJsonType::string_t;
  4314. using exception_t = typename BasicJsonType::exception;
  4315. public:
  4316. static constexpr bool value =
  4317. is_detected_exact<bool, null_function_t, SAX>::value &&
  4318. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  4319. is_detected_exact<bool, number_integer_function_t, SAX,
  4320. number_integer_t>::value &&
  4321. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4322. number_unsigned_t>::value &&
  4323. is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
  4324. string_t>::value &&
  4325. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  4326. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  4327. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  4328. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  4329. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  4330. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  4331. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  4332. };
  4333. template <typename SAX, typename BasicJsonType>
  4334. struct is_sax_static_asserts
  4335. {
  4336. private:
  4337. static_assert(is_basic_json<BasicJsonType>::value,
  4338. "BasicJsonType must be of type basic_json<...>");
  4339. using number_integer_t = typename BasicJsonType::number_integer_t;
  4340. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4341. using number_float_t = typename BasicJsonType::number_float_t;
  4342. using string_t = typename BasicJsonType::string_t;
  4343. using exception_t = typename BasicJsonType::exception;
  4344. public:
  4345. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  4346. "Missing/invalid function: bool null()");
  4347. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4348. "Missing/invalid function: bool boolean(bool)");
  4349. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4350. "Missing/invalid function: bool boolean(bool)");
  4351. static_assert(
  4352. is_detected_exact<bool, number_integer_function_t, SAX,
  4353. number_integer_t>::value,
  4354. "Missing/invalid function: bool number_integer(number_integer_t)");
  4355. static_assert(
  4356. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4357. number_unsigned_t>::value,
  4358. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  4359. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  4360. number_float_t, string_t>::value,
  4361. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  4362. static_assert(
  4363. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  4364. "Missing/invalid function: bool string(string_t&)");
  4365. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  4366. "Missing/invalid function: bool start_object(std::size_t)");
  4367. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  4368. "Missing/invalid function: bool key(string_t&)");
  4369. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  4370. "Missing/invalid function: bool end_object()");
  4371. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  4372. "Missing/invalid function: bool start_array(std::size_t)");
  4373. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  4374. "Missing/invalid function: bool end_array()");
  4375. static_assert(
  4376. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  4377. "Missing/invalid function: bool parse_error(std::size_t, const "
  4378. "std::string&, const exception&)");
  4379. };
  4380. } // namespace detail
  4381. } // namespace nlohmann
  4382. // #include <nlohmann/detail/value_t.hpp>
  4383. namespace nlohmann
  4384. {
  4385. namespace detail
  4386. {
  4387. ///////////////////
  4388. // binary reader //
  4389. ///////////////////
  4390. /*!
  4391. @brief deserialization of CBOR, MessagePack, and UBJSON values
  4392. */
  4393. template<typename BasicJsonType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  4394. class binary_reader
  4395. {
  4396. using number_integer_t = typename BasicJsonType::number_integer_t;
  4397. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4398. using number_float_t = typename BasicJsonType::number_float_t;
  4399. using string_t = typename BasicJsonType::string_t;
  4400. using json_sax_t = SAX;
  4401. public:
  4402. /*!
  4403. @brief create a binary reader
  4404. @param[in] adapter input adapter to read from
  4405. */
  4406. explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
  4407. {
  4408. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  4409. assert(ia);
  4410. }
  4411. // make class move-only
  4412. binary_reader(const binary_reader&) = delete;
  4413. binary_reader(binary_reader&&) = default;
  4414. binary_reader& operator=(const binary_reader&) = delete;
  4415. binary_reader& operator=(binary_reader&&) = default;
  4416. ~binary_reader() = default;
  4417. /*!
  4418. @param[in] format the binary format to parse
  4419. @param[in] sax_ a SAX event processor
  4420. @param[in] strict whether to expect the input to be consumed completed
  4421. @return
  4422. */
  4423. JSON_HEDLEY_NON_NULL(3)
  4424. bool sax_parse(const input_format_t format,
  4425. json_sax_t* sax_,
  4426. const bool strict = true)
  4427. {
  4428. sax = sax_;
  4429. bool result = false;
  4430. switch (format)
  4431. {
  4432. case input_format_t::bson:
  4433. result = parse_bson_internal();
  4434. break;
  4435. case input_format_t::cbor:
  4436. result = parse_cbor_internal();
  4437. break;
  4438. case input_format_t::msgpack:
  4439. result = parse_msgpack_internal();
  4440. break;
  4441. case input_format_t::ubjson:
  4442. result = parse_ubjson_internal();
  4443. break;
  4444. default: // LCOV_EXCL_LINE
  4445. assert(false); // LCOV_EXCL_LINE
  4446. }
  4447. // strict mode: next byte must be EOF
  4448. if (result and strict)
  4449. {
  4450. if (format == input_format_t::ubjson)
  4451. {
  4452. get_ignore_noop();
  4453. }
  4454. else
  4455. {
  4456. get();
  4457. }
  4458. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char>::eof()))
  4459. {
  4460. return sax->parse_error(chars_read, get_token_string(),
  4461. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
  4462. }
  4463. }
  4464. return result;
  4465. }
  4466. /*!
  4467. @brief determine system byte order
  4468. @return true if and only if system's byte order is little endian
  4469. @note from http://stackoverflow.com/a/1001328/266378
  4470. */
  4471. static constexpr bool little_endianess(int num = 1) noexcept
  4472. {
  4473. return *reinterpret_cast<char*>(&num) == 1;
  4474. }
  4475. private:
  4476. //////////
  4477. // BSON //
  4478. //////////
  4479. /*!
  4480. @brief Reads in a BSON-object and passes it to the SAX-parser.
  4481. @return whether a valid BSON-value was passed to the SAX parser
  4482. */
  4483. bool parse_bson_internal()
  4484. {
  4485. std::int32_t document_size;
  4486. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  4487. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  4488. {
  4489. return false;
  4490. }
  4491. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/false)))
  4492. {
  4493. return false;
  4494. }
  4495. return sax->end_object();
  4496. }
  4497. /*!
  4498. @brief Parses a C-style string from the BSON input.
  4499. @param[in, out] result A reference to the string variable where the read
  4500. string is to be stored.
  4501. @return `true` if the \x00-byte indicating the end of the string was
  4502. encountered before the EOF; false` indicates an unexpected EOF.
  4503. */
  4504. bool get_bson_cstr(string_t& result)
  4505. {
  4506. auto out = std::back_inserter(result);
  4507. while (true)
  4508. {
  4509. get();
  4510. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "cstring")))
  4511. {
  4512. return false;
  4513. }
  4514. if (current == 0x00)
  4515. {
  4516. return true;
  4517. }
  4518. *out++ = static_cast<char>(current);
  4519. }
  4520. return true;
  4521. }
  4522. /*!
  4523. @brief Parses a zero-terminated string of length @a len from the BSON
  4524. input.
  4525. @param[in] len The length (including the zero-byte at the end) of the
  4526. string to be read.
  4527. @param[in, out] result A reference to the string variable where the read
  4528. string is to be stored.
  4529. @tparam NumberType The type of the length @a len
  4530. @pre len >= 1
  4531. @return `true` if the string was successfully parsed
  4532. */
  4533. template<typename NumberType>
  4534. bool get_bson_string(const NumberType len, string_t& result)
  4535. {
  4536. if (JSON_HEDLEY_UNLIKELY(len < 1))
  4537. {
  4538. auto last_token = get_token_string();
  4539. 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")));
  4540. }
  4541. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) and get() != std::char_traits<char>::eof();
  4542. }
  4543. /*!
  4544. @brief Read a BSON document element of the given @a element_type.
  4545. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  4546. @param[in] element_type_parse_position The position in the input stream,
  4547. where the `element_type` was read.
  4548. @warning Not all BSON element types are supported yet. An unsupported
  4549. @a element_type will give rise to a parse_error.114:
  4550. Unsupported BSON record type 0x...
  4551. @return whether a valid BSON-object/array was passed to the SAX parser
  4552. */
  4553. bool parse_bson_element_internal(const int element_type,
  4554. const std::size_t element_type_parse_position)
  4555. {
  4556. switch (element_type)
  4557. {
  4558. case 0x01: // double
  4559. {
  4560. double number;
  4561. return get_number<double, true>(input_format_t::bson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  4562. }
  4563. case 0x02: // string
  4564. {
  4565. std::int32_t len;
  4566. string_t value;
  4567. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_string(len, value) and sax->string(value);
  4568. }
  4569. case 0x03: // object
  4570. {
  4571. return parse_bson_internal();
  4572. }
  4573. case 0x04: // array
  4574. {
  4575. return parse_bson_array();
  4576. }
  4577. case 0x08: // boolean
  4578. {
  4579. return sax->boolean(get() != 0);
  4580. }
  4581. case 0x0A: // null
  4582. {
  4583. return sax->null();
  4584. }
  4585. case 0x10: // int32
  4586. {
  4587. std::int32_t value;
  4588. return get_number<std::int32_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  4589. }
  4590. case 0x12: // int64
  4591. {
  4592. std::int64_t value;
  4593. return get_number<std::int64_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  4594. }
  4595. default: // anything else not supported (yet)
  4596. {
  4597. std::array<char, 3> cr{{}};
  4598. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type));
  4599. 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())));
  4600. }
  4601. }
  4602. }
  4603. /*!
  4604. @brief Read a BSON element list (as specified in the BSON-spec)
  4605. The same binary layout is used for objects and arrays, hence it must be
  4606. indicated with the argument @a is_array which one is expected
  4607. (true --> array, false --> object).
  4608. @param[in] is_array Determines if the element list being read is to be
  4609. treated as an object (@a is_array == false), or as an
  4610. array (@a is_array == true).
  4611. @return whether a valid BSON-object/array was passed to the SAX parser
  4612. */
  4613. bool parse_bson_element_list(const bool is_array)
  4614. {
  4615. string_t key;
  4616. while (int element_type = get())
  4617. {
  4618. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "element list")))
  4619. {
  4620. return false;
  4621. }
  4622. const std::size_t element_type_parse_position = chars_read;
  4623. if (JSON_HEDLEY_UNLIKELY(not get_bson_cstr(key)))
  4624. {
  4625. return false;
  4626. }
  4627. if (not is_array and not sax->key(key))
  4628. {
  4629. return false;
  4630. }
  4631. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_internal(element_type, element_type_parse_position)))
  4632. {
  4633. return false;
  4634. }
  4635. // get_bson_cstr only appends
  4636. key.clear();
  4637. }
  4638. return true;
  4639. }
  4640. /*!
  4641. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  4642. @return whether a valid BSON-array was passed to the SAX parser
  4643. */
  4644. bool parse_bson_array()
  4645. {
  4646. std::int32_t document_size;
  4647. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  4648. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  4649. {
  4650. return false;
  4651. }
  4652. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/true)))
  4653. {
  4654. return false;
  4655. }
  4656. return sax->end_array();
  4657. }
  4658. //////////
  4659. // CBOR //
  4660. //////////
  4661. /*!
  4662. @param[in] get_char whether a new character should be retrieved from the
  4663. input (true, default) or whether the last read
  4664. character should be considered instead
  4665. @return whether a valid CBOR value was passed to the SAX parser
  4666. */
  4667. bool parse_cbor_internal(const bool get_char = true)
  4668. {
  4669. switch (get_char ? get() : current)
  4670. {
  4671. // EOF
  4672. case std::char_traits<char>::eof():
  4673. return unexpect_eof(input_format_t::cbor, "value");
  4674. // Integer 0x00..0x17 (0..23)
  4675. case 0x00:
  4676. case 0x01:
  4677. case 0x02:
  4678. case 0x03:
  4679. case 0x04:
  4680. case 0x05:
  4681. case 0x06:
  4682. case 0x07:
  4683. case 0x08:
  4684. case 0x09:
  4685. case 0x0A:
  4686. case 0x0B:
  4687. case 0x0C:
  4688. case 0x0D:
  4689. case 0x0E:
  4690. case 0x0F:
  4691. case 0x10:
  4692. case 0x11:
  4693. case 0x12:
  4694. case 0x13:
  4695. case 0x14:
  4696. case 0x15:
  4697. case 0x16:
  4698. case 0x17:
  4699. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  4700. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  4701. {
  4702. std::uint8_t number;
  4703. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4704. }
  4705. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  4706. {
  4707. std::uint16_t number;
  4708. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4709. }
  4710. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  4711. {
  4712. std::uint32_t number;
  4713. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4714. }
  4715. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  4716. {
  4717. std::uint64_t number;
  4718. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4719. }
  4720. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  4721. case 0x20:
  4722. case 0x21:
  4723. case 0x22:
  4724. case 0x23:
  4725. case 0x24:
  4726. case 0x25:
  4727. case 0x26:
  4728. case 0x27:
  4729. case 0x28:
  4730. case 0x29:
  4731. case 0x2A:
  4732. case 0x2B:
  4733. case 0x2C:
  4734. case 0x2D:
  4735. case 0x2E:
  4736. case 0x2F:
  4737. case 0x30:
  4738. case 0x31:
  4739. case 0x32:
  4740. case 0x33:
  4741. case 0x34:
  4742. case 0x35:
  4743. case 0x36:
  4744. case 0x37:
  4745. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  4746. case 0x38: // Negative integer (one-byte uint8_t follows)
  4747. {
  4748. std::uint8_t number;
  4749. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  4750. }
  4751. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  4752. {
  4753. std::uint16_t number;
  4754. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  4755. }
  4756. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  4757. {
  4758. std::uint32_t number;
  4759. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  4760. }
  4761. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  4762. {
  4763. std::uint64_t number;
  4764. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1)
  4765. - static_cast<number_integer_t>(number));
  4766. }
  4767. // UTF-8 string (0x00..0x17 bytes follow)
  4768. case 0x60:
  4769. case 0x61:
  4770. case 0x62:
  4771. case 0x63:
  4772. case 0x64:
  4773. case 0x65:
  4774. case 0x66:
  4775. case 0x67:
  4776. case 0x68:
  4777. case 0x69:
  4778. case 0x6A:
  4779. case 0x6B:
  4780. case 0x6C:
  4781. case 0x6D:
  4782. case 0x6E:
  4783. case 0x6F:
  4784. case 0x70:
  4785. case 0x71:
  4786. case 0x72:
  4787. case 0x73:
  4788. case 0x74:
  4789. case 0x75:
  4790. case 0x76:
  4791. case 0x77:
  4792. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  4793. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  4794. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  4795. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  4796. case 0x7F: // UTF-8 string (indefinite length)
  4797. {
  4798. string_t s;
  4799. return get_cbor_string(s) and sax->string(s);
  4800. }
  4801. // array (0x00..0x17 data items follow)
  4802. case 0x80:
  4803. case 0x81:
  4804. case 0x82:
  4805. case 0x83:
  4806. case 0x84:
  4807. case 0x85:
  4808. case 0x86:
  4809. case 0x87:
  4810. case 0x88:
  4811. case 0x89:
  4812. case 0x8A:
  4813. case 0x8B:
  4814. case 0x8C:
  4815. case 0x8D:
  4816. case 0x8E:
  4817. case 0x8F:
  4818. case 0x90:
  4819. case 0x91:
  4820. case 0x92:
  4821. case 0x93:
  4822. case 0x94:
  4823. case 0x95:
  4824. case 0x96:
  4825. case 0x97:
  4826. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  4827. case 0x98: // array (one-byte uint8_t for n follows)
  4828. {
  4829. std::uint8_t len;
  4830. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4831. }
  4832. case 0x99: // array (two-byte uint16_t for n follow)
  4833. {
  4834. std::uint16_t len;
  4835. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4836. }
  4837. case 0x9A: // array (four-byte uint32_t for n follow)
  4838. {
  4839. std::uint32_t len;
  4840. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4841. }
  4842. case 0x9B: // array (eight-byte uint64_t for n follow)
  4843. {
  4844. std::uint64_t len;
  4845. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4846. }
  4847. case 0x9F: // array (indefinite length)
  4848. return get_cbor_array(std::size_t(-1));
  4849. // map (0x00..0x17 pairs of data items follow)
  4850. case 0xA0:
  4851. case 0xA1:
  4852. case 0xA2:
  4853. case 0xA3:
  4854. case 0xA4:
  4855. case 0xA5:
  4856. case 0xA6:
  4857. case 0xA7:
  4858. case 0xA8:
  4859. case 0xA9:
  4860. case 0xAA:
  4861. case 0xAB:
  4862. case 0xAC:
  4863. case 0xAD:
  4864. case 0xAE:
  4865. case 0xAF:
  4866. case 0xB0:
  4867. case 0xB1:
  4868. case 0xB2:
  4869. case 0xB3:
  4870. case 0xB4:
  4871. case 0xB5:
  4872. case 0xB6:
  4873. case 0xB7:
  4874. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  4875. case 0xB8: // map (one-byte uint8_t for n follows)
  4876. {
  4877. std::uint8_t len;
  4878. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4879. }
  4880. case 0xB9: // map (two-byte uint16_t for n follow)
  4881. {
  4882. std::uint16_t len;
  4883. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4884. }
  4885. case 0xBA: // map (four-byte uint32_t for n follow)
  4886. {
  4887. std::uint32_t len;
  4888. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4889. }
  4890. case 0xBB: // map (eight-byte uint64_t for n follow)
  4891. {
  4892. std::uint64_t len;
  4893. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4894. }
  4895. case 0xBF: // map (indefinite length)
  4896. return get_cbor_object(std::size_t(-1));
  4897. case 0xF4: // false
  4898. return sax->boolean(false);
  4899. case 0xF5: // true
  4900. return sax->boolean(true);
  4901. case 0xF6: // null
  4902. return sax->null();
  4903. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  4904. {
  4905. const int byte1_raw = get();
  4906. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  4907. {
  4908. return false;
  4909. }
  4910. const int byte2_raw = get();
  4911. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  4912. {
  4913. return false;
  4914. }
  4915. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  4916. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  4917. // code from RFC 7049, Appendix D, Figure 3:
  4918. // As half-precision floating-point numbers were only added
  4919. // to IEEE 754 in 2008, today's programming platforms often
  4920. // still only have limited support for them. It is very
  4921. // easy to include at least decoding support for them even
  4922. // without such support. An example of a small decoder for
  4923. // half-precision floating-point numbers in the C language
  4924. // is shown in Fig. 3.
  4925. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  4926. const double val = [&half]
  4927. {
  4928. const int exp = (half >> 10u) & 0x1Fu;
  4929. const unsigned int mant = half & 0x3FFu;
  4930. assert(0 <= exp and exp <= 32);
  4931. assert(0 <= mant and mant <= 1024);
  4932. switch (exp)
  4933. {
  4934. case 0:
  4935. return std::ldexp(mant, -24);
  4936. case 31:
  4937. return (mant == 0)
  4938. ? std::numeric_limits<double>::infinity()
  4939. : std::numeric_limits<double>::quiet_NaN();
  4940. default:
  4941. return std::ldexp(mant + 1024, exp - 25);
  4942. }
  4943. }();
  4944. return sax->number_float((half & 0x8000u) != 0
  4945. ? static_cast<number_float_t>(-val)
  4946. : static_cast<number_float_t>(val), "");
  4947. }
  4948. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  4949. {
  4950. float number;
  4951. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  4952. }
  4953. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  4954. {
  4955. double number;
  4956. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  4957. }
  4958. default: // anything else (0xFF is handled inside the other types)
  4959. {
  4960. auto last_token = get_token_string();
  4961. 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")));
  4962. }
  4963. }
  4964. }
  4965. /*!
  4966. @brief reads a CBOR string
  4967. This function first reads starting bytes to determine the expected
  4968. string length and then copies this number of bytes into a string.
  4969. Additionally, CBOR's strings with indefinite lengths are supported.
  4970. @param[out] result created string
  4971. @return whether string creation completed
  4972. */
  4973. bool get_cbor_string(string_t& result)
  4974. {
  4975. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "string")))
  4976. {
  4977. return false;
  4978. }
  4979. switch (current)
  4980. {
  4981. // UTF-8 string (0x00..0x17 bytes follow)
  4982. case 0x60:
  4983. case 0x61:
  4984. case 0x62:
  4985. case 0x63:
  4986. case 0x64:
  4987. case 0x65:
  4988. case 0x66:
  4989. case 0x67:
  4990. case 0x68:
  4991. case 0x69:
  4992. case 0x6A:
  4993. case 0x6B:
  4994. case 0x6C:
  4995. case 0x6D:
  4996. case 0x6E:
  4997. case 0x6F:
  4998. case 0x70:
  4999. case 0x71:
  5000. case 0x72:
  5001. case 0x73:
  5002. case 0x74:
  5003. case 0x75:
  5004. case 0x76:
  5005. case 0x77:
  5006. {
  5007. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  5008. }
  5009. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5010. {
  5011. std::uint8_t len;
  5012. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5013. }
  5014. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5015. {
  5016. std::uint16_t len;
  5017. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5018. }
  5019. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5020. {
  5021. std::uint32_t len;
  5022. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5023. }
  5024. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5025. {
  5026. std::uint64_t len;
  5027. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5028. }
  5029. case 0x7F: // UTF-8 string (indefinite length)
  5030. {
  5031. while (get() != 0xFF)
  5032. {
  5033. string_t chunk;
  5034. if (not get_cbor_string(chunk))
  5035. {
  5036. return false;
  5037. }
  5038. result.append(chunk);
  5039. }
  5040. return true;
  5041. }
  5042. default:
  5043. {
  5044. auto last_token = get_token_string();
  5045. 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")));
  5046. }
  5047. }
  5048. }
  5049. /*!
  5050. @param[in] len the length of the array or std::size_t(-1) for an
  5051. array of indefinite size
  5052. @return whether array creation completed
  5053. */
  5054. bool get_cbor_array(const std::size_t len)
  5055. {
  5056. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  5057. {
  5058. return false;
  5059. }
  5060. if (len != std::size_t(-1))
  5061. {
  5062. for (std::size_t i = 0; i < len; ++i)
  5063. {
  5064. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5065. {
  5066. return false;
  5067. }
  5068. }
  5069. }
  5070. else
  5071. {
  5072. while (get() != 0xFF)
  5073. {
  5074. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal(false)))
  5075. {
  5076. return false;
  5077. }
  5078. }
  5079. }
  5080. return sax->end_array();
  5081. }
  5082. /*!
  5083. @param[in] len the length of the object or std::size_t(-1) for an
  5084. object of indefinite size
  5085. @return whether object creation completed
  5086. */
  5087. bool get_cbor_object(const std::size_t len)
  5088. {
  5089. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  5090. {
  5091. return false;
  5092. }
  5093. string_t key;
  5094. if (len != std::size_t(-1))
  5095. {
  5096. for (std::size_t i = 0; i < len; ++i)
  5097. {
  5098. get();
  5099. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5100. {
  5101. return false;
  5102. }
  5103. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5104. {
  5105. return false;
  5106. }
  5107. key.clear();
  5108. }
  5109. }
  5110. else
  5111. {
  5112. while (get() != 0xFF)
  5113. {
  5114. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5115. {
  5116. return false;
  5117. }
  5118. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5119. {
  5120. return false;
  5121. }
  5122. key.clear();
  5123. }
  5124. }
  5125. return sax->end_object();
  5126. }
  5127. /////////////
  5128. // MsgPack //
  5129. /////////////
  5130. /*!
  5131. @return whether a valid MessagePack value was passed to the SAX parser
  5132. */
  5133. bool parse_msgpack_internal()
  5134. {
  5135. switch (get())
  5136. {
  5137. // EOF
  5138. case std::char_traits<char>::eof():
  5139. return unexpect_eof(input_format_t::msgpack, "value");
  5140. // positive fixint
  5141. case 0x00:
  5142. case 0x01:
  5143. case 0x02:
  5144. case 0x03:
  5145. case 0x04:
  5146. case 0x05:
  5147. case 0x06:
  5148. case 0x07:
  5149. case 0x08:
  5150. case 0x09:
  5151. case 0x0A:
  5152. case 0x0B:
  5153. case 0x0C:
  5154. case 0x0D:
  5155. case 0x0E:
  5156. case 0x0F:
  5157. case 0x10:
  5158. case 0x11:
  5159. case 0x12:
  5160. case 0x13:
  5161. case 0x14:
  5162. case 0x15:
  5163. case 0x16:
  5164. case 0x17:
  5165. case 0x18:
  5166. case 0x19:
  5167. case 0x1A:
  5168. case 0x1B:
  5169. case 0x1C:
  5170. case 0x1D:
  5171. case 0x1E:
  5172. case 0x1F:
  5173. case 0x20:
  5174. case 0x21:
  5175. case 0x22:
  5176. case 0x23:
  5177. case 0x24:
  5178. case 0x25:
  5179. case 0x26:
  5180. case 0x27:
  5181. case 0x28:
  5182. case 0x29:
  5183. case 0x2A:
  5184. case 0x2B:
  5185. case 0x2C:
  5186. case 0x2D:
  5187. case 0x2E:
  5188. case 0x2F:
  5189. case 0x30:
  5190. case 0x31:
  5191. case 0x32:
  5192. case 0x33:
  5193. case 0x34:
  5194. case 0x35:
  5195. case 0x36:
  5196. case 0x37:
  5197. case 0x38:
  5198. case 0x39:
  5199. case 0x3A:
  5200. case 0x3B:
  5201. case 0x3C:
  5202. case 0x3D:
  5203. case 0x3E:
  5204. case 0x3F:
  5205. case 0x40:
  5206. case 0x41:
  5207. case 0x42:
  5208. case 0x43:
  5209. case 0x44:
  5210. case 0x45:
  5211. case 0x46:
  5212. case 0x47:
  5213. case 0x48:
  5214. case 0x49:
  5215. case 0x4A:
  5216. case 0x4B:
  5217. case 0x4C:
  5218. case 0x4D:
  5219. case 0x4E:
  5220. case 0x4F:
  5221. case 0x50:
  5222. case 0x51:
  5223. case 0x52:
  5224. case 0x53:
  5225. case 0x54:
  5226. case 0x55:
  5227. case 0x56:
  5228. case 0x57:
  5229. case 0x58:
  5230. case 0x59:
  5231. case 0x5A:
  5232. case 0x5B:
  5233. case 0x5C:
  5234. case 0x5D:
  5235. case 0x5E:
  5236. case 0x5F:
  5237. case 0x60:
  5238. case 0x61:
  5239. case 0x62:
  5240. case 0x63:
  5241. case 0x64:
  5242. case 0x65:
  5243. case 0x66:
  5244. case 0x67:
  5245. case 0x68:
  5246. case 0x69:
  5247. case 0x6A:
  5248. case 0x6B:
  5249. case 0x6C:
  5250. case 0x6D:
  5251. case 0x6E:
  5252. case 0x6F:
  5253. case 0x70:
  5254. case 0x71:
  5255. case 0x72:
  5256. case 0x73:
  5257. case 0x74:
  5258. case 0x75:
  5259. case 0x76:
  5260. case 0x77:
  5261. case 0x78:
  5262. case 0x79:
  5263. case 0x7A:
  5264. case 0x7B:
  5265. case 0x7C:
  5266. case 0x7D:
  5267. case 0x7E:
  5268. case 0x7F:
  5269. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5270. // fixmap
  5271. case 0x80:
  5272. case 0x81:
  5273. case 0x82:
  5274. case 0x83:
  5275. case 0x84:
  5276. case 0x85:
  5277. case 0x86:
  5278. case 0x87:
  5279. case 0x88:
  5280. case 0x89:
  5281. case 0x8A:
  5282. case 0x8B:
  5283. case 0x8C:
  5284. case 0x8D:
  5285. case 0x8E:
  5286. case 0x8F:
  5287. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  5288. // fixarray
  5289. case 0x90:
  5290. case 0x91:
  5291. case 0x92:
  5292. case 0x93:
  5293. case 0x94:
  5294. case 0x95:
  5295. case 0x96:
  5296. case 0x97:
  5297. case 0x98:
  5298. case 0x99:
  5299. case 0x9A:
  5300. case 0x9B:
  5301. case 0x9C:
  5302. case 0x9D:
  5303. case 0x9E:
  5304. case 0x9F:
  5305. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  5306. // fixstr
  5307. case 0xA0:
  5308. case 0xA1:
  5309. case 0xA2:
  5310. case 0xA3:
  5311. case 0xA4:
  5312. case 0xA5:
  5313. case 0xA6:
  5314. case 0xA7:
  5315. case 0xA8:
  5316. case 0xA9:
  5317. case 0xAA:
  5318. case 0xAB:
  5319. case 0xAC:
  5320. case 0xAD:
  5321. case 0xAE:
  5322. case 0xAF:
  5323. case 0xB0:
  5324. case 0xB1:
  5325. case 0xB2:
  5326. case 0xB3:
  5327. case 0xB4:
  5328. case 0xB5:
  5329. case 0xB6:
  5330. case 0xB7:
  5331. case 0xB8:
  5332. case 0xB9:
  5333. case 0xBA:
  5334. case 0xBB:
  5335. case 0xBC:
  5336. case 0xBD:
  5337. case 0xBE:
  5338. case 0xBF:
  5339. case 0xD9: // str 8
  5340. case 0xDA: // str 16
  5341. case 0xDB: // str 32
  5342. {
  5343. string_t s;
  5344. return get_msgpack_string(s) and sax->string(s);
  5345. }
  5346. case 0xC0: // nil
  5347. return sax->null();
  5348. case 0xC2: // false
  5349. return sax->boolean(false);
  5350. case 0xC3: // true
  5351. return sax->boolean(true);
  5352. case 0xCA: // float 32
  5353. {
  5354. float number;
  5355. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5356. }
  5357. case 0xCB: // float 64
  5358. {
  5359. double number;
  5360. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5361. }
  5362. case 0xCC: // uint 8
  5363. {
  5364. std::uint8_t number;
  5365. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5366. }
  5367. case 0xCD: // uint 16
  5368. {
  5369. std::uint16_t number;
  5370. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5371. }
  5372. case 0xCE: // uint 32
  5373. {
  5374. std::uint32_t number;
  5375. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5376. }
  5377. case 0xCF: // uint 64
  5378. {
  5379. std::uint64_t number;
  5380. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5381. }
  5382. case 0xD0: // int 8
  5383. {
  5384. std::int8_t number;
  5385. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5386. }
  5387. case 0xD1: // int 16
  5388. {
  5389. std::int16_t number;
  5390. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5391. }
  5392. case 0xD2: // int 32
  5393. {
  5394. std::int32_t number;
  5395. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5396. }
  5397. case 0xD3: // int 64
  5398. {
  5399. std::int64_t number;
  5400. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5401. }
  5402. case 0xDC: // array 16
  5403. {
  5404. std::uint16_t len;
  5405. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  5406. }
  5407. case 0xDD: // array 32
  5408. {
  5409. std::uint32_t len;
  5410. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  5411. }
  5412. case 0xDE: // map 16
  5413. {
  5414. std::uint16_t len;
  5415. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  5416. }
  5417. case 0xDF: // map 32
  5418. {
  5419. std::uint32_t len;
  5420. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  5421. }
  5422. // negative fixint
  5423. case 0xE0:
  5424. case 0xE1:
  5425. case 0xE2:
  5426. case 0xE3:
  5427. case 0xE4:
  5428. case 0xE5:
  5429. case 0xE6:
  5430. case 0xE7:
  5431. case 0xE8:
  5432. case 0xE9:
  5433. case 0xEA:
  5434. case 0xEB:
  5435. case 0xEC:
  5436. case 0xED:
  5437. case 0xEE:
  5438. case 0xEF:
  5439. case 0xF0:
  5440. case 0xF1:
  5441. case 0xF2:
  5442. case 0xF3:
  5443. case 0xF4:
  5444. case 0xF5:
  5445. case 0xF6:
  5446. case 0xF7:
  5447. case 0xF8:
  5448. case 0xF9:
  5449. case 0xFA:
  5450. case 0xFB:
  5451. case 0xFC:
  5452. case 0xFD:
  5453. case 0xFE:
  5454. case 0xFF:
  5455. return sax->number_integer(static_cast<std::int8_t>(current));
  5456. default: // anything else
  5457. {
  5458. auto last_token = get_token_string();
  5459. 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")));
  5460. }
  5461. }
  5462. }
  5463. /*!
  5464. @brief reads a MessagePack string
  5465. This function first reads starting bytes to determine the expected
  5466. string length and then copies this number of bytes into a string.
  5467. @param[out] result created string
  5468. @return whether string creation completed
  5469. */
  5470. bool get_msgpack_string(string_t& result)
  5471. {
  5472. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "string")))
  5473. {
  5474. return false;
  5475. }
  5476. switch (current)
  5477. {
  5478. // fixstr
  5479. case 0xA0:
  5480. case 0xA1:
  5481. case 0xA2:
  5482. case 0xA3:
  5483. case 0xA4:
  5484. case 0xA5:
  5485. case 0xA6:
  5486. case 0xA7:
  5487. case 0xA8:
  5488. case 0xA9:
  5489. case 0xAA:
  5490. case 0xAB:
  5491. case 0xAC:
  5492. case 0xAD:
  5493. case 0xAE:
  5494. case 0xAF:
  5495. case 0xB0:
  5496. case 0xB1:
  5497. case 0xB2:
  5498. case 0xB3:
  5499. case 0xB4:
  5500. case 0xB5:
  5501. case 0xB6:
  5502. case 0xB7:
  5503. case 0xB8:
  5504. case 0xB9:
  5505. case 0xBA:
  5506. case 0xBB:
  5507. case 0xBC:
  5508. case 0xBD:
  5509. case 0xBE:
  5510. case 0xBF:
  5511. {
  5512. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  5513. }
  5514. case 0xD9: // str 8
  5515. {
  5516. std::uint8_t len;
  5517. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  5518. }
  5519. case 0xDA: // str 16
  5520. {
  5521. std::uint16_t len;
  5522. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  5523. }
  5524. case 0xDB: // str 32
  5525. {
  5526. std::uint32_t len;
  5527. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  5528. }
  5529. default:
  5530. {
  5531. auto last_token = get_token_string();
  5532. 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")));
  5533. }
  5534. }
  5535. }
  5536. /*!
  5537. @param[in] len the length of the array
  5538. @return whether array creation completed
  5539. */
  5540. bool get_msgpack_array(const std::size_t len)
  5541. {
  5542. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  5543. {
  5544. return false;
  5545. }
  5546. for (std::size_t i = 0; i < len; ++i)
  5547. {
  5548. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  5549. {
  5550. return false;
  5551. }
  5552. }
  5553. return sax->end_array();
  5554. }
  5555. /*!
  5556. @param[in] len the length of the object
  5557. @return whether object creation completed
  5558. */
  5559. bool get_msgpack_object(const std::size_t len)
  5560. {
  5561. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  5562. {
  5563. return false;
  5564. }
  5565. string_t key;
  5566. for (std::size_t i = 0; i < len; ++i)
  5567. {
  5568. get();
  5569. if (JSON_HEDLEY_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
  5570. {
  5571. return false;
  5572. }
  5573. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  5574. {
  5575. return false;
  5576. }
  5577. key.clear();
  5578. }
  5579. return sax->end_object();
  5580. }
  5581. ////////////
  5582. // UBJSON //
  5583. ////////////
  5584. /*!
  5585. @param[in] get_char whether a new character should be retrieved from the
  5586. input (true, default) or whether the last read
  5587. character should be considered instead
  5588. @return whether a valid UBJSON value was passed to the SAX parser
  5589. */
  5590. bool parse_ubjson_internal(const bool get_char = true)
  5591. {
  5592. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  5593. }
  5594. /*!
  5595. @brief reads a UBJSON string
  5596. This function is either called after reading the 'S' byte explicitly
  5597. indicating a string, or in case of an object key where the 'S' byte can be
  5598. left out.
  5599. @param[out] result created string
  5600. @param[in] get_char whether a new character should be retrieved from the
  5601. input (true, default) or whether the last read
  5602. character should be considered instead
  5603. @return whether string creation completed
  5604. */
  5605. bool get_ubjson_string(string_t& result, const bool get_char = true)
  5606. {
  5607. if (get_char)
  5608. {
  5609. get(); // TODO(niels): may we ignore N here?
  5610. }
  5611. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  5612. {
  5613. return false;
  5614. }
  5615. switch (current)
  5616. {
  5617. case 'U':
  5618. {
  5619. std::uint8_t len;
  5620. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5621. }
  5622. case 'i':
  5623. {
  5624. std::int8_t len;
  5625. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5626. }
  5627. case 'I':
  5628. {
  5629. std::int16_t len;
  5630. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5631. }
  5632. case 'l':
  5633. {
  5634. std::int32_t len;
  5635. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5636. }
  5637. case 'L':
  5638. {
  5639. std::int64_t len;
  5640. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5641. }
  5642. default:
  5643. auto last_token = get_token_string();
  5644. 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")));
  5645. }
  5646. }
  5647. /*!
  5648. @param[out] result determined size
  5649. @return whether size determination completed
  5650. */
  5651. bool get_ubjson_size_value(std::size_t& result)
  5652. {
  5653. switch (get_ignore_noop())
  5654. {
  5655. case 'U':
  5656. {
  5657. std::uint8_t number;
  5658. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5659. {
  5660. return false;
  5661. }
  5662. result = static_cast<std::size_t>(number);
  5663. return true;
  5664. }
  5665. case 'i':
  5666. {
  5667. std::int8_t number;
  5668. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5669. {
  5670. return false;
  5671. }
  5672. result = static_cast<std::size_t>(number);
  5673. return true;
  5674. }
  5675. case 'I':
  5676. {
  5677. std::int16_t number;
  5678. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5679. {
  5680. return false;
  5681. }
  5682. result = static_cast<std::size_t>(number);
  5683. return true;
  5684. }
  5685. case 'l':
  5686. {
  5687. std::int32_t number;
  5688. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5689. {
  5690. return false;
  5691. }
  5692. result = static_cast<std::size_t>(number);
  5693. return true;
  5694. }
  5695. case 'L':
  5696. {
  5697. std::int64_t number;
  5698. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5699. {
  5700. return false;
  5701. }
  5702. result = static_cast<std::size_t>(number);
  5703. return true;
  5704. }
  5705. default:
  5706. {
  5707. auto last_token = get_token_string();
  5708. 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")));
  5709. }
  5710. }
  5711. }
  5712. /*!
  5713. @brief determine the type and size for a container
  5714. In the optimized UBJSON format, a type and a size can be provided to allow
  5715. for a more compact representation.
  5716. @param[out] result pair of the size and the type
  5717. @return whether pair creation completed
  5718. */
  5719. bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
  5720. {
  5721. result.first = string_t::npos; // size
  5722. result.second = 0; // type
  5723. get_ignore_noop();
  5724. if (current == '$')
  5725. {
  5726. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  5727. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "type")))
  5728. {
  5729. return false;
  5730. }
  5731. get_ignore_noop();
  5732. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  5733. {
  5734. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  5735. {
  5736. return false;
  5737. }
  5738. auto last_token = get_token_string();
  5739. 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")));
  5740. }
  5741. return get_ubjson_size_value(result.first);
  5742. }
  5743. if (current == '#')
  5744. {
  5745. return get_ubjson_size_value(result.first);
  5746. }
  5747. return true;
  5748. }
  5749. /*!
  5750. @param prefix the previously read or set type prefix
  5751. @return whether value creation completed
  5752. */
  5753. bool get_ubjson_value(const int prefix)
  5754. {
  5755. switch (prefix)
  5756. {
  5757. case std::char_traits<char>::eof(): // EOF
  5758. return unexpect_eof(input_format_t::ubjson, "value");
  5759. case 'T': // true
  5760. return sax->boolean(true);
  5761. case 'F': // false
  5762. return sax->boolean(false);
  5763. case 'Z': // null
  5764. return sax->null();
  5765. case 'U':
  5766. {
  5767. std::uint8_t number;
  5768. return get_number(input_format_t::ubjson, number) and sax->number_unsigned(number);
  5769. }
  5770. case 'i':
  5771. {
  5772. std::int8_t number;
  5773. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5774. }
  5775. case 'I':
  5776. {
  5777. std::int16_t number;
  5778. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5779. }
  5780. case 'l':
  5781. {
  5782. std::int32_t number;
  5783. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5784. }
  5785. case 'L':
  5786. {
  5787. std::int64_t number;
  5788. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5789. }
  5790. case 'd':
  5791. {
  5792. float number;
  5793. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5794. }
  5795. case 'D':
  5796. {
  5797. double number;
  5798. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5799. }
  5800. case 'C': // char
  5801. {
  5802. get();
  5803. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "char")))
  5804. {
  5805. return false;
  5806. }
  5807. if (JSON_HEDLEY_UNLIKELY(current > 127))
  5808. {
  5809. auto last_token = get_token_string();
  5810. 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")));
  5811. }
  5812. string_t s(1, static_cast<char>(current));
  5813. return sax->string(s);
  5814. }
  5815. case 'S': // string
  5816. {
  5817. string_t s;
  5818. return get_ubjson_string(s) and sax->string(s);
  5819. }
  5820. case '[': // array
  5821. return get_ubjson_array();
  5822. case '{': // object
  5823. return get_ubjson_object();
  5824. default: // anything else
  5825. {
  5826. auto last_token = get_token_string();
  5827. 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")));
  5828. }
  5829. }
  5830. }
  5831. /*!
  5832. @return whether array creation completed
  5833. */
  5834. bool get_ubjson_array()
  5835. {
  5836. std::pair<std::size_t, int> size_and_type;
  5837. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  5838. {
  5839. return false;
  5840. }
  5841. if (size_and_type.first != string_t::npos)
  5842. {
  5843. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(size_and_type.first)))
  5844. {
  5845. return false;
  5846. }
  5847. if (size_and_type.second != 0)
  5848. {
  5849. if (size_and_type.second != 'N')
  5850. {
  5851. for (std::size_t i = 0; i < size_and_type.first; ++i)
  5852. {
  5853. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  5854. {
  5855. return false;
  5856. }
  5857. }
  5858. }
  5859. }
  5860. else
  5861. {
  5862. for (std::size_t i = 0; i < size_and_type.first; ++i)
  5863. {
  5864. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  5865. {
  5866. return false;
  5867. }
  5868. }
  5869. }
  5870. }
  5871. else
  5872. {
  5873. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  5874. {
  5875. return false;
  5876. }
  5877. while (current != ']')
  5878. {
  5879. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal(false)))
  5880. {
  5881. return false;
  5882. }
  5883. get_ignore_noop();
  5884. }
  5885. }
  5886. return sax->end_array();
  5887. }
  5888. /*!
  5889. @return whether object creation completed
  5890. */
  5891. bool get_ubjson_object()
  5892. {
  5893. std::pair<std::size_t, int> size_and_type;
  5894. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  5895. {
  5896. return false;
  5897. }
  5898. string_t key;
  5899. if (size_and_type.first != string_t::npos)
  5900. {
  5901. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(size_and_type.first)))
  5902. {
  5903. return false;
  5904. }
  5905. if (size_and_type.second != 0)
  5906. {
  5907. for (std::size_t i = 0; i < size_and_type.first; ++i)
  5908. {
  5909. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  5910. {
  5911. return false;
  5912. }
  5913. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  5914. {
  5915. return false;
  5916. }
  5917. key.clear();
  5918. }
  5919. }
  5920. else
  5921. {
  5922. for (std::size_t i = 0; i < size_and_type.first; ++i)
  5923. {
  5924. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  5925. {
  5926. return false;
  5927. }
  5928. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  5929. {
  5930. return false;
  5931. }
  5932. key.clear();
  5933. }
  5934. }
  5935. }
  5936. else
  5937. {
  5938. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  5939. {
  5940. return false;
  5941. }
  5942. while (current != '}')
  5943. {
  5944. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
  5945. {
  5946. return false;
  5947. }
  5948. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  5949. {
  5950. return false;
  5951. }
  5952. get_ignore_noop();
  5953. key.clear();
  5954. }
  5955. }
  5956. return sax->end_object();
  5957. }
  5958. ///////////////////////
  5959. // Utility functions //
  5960. ///////////////////////
  5961. /*!
  5962. @brief get next character from the input
  5963. This function provides the interface to the used input adapter. It does
  5964. not throw in case the input reached EOF, but returns a -'ve valued
  5965. `std::char_traits<char>::eof()` in that case.
  5966. @return character read from the input
  5967. */
  5968. int get()
  5969. {
  5970. ++chars_read;
  5971. return current = ia->get_character();
  5972. }
  5973. /*!
  5974. @return character read from the input after ignoring all 'N' entries
  5975. */
  5976. int get_ignore_noop()
  5977. {
  5978. do
  5979. {
  5980. get();
  5981. }
  5982. while (current == 'N');
  5983. return current;
  5984. }
  5985. /*
  5986. @brief read a number from the input
  5987. @tparam NumberType the type of the number
  5988. @param[in] format the current format (for diagnostics)
  5989. @param[out] result number of type @a NumberType
  5990. @return whether conversion completed
  5991. @note This function needs to respect the system's endianess, because
  5992. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  5993. (big endian) and therefore need reordering on little endian systems.
  5994. */
  5995. template<typename NumberType, bool InputIsLittleEndian = false>
  5996. bool get_number(const input_format_t format, NumberType& result)
  5997. {
  5998. // step 1: read input into array with system's byte order
  5999. std::array<std::uint8_t, sizeof(NumberType)> vec;
  6000. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  6001. {
  6002. get();
  6003. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "number")))
  6004. {
  6005. return false;
  6006. }
  6007. // reverse byte order prior to conversion if necessary
  6008. if (is_little_endian != InputIsLittleEndian)
  6009. {
  6010. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  6011. }
  6012. else
  6013. {
  6014. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  6015. }
  6016. }
  6017. // step 2: convert array into number of type T and return
  6018. std::memcpy(&result, vec.data(), sizeof(NumberType));
  6019. return true;
  6020. }
  6021. /*!
  6022. @brief create a string by reading characters from the input
  6023. @tparam NumberType the type of the number
  6024. @param[in] format the current format (for diagnostics)
  6025. @param[in] len number of characters to read
  6026. @param[out] result string created by reading @a len bytes
  6027. @return whether string creation completed
  6028. @note We can not reserve @a len bytes for the result, because @a len
  6029. may be too large. Usually, @ref unexpect_eof() detects the end of
  6030. the input before we run out of string memory.
  6031. */
  6032. template<typename NumberType>
  6033. bool get_string(const input_format_t format,
  6034. const NumberType len,
  6035. string_t& result)
  6036. {
  6037. bool success = true;
  6038. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  6039. {
  6040. get();
  6041. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "string")))
  6042. {
  6043. success = false;
  6044. }
  6045. return static_cast<char>(current);
  6046. });
  6047. return success;
  6048. }
  6049. /*!
  6050. @param[in] format the current format (for diagnostics)
  6051. @param[in] context further context information (for diagnostics)
  6052. @return whether the last read character is not EOF
  6053. */
  6054. JSON_HEDLEY_NON_NULL(3)
  6055. bool unexpect_eof(const input_format_t format, const char* context) const
  6056. {
  6057. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char>::eof()))
  6058. {
  6059. return sax->parse_error(chars_read, "<end of file>",
  6060. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
  6061. }
  6062. return true;
  6063. }
  6064. /*!
  6065. @return a string representation of the last read byte
  6066. */
  6067. std::string get_token_string() const
  6068. {
  6069. std::array<char, 3> cr{{}};
  6070. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current));
  6071. return std::string{cr.data()};
  6072. }
  6073. /*!
  6074. @param[in] format the current format
  6075. @param[in] detail a detailed error message
  6076. @param[in] context further contect information
  6077. @return a message string to use in the parse_error exceptions
  6078. */
  6079. std::string exception_message(const input_format_t format,
  6080. const std::string& detail,
  6081. const std::string& context) const
  6082. {
  6083. std::string error_msg = "syntax error while parsing ";
  6084. switch (format)
  6085. {
  6086. case input_format_t::cbor:
  6087. error_msg += "CBOR";
  6088. break;
  6089. case input_format_t::msgpack:
  6090. error_msg += "MessagePack";
  6091. break;
  6092. case input_format_t::ubjson:
  6093. error_msg += "UBJSON";
  6094. break;
  6095. case input_format_t::bson:
  6096. error_msg += "BSON";
  6097. break;
  6098. default: // LCOV_EXCL_LINE
  6099. assert(false); // LCOV_EXCL_LINE
  6100. }
  6101. return error_msg + " " + context + ": " + detail;
  6102. }
  6103. private:
  6104. /// input adapter
  6105. input_adapter_t ia = nullptr;
  6106. /// the current character
  6107. int current = std::char_traits<char>::eof();
  6108. /// the number of characters read
  6109. std::size_t chars_read = 0;
  6110. /// whether we can assume little endianess
  6111. const bool is_little_endian = little_endianess();
  6112. /// the SAX parser
  6113. json_sax_t* sax = nullptr;
  6114. };
  6115. } // namespace detail
  6116. } // namespace nlohmann
  6117. // #include <nlohmann/detail/input/input_adapters.hpp>
  6118. // #include <nlohmann/detail/input/lexer.hpp>
  6119. #include <array> // array
  6120. #include <clocale> // localeconv
  6121. #include <cstddef> // size_t
  6122. #include <cstdio> // snprintf
  6123. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  6124. #include <initializer_list> // initializer_list
  6125. #include <string> // char_traits, string
  6126. #include <utility> // move
  6127. #include <vector> // vector
  6128. // #include <nlohmann/detail/input/input_adapters.hpp>
  6129. // #include <nlohmann/detail/input/position_t.hpp>
  6130. // #include <nlohmann/detail/macro_scope.hpp>
  6131. namespace nlohmann
  6132. {
  6133. namespace detail
  6134. {
  6135. ///////////
  6136. // lexer //
  6137. ///////////
  6138. /*!
  6139. @brief lexical analysis
  6140. This class organizes the lexical analysis during JSON deserialization.
  6141. */
  6142. template<typename BasicJsonType>
  6143. class lexer
  6144. {
  6145. using number_integer_t = typename BasicJsonType::number_integer_t;
  6146. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  6147. using number_float_t = typename BasicJsonType::number_float_t;
  6148. using string_t = typename BasicJsonType::string_t;
  6149. public:
  6150. /// token types for the parser
  6151. enum class token_type
  6152. {
  6153. uninitialized, ///< indicating the scanner is uninitialized
  6154. literal_true, ///< the `true` literal
  6155. literal_false, ///< the `false` literal
  6156. literal_null, ///< the `null` literal
  6157. value_string, ///< a string -- use get_string() for actual value
  6158. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  6159. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  6160. value_float, ///< an floating point number -- use get_number_float() for actual value
  6161. begin_array, ///< the character for array begin `[`
  6162. begin_object, ///< the character for object begin `{`
  6163. end_array, ///< the character for array end `]`
  6164. end_object, ///< the character for object end `}`
  6165. name_separator, ///< the name separator `:`
  6166. value_separator, ///< the value separator `,`
  6167. parse_error, ///< indicating a parse error
  6168. end_of_input, ///< indicating the end of the input buffer
  6169. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  6170. };
  6171. /// return name of values of type token_type (only used for errors)
  6172. JSON_HEDLEY_RETURNS_NON_NULL
  6173. JSON_HEDLEY_CONST
  6174. static const char* token_type_name(const token_type t) noexcept
  6175. {
  6176. switch (t)
  6177. {
  6178. case token_type::uninitialized:
  6179. return "<uninitialized>";
  6180. case token_type::literal_true:
  6181. return "true literal";
  6182. case token_type::literal_false:
  6183. return "false literal";
  6184. case token_type::literal_null:
  6185. return "null literal";
  6186. case token_type::value_string:
  6187. return "string literal";
  6188. case lexer::token_type::value_unsigned:
  6189. case lexer::token_type::value_integer:
  6190. case lexer::token_type::value_float:
  6191. return "number literal";
  6192. case token_type::begin_array:
  6193. return "'['";
  6194. case token_type::begin_object:
  6195. return "'{'";
  6196. case token_type::end_array:
  6197. return "']'";
  6198. case token_type::end_object:
  6199. return "'}'";
  6200. case token_type::name_separator:
  6201. return "':'";
  6202. case token_type::value_separator:
  6203. return "','";
  6204. case token_type::parse_error:
  6205. return "<parse error>";
  6206. case token_type::end_of_input:
  6207. return "end of input";
  6208. case token_type::literal_or_value:
  6209. return "'[', '{', or a literal";
  6210. // LCOV_EXCL_START
  6211. default: // catch non-enum values
  6212. return "unknown token";
  6213. // LCOV_EXCL_STOP
  6214. }
  6215. }
  6216. explicit lexer(detail::input_adapter_t&& adapter)
  6217. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  6218. // delete because of pointer members
  6219. lexer(const lexer&) = delete;
  6220. lexer(lexer&&) = delete;
  6221. lexer& operator=(lexer&) = delete;
  6222. lexer& operator=(lexer&&) = delete;
  6223. ~lexer() = default;
  6224. private:
  6225. /////////////////////
  6226. // locales
  6227. /////////////////////
  6228. /// return the locale-dependent decimal point
  6229. JSON_HEDLEY_PURE
  6230. static char get_decimal_point() noexcept
  6231. {
  6232. const auto loc = localeconv();
  6233. assert(loc != nullptr);
  6234. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  6235. }
  6236. /////////////////////
  6237. // scan functions
  6238. /////////////////////
  6239. /*!
  6240. @brief get codepoint from 4 hex characters following `\u`
  6241. For input "\u c1 c2 c3 c4" the codepoint is:
  6242. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  6243. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  6244. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  6245. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  6246. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  6247. between the ASCII value of the character and the desired integer value.
  6248. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  6249. non-hex character)
  6250. */
  6251. int get_codepoint()
  6252. {
  6253. // this function only makes sense after reading `\u`
  6254. assert(current == 'u');
  6255. int codepoint = 0;
  6256. const auto factors = { 12u, 8u, 4u, 0u };
  6257. for (const auto factor : factors)
  6258. {
  6259. get();
  6260. if (current >= '0' and current <= '9')
  6261. {
  6262. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  6263. }
  6264. else if (current >= 'A' and current <= 'F')
  6265. {
  6266. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  6267. }
  6268. else if (current >= 'a' and current <= 'f')
  6269. {
  6270. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  6271. }
  6272. else
  6273. {
  6274. return -1;
  6275. }
  6276. }
  6277. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  6278. return codepoint;
  6279. }
  6280. /*!
  6281. @brief check if the next byte(s) are inside a given range
  6282. Adds the current byte and, for each passed range, reads a new byte and
  6283. checks if it is inside the range. If a violation was detected, set up an
  6284. error message and return false. Otherwise, return true.
  6285. @param[in] ranges list of integers; interpreted as list of pairs of
  6286. inclusive lower and upper bound, respectively
  6287. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  6288. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  6289. @return true if and only if no range violation was detected
  6290. */
  6291. bool next_byte_in_range(std::initializer_list<int> ranges)
  6292. {
  6293. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  6294. add(current);
  6295. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  6296. {
  6297. get();
  6298. if (JSON_HEDLEY_LIKELY(*range <= current and current <= *(++range)))
  6299. {
  6300. add(current);
  6301. }
  6302. else
  6303. {
  6304. error_message = "invalid string: ill-formed UTF-8 byte";
  6305. return false;
  6306. }
  6307. }
  6308. return true;
  6309. }
  6310. /*!
  6311. @brief scan a string literal
  6312. This function scans a string according to Sect. 7 of RFC 7159. While
  6313. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  6314. function returns successfully, token_buffer is *not* null-terminated (as it
  6315. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  6316. string.
  6317. @return token_type::value_string if string could be successfully scanned,
  6318. token_type::parse_error otherwise
  6319. @note In case of errors, variable error_message contains a textual
  6320. description.
  6321. */
  6322. token_type scan_string()
  6323. {
  6324. // reset token_buffer (ignore opening quote)
  6325. reset();
  6326. // we entered the function by reading an open quote
  6327. assert(current == '\"');
  6328. while (true)
  6329. {
  6330. // get next character
  6331. switch (get())
  6332. {
  6333. // end of file while parsing string
  6334. case std::char_traits<char>::eof():
  6335. {
  6336. error_message = "invalid string: missing closing quote";
  6337. return token_type::parse_error;
  6338. }
  6339. // closing quote
  6340. case '\"':
  6341. {
  6342. return token_type::value_string;
  6343. }
  6344. // escapes
  6345. case '\\':
  6346. {
  6347. switch (get())
  6348. {
  6349. // quotation mark
  6350. case '\"':
  6351. add('\"');
  6352. break;
  6353. // reverse solidus
  6354. case '\\':
  6355. add('\\');
  6356. break;
  6357. // solidus
  6358. case '/':
  6359. add('/');
  6360. break;
  6361. // backspace
  6362. case 'b':
  6363. add('\b');
  6364. break;
  6365. // form feed
  6366. case 'f':
  6367. add('\f');
  6368. break;
  6369. // line feed
  6370. case 'n':
  6371. add('\n');
  6372. break;
  6373. // carriage return
  6374. case 'r':
  6375. add('\r');
  6376. break;
  6377. // tab
  6378. case 't':
  6379. add('\t');
  6380. break;
  6381. // unicode escapes
  6382. case 'u':
  6383. {
  6384. const int codepoint1 = get_codepoint();
  6385. int codepoint = codepoint1; // start with codepoint1
  6386. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  6387. {
  6388. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  6389. return token_type::parse_error;
  6390. }
  6391. // check if code point is a high surrogate
  6392. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  6393. {
  6394. // expect next \uxxxx entry
  6395. if (JSON_HEDLEY_LIKELY(get() == '\\' and get() == 'u'))
  6396. {
  6397. const int codepoint2 = get_codepoint();
  6398. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  6399. {
  6400. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  6401. return token_type::parse_error;
  6402. }
  6403. // check if codepoint2 is a low surrogate
  6404. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  6405. {
  6406. // overwrite codepoint
  6407. codepoint = static_cast<int>(
  6408. // high surrogate occupies the most significant 22 bits
  6409. (static_cast<unsigned int>(codepoint1) << 10u)
  6410. // low surrogate occupies the least significant 15 bits
  6411. + static_cast<unsigned int>(codepoint2)
  6412. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  6413. // in the result so we have to subtract with:
  6414. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  6415. - 0x35FDC00u);
  6416. }
  6417. else
  6418. {
  6419. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  6420. return token_type::parse_error;
  6421. }
  6422. }
  6423. else
  6424. {
  6425. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  6426. return token_type::parse_error;
  6427. }
  6428. }
  6429. else
  6430. {
  6431. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  6432. {
  6433. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  6434. return token_type::parse_error;
  6435. }
  6436. }
  6437. // result of the above calculation yields a proper codepoint
  6438. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  6439. // translate codepoint into bytes
  6440. if (codepoint < 0x80)
  6441. {
  6442. // 1-byte characters: 0xxxxxxx (ASCII)
  6443. add(codepoint);
  6444. }
  6445. else if (codepoint <= 0x7FF)
  6446. {
  6447. // 2-byte characters: 110xxxxx 10xxxxxx
  6448. add(static_cast<int>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  6449. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6450. }
  6451. else if (codepoint <= 0xFFFF)
  6452. {
  6453. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  6454. add(static_cast<int>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  6455. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6456. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6457. }
  6458. else
  6459. {
  6460. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  6461. add(static_cast<int>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  6462. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  6463. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6464. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6465. }
  6466. break;
  6467. }
  6468. // other characters after escape
  6469. default:
  6470. error_message = "invalid string: forbidden character after backslash";
  6471. return token_type::parse_error;
  6472. }
  6473. break;
  6474. }
  6475. // invalid control characters
  6476. case 0x00:
  6477. {
  6478. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  6479. return token_type::parse_error;
  6480. }
  6481. case 0x01:
  6482. {
  6483. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  6484. return token_type::parse_error;
  6485. }
  6486. case 0x02:
  6487. {
  6488. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  6489. return token_type::parse_error;
  6490. }
  6491. case 0x03:
  6492. {
  6493. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  6494. return token_type::parse_error;
  6495. }
  6496. case 0x04:
  6497. {
  6498. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  6499. return token_type::parse_error;
  6500. }
  6501. case 0x05:
  6502. {
  6503. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  6504. return token_type::parse_error;
  6505. }
  6506. case 0x06:
  6507. {
  6508. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  6509. return token_type::parse_error;
  6510. }
  6511. case 0x07:
  6512. {
  6513. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  6514. return token_type::parse_error;
  6515. }
  6516. case 0x08:
  6517. {
  6518. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  6519. return token_type::parse_error;
  6520. }
  6521. case 0x09:
  6522. {
  6523. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  6524. return token_type::parse_error;
  6525. }
  6526. case 0x0A:
  6527. {
  6528. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  6529. return token_type::parse_error;
  6530. }
  6531. case 0x0B:
  6532. {
  6533. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  6534. return token_type::parse_error;
  6535. }
  6536. case 0x0C:
  6537. {
  6538. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  6539. return token_type::parse_error;
  6540. }
  6541. case 0x0D:
  6542. {
  6543. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  6544. return token_type::parse_error;
  6545. }
  6546. case 0x0E:
  6547. {
  6548. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  6549. return token_type::parse_error;
  6550. }
  6551. case 0x0F:
  6552. {
  6553. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  6554. return token_type::parse_error;
  6555. }
  6556. case 0x10:
  6557. {
  6558. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  6559. return token_type::parse_error;
  6560. }
  6561. case 0x11:
  6562. {
  6563. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  6564. return token_type::parse_error;
  6565. }
  6566. case 0x12:
  6567. {
  6568. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  6569. return token_type::parse_error;
  6570. }
  6571. case 0x13:
  6572. {
  6573. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  6574. return token_type::parse_error;
  6575. }
  6576. case 0x14:
  6577. {
  6578. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  6579. return token_type::parse_error;
  6580. }
  6581. case 0x15:
  6582. {
  6583. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  6584. return token_type::parse_error;
  6585. }
  6586. case 0x16:
  6587. {
  6588. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  6589. return token_type::parse_error;
  6590. }
  6591. case 0x17:
  6592. {
  6593. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  6594. return token_type::parse_error;
  6595. }
  6596. case 0x18:
  6597. {
  6598. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  6599. return token_type::parse_error;
  6600. }
  6601. case 0x19:
  6602. {
  6603. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  6604. return token_type::parse_error;
  6605. }
  6606. case 0x1A:
  6607. {
  6608. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  6609. return token_type::parse_error;
  6610. }
  6611. case 0x1B:
  6612. {
  6613. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  6614. return token_type::parse_error;
  6615. }
  6616. case 0x1C:
  6617. {
  6618. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  6619. return token_type::parse_error;
  6620. }
  6621. case 0x1D:
  6622. {
  6623. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  6624. return token_type::parse_error;
  6625. }
  6626. case 0x1E:
  6627. {
  6628. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  6629. return token_type::parse_error;
  6630. }
  6631. case 0x1F:
  6632. {
  6633. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  6634. return token_type::parse_error;
  6635. }
  6636. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  6637. case 0x20:
  6638. case 0x21:
  6639. case 0x23:
  6640. case 0x24:
  6641. case 0x25:
  6642. case 0x26:
  6643. case 0x27:
  6644. case 0x28:
  6645. case 0x29:
  6646. case 0x2A:
  6647. case 0x2B:
  6648. case 0x2C:
  6649. case 0x2D:
  6650. case 0x2E:
  6651. case 0x2F:
  6652. case 0x30:
  6653. case 0x31:
  6654. case 0x32:
  6655. case 0x33:
  6656. case 0x34:
  6657. case 0x35:
  6658. case 0x36:
  6659. case 0x37:
  6660. case 0x38:
  6661. case 0x39:
  6662. case 0x3A:
  6663. case 0x3B:
  6664. case 0x3C:
  6665. case 0x3D:
  6666. case 0x3E:
  6667. case 0x3F:
  6668. case 0x40:
  6669. case 0x41:
  6670. case 0x42:
  6671. case 0x43:
  6672. case 0x44:
  6673. case 0x45:
  6674. case 0x46:
  6675. case 0x47:
  6676. case 0x48:
  6677. case 0x49:
  6678. case 0x4A:
  6679. case 0x4B:
  6680. case 0x4C:
  6681. case 0x4D:
  6682. case 0x4E:
  6683. case 0x4F:
  6684. case 0x50:
  6685. case 0x51:
  6686. case 0x52:
  6687. case 0x53:
  6688. case 0x54:
  6689. case 0x55:
  6690. case 0x56:
  6691. case 0x57:
  6692. case 0x58:
  6693. case 0x59:
  6694. case 0x5A:
  6695. case 0x5B:
  6696. case 0x5D:
  6697. case 0x5E:
  6698. case 0x5F:
  6699. case 0x60:
  6700. case 0x61:
  6701. case 0x62:
  6702. case 0x63:
  6703. case 0x64:
  6704. case 0x65:
  6705. case 0x66:
  6706. case 0x67:
  6707. case 0x68:
  6708. case 0x69:
  6709. case 0x6A:
  6710. case 0x6B:
  6711. case 0x6C:
  6712. case 0x6D:
  6713. case 0x6E:
  6714. case 0x6F:
  6715. case 0x70:
  6716. case 0x71:
  6717. case 0x72:
  6718. case 0x73:
  6719. case 0x74:
  6720. case 0x75:
  6721. case 0x76:
  6722. case 0x77:
  6723. case 0x78:
  6724. case 0x79:
  6725. case 0x7A:
  6726. case 0x7B:
  6727. case 0x7C:
  6728. case 0x7D:
  6729. case 0x7E:
  6730. case 0x7F:
  6731. {
  6732. add(current);
  6733. break;
  6734. }
  6735. // U+0080..U+07FF: bytes C2..DF 80..BF
  6736. case 0xC2:
  6737. case 0xC3:
  6738. case 0xC4:
  6739. case 0xC5:
  6740. case 0xC6:
  6741. case 0xC7:
  6742. case 0xC8:
  6743. case 0xC9:
  6744. case 0xCA:
  6745. case 0xCB:
  6746. case 0xCC:
  6747. case 0xCD:
  6748. case 0xCE:
  6749. case 0xCF:
  6750. case 0xD0:
  6751. case 0xD1:
  6752. case 0xD2:
  6753. case 0xD3:
  6754. case 0xD4:
  6755. case 0xD5:
  6756. case 0xD6:
  6757. case 0xD7:
  6758. case 0xD8:
  6759. case 0xD9:
  6760. case 0xDA:
  6761. case 0xDB:
  6762. case 0xDC:
  6763. case 0xDD:
  6764. case 0xDE:
  6765. case 0xDF:
  6766. {
  6767. if (JSON_HEDLEY_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  6768. {
  6769. return token_type::parse_error;
  6770. }
  6771. break;
  6772. }
  6773. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  6774. case 0xE0:
  6775. {
  6776. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  6777. {
  6778. return token_type::parse_error;
  6779. }
  6780. break;
  6781. }
  6782. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  6783. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  6784. case 0xE1:
  6785. case 0xE2:
  6786. case 0xE3:
  6787. case 0xE4:
  6788. case 0xE5:
  6789. case 0xE6:
  6790. case 0xE7:
  6791. case 0xE8:
  6792. case 0xE9:
  6793. case 0xEA:
  6794. case 0xEB:
  6795. case 0xEC:
  6796. case 0xEE:
  6797. case 0xEF:
  6798. {
  6799. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  6800. {
  6801. return token_type::parse_error;
  6802. }
  6803. break;
  6804. }
  6805. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  6806. case 0xED:
  6807. {
  6808. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  6809. {
  6810. return token_type::parse_error;
  6811. }
  6812. break;
  6813. }
  6814. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  6815. case 0xF0:
  6816. {
  6817. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6818. {
  6819. return token_type::parse_error;
  6820. }
  6821. break;
  6822. }
  6823. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  6824. case 0xF1:
  6825. case 0xF2:
  6826. case 0xF3:
  6827. {
  6828. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6829. {
  6830. return token_type::parse_error;
  6831. }
  6832. break;
  6833. }
  6834. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  6835. case 0xF4:
  6836. {
  6837. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  6838. {
  6839. return token_type::parse_error;
  6840. }
  6841. break;
  6842. }
  6843. // remaining bytes (80..C1 and F5..FF) are ill-formed
  6844. default:
  6845. {
  6846. error_message = "invalid string: ill-formed UTF-8 byte";
  6847. return token_type::parse_error;
  6848. }
  6849. }
  6850. }
  6851. }
  6852. JSON_HEDLEY_NON_NULL(2)
  6853. static void strtof(float& f, const char* str, char** endptr) noexcept
  6854. {
  6855. f = std::strtof(str, endptr);
  6856. }
  6857. JSON_HEDLEY_NON_NULL(2)
  6858. static void strtof(double& f, const char* str, char** endptr) noexcept
  6859. {
  6860. f = std::strtod(str, endptr);
  6861. }
  6862. JSON_HEDLEY_NON_NULL(2)
  6863. static void strtof(long double& f, const char* str, char** endptr) noexcept
  6864. {
  6865. f = std::strtold(str, endptr);
  6866. }
  6867. /*!
  6868. @brief scan a number literal
  6869. This function scans a string according to Sect. 6 of RFC 7159.
  6870. The function is realized with a deterministic finite state machine derived
  6871. from the grammar described in RFC 7159. Starting in state "init", the
  6872. input is read and used to determined the next state. Only state "done"
  6873. accepts the number. State "error" is a trap state to model errors. In the
  6874. table below, "anything" means any character but the ones listed before.
  6875. state | 0 | 1-9 | e E | + | - | . | anything
  6876. ---------|----------|----------|----------|---------|---------|----------|-----------
  6877. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  6878. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  6879. zero | done | done | exponent | done | done | decimal1 | done
  6880. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  6881. decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
  6882. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  6883. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  6884. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  6885. any2 | any2 | any2 | done | done | done | done | done
  6886. The state machine is realized with one label per state (prefixed with
  6887. "scan_number_") and `goto` statements between them. The state machine
  6888. contains cycles, but any cycle can be left when EOF is read. Therefore,
  6889. the function is guaranteed to terminate.
  6890. During scanning, the read bytes are stored in token_buffer. This string is
  6891. then converted to a signed integer, an unsigned integer, or a
  6892. floating-point number.
  6893. @return token_type::value_unsigned, token_type::value_integer, or
  6894. token_type::value_float if number could be successfully scanned,
  6895. token_type::parse_error otherwise
  6896. @note The scanner is independent of the current locale. Internally, the
  6897. locale's decimal point is used instead of `.` to work with the
  6898. locale-dependent converters.
  6899. */
  6900. token_type scan_number() // lgtm [cpp/use-of-goto]
  6901. {
  6902. // reset token_buffer to store the number's bytes
  6903. reset();
  6904. // the type of the parsed number; initially set to unsigned; will be
  6905. // changed if minus sign, decimal point or exponent is read
  6906. token_type number_type = token_type::value_unsigned;
  6907. // state (init): we just found out we need to scan a number
  6908. switch (current)
  6909. {
  6910. case '-':
  6911. {
  6912. add(current);
  6913. goto scan_number_minus;
  6914. }
  6915. case '0':
  6916. {
  6917. add(current);
  6918. goto scan_number_zero;
  6919. }
  6920. case '1':
  6921. case '2':
  6922. case '3':
  6923. case '4':
  6924. case '5':
  6925. case '6':
  6926. case '7':
  6927. case '8':
  6928. case '9':
  6929. {
  6930. add(current);
  6931. goto scan_number_any1;
  6932. }
  6933. // all other characters are rejected outside scan_number()
  6934. default: // LCOV_EXCL_LINE
  6935. assert(false); // LCOV_EXCL_LINE
  6936. }
  6937. scan_number_minus:
  6938. // state: we just parsed a leading minus sign
  6939. number_type = token_type::value_integer;
  6940. switch (get())
  6941. {
  6942. case '0':
  6943. {
  6944. add(current);
  6945. goto scan_number_zero;
  6946. }
  6947. case '1':
  6948. case '2':
  6949. case '3':
  6950. case '4':
  6951. case '5':
  6952. case '6':
  6953. case '7':
  6954. case '8':
  6955. case '9':
  6956. {
  6957. add(current);
  6958. goto scan_number_any1;
  6959. }
  6960. default:
  6961. {
  6962. error_message = "invalid number; expected digit after '-'";
  6963. return token_type::parse_error;
  6964. }
  6965. }
  6966. scan_number_zero:
  6967. // state: we just parse a zero (maybe with a leading minus sign)
  6968. switch (get())
  6969. {
  6970. case '.':
  6971. {
  6972. add(decimal_point_char);
  6973. goto scan_number_decimal1;
  6974. }
  6975. case 'e':
  6976. case 'E':
  6977. {
  6978. add(current);
  6979. goto scan_number_exponent;
  6980. }
  6981. default:
  6982. goto scan_number_done;
  6983. }
  6984. scan_number_any1:
  6985. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  6986. switch (get())
  6987. {
  6988. case '0':
  6989. case '1':
  6990. case '2':
  6991. case '3':
  6992. case '4':
  6993. case '5':
  6994. case '6':
  6995. case '7':
  6996. case '8':
  6997. case '9':
  6998. {
  6999. add(current);
  7000. goto scan_number_any1;
  7001. }
  7002. case '.':
  7003. {
  7004. add(decimal_point_char);
  7005. goto scan_number_decimal1;
  7006. }
  7007. case 'e':
  7008. case 'E':
  7009. {
  7010. add(current);
  7011. goto scan_number_exponent;
  7012. }
  7013. default:
  7014. goto scan_number_done;
  7015. }
  7016. scan_number_decimal1:
  7017. // state: we just parsed a decimal point
  7018. number_type = token_type::value_float;
  7019. switch (get())
  7020. {
  7021. case '0':
  7022. case '1':
  7023. case '2':
  7024. case '3':
  7025. case '4':
  7026. case '5':
  7027. case '6':
  7028. case '7':
  7029. case '8':
  7030. case '9':
  7031. {
  7032. add(current);
  7033. goto scan_number_decimal2;
  7034. }
  7035. default:
  7036. {
  7037. error_message = "invalid number; expected digit after '.'";
  7038. return token_type::parse_error;
  7039. }
  7040. }
  7041. scan_number_decimal2:
  7042. // we just parsed at least one number after a decimal point
  7043. switch (get())
  7044. {
  7045. case '0':
  7046. case '1':
  7047. case '2':
  7048. case '3':
  7049. case '4':
  7050. case '5':
  7051. case '6':
  7052. case '7':
  7053. case '8':
  7054. case '9':
  7055. {
  7056. add(current);
  7057. goto scan_number_decimal2;
  7058. }
  7059. case 'e':
  7060. case 'E':
  7061. {
  7062. add(current);
  7063. goto scan_number_exponent;
  7064. }
  7065. default:
  7066. goto scan_number_done;
  7067. }
  7068. scan_number_exponent:
  7069. // we just parsed an exponent
  7070. number_type = token_type::value_float;
  7071. switch (get())
  7072. {
  7073. case '+':
  7074. case '-':
  7075. {
  7076. add(current);
  7077. goto scan_number_sign;
  7078. }
  7079. case '0':
  7080. case '1':
  7081. case '2':
  7082. case '3':
  7083. case '4':
  7084. case '5':
  7085. case '6':
  7086. case '7':
  7087. case '8':
  7088. case '9':
  7089. {
  7090. add(current);
  7091. goto scan_number_any2;
  7092. }
  7093. default:
  7094. {
  7095. error_message =
  7096. "invalid number; expected '+', '-', or digit after exponent";
  7097. return token_type::parse_error;
  7098. }
  7099. }
  7100. scan_number_sign:
  7101. // we just parsed an exponent sign
  7102. switch (get())
  7103. {
  7104. case '0':
  7105. case '1':
  7106. case '2':
  7107. case '3':
  7108. case '4':
  7109. case '5':
  7110. case '6':
  7111. case '7':
  7112. case '8':
  7113. case '9':
  7114. {
  7115. add(current);
  7116. goto scan_number_any2;
  7117. }
  7118. default:
  7119. {
  7120. error_message = "invalid number; expected digit after exponent sign";
  7121. return token_type::parse_error;
  7122. }
  7123. }
  7124. scan_number_any2:
  7125. // we just parsed a number after the exponent or exponent sign
  7126. switch (get())
  7127. {
  7128. case '0':
  7129. case '1':
  7130. case '2':
  7131. case '3':
  7132. case '4':
  7133. case '5':
  7134. case '6':
  7135. case '7':
  7136. case '8':
  7137. case '9':
  7138. {
  7139. add(current);
  7140. goto scan_number_any2;
  7141. }
  7142. default:
  7143. goto scan_number_done;
  7144. }
  7145. scan_number_done:
  7146. // unget the character after the number (we only read it to know that
  7147. // we are done scanning a number)
  7148. unget();
  7149. char* endptr = nullptr;
  7150. errno = 0;
  7151. // try to parse integers first and fall back to floats
  7152. if (number_type == token_type::value_unsigned)
  7153. {
  7154. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  7155. // we checked the number format before
  7156. assert(endptr == token_buffer.data() + token_buffer.size());
  7157. if (errno == 0)
  7158. {
  7159. value_unsigned = static_cast<number_unsigned_t>(x);
  7160. if (value_unsigned == x)
  7161. {
  7162. return token_type::value_unsigned;
  7163. }
  7164. }
  7165. }
  7166. else if (number_type == token_type::value_integer)
  7167. {
  7168. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  7169. // we checked the number format before
  7170. assert(endptr == token_buffer.data() + token_buffer.size());
  7171. if (errno == 0)
  7172. {
  7173. value_integer = static_cast<number_integer_t>(x);
  7174. if (value_integer == x)
  7175. {
  7176. return token_type::value_integer;
  7177. }
  7178. }
  7179. }
  7180. // this code is reached if we parse a floating-point number or if an
  7181. // integer conversion above failed
  7182. strtof(value_float, token_buffer.data(), &endptr);
  7183. // we checked the number format before
  7184. assert(endptr == token_buffer.data() + token_buffer.size());
  7185. return token_type::value_float;
  7186. }
  7187. /*!
  7188. @param[in] literal_text the literal text to expect
  7189. @param[in] length the length of the passed literal text
  7190. @param[in] return_type the token type to return on success
  7191. */
  7192. JSON_HEDLEY_NON_NULL(2)
  7193. token_type scan_literal(const char* literal_text, const std::size_t length,
  7194. token_type return_type)
  7195. {
  7196. assert(current == literal_text[0]);
  7197. for (std::size_t i = 1; i < length; ++i)
  7198. {
  7199. if (JSON_HEDLEY_UNLIKELY(get() != literal_text[i]))
  7200. {
  7201. error_message = "invalid literal";
  7202. return token_type::parse_error;
  7203. }
  7204. }
  7205. return return_type;
  7206. }
  7207. /////////////////////
  7208. // input management
  7209. /////////////////////
  7210. /// reset token_buffer; current character is beginning of token
  7211. void reset() noexcept
  7212. {
  7213. token_buffer.clear();
  7214. token_string.clear();
  7215. token_string.push_back(std::char_traits<char>::to_char_type(current));
  7216. }
  7217. /*
  7218. @brief get next character from the input
  7219. This function provides the interface to the used input adapter. It does
  7220. not throw in case the input reached EOF, but returns a
  7221. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  7222. for use in error messages.
  7223. @return character read from the input
  7224. */
  7225. std::char_traits<char>::int_type get()
  7226. {
  7227. ++position.chars_read_total;
  7228. ++position.chars_read_current_line;
  7229. if (next_unget)
  7230. {
  7231. // just reset the next_unget variable and work with current
  7232. next_unget = false;
  7233. }
  7234. else
  7235. {
  7236. current = ia->get_character();
  7237. }
  7238. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  7239. {
  7240. token_string.push_back(std::char_traits<char>::to_char_type(current));
  7241. }
  7242. if (current == '\n')
  7243. {
  7244. ++position.lines_read;
  7245. position.chars_read_current_line = 0;
  7246. }
  7247. return current;
  7248. }
  7249. /*!
  7250. @brief unget current character (read it again on next get)
  7251. We implement unget by setting variable next_unget to true. The input is not
  7252. changed - we just simulate ungetting by modifying chars_read_total,
  7253. chars_read_current_line, and token_string. The next call to get() will
  7254. behave as if the unget character is read again.
  7255. */
  7256. void unget()
  7257. {
  7258. next_unget = true;
  7259. --position.chars_read_total;
  7260. // in case we "unget" a newline, we have to also decrement the lines_read
  7261. if (position.chars_read_current_line == 0)
  7262. {
  7263. if (position.lines_read > 0)
  7264. {
  7265. --position.lines_read;
  7266. }
  7267. }
  7268. else
  7269. {
  7270. --position.chars_read_current_line;
  7271. }
  7272. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  7273. {
  7274. assert(not token_string.empty());
  7275. token_string.pop_back();
  7276. }
  7277. }
  7278. /// add a character to token_buffer
  7279. void add(int c)
  7280. {
  7281. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  7282. }
  7283. public:
  7284. /////////////////////
  7285. // value getters
  7286. /////////////////////
  7287. /// return integer value
  7288. constexpr number_integer_t get_number_integer() const noexcept
  7289. {
  7290. return value_integer;
  7291. }
  7292. /// return unsigned integer value
  7293. constexpr number_unsigned_t get_number_unsigned() const noexcept
  7294. {
  7295. return value_unsigned;
  7296. }
  7297. /// return floating-point value
  7298. constexpr number_float_t get_number_float() const noexcept
  7299. {
  7300. return value_float;
  7301. }
  7302. /// return current string value (implicitly resets the token; useful only once)
  7303. string_t& get_string()
  7304. {
  7305. return token_buffer;
  7306. }
  7307. /////////////////////
  7308. // diagnostics
  7309. /////////////////////
  7310. /// return position of last read token
  7311. constexpr position_t get_position() const noexcept
  7312. {
  7313. return position;
  7314. }
  7315. /// return the last read token (for errors only). Will never contain EOF
  7316. /// (an arbitrary value that is not a valid char value, often -1), because
  7317. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  7318. std::string get_token_string() const
  7319. {
  7320. // escape control characters
  7321. std::string result;
  7322. for (const auto c : token_string)
  7323. {
  7324. if ('\x00' <= c and c <= '\x1F')
  7325. {
  7326. // escape control characters
  7327. std::array<char, 9> cs{{}};
  7328. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
  7329. result += cs.data();
  7330. }
  7331. else
  7332. {
  7333. // add character as is
  7334. result.push_back(c);
  7335. }
  7336. }
  7337. return result;
  7338. }
  7339. /// return syntax error message
  7340. JSON_HEDLEY_RETURNS_NON_NULL
  7341. constexpr const char* get_error_message() const noexcept
  7342. {
  7343. return error_message;
  7344. }
  7345. /////////////////////
  7346. // actual scanner
  7347. /////////////////////
  7348. /*!
  7349. @brief skip the UTF-8 byte order mark
  7350. @return true iff there is no BOM or the correct BOM has been skipped
  7351. */
  7352. bool skip_bom()
  7353. {
  7354. if (get() == 0xEF)
  7355. {
  7356. // check if we completely parse the BOM
  7357. return get() == 0xBB and get() == 0xBF;
  7358. }
  7359. // the first character is not the beginning of the BOM; unget it to
  7360. // process is later
  7361. unget();
  7362. return true;
  7363. }
  7364. token_type scan()
  7365. {
  7366. // initially, skip the BOM
  7367. if (position.chars_read_total == 0 and not skip_bom())
  7368. {
  7369. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  7370. return token_type::parse_error;
  7371. }
  7372. // read next character and ignore whitespace
  7373. do
  7374. {
  7375. get();
  7376. }
  7377. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  7378. switch (current)
  7379. {
  7380. // structural characters
  7381. case '[':
  7382. return token_type::begin_array;
  7383. case ']':
  7384. return token_type::end_array;
  7385. case '{':
  7386. return token_type::begin_object;
  7387. case '}':
  7388. return token_type::end_object;
  7389. case ':':
  7390. return token_type::name_separator;
  7391. case ',':
  7392. return token_type::value_separator;
  7393. // literals
  7394. case 't':
  7395. return scan_literal("true", 4, token_type::literal_true);
  7396. case 'f':
  7397. return scan_literal("false", 5, token_type::literal_false);
  7398. case 'n':
  7399. return scan_literal("null", 4, token_type::literal_null);
  7400. // string
  7401. case '\"':
  7402. return scan_string();
  7403. // number
  7404. case '-':
  7405. case '0':
  7406. case '1':
  7407. case '2':
  7408. case '3':
  7409. case '4':
  7410. case '5':
  7411. case '6':
  7412. case '7':
  7413. case '8':
  7414. case '9':
  7415. return scan_number();
  7416. // end of input (the null byte is needed when parsing from
  7417. // string literals)
  7418. case '\0':
  7419. case std::char_traits<char>::eof():
  7420. return token_type::end_of_input;
  7421. // error
  7422. default:
  7423. error_message = "invalid literal";
  7424. return token_type::parse_error;
  7425. }
  7426. }
  7427. private:
  7428. /// input adapter
  7429. detail::input_adapter_t ia = nullptr;
  7430. /// the current character
  7431. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  7432. /// whether the next get() call should just return current
  7433. bool next_unget = false;
  7434. /// the start position of the current token
  7435. position_t position {};
  7436. /// raw input token string (for error messages)
  7437. std::vector<char> token_string {};
  7438. /// buffer for variable-length tokens (numbers, strings)
  7439. string_t token_buffer {};
  7440. /// a description of occurred lexer errors
  7441. const char* error_message = "";
  7442. // number values
  7443. number_integer_t value_integer = 0;
  7444. number_unsigned_t value_unsigned = 0;
  7445. number_float_t value_float = 0;
  7446. /// the decimal point
  7447. const char decimal_point_char = '.';
  7448. };
  7449. } // namespace detail
  7450. } // namespace nlohmann
  7451. // #include <nlohmann/detail/input/parser.hpp>
  7452. #include <cassert> // assert
  7453. #include <cmath> // isfinite
  7454. #include <cstdint> // uint8_t
  7455. #include <functional> // function
  7456. #include <string> // string
  7457. #include <utility> // move
  7458. #include <vector> // vector
  7459. // #include <nlohmann/detail/exceptions.hpp>
  7460. // #include <nlohmann/detail/input/input_adapters.hpp>
  7461. // #include <nlohmann/detail/input/json_sax.hpp>
  7462. // #include <nlohmann/detail/input/lexer.hpp>
  7463. // #include <nlohmann/detail/macro_scope.hpp>
  7464. // #include <nlohmann/detail/meta/is_sax.hpp>
  7465. // #include <nlohmann/detail/value_t.hpp>
  7466. namespace nlohmann
  7467. {
  7468. namespace detail
  7469. {
  7470. ////////////
  7471. // parser //
  7472. ////////////
  7473. /*!
  7474. @brief syntax analysis
  7475. This class implements a recursive decent parser.
  7476. */
  7477. template<typename BasicJsonType>
  7478. class parser
  7479. {
  7480. using number_integer_t = typename BasicJsonType::number_integer_t;
  7481. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7482. using number_float_t = typename BasicJsonType::number_float_t;
  7483. using string_t = typename BasicJsonType::string_t;
  7484. using lexer_t = lexer<BasicJsonType>;
  7485. using token_type = typename lexer_t::token_type;
  7486. public:
  7487. enum class parse_event_t : uint8_t
  7488. {
  7489. /// the parser read `{` and started to process a JSON object
  7490. object_start,
  7491. /// the parser read `}` and finished processing a JSON object
  7492. object_end,
  7493. /// the parser read `[` and started to process a JSON array
  7494. array_start,
  7495. /// the parser read `]` and finished processing a JSON array
  7496. array_end,
  7497. /// the parser read a key of a value in an object
  7498. key,
  7499. /// the parser finished reading a JSON value
  7500. value
  7501. };
  7502. using parser_callback_t =
  7503. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  7504. /// a parser reading from an input adapter
  7505. explicit parser(detail::input_adapter_t&& adapter,
  7506. const parser_callback_t cb = nullptr,
  7507. const bool allow_exceptions_ = true)
  7508. : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
  7509. {
  7510. // read first token
  7511. get_token();
  7512. }
  7513. /*!
  7514. @brief public parser interface
  7515. @param[in] strict whether to expect the last token to be EOF
  7516. @param[in,out] result parsed JSON value
  7517. @throw parse_error.101 in case of an unexpected token
  7518. @throw parse_error.102 if to_unicode fails or surrogate error
  7519. @throw parse_error.103 if to_unicode fails
  7520. */
  7521. void parse(const bool strict, BasicJsonType& result)
  7522. {
  7523. if (callback)
  7524. {
  7525. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  7526. sax_parse_internal(&sdp);
  7527. result.assert_invariant();
  7528. // in strict mode, input must be completely read
  7529. if (strict and (get_token() != token_type::end_of_input))
  7530. {
  7531. sdp.parse_error(m_lexer.get_position(),
  7532. m_lexer.get_token_string(),
  7533. parse_error::create(101, m_lexer.get_position(),
  7534. exception_message(token_type::end_of_input, "value")));
  7535. }
  7536. // in case of an error, return discarded value
  7537. if (sdp.is_errored())
  7538. {
  7539. result = value_t::discarded;
  7540. return;
  7541. }
  7542. // set top-level value to null if it was discarded by the callback
  7543. // function
  7544. if (result.is_discarded())
  7545. {
  7546. result = nullptr;
  7547. }
  7548. }
  7549. else
  7550. {
  7551. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  7552. sax_parse_internal(&sdp);
  7553. result.assert_invariant();
  7554. // in strict mode, input must be completely read
  7555. if (strict and (get_token() != token_type::end_of_input))
  7556. {
  7557. sdp.parse_error(m_lexer.get_position(),
  7558. m_lexer.get_token_string(),
  7559. parse_error::create(101, m_lexer.get_position(),
  7560. exception_message(token_type::end_of_input, "value")));
  7561. }
  7562. // in case of an error, return discarded value
  7563. if (sdp.is_errored())
  7564. {
  7565. result = value_t::discarded;
  7566. return;
  7567. }
  7568. }
  7569. }
  7570. /*!
  7571. @brief public accept interface
  7572. @param[in] strict whether to expect the last token to be EOF
  7573. @return whether the input is a proper JSON text
  7574. */
  7575. bool accept(const bool strict = true)
  7576. {
  7577. json_sax_acceptor<BasicJsonType> sax_acceptor;
  7578. return sax_parse(&sax_acceptor, strict);
  7579. }
  7580. template <typename SAX>
  7581. JSON_HEDLEY_NON_NULL(2)
  7582. bool sax_parse(SAX* sax, const bool strict = true)
  7583. {
  7584. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  7585. const bool result = sax_parse_internal(sax);
  7586. // strict mode: next byte must be EOF
  7587. if (result and strict and (get_token() != token_type::end_of_input))
  7588. {
  7589. return sax->parse_error(m_lexer.get_position(),
  7590. m_lexer.get_token_string(),
  7591. parse_error::create(101, m_lexer.get_position(),
  7592. exception_message(token_type::end_of_input, "value")));
  7593. }
  7594. return result;
  7595. }
  7596. private:
  7597. template <typename SAX>
  7598. JSON_HEDLEY_NON_NULL(2)
  7599. bool sax_parse_internal(SAX* sax)
  7600. {
  7601. // stack to remember the hierarchy of structured values we are parsing
  7602. // true = array; false = object
  7603. std::vector<bool> states;
  7604. // value to avoid a goto (see comment where set to true)
  7605. bool skip_to_state_evaluation = false;
  7606. while (true)
  7607. {
  7608. if (not skip_to_state_evaluation)
  7609. {
  7610. // invariant: get_token() was called before each iteration
  7611. switch (last_token)
  7612. {
  7613. case token_type::begin_object:
  7614. {
  7615. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  7616. {
  7617. return false;
  7618. }
  7619. // closing } -> we are done
  7620. if (get_token() == token_type::end_object)
  7621. {
  7622. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  7623. {
  7624. return false;
  7625. }
  7626. break;
  7627. }
  7628. // parse key
  7629. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  7630. {
  7631. return sax->parse_error(m_lexer.get_position(),
  7632. m_lexer.get_token_string(),
  7633. parse_error::create(101, m_lexer.get_position(),
  7634. exception_message(token_type::value_string, "object key")));
  7635. }
  7636. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  7637. {
  7638. return false;
  7639. }
  7640. // parse separator (:)
  7641. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  7642. {
  7643. return sax->parse_error(m_lexer.get_position(),
  7644. m_lexer.get_token_string(),
  7645. parse_error::create(101, m_lexer.get_position(),
  7646. exception_message(token_type::name_separator, "object separator")));
  7647. }
  7648. // remember we are now inside an object
  7649. states.push_back(false);
  7650. // parse values
  7651. get_token();
  7652. continue;
  7653. }
  7654. case token_type::begin_array:
  7655. {
  7656. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  7657. {
  7658. return false;
  7659. }
  7660. // closing ] -> we are done
  7661. if (get_token() == token_type::end_array)
  7662. {
  7663. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  7664. {
  7665. return false;
  7666. }
  7667. break;
  7668. }
  7669. // remember we are now inside an array
  7670. states.push_back(true);
  7671. // parse values (no need to call get_token)
  7672. continue;
  7673. }
  7674. case token_type::value_float:
  7675. {
  7676. const auto res = m_lexer.get_number_float();
  7677. if (JSON_HEDLEY_UNLIKELY(not std::isfinite(res)))
  7678. {
  7679. return sax->parse_error(m_lexer.get_position(),
  7680. m_lexer.get_token_string(),
  7681. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  7682. }
  7683. if (JSON_HEDLEY_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
  7684. {
  7685. return false;
  7686. }
  7687. break;
  7688. }
  7689. case token_type::literal_false:
  7690. {
  7691. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(false)))
  7692. {
  7693. return false;
  7694. }
  7695. break;
  7696. }
  7697. case token_type::literal_null:
  7698. {
  7699. if (JSON_HEDLEY_UNLIKELY(not sax->null()))
  7700. {
  7701. return false;
  7702. }
  7703. break;
  7704. }
  7705. case token_type::literal_true:
  7706. {
  7707. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(true)))
  7708. {
  7709. return false;
  7710. }
  7711. break;
  7712. }
  7713. case token_type::value_integer:
  7714. {
  7715. if (JSON_HEDLEY_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
  7716. {
  7717. return false;
  7718. }
  7719. break;
  7720. }
  7721. case token_type::value_string:
  7722. {
  7723. if (JSON_HEDLEY_UNLIKELY(not sax->string(m_lexer.get_string())))
  7724. {
  7725. return false;
  7726. }
  7727. break;
  7728. }
  7729. case token_type::value_unsigned:
  7730. {
  7731. if (JSON_HEDLEY_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
  7732. {
  7733. return false;
  7734. }
  7735. break;
  7736. }
  7737. case token_type::parse_error:
  7738. {
  7739. // using "uninitialized" to avoid "expected" message
  7740. return sax->parse_error(m_lexer.get_position(),
  7741. m_lexer.get_token_string(),
  7742. parse_error::create(101, m_lexer.get_position(),
  7743. exception_message(token_type::uninitialized, "value")));
  7744. }
  7745. default: // the last token was unexpected
  7746. {
  7747. return sax->parse_error(m_lexer.get_position(),
  7748. m_lexer.get_token_string(),
  7749. parse_error::create(101, m_lexer.get_position(),
  7750. exception_message(token_type::literal_or_value, "value")));
  7751. }
  7752. }
  7753. }
  7754. else
  7755. {
  7756. skip_to_state_evaluation = false;
  7757. }
  7758. // we reached this line after we successfully parsed a value
  7759. if (states.empty())
  7760. {
  7761. // empty stack: we reached the end of the hierarchy: done
  7762. return true;
  7763. }
  7764. if (states.back()) // array
  7765. {
  7766. // comma -> next value
  7767. if (get_token() == token_type::value_separator)
  7768. {
  7769. // parse a new value
  7770. get_token();
  7771. continue;
  7772. }
  7773. // closing ]
  7774. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  7775. {
  7776. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  7777. {
  7778. return false;
  7779. }
  7780. // We are done with this array. Before we can parse a
  7781. // new value, we need to evaluate the new state first.
  7782. // By setting skip_to_state_evaluation to false, we
  7783. // are effectively jumping to the beginning of this if.
  7784. assert(not states.empty());
  7785. states.pop_back();
  7786. skip_to_state_evaluation = true;
  7787. continue;
  7788. }
  7789. return sax->parse_error(m_lexer.get_position(),
  7790. m_lexer.get_token_string(),
  7791. parse_error::create(101, m_lexer.get_position(),
  7792. exception_message(token_type::end_array, "array")));
  7793. }
  7794. else // object
  7795. {
  7796. // comma -> next value
  7797. if (get_token() == token_type::value_separator)
  7798. {
  7799. // parse key
  7800. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  7801. {
  7802. return sax->parse_error(m_lexer.get_position(),
  7803. m_lexer.get_token_string(),
  7804. parse_error::create(101, m_lexer.get_position(),
  7805. exception_message(token_type::value_string, "object key")));
  7806. }
  7807. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  7808. {
  7809. return false;
  7810. }
  7811. // parse separator (:)
  7812. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  7813. {
  7814. return sax->parse_error(m_lexer.get_position(),
  7815. m_lexer.get_token_string(),
  7816. parse_error::create(101, m_lexer.get_position(),
  7817. exception_message(token_type::name_separator, "object separator")));
  7818. }
  7819. // parse values
  7820. get_token();
  7821. continue;
  7822. }
  7823. // closing }
  7824. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  7825. {
  7826. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  7827. {
  7828. return false;
  7829. }
  7830. // We are done with this object. Before we can parse a
  7831. // new value, we need to evaluate the new state first.
  7832. // By setting skip_to_state_evaluation to false, we
  7833. // are effectively jumping to the beginning of this if.
  7834. assert(not states.empty());
  7835. states.pop_back();
  7836. skip_to_state_evaluation = true;
  7837. continue;
  7838. }
  7839. return sax->parse_error(m_lexer.get_position(),
  7840. m_lexer.get_token_string(),
  7841. parse_error::create(101, m_lexer.get_position(),
  7842. exception_message(token_type::end_object, "object")));
  7843. }
  7844. }
  7845. }
  7846. /// get next token from lexer
  7847. token_type get_token()
  7848. {
  7849. return last_token = m_lexer.scan();
  7850. }
  7851. std::string exception_message(const token_type expected, const std::string& context)
  7852. {
  7853. std::string error_msg = "syntax error ";
  7854. if (not context.empty())
  7855. {
  7856. error_msg += "while parsing " + context + " ";
  7857. }
  7858. error_msg += "- ";
  7859. if (last_token == token_type::parse_error)
  7860. {
  7861. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  7862. m_lexer.get_token_string() + "'";
  7863. }
  7864. else
  7865. {
  7866. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  7867. }
  7868. if (expected != token_type::uninitialized)
  7869. {
  7870. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  7871. }
  7872. return error_msg;
  7873. }
  7874. private:
  7875. /// callback function
  7876. const parser_callback_t callback = nullptr;
  7877. /// the type of the last read token
  7878. token_type last_token = token_type::uninitialized;
  7879. /// the lexer
  7880. lexer_t m_lexer;
  7881. /// whether to throw exceptions in case of errors
  7882. const bool allow_exceptions = true;
  7883. };
  7884. } // namespace detail
  7885. } // namespace nlohmann
  7886. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  7887. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  7888. #include <cstddef> // ptrdiff_t
  7889. #include <limits> // numeric_limits
  7890. namespace nlohmann
  7891. {
  7892. namespace detail
  7893. {
  7894. /*
  7895. @brief an iterator for primitive JSON types
  7896. This class models an iterator for primitive JSON types (boolean, number,
  7897. string). It's only purpose is to allow the iterator/const_iterator classes
  7898. to "iterate" over primitive values. Internally, the iterator is modeled by
  7899. a `difference_type` variable. Value begin_value (`0`) models the begin,
  7900. end_value (`1`) models past the end.
  7901. */
  7902. class primitive_iterator_t
  7903. {
  7904. private:
  7905. using difference_type = std::ptrdiff_t;
  7906. static constexpr difference_type begin_value = 0;
  7907. static constexpr difference_type end_value = begin_value + 1;
  7908. /// iterator as signed integer type
  7909. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  7910. public:
  7911. constexpr difference_type get_value() const noexcept
  7912. {
  7913. return m_it;
  7914. }
  7915. /// set iterator to a defined beginning
  7916. void set_begin() noexcept
  7917. {
  7918. m_it = begin_value;
  7919. }
  7920. /// set iterator to a defined past the end
  7921. void set_end() noexcept
  7922. {
  7923. m_it = end_value;
  7924. }
  7925. /// return whether the iterator can be dereferenced
  7926. constexpr bool is_begin() const noexcept
  7927. {
  7928. return m_it == begin_value;
  7929. }
  7930. /// return whether the iterator is at end
  7931. constexpr bool is_end() const noexcept
  7932. {
  7933. return m_it == end_value;
  7934. }
  7935. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7936. {
  7937. return lhs.m_it == rhs.m_it;
  7938. }
  7939. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7940. {
  7941. return lhs.m_it < rhs.m_it;
  7942. }
  7943. primitive_iterator_t operator+(difference_type n) noexcept
  7944. {
  7945. auto result = *this;
  7946. result += n;
  7947. return result;
  7948. }
  7949. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7950. {
  7951. return lhs.m_it - rhs.m_it;
  7952. }
  7953. primitive_iterator_t& operator++() noexcept
  7954. {
  7955. ++m_it;
  7956. return *this;
  7957. }
  7958. primitive_iterator_t const operator++(int) noexcept
  7959. {
  7960. auto result = *this;
  7961. ++m_it;
  7962. return result;
  7963. }
  7964. primitive_iterator_t& operator--() noexcept
  7965. {
  7966. --m_it;
  7967. return *this;
  7968. }
  7969. primitive_iterator_t const operator--(int) noexcept
  7970. {
  7971. auto result = *this;
  7972. --m_it;
  7973. return result;
  7974. }
  7975. primitive_iterator_t& operator+=(difference_type n) noexcept
  7976. {
  7977. m_it += n;
  7978. return *this;
  7979. }
  7980. primitive_iterator_t& operator-=(difference_type n) noexcept
  7981. {
  7982. m_it -= n;
  7983. return *this;
  7984. }
  7985. };
  7986. } // namespace detail
  7987. } // namespace nlohmann
  7988. namespace nlohmann
  7989. {
  7990. namespace detail
  7991. {
  7992. /*!
  7993. @brief an iterator value
  7994. @note This structure could easily be a union, but MSVC currently does not allow
  7995. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  7996. */
  7997. template<typename BasicJsonType> struct internal_iterator
  7998. {
  7999. /// iterator for JSON objects
  8000. typename BasicJsonType::object_t::iterator object_iterator {};
  8001. /// iterator for JSON arrays
  8002. typename BasicJsonType::array_t::iterator array_iterator {};
  8003. /// generic iterator for all other types
  8004. primitive_iterator_t primitive_iterator {};
  8005. };
  8006. } // namespace detail
  8007. } // namespace nlohmann
  8008. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  8009. #include <ciso646> // not
  8010. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  8011. #include <type_traits> // conditional, is_const, remove_const
  8012. // #include <nlohmann/detail/exceptions.hpp>
  8013. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  8014. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8015. // #include <nlohmann/detail/macro_scope.hpp>
  8016. // #include <nlohmann/detail/meta/cpp_future.hpp>
  8017. // #include <nlohmann/detail/meta/type_traits.hpp>
  8018. // #include <nlohmann/detail/value_t.hpp>
  8019. namespace nlohmann
  8020. {
  8021. namespace detail
  8022. {
  8023. // forward declare, to be able to friend it later on
  8024. template<typename IteratorType> class iteration_proxy;
  8025. template<typename IteratorType> class iteration_proxy_value;
  8026. /*!
  8027. @brief a template for a bidirectional iterator for the @ref basic_json class
  8028. This class implements a both iterators (iterator and const_iterator) for the
  8029. @ref basic_json class.
  8030. @note An iterator is called *initialized* when a pointer to a JSON value has
  8031. been set (e.g., by a constructor or a copy assignment). If the iterator is
  8032. default-constructed, it is *uninitialized* and most methods are undefined.
  8033. **The library uses assertions to detect calls on uninitialized iterators.**
  8034. @requirement The class satisfies the following concept requirements:
  8035. -
  8036. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  8037. The iterator that can be moved can be moved in both directions (i.e.
  8038. incremented and decremented).
  8039. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  8040. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  8041. */
  8042. template<typename BasicJsonType>
  8043. class iter_impl
  8044. {
  8045. /// allow basic_json to access private members
  8046. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  8047. friend BasicJsonType;
  8048. friend iteration_proxy<iter_impl>;
  8049. friend iteration_proxy_value<iter_impl>;
  8050. using object_t = typename BasicJsonType::object_t;
  8051. using array_t = typename BasicJsonType::array_t;
  8052. // make sure BasicJsonType is basic_json or const basic_json
  8053. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  8054. "iter_impl only accepts (const) basic_json");
  8055. public:
  8056. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  8057. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  8058. /// A user-defined iterator should provide publicly accessible typedefs named
  8059. /// iterator_category, value_type, difference_type, pointer, and reference.
  8060. /// Note that value_type is required to be non-const, even for constant iterators.
  8061. using iterator_category = std::bidirectional_iterator_tag;
  8062. /// the type of the values when the iterator is dereferenced
  8063. using value_type = typename BasicJsonType::value_type;
  8064. /// a type to represent differences between iterators
  8065. using difference_type = typename BasicJsonType::difference_type;
  8066. /// defines a pointer to the type iterated over (value_type)
  8067. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  8068. typename BasicJsonType::const_pointer,
  8069. typename BasicJsonType::pointer>::type;
  8070. /// defines a reference to the type iterated over (value_type)
  8071. using reference =
  8072. typename std::conditional<std::is_const<BasicJsonType>::value,
  8073. typename BasicJsonType::const_reference,
  8074. typename BasicJsonType::reference>::type;
  8075. /// default constructor
  8076. iter_impl() = default;
  8077. /*!
  8078. @brief constructor for a given JSON instance
  8079. @param[in] object pointer to a JSON object for this iterator
  8080. @pre object != nullptr
  8081. @post The iterator is initialized; i.e. `m_object != nullptr`.
  8082. */
  8083. explicit iter_impl(pointer object) noexcept : m_object(object)
  8084. {
  8085. assert(m_object != nullptr);
  8086. switch (m_object->m_type)
  8087. {
  8088. case value_t::object:
  8089. {
  8090. m_it.object_iterator = typename object_t::iterator();
  8091. break;
  8092. }
  8093. case value_t::array:
  8094. {
  8095. m_it.array_iterator = typename array_t::iterator();
  8096. break;
  8097. }
  8098. default:
  8099. {
  8100. m_it.primitive_iterator = primitive_iterator_t();
  8101. break;
  8102. }
  8103. }
  8104. }
  8105. /*!
  8106. @note The conventional copy constructor and copy assignment are implicitly
  8107. defined. Combined with the following converting constructor and
  8108. assignment, they support: (1) copy from iterator to iterator, (2)
  8109. copy from const iterator to const iterator, and (3) conversion from
  8110. iterator to const iterator. However conversion from const iterator
  8111. to iterator is not defined.
  8112. */
  8113. /*!
  8114. @brief const copy constructor
  8115. @param[in] other const iterator to copy from
  8116. @note This copy constuctor had to be defined explicitely to circumvent a bug
  8117. occuring on msvc v19.0 compiler (VS 2015) debug build. For more
  8118. information refer to: https://github.com/nlohmann/json/issues/1608
  8119. */
  8120. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  8121. : m_object(other.m_object), m_it(other.m_it)
  8122. {}
  8123. /*!
  8124. @brief converting assignment
  8125. @param[in] other const iterator to copy from
  8126. @return const/non-const iterator
  8127. @note It is not checked whether @a other is initialized.
  8128. */
  8129. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  8130. {
  8131. m_object = other.m_object;
  8132. m_it = other.m_it;
  8133. return *this;
  8134. }
  8135. /*!
  8136. @brief converting constructor
  8137. @param[in] other non-const iterator to copy from
  8138. @note It is not checked whether @a other is initialized.
  8139. */
  8140. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  8141. : m_object(other.m_object), m_it(other.m_it)
  8142. {}
  8143. /*!
  8144. @brief converting assignment
  8145. @param[in] other non-const iterator to copy from
  8146. @return const/non-const iterator
  8147. @note It is not checked whether @a other is initialized.
  8148. */
  8149. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  8150. {
  8151. m_object = other.m_object;
  8152. m_it = other.m_it;
  8153. return *this;
  8154. }
  8155. private:
  8156. /*!
  8157. @brief set the iterator to the first value
  8158. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8159. */
  8160. void set_begin() noexcept
  8161. {
  8162. assert(m_object != nullptr);
  8163. switch (m_object->m_type)
  8164. {
  8165. case value_t::object:
  8166. {
  8167. m_it.object_iterator = m_object->m_value.object->begin();
  8168. break;
  8169. }
  8170. case value_t::array:
  8171. {
  8172. m_it.array_iterator = m_object->m_value.array->begin();
  8173. break;
  8174. }
  8175. case value_t::null:
  8176. {
  8177. // set to end so begin()==end() is true: null is empty
  8178. m_it.primitive_iterator.set_end();
  8179. break;
  8180. }
  8181. default:
  8182. {
  8183. m_it.primitive_iterator.set_begin();
  8184. break;
  8185. }
  8186. }
  8187. }
  8188. /*!
  8189. @brief set the iterator past the last value
  8190. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8191. */
  8192. void set_end() noexcept
  8193. {
  8194. assert(m_object != nullptr);
  8195. switch (m_object->m_type)
  8196. {
  8197. case value_t::object:
  8198. {
  8199. m_it.object_iterator = m_object->m_value.object->end();
  8200. break;
  8201. }
  8202. case value_t::array:
  8203. {
  8204. m_it.array_iterator = m_object->m_value.array->end();
  8205. break;
  8206. }
  8207. default:
  8208. {
  8209. m_it.primitive_iterator.set_end();
  8210. break;
  8211. }
  8212. }
  8213. }
  8214. public:
  8215. /*!
  8216. @brief return a reference to the value pointed to by the iterator
  8217. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8218. */
  8219. reference operator*() const
  8220. {
  8221. assert(m_object != nullptr);
  8222. switch (m_object->m_type)
  8223. {
  8224. case value_t::object:
  8225. {
  8226. assert(m_it.object_iterator != m_object->m_value.object->end());
  8227. return m_it.object_iterator->second;
  8228. }
  8229. case value_t::array:
  8230. {
  8231. assert(m_it.array_iterator != m_object->m_value.array->end());
  8232. return *m_it.array_iterator;
  8233. }
  8234. case value_t::null:
  8235. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8236. default:
  8237. {
  8238. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  8239. {
  8240. return *m_object;
  8241. }
  8242. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8243. }
  8244. }
  8245. }
  8246. /*!
  8247. @brief dereference the iterator
  8248. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8249. */
  8250. pointer operator->() const
  8251. {
  8252. assert(m_object != nullptr);
  8253. switch (m_object->m_type)
  8254. {
  8255. case value_t::object:
  8256. {
  8257. assert(m_it.object_iterator != m_object->m_value.object->end());
  8258. return &(m_it.object_iterator->second);
  8259. }
  8260. case value_t::array:
  8261. {
  8262. assert(m_it.array_iterator != m_object->m_value.array->end());
  8263. return &*m_it.array_iterator;
  8264. }
  8265. default:
  8266. {
  8267. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  8268. {
  8269. return m_object;
  8270. }
  8271. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8272. }
  8273. }
  8274. }
  8275. /*!
  8276. @brief post-increment (it++)
  8277. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8278. */
  8279. iter_impl const operator++(int)
  8280. {
  8281. auto result = *this;
  8282. ++(*this);
  8283. return result;
  8284. }
  8285. /*!
  8286. @brief pre-increment (++it)
  8287. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8288. */
  8289. iter_impl& operator++()
  8290. {
  8291. assert(m_object != nullptr);
  8292. switch (m_object->m_type)
  8293. {
  8294. case value_t::object:
  8295. {
  8296. std::advance(m_it.object_iterator, 1);
  8297. break;
  8298. }
  8299. case value_t::array:
  8300. {
  8301. std::advance(m_it.array_iterator, 1);
  8302. break;
  8303. }
  8304. default:
  8305. {
  8306. ++m_it.primitive_iterator;
  8307. break;
  8308. }
  8309. }
  8310. return *this;
  8311. }
  8312. /*!
  8313. @brief post-decrement (it--)
  8314. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8315. */
  8316. iter_impl const operator--(int)
  8317. {
  8318. auto result = *this;
  8319. --(*this);
  8320. return result;
  8321. }
  8322. /*!
  8323. @brief pre-decrement (--it)
  8324. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8325. */
  8326. iter_impl& operator--()
  8327. {
  8328. assert(m_object != nullptr);
  8329. switch (m_object->m_type)
  8330. {
  8331. case value_t::object:
  8332. {
  8333. std::advance(m_it.object_iterator, -1);
  8334. break;
  8335. }
  8336. case value_t::array:
  8337. {
  8338. std::advance(m_it.array_iterator, -1);
  8339. break;
  8340. }
  8341. default:
  8342. {
  8343. --m_it.primitive_iterator;
  8344. break;
  8345. }
  8346. }
  8347. return *this;
  8348. }
  8349. /*!
  8350. @brief comparison: equal
  8351. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8352. */
  8353. bool operator==(const iter_impl& other) const
  8354. {
  8355. // if objects are not the same, the comparison is undefined
  8356. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  8357. {
  8358. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  8359. }
  8360. assert(m_object != nullptr);
  8361. switch (m_object->m_type)
  8362. {
  8363. case value_t::object:
  8364. return (m_it.object_iterator == other.m_it.object_iterator);
  8365. case value_t::array:
  8366. return (m_it.array_iterator == other.m_it.array_iterator);
  8367. default:
  8368. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  8369. }
  8370. }
  8371. /*!
  8372. @brief comparison: not equal
  8373. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8374. */
  8375. bool operator!=(const iter_impl& other) const
  8376. {
  8377. return not operator==(other);
  8378. }
  8379. /*!
  8380. @brief comparison: smaller
  8381. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8382. */
  8383. bool operator<(const iter_impl& other) const
  8384. {
  8385. // if objects are not the same, the comparison is undefined
  8386. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  8387. {
  8388. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  8389. }
  8390. assert(m_object != nullptr);
  8391. switch (m_object->m_type)
  8392. {
  8393. case value_t::object:
  8394. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  8395. case value_t::array:
  8396. return (m_it.array_iterator < other.m_it.array_iterator);
  8397. default:
  8398. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  8399. }
  8400. }
  8401. /*!
  8402. @brief comparison: less than or equal
  8403. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8404. */
  8405. bool operator<=(const iter_impl& other) const
  8406. {
  8407. return not other.operator < (*this);
  8408. }
  8409. /*!
  8410. @brief comparison: greater than
  8411. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8412. */
  8413. bool operator>(const iter_impl& other) const
  8414. {
  8415. return not operator<=(other);
  8416. }
  8417. /*!
  8418. @brief comparison: greater than or equal
  8419. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8420. */
  8421. bool operator>=(const iter_impl& other) const
  8422. {
  8423. return not operator<(other);
  8424. }
  8425. /*!
  8426. @brief add to iterator
  8427. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8428. */
  8429. iter_impl& operator+=(difference_type i)
  8430. {
  8431. assert(m_object != nullptr);
  8432. switch (m_object->m_type)
  8433. {
  8434. case value_t::object:
  8435. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  8436. case value_t::array:
  8437. {
  8438. std::advance(m_it.array_iterator, i);
  8439. break;
  8440. }
  8441. default:
  8442. {
  8443. m_it.primitive_iterator += i;
  8444. break;
  8445. }
  8446. }
  8447. return *this;
  8448. }
  8449. /*!
  8450. @brief subtract from iterator
  8451. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8452. */
  8453. iter_impl& operator-=(difference_type i)
  8454. {
  8455. return operator+=(-i);
  8456. }
  8457. /*!
  8458. @brief add to iterator
  8459. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8460. */
  8461. iter_impl operator+(difference_type i) const
  8462. {
  8463. auto result = *this;
  8464. result += i;
  8465. return result;
  8466. }
  8467. /*!
  8468. @brief addition of distance and iterator
  8469. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8470. */
  8471. friend iter_impl operator+(difference_type i, const iter_impl& it)
  8472. {
  8473. auto result = it;
  8474. result += i;
  8475. return result;
  8476. }
  8477. /*!
  8478. @brief subtract from iterator
  8479. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8480. */
  8481. iter_impl operator-(difference_type i) const
  8482. {
  8483. auto result = *this;
  8484. result -= i;
  8485. return result;
  8486. }
  8487. /*!
  8488. @brief return difference
  8489. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8490. */
  8491. difference_type operator-(const iter_impl& other) const
  8492. {
  8493. assert(m_object != nullptr);
  8494. switch (m_object->m_type)
  8495. {
  8496. case value_t::object:
  8497. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  8498. case value_t::array:
  8499. return m_it.array_iterator - other.m_it.array_iterator;
  8500. default:
  8501. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  8502. }
  8503. }
  8504. /*!
  8505. @brief access to successor
  8506. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8507. */
  8508. reference operator[](difference_type n) const
  8509. {
  8510. assert(m_object != nullptr);
  8511. switch (m_object->m_type)
  8512. {
  8513. case value_t::object:
  8514. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  8515. case value_t::array:
  8516. return *std::next(m_it.array_iterator, n);
  8517. case value_t::null:
  8518. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8519. default:
  8520. {
  8521. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  8522. {
  8523. return *m_object;
  8524. }
  8525. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8526. }
  8527. }
  8528. }
  8529. /*!
  8530. @brief return the key of an object iterator
  8531. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8532. */
  8533. const typename object_t::key_type& key() const
  8534. {
  8535. assert(m_object != nullptr);
  8536. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  8537. {
  8538. return m_it.object_iterator->first;
  8539. }
  8540. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  8541. }
  8542. /*!
  8543. @brief return the value of an iterator
  8544. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8545. */
  8546. reference value() const
  8547. {
  8548. return operator*();
  8549. }
  8550. private:
  8551. /// associated JSON instance
  8552. pointer m_object = nullptr;
  8553. /// the actual iterator of the associated instance
  8554. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  8555. };
  8556. } // namespace detail
  8557. } // namespace nlohmann
  8558. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  8559. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  8560. #include <cstddef> // ptrdiff_t
  8561. #include <iterator> // reverse_iterator
  8562. #include <utility> // declval
  8563. namespace nlohmann
  8564. {
  8565. namespace detail
  8566. {
  8567. //////////////////////
  8568. // reverse_iterator //
  8569. //////////////////////
  8570. /*!
  8571. @brief a template for a reverse iterator class
  8572. @tparam Base the base iterator type to reverse. Valid types are @ref
  8573. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  8574. create @ref const_reverse_iterator).
  8575. @requirement The class satisfies the following concept requirements:
  8576. -
  8577. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  8578. The iterator that can be moved can be moved in both directions (i.e.
  8579. incremented and decremented).
  8580. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  8581. It is possible to write to the pointed-to element (only if @a Base is
  8582. @ref iterator).
  8583. @since version 1.0.0
  8584. */
  8585. template<typename Base>
  8586. class json_reverse_iterator : public std::reverse_iterator<Base>
  8587. {
  8588. public:
  8589. using difference_type = std::ptrdiff_t;
  8590. /// shortcut to the reverse iterator adapter
  8591. using base_iterator = std::reverse_iterator<Base>;
  8592. /// the reference type for the pointed-to element
  8593. using reference = typename Base::reference;
  8594. /// create reverse iterator from iterator
  8595. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  8596. : base_iterator(it) {}
  8597. /// create reverse iterator from base class
  8598. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  8599. /// post-increment (it++)
  8600. json_reverse_iterator const operator++(int)
  8601. {
  8602. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  8603. }
  8604. /// pre-increment (++it)
  8605. json_reverse_iterator& operator++()
  8606. {
  8607. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  8608. }
  8609. /// post-decrement (it--)
  8610. json_reverse_iterator const operator--(int)
  8611. {
  8612. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  8613. }
  8614. /// pre-decrement (--it)
  8615. json_reverse_iterator& operator--()
  8616. {
  8617. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  8618. }
  8619. /// add to iterator
  8620. json_reverse_iterator& operator+=(difference_type i)
  8621. {
  8622. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  8623. }
  8624. /// add to iterator
  8625. json_reverse_iterator operator+(difference_type i) const
  8626. {
  8627. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  8628. }
  8629. /// subtract from iterator
  8630. json_reverse_iterator operator-(difference_type i) const
  8631. {
  8632. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  8633. }
  8634. /// return difference
  8635. difference_type operator-(const json_reverse_iterator& other) const
  8636. {
  8637. return base_iterator(*this) - base_iterator(other);
  8638. }
  8639. /// access to successor
  8640. reference operator[](difference_type n) const
  8641. {
  8642. return *(this->operator+(n));
  8643. }
  8644. /// return the key of an object iterator
  8645. auto key() const -> decltype(std::declval<Base>().key())
  8646. {
  8647. auto it = --this->base();
  8648. return it.key();
  8649. }
  8650. /// return the value of an iterator
  8651. reference value() const
  8652. {
  8653. auto it = --this->base();
  8654. return it.operator * ();
  8655. }
  8656. };
  8657. } // namespace detail
  8658. } // namespace nlohmann
  8659. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8660. // #include <nlohmann/detail/json_pointer.hpp>
  8661. #include <algorithm> // all_of
  8662. #include <cassert> // assert
  8663. #include <cctype> // isdigit
  8664. #include <numeric> // accumulate
  8665. #include <string> // string
  8666. #include <utility> // move
  8667. #include <vector> // vector
  8668. // #include <nlohmann/detail/exceptions.hpp>
  8669. // #include <nlohmann/detail/macro_scope.hpp>
  8670. // #include <nlohmann/detail/value_t.hpp>
  8671. namespace nlohmann
  8672. {
  8673. template<typename BasicJsonType>
  8674. class json_pointer
  8675. {
  8676. // allow basic_json to access private members
  8677. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  8678. friend class basic_json;
  8679. public:
  8680. /*!
  8681. @brief create JSON pointer
  8682. Create a JSON pointer according to the syntax described in
  8683. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  8684. @param[in] s string representing the JSON pointer; if omitted, the empty
  8685. string is assumed which references the whole JSON value
  8686. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  8687. not begin with a slash (`/`); see example below
  8688. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  8689. not followed by `0` (representing `~`) or `1` (representing `/`); see
  8690. example below
  8691. @liveexample{The example shows the construction several valid JSON pointers
  8692. as well as the exceptional behavior.,json_pointer}
  8693. @since version 2.0.0
  8694. */
  8695. explicit json_pointer(const std::string& s = "")
  8696. : reference_tokens(split(s))
  8697. {}
  8698. /*!
  8699. @brief return a string representation of the JSON pointer
  8700. @invariant For each JSON pointer `ptr`, it holds:
  8701. @code {.cpp}
  8702. ptr == json_pointer(ptr.to_string());
  8703. @endcode
  8704. @return a string representation of the JSON pointer
  8705. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  8706. @since version 2.0.0
  8707. */
  8708. std::string to_string() const
  8709. {
  8710. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  8711. std::string{},
  8712. [](const std::string & a, const std::string & b)
  8713. {
  8714. return a + "/" + escape(b);
  8715. });
  8716. }
  8717. /// @copydoc to_string()
  8718. operator std::string() const
  8719. {
  8720. return to_string();
  8721. }
  8722. /*!
  8723. @brief append another JSON pointer at the end of this JSON pointer
  8724. @param[in] ptr JSON pointer to append
  8725. @return JSON pointer with @a ptr appended
  8726. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  8727. @complexity Linear in the length of @a ptr.
  8728. @sa @ref operator/=(std::string) to append a reference token
  8729. @sa @ref operator/=(std::size_t) to append an array index
  8730. @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  8731. @since version 3.6.0
  8732. */
  8733. json_pointer& operator/=(const json_pointer& ptr)
  8734. {
  8735. reference_tokens.insert(reference_tokens.end(),
  8736. ptr.reference_tokens.begin(),
  8737. ptr.reference_tokens.end());
  8738. return *this;
  8739. }
  8740. /*!
  8741. @brief append an unescaped reference token at the end of this JSON pointer
  8742. @param[in] token reference token to append
  8743. @return JSON pointer with @a token appended without escaping @a token
  8744. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  8745. @complexity Amortized constant.
  8746. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  8747. @sa @ref operator/=(std::size_t) to append an array index
  8748. @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator
  8749. @since version 3.6.0
  8750. */
  8751. json_pointer& operator/=(std::string token)
  8752. {
  8753. push_back(std::move(token));
  8754. return *this;
  8755. }
  8756. /*!
  8757. @brief append an array index at the end of this JSON pointer
  8758. @param[in] array_index array index ot append
  8759. @return JSON pointer with @a array_index appended
  8760. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  8761. @complexity Amortized constant.
  8762. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  8763. @sa @ref operator/=(std::string) to append a reference token
  8764. @sa @ref operator/(const json_pointer&, std::string) for a binary operator
  8765. @since version 3.6.0
  8766. */
  8767. json_pointer& operator/=(std::size_t array_index)
  8768. {
  8769. return *this /= std::to_string(array_index);
  8770. }
  8771. /*!
  8772. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  8773. @param[in] lhs JSON pointer
  8774. @param[in] rhs JSON pointer
  8775. @return a new JSON pointer with @a rhs appended to @a lhs
  8776. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  8777. @complexity Linear in the length of @a lhs and @a rhs.
  8778. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  8779. @since version 3.6.0
  8780. */
  8781. friend json_pointer operator/(const json_pointer& lhs,
  8782. const json_pointer& rhs)
  8783. {
  8784. return json_pointer(lhs) /= rhs;
  8785. }
  8786. /*!
  8787. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  8788. @param[in] ptr JSON pointer
  8789. @param[in] token reference token
  8790. @return a new JSON pointer with unescaped @a token appended to @a ptr
  8791. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  8792. @complexity Linear in the length of @a ptr.
  8793. @sa @ref operator/=(std::string) to append a reference token
  8794. @since version 3.6.0
  8795. */
  8796. friend json_pointer operator/(const json_pointer& ptr, std::string token)
  8797. {
  8798. return json_pointer(ptr) /= std::move(token);
  8799. }
  8800. /*!
  8801. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  8802. @param[in] ptr JSON pointer
  8803. @param[in] array_index array index
  8804. @return a new JSON pointer with @a array_index appended to @a ptr
  8805. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  8806. @complexity Linear in the length of @a ptr.
  8807. @sa @ref operator/=(std::size_t) to append an array index
  8808. @since version 3.6.0
  8809. */
  8810. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_index)
  8811. {
  8812. return json_pointer(ptr) /= array_index;
  8813. }
  8814. /*!
  8815. @brief returns the parent of this JSON pointer
  8816. @return parent of this JSON pointer; in case this JSON pointer is the root,
  8817. the root itself is returned
  8818. @complexity Linear in the length of the JSON pointer.
  8819. @liveexample{The example shows the result of `parent_pointer` for different
  8820. JSON Pointers.,json_pointer__parent_pointer}
  8821. @since version 3.6.0
  8822. */
  8823. json_pointer parent_pointer() const
  8824. {
  8825. if (empty())
  8826. {
  8827. return *this;
  8828. }
  8829. json_pointer res = *this;
  8830. res.pop_back();
  8831. return res;
  8832. }
  8833. /*!
  8834. @brief remove last reference token
  8835. @pre not `empty()`
  8836. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  8837. @complexity Constant.
  8838. @throw out_of_range.405 if JSON pointer has no parent
  8839. @since version 3.6.0
  8840. */
  8841. void pop_back()
  8842. {
  8843. if (JSON_HEDLEY_UNLIKELY(empty()))
  8844. {
  8845. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  8846. }
  8847. reference_tokens.pop_back();
  8848. }
  8849. /*!
  8850. @brief return last reference token
  8851. @pre not `empty()`
  8852. @return last reference token
  8853. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  8854. @complexity Constant.
  8855. @throw out_of_range.405 if JSON pointer has no parent
  8856. @since version 3.6.0
  8857. */
  8858. const std::string& back()
  8859. {
  8860. if (JSON_HEDLEY_UNLIKELY(empty()))
  8861. {
  8862. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  8863. }
  8864. return reference_tokens.back();
  8865. }
  8866. /*!
  8867. @brief append an unescaped token at the end of the reference pointer
  8868. @param[in] token token to add
  8869. @complexity Amortized constant.
  8870. @liveexample{The example shows the result of `push_back` for different
  8871. JSON Pointers.,json_pointer__push_back}
  8872. @since version 3.6.0
  8873. */
  8874. void push_back(const std::string& token)
  8875. {
  8876. reference_tokens.push_back(token);
  8877. }
  8878. /// @copydoc push_back(const std::string&)
  8879. void push_back(std::string&& token)
  8880. {
  8881. reference_tokens.push_back(std::move(token));
  8882. }
  8883. /*!
  8884. @brief return whether pointer points to the root document
  8885. @return true iff the JSON pointer points to the root document
  8886. @complexity Constant.
  8887. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  8888. @liveexample{The example shows the result of `empty` for different JSON
  8889. Pointers.,json_pointer__empty}
  8890. @since version 3.6.0
  8891. */
  8892. bool empty() const noexcept
  8893. {
  8894. return reference_tokens.empty();
  8895. }
  8896. private:
  8897. /*!
  8898. @param[in] s reference token to be converted into an array index
  8899. @return integer representation of @a s
  8900. @throw out_of_range.404 if string @a s could not be converted to an integer
  8901. */
  8902. static int array_index(const std::string& s)
  8903. {
  8904. std::size_t processed_chars = 0;
  8905. const int res = std::stoi(s, &processed_chars);
  8906. // check if the string was completely read
  8907. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  8908. {
  8909. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  8910. }
  8911. return res;
  8912. }
  8913. json_pointer top() const
  8914. {
  8915. if (JSON_HEDLEY_UNLIKELY(empty()))
  8916. {
  8917. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  8918. }
  8919. json_pointer result = *this;
  8920. result.reference_tokens = {reference_tokens[0]};
  8921. return result;
  8922. }
  8923. /*!
  8924. @brief create and return a reference to the pointed to value
  8925. @complexity Linear in the number of reference tokens.
  8926. @throw parse_error.109 if array index is not a number
  8927. @throw type_error.313 if value cannot be unflattened
  8928. */
  8929. BasicJsonType& get_and_create(BasicJsonType& j) const
  8930. {
  8931. using size_type = typename BasicJsonType::size_type;
  8932. auto result = &j;
  8933. // in case no reference tokens exist, return a reference to the JSON value
  8934. // j which will be overwritten by a primitive value
  8935. for (const auto& reference_token : reference_tokens)
  8936. {
  8937. switch (result->type())
  8938. {
  8939. case detail::value_t::null:
  8940. {
  8941. if (reference_token == "0")
  8942. {
  8943. // start a new array if reference token is 0
  8944. result = &result->operator[](0);
  8945. }
  8946. else
  8947. {
  8948. // start a new object otherwise
  8949. result = &result->operator[](reference_token);
  8950. }
  8951. break;
  8952. }
  8953. case detail::value_t::object:
  8954. {
  8955. // create an entry in the object
  8956. result = &result->operator[](reference_token);
  8957. break;
  8958. }
  8959. case detail::value_t::array:
  8960. {
  8961. // create an entry in the array
  8962. JSON_TRY
  8963. {
  8964. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  8965. }
  8966. JSON_CATCH(std::invalid_argument&)
  8967. {
  8968. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  8969. }
  8970. break;
  8971. }
  8972. /*
  8973. The following code is only reached if there exists a reference
  8974. token _and_ the current value is primitive. In this case, we have
  8975. an error situation, because primitive values may only occur as
  8976. single value; that is, with an empty list of reference tokens.
  8977. */
  8978. default:
  8979. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  8980. }
  8981. }
  8982. return *result;
  8983. }
  8984. /*!
  8985. @brief return a reference to the pointed to value
  8986. @note This version does not throw if a value is not present, but tries to
  8987. create nested values instead. For instance, calling this function
  8988. with pointer `"/this/that"` on a null value is equivalent to calling
  8989. `operator[]("this").operator[]("that")` on that value, effectively
  8990. changing the null value to an object.
  8991. @param[in] ptr a JSON value
  8992. @return reference to the JSON value pointed to by the JSON pointer
  8993. @complexity Linear in the length of the JSON pointer.
  8994. @throw parse_error.106 if an array index begins with '0'
  8995. @throw parse_error.109 if an array index was not a number
  8996. @throw out_of_range.404 if the JSON pointer can not be resolved
  8997. */
  8998. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  8999. {
  9000. using size_type = typename BasicJsonType::size_type;
  9001. for (const auto& reference_token : reference_tokens)
  9002. {
  9003. // convert null values to arrays or objects before continuing
  9004. if (ptr->is_null())
  9005. {
  9006. // check if reference token is a number
  9007. const bool nums =
  9008. std::all_of(reference_token.begin(), reference_token.end(),
  9009. [](const unsigned char x)
  9010. {
  9011. return std::isdigit(x);
  9012. });
  9013. // change value to array for numbers or "-" or to object otherwise
  9014. *ptr = (nums or reference_token == "-")
  9015. ? detail::value_t::array
  9016. : detail::value_t::object;
  9017. }
  9018. switch (ptr->type())
  9019. {
  9020. case detail::value_t::object:
  9021. {
  9022. // use unchecked object access
  9023. ptr = &ptr->operator[](reference_token);
  9024. break;
  9025. }
  9026. case detail::value_t::array:
  9027. {
  9028. // error condition (cf. RFC 6901, Sect. 4)
  9029. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9030. {
  9031. JSON_THROW(detail::parse_error::create(106, 0,
  9032. "array index '" + reference_token +
  9033. "' must not begin with '0'"));
  9034. }
  9035. if (reference_token == "-")
  9036. {
  9037. // explicitly treat "-" as index beyond the end
  9038. ptr = &ptr->operator[](ptr->m_value.array->size());
  9039. }
  9040. else
  9041. {
  9042. // convert array index to number; unchecked access
  9043. JSON_TRY
  9044. {
  9045. ptr = &ptr->operator[](
  9046. static_cast<size_type>(array_index(reference_token)));
  9047. }
  9048. JSON_CATCH(std::invalid_argument&)
  9049. {
  9050. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9051. }
  9052. }
  9053. break;
  9054. }
  9055. default:
  9056. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9057. }
  9058. }
  9059. return *ptr;
  9060. }
  9061. /*!
  9062. @throw parse_error.106 if an array index begins with '0'
  9063. @throw parse_error.109 if an array index was not a number
  9064. @throw out_of_range.402 if the array index '-' is used
  9065. @throw out_of_range.404 if the JSON pointer can not be resolved
  9066. */
  9067. BasicJsonType& get_checked(BasicJsonType* ptr) const
  9068. {
  9069. using size_type = typename BasicJsonType::size_type;
  9070. for (const auto& reference_token : reference_tokens)
  9071. {
  9072. switch (ptr->type())
  9073. {
  9074. case detail::value_t::object:
  9075. {
  9076. // note: at performs range check
  9077. ptr = &ptr->at(reference_token);
  9078. break;
  9079. }
  9080. case detail::value_t::array:
  9081. {
  9082. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9083. {
  9084. // "-" always fails the range check
  9085. JSON_THROW(detail::out_of_range::create(402,
  9086. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9087. ") is out of range"));
  9088. }
  9089. // error condition (cf. RFC 6901, Sect. 4)
  9090. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9091. {
  9092. JSON_THROW(detail::parse_error::create(106, 0,
  9093. "array index '" + reference_token +
  9094. "' must not begin with '0'"));
  9095. }
  9096. // note: at performs range check
  9097. JSON_TRY
  9098. {
  9099. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9100. }
  9101. JSON_CATCH(std::invalid_argument&)
  9102. {
  9103. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9104. }
  9105. break;
  9106. }
  9107. default:
  9108. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9109. }
  9110. }
  9111. return *ptr;
  9112. }
  9113. /*!
  9114. @brief return a const reference to the pointed to value
  9115. @param[in] ptr a JSON value
  9116. @return const reference to the JSON value pointed to by the JSON
  9117. pointer
  9118. @throw parse_error.106 if an array index begins with '0'
  9119. @throw parse_error.109 if an array index was not a number
  9120. @throw out_of_range.402 if the array index '-' is used
  9121. @throw out_of_range.404 if the JSON pointer can not be resolved
  9122. */
  9123. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  9124. {
  9125. using size_type = typename BasicJsonType::size_type;
  9126. for (const auto& reference_token : reference_tokens)
  9127. {
  9128. switch (ptr->type())
  9129. {
  9130. case detail::value_t::object:
  9131. {
  9132. // use unchecked object access
  9133. ptr = &ptr->operator[](reference_token);
  9134. break;
  9135. }
  9136. case detail::value_t::array:
  9137. {
  9138. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9139. {
  9140. // "-" cannot be used for const access
  9141. JSON_THROW(detail::out_of_range::create(402,
  9142. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9143. ") is out of range"));
  9144. }
  9145. // error condition (cf. RFC 6901, Sect. 4)
  9146. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9147. {
  9148. JSON_THROW(detail::parse_error::create(106, 0,
  9149. "array index '" + reference_token +
  9150. "' must not begin with '0'"));
  9151. }
  9152. // use unchecked array access
  9153. JSON_TRY
  9154. {
  9155. ptr = &ptr->operator[](
  9156. static_cast<size_type>(array_index(reference_token)));
  9157. }
  9158. JSON_CATCH(std::invalid_argument&)
  9159. {
  9160. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9161. }
  9162. break;
  9163. }
  9164. default:
  9165. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9166. }
  9167. }
  9168. return *ptr;
  9169. }
  9170. /*!
  9171. @throw parse_error.106 if an array index begins with '0'
  9172. @throw parse_error.109 if an array index was not a number
  9173. @throw out_of_range.402 if the array index '-' is used
  9174. @throw out_of_range.404 if the JSON pointer can not be resolved
  9175. */
  9176. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  9177. {
  9178. using size_type = typename BasicJsonType::size_type;
  9179. for (const auto& reference_token : reference_tokens)
  9180. {
  9181. switch (ptr->type())
  9182. {
  9183. case detail::value_t::object:
  9184. {
  9185. // note: at performs range check
  9186. ptr = &ptr->at(reference_token);
  9187. break;
  9188. }
  9189. case detail::value_t::array:
  9190. {
  9191. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9192. {
  9193. // "-" always fails the range check
  9194. JSON_THROW(detail::out_of_range::create(402,
  9195. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9196. ") is out of range"));
  9197. }
  9198. // error condition (cf. RFC 6901, Sect. 4)
  9199. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9200. {
  9201. JSON_THROW(detail::parse_error::create(106, 0,
  9202. "array index '" + reference_token +
  9203. "' must not begin with '0'"));
  9204. }
  9205. // note: at performs range check
  9206. JSON_TRY
  9207. {
  9208. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9209. }
  9210. JSON_CATCH(std::invalid_argument&)
  9211. {
  9212. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9213. }
  9214. break;
  9215. }
  9216. default:
  9217. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9218. }
  9219. }
  9220. return *ptr;
  9221. }
  9222. /*!
  9223. @throw parse_error.106 if an array index begins with '0'
  9224. @throw parse_error.109 if an array index was not a number
  9225. */
  9226. bool contains(const BasicJsonType* ptr) const
  9227. {
  9228. using size_type = typename BasicJsonType::size_type;
  9229. for (const auto& reference_token : reference_tokens)
  9230. {
  9231. switch (ptr->type())
  9232. {
  9233. case detail::value_t::object:
  9234. {
  9235. if (not ptr->contains(reference_token))
  9236. {
  9237. // we did not find the key in the object
  9238. return false;
  9239. }
  9240. ptr = &ptr->operator[](reference_token);
  9241. break;
  9242. }
  9243. case detail::value_t::array:
  9244. {
  9245. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9246. {
  9247. // "-" always fails the range check
  9248. return false;
  9249. }
  9250. // error condition (cf. RFC 6901, Sect. 4)
  9251. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9252. {
  9253. JSON_THROW(detail::parse_error::create(106, 0,
  9254. "array index '" + reference_token +
  9255. "' must not begin with '0'"));
  9256. }
  9257. JSON_TRY
  9258. {
  9259. const auto idx = static_cast<size_type>(array_index(reference_token));
  9260. if (idx >= ptr->size())
  9261. {
  9262. // index out of range
  9263. return false;
  9264. }
  9265. ptr = &ptr->operator[](idx);
  9266. break;
  9267. }
  9268. JSON_CATCH(std::invalid_argument&)
  9269. {
  9270. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9271. }
  9272. break;
  9273. }
  9274. default:
  9275. {
  9276. // we do not expect primitive values if there is still a
  9277. // reference token to process
  9278. return false;
  9279. }
  9280. }
  9281. }
  9282. // no reference token left means we found a primitive value
  9283. return true;
  9284. }
  9285. /*!
  9286. @brief split the string input to reference tokens
  9287. @note This function is only called by the json_pointer constructor.
  9288. All exceptions below are documented there.
  9289. @throw parse_error.107 if the pointer is not empty or begins with '/'
  9290. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  9291. */
  9292. static std::vector<std::string> split(const std::string& reference_string)
  9293. {
  9294. std::vector<std::string> result;
  9295. // special case: empty reference string -> no reference tokens
  9296. if (reference_string.empty())
  9297. {
  9298. return result;
  9299. }
  9300. // check if nonempty reference string begins with slash
  9301. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  9302. {
  9303. JSON_THROW(detail::parse_error::create(107, 1,
  9304. "JSON pointer must be empty or begin with '/' - was: '" +
  9305. reference_string + "'"));
  9306. }
  9307. // extract the reference tokens:
  9308. // - slash: position of the last read slash (or end of string)
  9309. // - start: position after the previous slash
  9310. for (
  9311. // search for the first slash after the first character
  9312. std::size_t slash = reference_string.find_first_of('/', 1),
  9313. // set the beginning of the first reference token
  9314. start = 1;
  9315. // we can stop if start == 0 (if slash == std::string::npos)
  9316. start != 0;
  9317. // set the beginning of the next reference token
  9318. // (will eventually be 0 if slash == std::string::npos)
  9319. start = (slash == std::string::npos) ? 0 : slash + 1,
  9320. // find next slash
  9321. slash = reference_string.find_first_of('/', start))
  9322. {
  9323. // use the text between the beginning of the reference token
  9324. // (start) and the last slash (slash).
  9325. auto reference_token = reference_string.substr(start, slash - start);
  9326. // check reference tokens are properly escaped
  9327. for (std::size_t pos = reference_token.find_first_of('~');
  9328. pos != std::string::npos;
  9329. pos = reference_token.find_first_of('~', pos + 1))
  9330. {
  9331. assert(reference_token[pos] == '~');
  9332. // ~ must be followed by 0 or 1
  9333. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 or
  9334. (reference_token[pos + 1] != '0' and
  9335. reference_token[pos + 1] != '1')))
  9336. {
  9337. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  9338. }
  9339. }
  9340. // finally, store the reference token
  9341. unescape(reference_token);
  9342. result.push_back(reference_token);
  9343. }
  9344. return result;
  9345. }
  9346. /*!
  9347. @brief replace all occurrences of a substring by another string
  9348. @param[in,out] s the string to manipulate; changed so that all
  9349. occurrences of @a f are replaced with @a t
  9350. @param[in] f the substring to replace with @a t
  9351. @param[in] t the string to replace @a f
  9352. @pre The search string @a f must not be empty. **This precondition is
  9353. enforced with an assertion.**
  9354. @since version 2.0.0
  9355. */
  9356. static void replace_substring(std::string& s, const std::string& f,
  9357. const std::string& t)
  9358. {
  9359. assert(not f.empty());
  9360. for (auto pos = s.find(f); // find first occurrence of f
  9361. pos != std::string::npos; // make sure f was found
  9362. s.replace(pos, f.size(), t), // replace with t, and
  9363. pos = s.find(f, pos + t.size())) // find next occurrence of f
  9364. {}
  9365. }
  9366. /// escape "~" to "~0" and "/" to "~1"
  9367. static std::string escape(std::string s)
  9368. {
  9369. replace_substring(s, "~", "~0");
  9370. replace_substring(s, "/", "~1");
  9371. return s;
  9372. }
  9373. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  9374. static void unescape(std::string& s)
  9375. {
  9376. replace_substring(s, "~1", "/");
  9377. replace_substring(s, "~0", "~");
  9378. }
  9379. /*!
  9380. @param[in] reference_string the reference string to the current value
  9381. @param[in] value the value to consider
  9382. @param[in,out] result the result object to insert values to
  9383. @note Empty objects or arrays are flattened to `null`.
  9384. */
  9385. static void flatten(const std::string& reference_string,
  9386. const BasicJsonType& value,
  9387. BasicJsonType& result)
  9388. {
  9389. switch (value.type())
  9390. {
  9391. case detail::value_t::array:
  9392. {
  9393. if (value.m_value.array->empty())
  9394. {
  9395. // flatten empty array as null
  9396. result[reference_string] = nullptr;
  9397. }
  9398. else
  9399. {
  9400. // iterate array and use index as reference string
  9401. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  9402. {
  9403. flatten(reference_string + "/" + std::to_string(i),
  9404. value.m_value.array->operator[](i), result);
  9405. }
  9406. }
  9407. break;
  9408. }
  9409. case detail::value_t::object:
  9410. {
  9411. if (value.m_value.object->empty())
  9412. {
  9413. // flatten empty object as null
  9414. result[reference_string] = nullptr;
  9415. }
  9416. else
  9417. {
  9418. // iterate object and use keys as reference string
  9419. for (const auto& element : *value.m_value.object)
  9420. {
  9421. flatten(reference_string + "/" + escape(element.first), element.second, result);
  9422. }
  9423. }
  9424. break;
  9425. }
  9426. default:
  9427. {
  9428. // add primitive value with its reference string
  9429. result[reference_string] = value;
  9430. break;
  9431. }
  9432. }
  9433. }
  9434. /*!
  9435. @param[in] value flattened JSON
  9436. @return unflattened JSON
  9437. @throw parse_error.109 if array index is not a number
  9438. @throw type_error.314 if value is not an object
  9439. @throw type_error.315 if object values are not primitive
  9440. @throw type_error.313 if value cannot be unflattened
  9441. */
  9442. static BasicJsonType
  9443. unflatten(const BasicJsonType& value)
  9444. {
  9445. if (JSON_HEDLEY_UNLIKELY(not value.is_object()))
  9446. {
  9447. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  9448. }
  9449. BasicJsonType result;
  9450. // iterate the JSON object values
  9451. for (const auto& element : *value.m_value.object)
  9452. {
  9453. if (JSON_HEDLEY_UNLIKELY(not element.second.is_primitive()))
  9454. {
  9455. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  9456. }
  9457. // assign value to reference pointed to by JSON pointer; Note that if
  9458. // the JSON pointer is "" (i.e., points to the whole value), function
  9459. // get_and_create returns a reference to result itself. An assignment
  9460. // will then create a primitive value.
  9461. json_pointer(element.first).get_and_create(result) = element.second;
  9462. }
  9463. return result;
  9464. }
  9465. /*!
  9466. @brief compares two JSON pointers for equality
  9467. @param[in] lhs JSON pointer to compare
  9468. @param[in] rhs JSON pointer to compare
  9469. @return whether @a lhs is equal to @a rhs
  9470. @complexity Linear in the length of the JSON pointer
  9471. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9472. */
  9473. friend bool operator==(json_pointer const& lhs,
  9474. json_pointer const& rhs) noexcept
  9475. {
  9476. return lhs.reference_tokens == rhs.reference_tokens;
  9477. }
  9478. /*!
  9479. @brief compares two JSON pointers for inequality
  9480. @param[in] lhs JSON pointer to compare
  9481. @param[in] rhs JSON pointer to compare
  9482. @return whether @a lhs is not equal @a rhs
  9483. @complexity Linear in the length of the JSON pointer
  9484. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9485. */
  9486. friend bool operator!=(json_pointer const& lhs,
  9487. json_pointer const& rhs) noexcept
  9488. {
  9489. return not (lhs == rhs);
  9490. }
  9491. /// the reference tokens
  9492. std::vector<std::string> reference_tokens;
  9493. };
  9494. } // namespace nlohmann
  9495. // #include <nlohmann/detail/json_ref.hpp>
  9496. #include <initializer_list>
  9497. #include <utility>
  9498. // #include <nlohmann/detail/meta/type_traits.hpp>
  9499. namespace nlohmann
  9500. {
  9501. namespace detail
  9502. {
  9503. template<typename BasicJsonType>
  9504. class json_ref
  9505. {
  9506. public:
  9507. using value_type = BasicJsonType;
  9508. json_ref(value_type&& value)
  9509. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  9510. {}
  9511. json_ref(const value_type& value)
  9512. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  9513. {}
  9514. json_ref(std::initializer_list<json_ref> init)
  9515. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  9516. {}
  9517. template <
  9518. class... Args,
  9519. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  9520. json_ref(Args && ... args)
  9521. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value),
  9522. is_rvalue(true) {}
  9523. // class should be movable only
  9524. json_ref(json_ref&&) = default;
  9525. json_ref(const json_ref&) = delete;
  9526. json_ref& operator=(const json_ref&) = delete;
  9527. json_ref& operator=(json_ref&&) = delete;
  9528. ~json_ref() = default;
  9529. value_type moved_or_copied() const
  9530. {
  9531. if (is_rvalue)
  9532. {
  9533. return std::move(*value_ref);
  9534. }
  9535. return *value_ref;
  9536. }
  9537. value_type const& operator*() const
  9538. {
  9539. return *static_cast<value_type const*>(value_ref);
  9540. }
  9541. value_type const* operator->() const
  9542. {
  9543. return static_cast<value_type const*>(value_ref);
  9544. }
  9545. private:
  9546. mutable value_type owned_value = nullptr;
  9547. value_type* value_ref = nullptr;
  9548. const bool is_rvalue;
  9549. };
  9550. } // namespace detail
  9551. } // namespace nlohmann
  9552. // #include <nlohmann/detail/macro_scope.hpp>
  9553. // #include <nlohmann/detail/meta/cpp_future.hpp>
  9554. // #include <nlohmann/detail/meta/type_traits.hpp>
  9555. // #include <nlohmann/detail/output/binary_writer.hpp>
  9556. #include <algorithm> // reverse
  9557. #include <array> // array
  9558. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  9559. #include <cstring> // memcpy
  9560. #include <limits> // numeric_limits
  9561. #include <string> // string
  9562. // #include <nlohmann/detail/input/binary_reader.hpp>
  9563. // #include <nlohmann/detail/macro_scope.hpp>
  9564. // #include <nlohmann/detail/output/output_adapters.hpp>
  9565. #include <algorithm> // copy
  9566. #include <cstddef> // size_t
  9567. #include <ios> // streamsize
  9568. #include <iterator> // back_inserter
  9569. #include <memory> // shared_ptr, make_shared
  9570. #include <ostream> // basic_ostream
  9571. #include <string> // basic_string
  9572. #include <vector> // vector
  9573. // #include <nlohmann/detail/macro_scope.hpp>
  9574. namespace nlohmann
  9575. {
  9576. namespace detail
  9577. {
  9578. /// abstract output adapter interface
  9579. template<typename CharType> struct output_adapter_protocol
  9580. {
  9581. virtual void write_character(CharType c) = 0;
  9582. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  9583. virtual ~output_adapter_protocol() = default;
  9584. };
  9585. /// a type to simplify interfaces
  9586. template<typename CharType>
  9587. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  9588. /// output adapter for byte vectors
  9589. template<typename CharType>
  9590. class output_vector_adapter : public output_adapter_protocol<CharType>
  9591. {
  9592. public:
  9593. explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
  9594. : v(vec)
  9595. {}
  9596. void write_character(CharType c) override
  9597. {
  9598. v.push_back(c);
  9599. }
  9600. JSON_HEDLEY_NON_NULL(2)
  9601. void write_characters(const CharType* s, std::size_t length) override
  9602. {
  9603. std::copy(s, s + length, std::back_inserter(v));
  9604. }
  9605. private:
  9606. std::vector<CharType>& v;
  9607. };
  9608. /// output adapter for output streams
  9609. template<typename CharType>
  9610. class output_stream_adapter : public output_adapter_protocol<CharType>
  9611. {
  9612. public:
  9613. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  9614. : stream(s)
  9615. {}
  9616. void write_character(CharType c) override
  9617. {
  9618. stream.put(c);
  9619. }
  9620. JSON_HEDLEY_NON_NULL(2)
  9621. void write_characters(const CharType* s, std::size_t length) override
  9622. {
  9623. stream.write(s, static_cast<std::streamsize>(length));
  9624. }
  9625. private:
  9626. std::basic_ostream<CharType>& stream;
  9627. };
  9628. /// output adapter for basic_string
  9629. template<typename CharType, typename StringType = std::basic_string<CharType>>
  9630. class output_string_adapter : public output_adapter_protocol<CharType>
  9631. {
  9632. public:
  9633. explicit output_string_adapter(StringType& s) noexcept
  9634. : str(s)
  9635. {}
  9636. void write_character(CharType c) override
  9637. {
  9638. str.push_back(c);
  9639. }
  9640. JSON_HEDLEY_NON_NULL(2)
  9641. void write_characters(const CharType* s, std::size_t length) override
  9642. {
  9643. str.append(s, length);
  9644. }
  9645. private:
  9646. StringType& str;
  9647. };
  9648. template<typename CharType, typename StringType = std::basic_string<CharType>>
  9649. class output_adapter
  9650. {
  9651. public:
  9652. output_adapter(std::vector<CharType>& vec)
  9653. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  9654. output_adapter(std::basic_ostream<CharType>& s)
  9655. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  9656. output_adapter(StringType& s)
  9657. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  9658. operator output_adapter_t<CharType>()
  9659. {
  9660. return oa;
  9661. }
  9662. private:
  9663. output_adapter_t<CharType> oa = nullptr;
  9664. };
  9665. } // namespace detail
  9666. } // namespace nlohmann
  9667. namespace nlohmann
  9668. {
  9669. namespace detail
  9670. {
  9671. ///////////////////
  9672. // binary writer //
  9673. ///////////////////
  9674. /*!
  9675. @brief serialization to CBOR and MessagePack values
  9676. */
  9677. template<typename BasicJsonType, typename CharType>
  9678. class binary_writer
  9679. {
  9680. using string_t = typename BasicJsonType::string_t;
  9681. public:
  9682. /*!
  9683. @brief create a binary writer
  9684. @param[in] adapter output adapter to write to
  9685. */
  9686. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  9687. {
  9688. assert(oa);
  9689. }
  9690. /*!
  9691. @param[in] j JSON value to serialize
  9692. @pre j.type() == value_t::object
  9693. */
  9694. void write_bson(const BasicJsonType& j)
  9695. {
  9696. switch (j.type())
  9697. {
  9698. case value_t::object:
  9699. {
  9700. write_bson_object(*j.m_value.object);
  9701. break;
  9702. }
  9703. default:
  9704. {
  9705. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
  9706. }
  9707. }
  9708. }
  9709. /*!
  9710. @param[in] j JSON value to serialize
  9711. */
  9712. void write_cbor(const BasicJsonType& j)
  9713. {
  9714. switch (j.type())
  9715. {
  9716. case value_t::null:
  9717. {
  9718. oa->write_character(to_char_type(0xF6));
  9719. break;
  9720. }
  9721. case value_t::boolean:
  9722. {
  9723. oa->write_character(j.m_value.boolean
  9724. ? to_char_type(0xF5)
  9725. : to_char_type(0xF4));
  9726. break;
  9727. }
  9728. case value_t::number_integer:
  9729. {
  9730. if (j.m_value.number_integer >= 0)
  9731. {
  9732. // CBOR does not differentiate between positive signed
  9733. // integers and unsigned integers. Therefore, we used the
  9734. // code from the value_t::number_unsigned case here.
  9735. if (j.m_value.number_integer <= 0x17)
  9736. {
  9737. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  9738. }
  9739. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  9740. {
  9741. oa->write_character(to_char_type(0x18));
  9742. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  9743. }
  9744. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  9745. {
  9746. oa->write_character(to_char_type(0x19));
  9747. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  9748. }
  9749. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  9750. {
  9751. oa->write_character(to_char_type(0x1A));
  9752. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  9753. }
  9754. else
  9755. {
  9756. oa->write_character(to_char_type(0x1B));
  9757. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  9758. }
  9759. }
  9760. else
  9761. {
  9762. // The conversions below encode the sign in the first
  9763. // byte, and the value is converted to a positive number.
  9764. const auto positive_number = -1 - j.m_value.number_integer;
  9765. if (j.m_value.number_integer >= -24)
  9766. {
  9767. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  9768. }
  9769. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  9770. {
  9771. oa->write_character(to_char_type(0x38));
  9772. write_number(static_cast<std::uint8_t>(positive_number));
  9773. }
  9774. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  9775. {
  9776. oa->write_character(to_char_type(0x39));
  9777. write_number(static_cast<std::uint16_t>(positive_number));
  9778. }
  9779. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  9780. {
  9781. oa->write_character(to_char_type(0x3A));
  9782. write_number(static_cast<std::uint32_t>(positive_number));
  9783. }
  9784. else
  9785. {
  9786. oa->write_character(to_char_type(0x3B));
  9787. write_number(static_cast<std::uint64_t>(positive_number));
  9788. }
  9789. }
  9790. break;
  9791. }
  9792. case value_t::number_unsigned:
  9793. {
  9794. if (j.m_value.number_unsigned <= 0x17)
  9795. {
  9796. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  9797. }
  9798. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  9799. {
  9800. oa->write_character(to_char_type(0x18));
  9801. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  9802. }
  9803. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  9804. {
  9805. oa->write_character(to_char_type(0x19));
  9806. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  9807. }
  9808. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  9809. {
  9810. oa->write_character(to_char_type(0x1A));
  9811. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  9812. }
  9813. else
  9814. {
  9815. oa->write_character(to_char_type(0x1B));
  9816. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  9817. }
  9818. break;
  9819. }
  9820. case value_t::number_float:
  9821. {
  9822. oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
  9823. write_number(j.m_value.number_float);
  9824. break;
  9825. }
  9826. case value_t::string:
  9827. {
  9828. // step 1: write control byte and the string length
  9829. const auto N = j.m_value.string->size();
  9830. if (N <= 0x17)
  9831. {
  9832. write_number(static_cast<std::uint8_t>(0x60 + N));
  9833. }
  9834. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  9835. {
  9836. oa->write_character(to_char_type(0x78));
  9837. write_number(static_cast<std::uint8_t>(N));
  9838. }
  9839. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  9840. {
  9841. oa->write_character(to_char_type(0x79));
  9842. write_number(static_cast<std::uint16_t>(N));
  9843. }
  9844. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  9845. {
  9846. oa->write_character(to_char_type(0x7A));
  9847. write_number(static_cast<std::uint32_t>(N));
  9848. }
  9849. // LCOV_EXCL_START
  9850. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  9851. {
  9852. oa->write_character(to_char_type(0x7B));
  9853. write_number(static_cast<std::uint64_t>(N));
  9854. }
  9855. // LCOV_EXCL_STOP
  9856. // step 2: write the string
  9857. oa->write_characters(
  9858. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  9859. j.m_value.string->size());
  9860. break;
  9861. }
  9862. case value_t::array:
  9863. {
  9864. // step 1: write control byte and the array size
  9865. const auto N = j.m_value.array->size();
  9866. if (N <= 0x17)
  9867. {
  9868. write_number(static_cast<std::uint8_t>(0x80 + N));
  9869. }
  9870. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  9871. {
  9872. oa->write_character(to_char_type(0x98));
  9873. write_number(static_cast<std::uint8_t>(N));
  9874. }
  9875. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  9876. {
  9877. oa->write_character(to_char_type(0x99));
  9878. write_number(static_cast<std::uint16_t>(N));
  9879. }
  9880. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  9881. {
  9882. oa->write_character(to_char_type(0x9A));
  9883. write_number(static_cast<std::uint32_t>(N));
  9884. }
  9885. // LCOV_EXCL_START
  9886. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  9887. {
  9888. oa->write_character(to_char_type(0x9B));
  9889. write_number(static_cast<std::uint64_t>(N));
  9890. }
  9891. // LCOV_EXCL_STOP
  9892. // step 2: write each element
  9893. for (const auto& el : *j.m_value.array)
  9894. {
  9895. write_cbor(el);
  9896. }
  9897. break;
  9898. }
  9899. case value_t::object:
  9900. {
  9901. // step 1: write control byte and the object size
  9902. const auto N = j.m_value.object->size();
  9903. if (N <= 0x17)
  9904. {
  9905. write_number(static_cast<std::uint8_t>(0xA0 + N));
  9906. }
  9907. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  9908. {
  9909. oa->write_character(to_char_type(0xB8));
  9910. write_number(static_cast<std::uint8_t>(N));
  9911. }
  9912. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  9913. {
  9914. oa->write_character(to_char_type(0xB9));
  9915. write_number(static_cast<std::uint16_t>(N));
  9916. }
  9917. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  9918. {
  9919. oa->write_character(to_char_type(0xBA));
  9920. write_number(static_cast<std::uint32_t>(N));
  9921. }
  9922. // LCOV_EXCL_START
  9923. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  9924. {
  9925. oa->write_character(to_char_type(0xBB));
  9926. write_number(static_cast<std::uint64_t>(N));
  9927. }
  9928. // LCOV_EXCL_STOP
  9929. // step 2: write each element
  9930. for (const auto& el : *j.m_value.object)
  9931. {
  9932. write_cbor(el.first);
  9933. write_cbor(el.second);
  9934. }
  9935. break;
  9936. }
  9937. default:
  9938. break;
  9939. }
  9940. }
  9941. /*!
  9942. @param[in] j JSON value to serialize
  9943. */
  9944. void write_msgpack(const BasicJsonType& j)
  9945. {
  9946. switch (j.type())
  9947. {
  9948. case value_t::null: // nil
  9949. {
  9950. oa->write_character(to_char_type(0xC0));
  9951. break;
  9952. }
  9953. case value_t::boolean: // true and false
  9954. {
  9955. oa->write_character(j.m_value.boolean
  9956. ? to_char_type(0xC3)
  9957. : to_char_type(0xC2));
  9958. break;
  9959. }
  9960. case value_t::number_integer:
  9961. {
  9962. if (j.m_value.number_integer >= 0)
  9963. {
  9964. // MessagePack does not differentiate between positive
  9965. // signed integers and unsigned integers. Therefore, we used
  9966. // the code from the value_t::number_unsigned case here.
  9967. if (j.m_value.number_unsigned < 128)
  9968. {
  9969. // positive fixnum
  9970. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  9971. }
  9972. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  9973. {
  9974. // uint 8
  9975. oa->write_character(to_char_type(0xCC));
  9976. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  9977. }
  9978. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  9979. {
  9980. // uint 16
  9981. oa->write_character(to_char_type(0xCD));
  9982. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  9983. }
  9984. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  9985. {
  9986. // uint 32
  9987. oa->write_character(to_char_type(0xCE));
  9988. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  9989. }
  9990. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  9991. {
  9992. // uint 64
  9993. oa->write_character(to_char_type(0xCF));
  9994. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  9995. }
  9996. }
  9997. else
  9998. {
  9999. if (j.m_value.number_integer >= -32)
  10000. {
  10001. // negative fixnum
  10002. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10003. }
  10004. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() and
  10005. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  10006. {
  10007. // int 8
  10008. oa->write_character(to_char_type(0xD0));
  10009. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10010. }
  10011. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() and
  10012. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  10013. {
  10014. // int 16
  10015. oa->write_character(to_char_type(0xD1));
  10016. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  10017. }
  10018. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() and
  10019. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  10020. {
  10021. // int 32
  10022. oa->write_character(to_char_type(0xD2));
  10023. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  10024. }
  10025. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() and
  10026. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  10027. {
  10028. // int 64
  10029. oa->write_character(to_char_type(0xD3));
  10030. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  10031. }
  10032. }
  10033. break;
  10034. }
  10035. case value_t::number_unsigned:
  10036. {
  10037. if (j.m_value.number_unsigned < 128)
  10038. {
  10039. // positive fixnum
  10040. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10041. }
  10042. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10043. {
  10044. // uint 8
  10045. oa->write_character(to_char_type(0xCC));
  10046. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10047. }
  10048. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10049. {
  10050. // uint 16
  10051. oa->write_character(to_char_type(0xCD));
  10052. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10053. }
  10054. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10055. {
  10056. // uint 32
  10057. oa->write_character(to_char_type(0xCE));
  10058. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10059. }
  10060. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  10061. {
  10062. // uint 64
  10063. oa->write_character(to_char_type(0xCF));
  10064. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10065. }
  10066. break;
  10067. }
  10068. case value_t::number_float:
  10069. {
  10070. oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
  10071. write_number(j.m_value.number_float);
  10072. break;
  10073. }
  10074. case value_t::string:
  10075. {
  10076. // step 1: write control byte and the string length
  10077. const auto N = j.m_value.string->size();
  10078. if (N <= 31)
  10079. {
  10080. // fixstr
  10081. write_number(static_cast<std::uint8_t>(0xA0 | N));
  10082. }
  10083. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10084. {
  10085. // str 8
  10086. oa->write_character(to_char_type(0xD9));
  10087. write_number(static_cast<std::uint8_t>(N));
  10088. }
  10089. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10090. {
  10091. // str 16
  10092. oa->write_character(to_char_type(0xDA));
  10093. write_number(static_cast<std::uint16_t>(N));
  10094. }
  10095. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10096. {
  10097. // str 32
  10098. oa->write_character(to_char_type(0xDB));
  10099. write_number(static_cast<std::uint32_t>(N));
  10100. }
  10101. // step 2: write the string
  10102. oa->write_characters(
  10103. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10104. j.m_value.string->size());
  10105. break;
  10106. }
  10107. case value_t::array:
  10108. {
  10109. // step 1: write control byte and the array size
  10110. const auto N = j.m_value.array->size();
  10111. if (N <= 15)
  10112. {
  10113. // fixarray
  10114. write_number(static_cast<std::uint8_t>(0x90 | N));
  10115. }
  10116. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10117. {
  10118. // array 16
  10119. oa->write_character(to_char_type(0xDC));
  10120. write_number(static_cast<std::uint16_t>(N));
  10121. }
  10122. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10123. {
  10124. // array 32
  10125. oa->write_character(to_char_type(0xDD));
  10126. write_number(static_cast<std::uint32_t>(N));
  10127. }
  10128. // step 2: write each element
  10129. for (const auto& el : *j.m_value.array)
  10130. {
  10131. write_msgpack(el);
  10132. }
  10133. break;
  10134. }
  10135. case value_t::object:
  10136. {
  10137. // step 1: write control byte and the object size
  10138. const auto N = j.m_value.object->size();
  10139. if (N <= 15)
  10140. {
  10141. // fixmap
  10142. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  10143. }
  10144. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10145. {
  10146. // map 16
  10147. oa->write_character(to_char_type(0xDE));
  10148. write_number(static_cast<std::uint16_t>(N));
  10149. }
  10150. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10151. {
  10152. // map 32
  10153. oa->write_character(to_char_type(0xDF));
  10154. write_number(static_cast<std::uint32_t>(N));
  10155. }
  10156. // step 2: write each element
  10157. for (const auto& el : *j.m_value.object)
  10158. {
  10159. write_msgpack(el.first);
  10160. write_msgpack(el.second);
  10161. }
  10162. break;
  10163. }
  10164. default:
  10165. break;
  10166. }
  10167. }
  10168. /*!
  10169. @param[in] j JSON value to serialize
  10170. @param[in] use_count whether to use '#' prefixes (optimized format)
  10171. @param[in] use_type whether to use '$' prefixes (optimized format)
  10172. @param[in] add_prefix whether prefixes need to be used for this value
  10173. */
  10174. void write_ubjson(const BasicJsonType& j, const bool use_count,
  10175. const bool use_type, const bool add_prefix = true)
  10176. {
  10177. switch (j.type())
  10178. {
  10179. case value_t::null:
  10180. {
  10181. if (add_prefix)
  10182. {
  10183. oa->write_character(to_char_type('Z'));
  10184. }
  10185. break;
  10186. }
  10187. case value_t::boolean:
  10188. {
  10189. if (add_prefix)
  10190. {
  10191. oa->write_character(j.m_value.boolean
  10192. ? to_char_type('T')
  10193. : to_char_type('F'));
  10194. }
  10195. break;
  10196. }
  10197. case value_t::number_integer:
  10198. {
  10199. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  10200. break;
  10201. }
  10202. case value_t::number_unsigned:
  10203. {
  10204. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  10205. break;
  10206. }
  10207. case value_t::number_float:
  10208. {
  10209. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  10210. break;
  10211. }
  10212. case value_t::string:
  10213. {
  10214. if (add_prefix)
  10215. {
  10216. oa->write_character(to_char_type('S'));
  10217. }
  10218. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  10219. oa->write_characters(
  10220. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10221. j.m_value.string->size());
  10222. break;
  10223. }
  10224. case value_t::array:
  10225. {
  10226. if (add_prefix)
  10227. {
  10228. oa->write_character(to_char_type('['));
  10229. }
  10230. bool prefix_required = true;
  10231. if (use_type and not j.m_value.array->empty())
  10232. {
  10233. assert(use_count);
  10234. const CharType first_prefix = ubjson_prefix(j.front());
  10235. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  10236. [this, first_prefix](const BasicJsonType & v)
  10237. {
  10238. return ubjson_prefix(v) == first_prefix;
  10239. });
  10240. if (same_prefix)
  10241. {
  10242. prefix_required = false;
  10243. oa->write_character(to_char_type('$'));
  10244. oa->write_character(first_prefix);
  10245. }
  10246. }
  10247. if (use_count)
  10248. {
  10249. oa->write_character(to_char_type('#'));
  10250. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  10251. }
  10252. for (const auto& el : *j.m_value.array)
  10253. {
  10254. write_ubjson(el, use_count, use_type, prefix_required);
  10255. }
  10256. if (not use_count)
  10257. {
  10258. oa->write_character(to_char_type(']'));
  10259. }
  10260. break;
  10261. }
  10262. case value_t::object:
  10263. {
  10264. if (add_prefix)
  10265. {
  10266. oa->write_character(to_char_type('{'));
  10267. }
  10268. bool prefix_required = true;
  10269. if (use_type and not j.m_value.object->empty())
  10270. {
  10271. assert(use_count);
  10272. const CharType first_prefix = ubjson_prefix(j.front());
  10273. const bool same_prefix = std::all_of(j.begin(), j.end(),
  10274. [this, first_prefix](const BasicJsonType & v)
  10275. {
  10276. return ubjson_prefix(v) == first_prefix;
  10277. });
  10278. if (same_prefix)
  10279. {
  10280. prefix_required = false;
  10281. oa->write_character(to_char_type('$'));
  10282. oa->write_character(first_prefix);
  10283. }
  10284. }
  10285. if (use_count)
  10286. {
  10287. oa->write_character(to_char_type('#'));
  10288. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  10289. }
  10290. for (const auto& el : *j.m_value.object)
  10291. {
  10292. write_number_with_ubjson_prefix(el.first.size(), true);
  10293. oa->write_characters(
  10294. reinterpret_cast<const CharType*>(el.first.c_str()),
  10295. el.first.size());
  10296. write_ubjson(el.second, use_count, use_type, prefix_required);
  10297. }
  10298. if (not use_count)
  10299. {
  10300. oa->write_character(to_char_type('}'));
  10301. }
  10302. break;
  10303. }
  10304. default:
  10305. break;
  10306. }
  10307. }
  10308. private:
  10309. //////////
  10310. // BSON //
  10311. //////////
  10312. /*!
  10313. @return The size of a BSON document entry header, including the id marker
  10314. and the entry name size (and its null-terminator).
  10315. */
  10316. static std::size_t calc_bson_entry_header_size(const string_t& name)
  10317. {
  10318. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  10319. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  10320. {
  10321. JSON_THROW(out_of_range::create(409,
  10322. "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
  10323. }
  10324. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  10325. }
  10326. /*!
  10327. @brief Writes the given @a element_type and @a name to the output adapter
  10328. */
  10329. void write_bson_entry_header(const string_t& name,
  10330. const std::uint8_t element_type)
  10331. {
  10332. oa->write_character(to_char_type(element_type)); // boolean
  10333. oa->write_characters(
  10334. reinterpret_cast<const CharType*>(name.c_str()),
  10335. name.size() + 1u);
  10336. }
  10337. /*!
  10338. @brief Writes a BSON element with key @a name and boolean value @a value
  10339. */
  10340. void write_bson_boolean(const string_t& name,
  10341. const bool value)
  10342. {
  10343. write_bson_entry_header(name, 0x08);
  10344. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  10345. }
  10346. /*!
  10347. @brief Writes a BSON element with key @a name and double value @a value
  10348. */
  10349. void write_bson_double(const string_t& name,
  10350. const double value)
  10351. {
  10352. write_bson_entry_header(name, 0x01);
  10353. write_number<double, true>(value);
  10354. }
  10355. /*!
  10356. @return The size of the BSON-encoded string in @a value
  10357. */
  10358. static std::size_t calc_bson_string_size(const string_t& value)
  10359. {
  10360. return sizeof(std::int32_t) + value.size() + 1ul;
  10361. }
  10362. /*!
  10363. @brief Writes a BSON element with key @a name and string value @a value
  10364. */
  10365. void write_bson_string(const string_t& name,
  10366. const string_t& value)
  10367. {
  10368. write_bson_entry_header(name, 0x02);
  10369. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  10370. oa->write_characters(
  10371. reinterpret_cast<const CharType*>(value.c_str()),
  10372. value.size() + 1);
  10373. }
  10374. /*!
  10375. @brief Writes a BSON element with key @a name and null value
  10376. */
  10377. void write_bson_null(const string_t& name)
  10378. {
  10379. write_bson_entry_header(name, 0x0A);
  10380. }
  10381. /*!
  10382. @return The size of the BSON-encoded integer @a value
  10383. */
  10384. static std::size_t calc_bson_integer_size(const std::int64_t value)
  10385. {
  10386. return (std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)()
  10387. ? sizeof(std::int32_t)
  10388. : sizeof(std::int64_t);
  10389. }
  10390. /*!
  10391. @brief Writes a BSON element with key @a name and integer @a value
  10392. */
  10393. void write_bson_integer(const string_t& name,
  10394. const std::int64_t value)
  10395. {
  10396. if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)())
  10397. {
  10398. write_bson_entry_header(name, 0x10); // int32
  10399. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  10400. }
  10401. else
  10402. {
  10403. write_bson_entry_header(name, 0x12); // int64
  10404. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  10405. }
  10406. }
  10407. /*!
  10408. @return The size of the BSON-encoded unsigned integer in @a j
  10409. */
  10410. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  10411. {
  10412. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10413. ? sizeof(std::int32_t)
  10414. : sizeof(std::int64_t);
  10415. }
  10416. /*!
  10417. @brief Writes a BSON element with key @a name and unsigned @a value
  10418. */
  10419. void write_bson_unsigned(const string_t& name,
  10420. const std::uint64_t value)
  10421. {
  10422. if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10423. {
  10424. write_bson_entry_header(name, 0x10 /* int32 */);
  10425. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  10426. }
  10427. else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  10428. {
  10429. write_bson_entry_header(name, 0x12 /* int64 */);
  10430. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  10431. }
  10432. else
  10433. {
  10434. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
  10435. }
  10436. }
  10437. /*!
  10438. @brief Writes a BSON element with key @a name and object @a value
  10439. */
  10440. void write_bson_object_entry(const string_t& name,
  10441. const typename BasicJsonType::object_t& value)
  10442. {
  10443. write_bson_entry_header(name, 0x03); // object
  10444. write_bson_object(value);
  10445. }
  10446. /*!
  10447. @return The size of the BSON-encoded array @a value
  10448. */
  10449. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  10450. {
  10451. std::size_t embedded_document_size = 0ul;
  10452. std::size_t array_index = 0ul;
  10453. for (const auto& el : value)
  10454. {
  10455. embedded_document_size += calc_bson_element_size(std::to_string(array_index++), el);
  10456. }
  10457. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  10458. }
  10459. /*!
  10460. @brief Writes a BSON element with key @a name and array @a value
  10461. */
  10462. void write_bson_array(const string_t& name,
  10463. const typename BasicJsonType::array_t& value)
  10464. {
  10465. write_bson_entry_header(name, 0x04); // array
  10466. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  10467. std::size_t array_index = 0ul;
  10468. for (const auto& el : value)
  10469. {
  10470. write_bson_element(std::to_string(array_index++), el);
  10471. }
  10472. oa->write_character(to_char_type(0x00));
  10473. }
  10474. /*!
  10475. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  10476. @return The calculated size for the BSON document entry for @a j with the given @a name.
  10477. */
  10478. static std::size_t calc_bson_element_size(const string_t& name,
  10479. const BasicJsonType& j)
  10480. {
  10481. const auto header_size = calc_bson_entry_header_size(name);
  10482. switch (j.type())
  10483. {
  10484. case value_t::object:
  10485. return header_size + calc_bson_object_size(*j.m_value.object);
  10486. case value_t::array:
  10487. return header_size + calc_bson_array_size(*j.m_value.array);
  10488. case value_t::boolean:
  10489. return header_size + 1ul;
  10490. case value_t::number_float:
  10491. return header_size + 8ul;
  10492. case value_t::number_integer:
  10493. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  10494. case value_t::number_unsigned:
  10495. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  10496. case value_t::string:
  10497. return header_size + calc_bson_string_size(*j.m_value.string);
  10498. case value_t::null:
  10499. return header_size + 0ul;
  10500. // LCOV_EXCL_START
  10501. default:
  10502. assert(false);
  10503. return 0ul;
  10504. // LCOV_EXCL_STOP
  10505. }
  10506. }
  10507. /*!
  10508. @brief Serializes the JSON value @a j to BSON and associates it with the
  10509. key @a name.
  10510. @param name The name to associate with the JSON entity @a j within the
  10511. current BSON document
  10512. @return The size of the BSON entry
  10513. */
  10514. void write_bson_element(const string_t& name,
  10515. const BasicJsonType& j)
  10516. {
  10517. switch (j.type())
  10518. {
  10519. case value_t::object:
  10520. return write_bson_object_entry(name, *j.m_value.object);
  10521. case value_t::array:
  10522. return write_bson_array(name, *j.m_value.array);
  10523. case value_t::boolean:
  10524. return write_bson_boolean(name, j.m_value.boolean);
  10525. case value_t::number_float:
  10526. return write_bson_double(name, j.m_value.number_float);
  10527. case value_t::number_integer:
  10528. return write_bson_integer(name, j.m_value.number_integer);
  10529. case value_t::number_unsigned:
  10530. return write_bson_unsigned(name, j.m_value.number_unsigned);
  10531. case value_t::string:
  10532. return write_bson_string(name, *j.m_value.string);
  10533. case value_t::null:
  10534. return write_bson_null(name);
  10535. // LCOV_EXCL_START
  10536. default:
  10537. assert(false);
  10538. return;
  10539. // LCOV_EXCL_STOP
  10540. }
  10541. }
  10542. /*!
  10543. @brief Calculates the size of the BSON serialization of the given
  10544. JSON-object @a j.
  10545. @param[in] j JSON value to serialize
  10546. @pre j.type() == value_t::object
  10547. */
  10548. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  10549. {
  10550. std::size_t document_size = std::accumulate(value.begin(), value.end(), 0ul,
  10551. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  10552. {
  10553. return result += calc_bson_element_size(el.first, el.second);
  10554. });
  10555. return sizeof(std::int32_t) + document_size + 1ul;
  10556. }
  10557. /*!
  10558. @param[in] j JSON value to serialize
  10559. @pre j.type() == value_t::object
  10560. */
  10561. void write_bson_object(const typename BasicJsonType::object_t& value)
  10562. {
  10563. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  10564. for (const auto& el : value)
  10565. {
  10566. write_bson_element(el.first, el.second);
  10567. }
  10568. oa->write_character(to_char_type(0x00));
  10569. }
  10570. //////////
  10571. // CBOR //
  10572. //////////
  10573. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  10574. {
  10575. return to_char_type(0xFA); // Single-Precision Float
  10576. }
  10577. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  10578. {
  10579. return to_char_type(0xFB); // Double-Precision Float
  10580. }
  10581. /////////////
  10582. // MsgPack //
  10583. /////////////
  10584. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  10585. {
  10586. return to_char_type(0xCA); // float 32
  10587. }
  10588. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  10589. {
  10590. return to_char_type(0xCB); // float 64
  10591. }
  10592. ////////////
  10593. // UBJSON //
  10594. ////////////
  10595. // UBJSON: write number (floating point)
  10596. template<typename NumberType, typename std::enable_if<
  10597. std::is_floating_point<NumberType>::value, int>::type = 0>
  10598. void write_number_with_ubjson_prefix(const NumberType n,
  10599. const bool add_prefix)
  10600. {
  10601. if (add_prefix)
  10602. {
  10603. oa->write_character(get_ubjson_float_prefix(n));
  10604. }
  10605. write_number(n);
  10606. }
  10607. // UBJSON: write number (unsigned integer)
  10608. template<typename NumberType, typename std::enable_if<
  10609. std::is_unsigned<NumberType>::value, int>::type = 0>
  10610. void write_number_with_ubjson_prefix(const NumberType n,
  10611. const bool add_prefix)
  10612. {
  10613. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  10614. {
  10615. if (add_prefix)
  10616. {
  10617. oa->write_character(to_char_type('i')); // int8
  10618. }
  10619. write_number(static_cast<std::uint8_t>(n));
  10620. }
  10621. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  10622. {
  10623. if (add_prefix)
  10624. {
  10625. oa->write_character(to_char_type('U')); // uint8
  10626. }
  10627. write_number(static_cast<std::uint8_t>(n));
  10628. }
  10629. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  10630. {
  10631. if (add_prefix)
  10632. {
  10633. oa->write_character(to_char_type('I')); // int16
  10634. }
  10635. write_number(static_cast<std::int16_t>(n));
  10636. }
  10637. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10638. {
  10639. if (add_prefix)
  10640. {
  10641. oa->write_character(to_char_type('l')); // int32
  10642. }
  10643. write_number(static_cast<std::int32_t>(n));
  10644. }
  10645. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  10646. {
  10647. if (add_prefix)
  10648. {
  10649. oa->write_character(to_char_type('L')); // int64
  10650. }
  10651. write_number(static_cast<std::int64_t>(n));
  10652. }
  10653. else
  10654. {
  10655. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  10656. }
  10657. }
  10658. // UBJSON: write number (signed integer)
  10659. template<typename NumberType, typename std::enable_if<
  10660. std::is_signed<NumberType>::value and
  10661. not std::is_floating_point<NumberType>::value, int>::type = 0>
  10662. void write_number_with_ubjson_prefix(const NumberType n,
  10663. const bool add_prefix)
  10664. {
  10665. if ((std::numeric_limits<std::int8_t>::min)() <= n and n <= (std::numeric_limits<std::int8_t>::max)())
  10666. {
  10667. if (add_prefix)
  10668. {
  10669. oa->write_character(to_char_type('i')); // int8
  10670. }
  10671. write_number(static_cast<std::int8_t>(n));
  10672. }
  10673. else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n and n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)()))
  10674. {
  10675. if (add_prefix)
  10676. {
  10677. oa->write_character(to_char_type('U')); // uint8
  10678. }
  10679. write_number(static_cast<std::uint8_t>(n));
  10680. }
  10681. else if ((std::numeric_limits<std::int16_t>::min)() <= n and n <= (std::numeric_limits<std::int16_t>::max)())
  10682. {
  10683. if (add_prefix)
  10684. {
  10685. oa->write_character(to_char_type('I')); // int16
  10686. }
  10687. write_number(static_cast<std::int16_t>(n));
  10688. }
  10689. else if ((std::numeric_limits<std::int32_t>::min)() <= n and n <= (std::numeric_limits<std::int32_t>::max)())
  10690. {
  10691. if (add_prefix)
  10692. {
  10693. oa->write_character(to_char_type('l')); // int32
  10694. }
  10695. write_number(static_cast<std::int32_t>(n));
  10696. }
  10697. else if ((std::numeric_limits<std::int64_t>::min)() <= n and n <= (std::numeric_limits<std::int64_t>::max)())
  10698. {
  10699. if (add_prefix)
  10700. {
  10701. oa->write_character(to_char_type('L')); // int64
  10702. }
  10703. write_number(static_cast<std::int64_t>(n));
  10704. }
  10705. // LCOV_EXCL_START
  10706. else
  10707. {
  10708. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  10709. }
  10710. // LCOV_EXCL_STOP
  10711. }
  10712. /*!
  10713. @brief determine the type prefix of container values
  10714. @note This function does not need to be 100% accurate when it comes to
  10715. integer limits. In case a number exceeds the limits of int64_t,
  10716. this will be detected by a later call to function
  10717. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  10718. value that does not fit the previous limits.
  10719. */
  10720. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  10721. {
  10722. switch (j.type())
  10723. {
  10724. case value_t::null:
  10725. return 'Z';
  10726. case value_t::boolean:
  10727. return j.m_value.boolean ? 'T' : 'F';
  10728. case value_t::number_integer:
  10729. {
  10730. if ((std::numeric_limits<std::int8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  10731. {
  10732. return 'i';
  10733. }
  10734. if ((std::numeric_limits<std::uint8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  10735. {
  10736. return 'U';
  10737. }
  10738. if ((std::numeric_limits<std::int16_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  10739. {
  10740. return 'I';
  10741. }
  10742. if ((std::numeric_limits<std::int32_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  10743. {
  10744. return 'l';
  10745. }
  10746. // no check and assume int64_t (see note above)
  10747. return 'L';
  10748. }
  10749. case value_t::number_unsigned:
  10750. {
  10751. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  10752. {
  10753. return 'i';
  10754. }
  10755. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  10756. {
  10757. return 'U';
  10758. }
  10759. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  10760. {
  10761. return 'I';
  10762. }
  10763. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10764. {
  10765. return 'l';
  10766. }
  10767. // no check and assume int64_t (see note above)
  10768. return 'L';
  10769. }
  10770. case value_t::number_float:
  10771. return get_ubjson_float_prefix(j.m_value.number_float);
  10772. case value_t::string:
  10773. return 'S';
  10774. case value_t::array:
  10775. return '[';
  10776. case value_t::object:
  10777. return '{';
  10778. default: // discarded values
  10779. return 'N';
  10780. }
  10781. }
  10782. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  10783. {
  10784. return 'd'; // float 32
  10785. }
  10786. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  10787. {
  10788. return 'D'; // float 64
  10789. }
  10790. ///////////////////////
  10791. // Utility functions //
  10792. ///////////////////////
  10793. /*
  10794. @brief write a number to output input
  10795. @param[in] n number of type @a NumberType
  10796. @tparam NumberType the type of the number
  10797. @tparam OutputIsLittleEndian Set to true if output data is
  10798. required to be little endian
  10799. @note This function needs to respect the system's endianess, because bytes
  10800. in CBOR, MessagePack, and UBJSON are stored in network order (big
  10801. endian) and therefore need reordering on little endian systems.
  10802. */
  10803. template<typename NumberType, bool OutputIsLittleEndian = false>
  10804. void write_number(const NumberType n)
  10805. {
  10806. // step 1: write number to array of length NumberType
  10807. std::array<CharType, sizeof(NumberType)> vec;
  10808. std::memcpy(vec.data(), &n, sizeof(NumberType));
  10809. // step 2: write array to output (with possible reordering)
  10810. if (is_little_endian != OutputIsLittleEndian)
  10811. {
  10812. // reverse byte order prior to conversion if necessary
  10813. std::reverse(vec.begin(), vec.end());
  10814. }
  10815. oa->write_characters(vec.data(), sizeof(NumberType));
  10816. }
  10817. public:
  10818. // The following to_char_type functions are implement the conversion
  10819. // between uint8_t and CharType. In case CharType is not unsigned,
  10820. // such a conversion is required to allow values greater than 128.
  10821. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  10822. template < typename C = CharType,
  10823. enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value > * = nullptr >
  10824. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  10825. {
  10826. return *reinterpret_cast<char*>(&x);
  10827. }
  10828. template < typename C = CharType,
  10829. enable_if_t < std::is_signed<C>::value and std::is_unsigned<char>::value > * = nullptr >
  10830. static CharType to_char_type(std::uint8_t x) noexcept
  10831. {
  10832. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  10833. static_assert(std::is_pod<CharType>::value, "CharType must be POD");
  10834. CharType result;
  10835. std::memcpy(&result, &x, sizeof(x));
  10836. return result;
  10837. }
  10838. template<typename C = CharType,
  10839. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  10840. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  10841. {
  10842. return x;
  10843. }
  10844. template < typename InputCharType, typename C = CharType,
  10845. enable_if_t <
  10846. std::is_signed<C>::value and
  10847. std::is_signed<char>::value and
  10848. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  10849. > * = nullptr >
  10850. static constexpr CharType to_char_type(InputCharType x) noexcept
  10851. {
  10852. return x;
  10853. }
  10854. private:
  10855. /// whether we can assume little endianess
  10856. const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
  10857. /// the output
  10858. output_adapter_t<CharType> oa = nullptr;
  10859. };
  10860. } // namespace detail
  10861. } // namespace nlohmann
  10862. // #include <nlohmann/detail/output/output_adapters.hpp>
  10863. // #include <nlohmann/detail/output/serializer.hpp>
  10864. #include <algorithm> // reverse, remove, fill, find, none_of
  10865. #include <array> // array
  10866. #include <cassert> // assert
  10867. #include <ciso646> // and, or
  10868. #include <clocale> // localeconv, lconv
  10869. #include <cmath> // labs, isfinite, isnan, signbit
  10870. #include <cstddef> // size_t, ptrdiff_t
  10871. #include <cstdint> // uint8_t
  10872. #include <cstdio> // snprintf
  10873. #include <limits> // numeric_limits
  10874. #include <string> // string
  10875. #include <type_traits> // is_same
  10876. #include <utility> // move
  10877. // #include <nlohmann/detail/conversions/to_chars.hpp>
  10878. #include <array> // array
  10879. #include <cassert> // assert
  10880. #include <ciso646> // or, and, not
  10881. #include <cmath> // signbit, isfinite
  10882. #include <cstdint> // intN_t, uintN_t
  10883. #include <cstring> // memcpy, memmove
  10884. #include <limits> // numeric_limits
  10885. #include <type_traits> // conditional
  10886. // #include <nlohmann/detail/macro_scope.hpp>
  10887. namespace nlohmann
  10888. {
  10889. namespace detail
  10890. {
  10891. /*!
  10892. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  10893. conversion.
  10894. This implementation is a slightly modified version of the reference
  10895. implementation which may be obtained from
  10896. http://florian.loitsch.com/publications (bench.tar.gz).
  10897. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  10898. For a detailed description of the algorithm see:
  10899. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  10900. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  10901. Language Design and Implementation, PLDI 2010
  10902. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  10903. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  10904. Design and Implementation, PLDI 1996
  10905. */
  10906. namespace dtoa_impl
  10907. {
  10908. template <typename Target, typename Source>
  10909. Target reinterpret_bits(const Source source)
  10910. {
  10911. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  10912. Target target;
  10913. std::memcpy(&target, &source, sizeof(Source));
  10914. return target;
  10915. }
  10916. struct diyfp // f * 2^e
  10917. {
  10918. static constexpr int kPrecision = 64; // = q
  10919. std::uint64_t f = 0;
  10920. int e = 0;
  10921. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  10922. /*!
  10923. @brief returns x - y
  10924. @pre x.e == y.e and x.f >= y.f
  10925. */
  10926. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  10927. {
  10928. assert(x.e == y.e);
  10929. assert(x.f >= y.f);
  10930. return {x.f - y.f, x.e};
  10931. }
  10932. /*!
  10933. @brief returns x * y
  10934. @note The result is rounded. (Only the upper q bits are returned.)
  10935. */
  10936. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  10937. {
  10938. static_assert(kPrecision == 64, "internal error");
  10939. // Computes:
  10940. // f = round((x.f * y.f) / 2^q)
  10941. // e = x.e + y.e + q
  10942. // Emulate the 64-bit * 64-bit multiplication:
  10943. //
  10944. // p = u * v
  10945. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  10946. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  10947. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  10948. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  10949. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  10950. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  10951. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  10952. //
  10953. // (Since Q might be larger than 2^32 - 1)
  10954. //
  10955. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  10956. //
  10957. // (Q_hi + H does not overflow a 64-bit int)
  10958. //
  10959. // = p_lo + 2^64 p_hi
  10960. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  10961. const std::uint64_t u_hi = x.f >> 32u;
  10962. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  10963. const std::uint64_t v_hi = y.f >> 32u;
  10964. const std::uint64_t p0 = u_lo * v_lo;
  10965. const std::uint64_t p1 = u_lo * v_hi;
  10966. const std::uint64_t p2 = u_hi * v_lo;
  10967. const std::uint64_t p3 = u_hi * v_hi;
  10968. const std::uint64_t p0_hi = p0 >> 32u;
  10969. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  10970. const std::uint64_t p1_hi = p1 >> 32u;
  10971. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  10972. const std::uint64_t p2_hi = p2 >> 32u;
  10973. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  10974. // The full product might now be computed as
  10975. //
  10976. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  10977. // p_lo = p0_lo + (Q << 32)
  10978. //
  10979. // But in this particular case here, the full p_lo is not required.
  10980. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  10981. // Q_hi + 1 does not overflow).
  10982. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  10983. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  10984. return {h, x.e + y.e + 64};
  10985. }
  10986. /*!
  10987. @brief normalize x such that the significand is >= 2^(q-1)
  10988. @pre x.f != 0
  10989. */
  10990. static diyfp normalize(diyfp x) noexcept
  10991. {
  10992. assert(x.f != 0);
  10993. while ((x.f >> 63u) == 0)
  10994. {
  10995. x.f <<= 1u;
  10996. x.e--;
  10997. }
  10998. return x;
  10999. }
  11000. /*!
  11001. @brief normalize x such that the result has the exponent E
  11002. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  11003. */
  11004. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  11005. {
  11006. const int delta = x.e - target_exponent;
  11007. assert(delta >= 0);
  11008. assert(((x.f << delta) >> delta) == x.f);
  11009. return {x.f << delta, target_exponent};
  11010. }
  11011. };
  11012. struct boundaries
  11013. {
  11014. diyfp w;
  11015. diyfp minus;
  11016. diyfp plus;
  11017. };
  11018. /*!
  11019. Compute the (normalized) diyfp representing the input number 'value' and its
  11020. boundaries.
  11021. @pre value must be finite and positive
  11022. */
  11023. template <typename FloatType>
  11024. boundaries compute_boundaries(FloatType value)
  11025. {
  11026. assert(std::isfinite(value));
  11027. assert(value > 0);
  11028. // Convert the IEEE representation into a diyfp.
  11029. //
  11030. // If v is denormal:
  11031. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  11032. // If v is normalized:
  11033. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  11034. static_assert(std::numeric_limits<FloatType>::is_iec559,
  11035. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  11036. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  11037. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  11038. constexpr int kMinExp = 1 - kBias;
  11039. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  11040. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  11041. const std::uint64_t bits = reinterpret_bits<bits_type>(value);
  11042. const std::uint64_t E = bits >> (kPrecision - 1);
  11043. const std::uint64_t F = bits & (kHiddenBit - 1);
  11044. const bool is_denormal = E == 0;
  11045. const diyfp v = is_denormal
  11046. ? diyfp(F, kMinExp)
  11047. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  11048. // Compute the boundaries m- and m+ of the floating-point value
  11049. // v = f * 2^e.
  11050. //
  11051. // Determine v- and v+, the floating-point predecessor and successor if v,
  11052. // respectively.
  11053. //
  11054. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  11055. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  11056. //
  11057. // v+ = v + 2^e
  11058. //
  11059. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  11060. // between m- and m+ round to v, regardless of how the input rounding
  11061. // algorithm breaks ties.
  11062. //
  11063. // ---+-------------+-------------+-------------+-------------+--- (A)
  11064. // v- m- v m+ v+
  11065. //
  11066. // -----------------+------+------+-------------+-------------+--- (B)
  11067. // v- m- v m+ v+
  11068. const bool lower_boundary_is_closer = F == 0 and E > 1;
  11069. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  11070. const diyfp m_minus = lower_boundary_is_closer
  11071. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  11072. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  11073. // Determine the normalized w+ = m+.
  11074. const diyfp w_plus = diyfp::normalize(m_plus);
  11075. // Determine w- = m- such that e_(w-) = e_(w+).
  11076. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  11077. return {diyfp::normalize(v), w_minus, w_plus};
  11078. }
  11079. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  11080. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  11081. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  11082. //
  11083. // alpha <= e = e_c + e_w + q <= gamma
  11084. //
  11085. // or
  11086. //
  11087. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  11088. // <= f_c * f_w * 2^gamma
  11089. //
  11090. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  11091. //
  11092. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  11093. //
  11094. // or
  11095. //
  11096. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  11097. //
  11098. // The choice of (alpha,gamma) determines the size of the table and the form of
  11099. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  11100. // in practice:
  11101. //
  11102. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  11103. // processed independently: An integral part p1, and a fractional part p2:
  11104. //
  11105. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  11106. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  11107. // = p1 + p2 * 2^e
  11108. //
  11109. // The conversion of p1 into decimal form requires a series of divisions and
  11110. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  11111. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  11112. // achieved by choosing
  11113. //
  11114. // -e >= 32 or e <= -32 := gamma
  11115. //
  11116. // In order to convert the fractional part
  11117. //
  11118. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  11119. //
  11120. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  11121. // d[-i] are extracted in order:
  11122. //
  11123. // (10 * p2) div 2^-e = d[-1]
  11124. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  11125. //
  11126. // The multiplication by 10 must not overflow. It is sufficient to choose
  11127. //
  11128. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  11129. //
  11130. // Since p2 = f mod 2^-e < 2^-e,
  11131. //
  11132. // -e <= 60 or e >= -60 := alpha
  11133. constexpr int kAlpha = -60;
  11134. constexpr int kGamma = -32;
  11135. struct cached_power // c = f * 2^e ~= 10^k
  11136. {
  11137. std::uint64_t f;
  11138. int e;
  11139. int k;
  11140. };
  11141. /*!
  11142. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  11143. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  11144. satisfies (Definition 3.2 from [1])
  11145. alpha <= e_c + e + q <= gamma.
  11146. */
  11147. inline cached_power get_cached_power_for_binary_exponent(int e)
  11148. {
  11149. // Now
  11150. //
  11151. // alpha <= e_c + e + q <= gamma (1)
  11152. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  11153. //
  11154. // and since the c's are normalized, 2^(q-1) <= f_c,
  11155. //
  11156. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  11157. // ==> 2^(alpha - e - 1) <= c
  11158. //
  11159. // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as
  11160. //
  11161. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  11162. // = ceil( (alpha - e - 1) * log_10(2) )
  11163. //
  11164. // From the paper:
  11165. // "In theory the result of the procedure could be wrong since c is rounded,
  11166. // and the computation itself is approximated [...]. In practice, however,
  11167. // this simple function is sufficient."
  11168. //
  11169. // For IEEE double precision floating-point numbers converted into
  11170. // normalized diyfp's w = f * 2^e, with q = 64,
  11171. //
  11172. // e >= -1022 (min IEEE exponent)
  11173. // -52 (p - 1)
  11174. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  11175. // -11 (normalize the diyfp)
  11176. // = -1137
  11177. //
  11178. // and
  11179. //
  11180. // e <= +1023 (max IEEE exponent)
  11181. // -52 (p - 1)
  11182. // -11 (normalize the diyfp)
  11183. // = 960
  11184. //
  11185. // This binary exponent range [-1137,960] results in a decimal exponent
  11186. // range [-307,324]. One does not need to store a cached power for each
  11187. // k in this range. For each such k it suffices to find a cached power
  11188. // such that the exponent of the product lies in [alpha,gamma].
  11189. // This implies that the difference of the decimal exponents of adjacent
  11190. // table entries must be less than or equal to
  11191. //
  11192. // floor( (gamma - alpha) * log_10(2) ) = 8.
  11193. //
  11194. // (A smaller distance gamma-alpha would require a larger table.)
  11195. // NB:
  11196. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  11197. constexpr int kCachedPowersMinDecExp = -300;
  11198. constexpr int kCachedPowersDecStep = 8;
  11199. static constexpr std::array<cached_power, 79> kCachedPowers =
  11200. {
  11201. {
  11202. { 0xAB70FE17C79AC6CA, -1060, -300 },
  11203. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  11204. { 0xBE5691EF416BD60C, -1007, -284 },
  11205. { 0x8DD01FAD907FFC3C, -980, -276 },
  11206. { 0xD3515C2831559A83, -954, -268 },
  11207. { 0x9D71AC8FADA6C9B5, -927, -260 },
  11208. { 0xEA9C227723EE8BCB, -901, -252 },
  11209. { 0xAECC49914078536D, -874, -244 },
  11210. { 0x823C12795DB6CE57, -847, -236 },
  11211. { 0xC21094364DFB5637, -821, -228 },
  11212. { 0x9096EA6F3848984F, -794, -220 },
  11213. { 0xD77485CB25823AC7, -768, -212 },
  11214. { 0xA086CFCD97BF97F4, -741, -204 },
  11215. { 0xEF340A98172AACE5, -715, -196 },
  11216. { 0xB23867FB2A35B28E, -688, -188 },
  11217. { 0x84C8D4DFD2C63F3B, -661, -180 },
  11218. { 0xC5DD44271AD3CDBA, -635, -172 },
  11219. { 0x936B9FCEBB25C996, -608, -164 },
  11220. { 0xDBAC6C247D62A584, -582, -156 },
  11221. { 0xA3AB66580D5FDAF6, -555, -148 },
  11222. { 0xF3E2F893DEC3F126, -529, -140 },
  11223. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  11224. { 0x87625F056C7C4A8B, -475, -124 },
  11225. { 0xC9BCFF6034C13053, -449, -116 },
  11226. { 0x964E858C91BA2655, -422, -108 },
  11227. { 0xDFF9772470297EBD, -396, -100 },
  11228. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  11229. { 0xF8A95FCF88747D94, -343, -84 },
  11230. { 0xB94470938FA89BCF, -316, -76 },
  11231. { 0x8A08F0F8BF0F156B, -289, -68 },
  11232. { 0xCDB02555653131B6, -263, -60 },
  11233. { 0x993FE2C6D07B7FAC, -236, -52 },
  11234. { 0xE45C10C42A2B3B06, -210, -44 },
  11235. { 0xAA242499697392D3, -183, -36 },
  11236. { 0xFD87B5F28300CA0E, -157, -28 },
  11237. { 0xBCE5086492111AEB, -130, -20 },
  11238. { 0x8CBCCC096F5088CC, -103, -12 },
  11239. { 0xD1B71758E219652C, -77, -4 },
  11240. { 0x9C40000000000000, -50, 4 },
  11241. { 0xE8D4A51000000000, -24, 12 },
  11242. { 0xAD78EBC5AC620000, 3, 20 },
  11243. { 0x813F3978F8940984, 30, 28 },
  11244. { 0xC097CE7BC90715B3, 56, 36 },
  11245. { 0x8F7E32CE7BEA5C70, 83, 44 },
  11246. { 0xD5D238A4ABE98068, 109, 52 },
  11247. { 0x9F4F2726179A2245, 136, 60 },
  11248. { 0xED63A231D4C4FB27, 162, 68 },
  11249. { 0xB0DE65388CC8ADA8, 189, 76 },
  11250. { 0x83C7088E1AAB65DB, 216, 84 },
  11251. { 0xC45D1DF942711D9A, 242, 92 },
  11252. { 0x924D692CA61BE758, 269, 100 },
  11253. { 0xDA01EE641A708DEA, 295, 108 },
  11254. { 0xA26DA3999AEF774A, 322, 116 },
  11255. { 0xF209787BB47D6B85, 348, 124 },
  11256. { 0xB454E4A179DD1877, 375, 132 },
  11257. { 0x865B86925B9BC5C2, 402, 140 },
  11258. { 0xC83553C5C8965D3D, 428, 148 },
  11259. { 0x952AB45CFA97A0B3, 455, 156 },
  11260. { 0xDE469FBD99A05FE3, 481, 164 },
  11261. { 0xA59BC234DB398C25, 508, 172 },
  11262. { 0xF6C69A72A3989F5C, 534, 180 },
  11263. { 0xB7DCBF5354E9BECE, 561, 188 },
  11264. { 0x88FCF317F22241E2, 588, 196 },
  11265. { 0xCC20CE9BD35C78A5, 614, 204 },
  11266. { 0x98165AF37B2153DF, 641, 212 },
  11267. { 0xE2A0B5DC971F303A, 667, 220 },
  11268. { 0xA8D9D1535CE3B396, 694, 228 },
  11269. { 0xFB9B7CD9A4A7443C, 720, 236 },
  11270. { 0xBB764C4CA7A44410, 747, 244 },
  11271. { 0x8BAB8EEFB6409C1A, 774, 252 },
  11272. { 0xD01FEF10A657842C, 800, 260 },
  11273. { 0x9B10A4E5E9913129, 827, 268 },
  11274. { 0xE7109BFBA19C0C9D, 853, 276 },
  11275. { 0xAC2820D9623BF429, 880, 284 },
  11276. { 0x80444B5E7AA7CF85, 907, 292 },
  11277. { 0xBF21E44003ACDD2D, 933, 300 },
  11278. { 0x8E679C2F5E44FF8F, 960, 308 },
  11279. { 0xD433179D9C8CB841, 986, 316 },
  11280. { 0x9E19DB92B4E31BA9, 1013, 324 },
  11281. }
  11282. };
  11283. // This computation gives exactly the same results for k as
  11284. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  11285. // for |e| <= 1500, but doesn't require floating-point operations.
  11286. // NB: log_10(2) ~= 78913 / 2^18
  11287. assert(e >= -1500);
  11288. assert(e <= 1500);
  11289. const int f = kAlpha - e - 1;
  11290. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  11291. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  11292. assert(index >= 0);
  11293. assert(static_cast<std::size_t>(index) < kCachedPowers.size());
  11294. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  11295. assert(kAlpha <= cached.e + e + 64);
  11296. assert(kGamma >= cached.e + e + 64);
  11297. return cached;
  11298. }
  11299. /*!
  11300. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  11301. For n == 0, returns 1 and sets pow10 := 1.
  11302. */
  11303. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  11304. {
  11305. // LCOV_EXCL_START
  11306. if (n >= 1000000000)
  11307. {
  11308. pow10 = 1000000000;
  11309. return 10;
  11310. }
  11311. // LCOV_EXCL_STOP
  11312. else if (n >= 100000000)
  11313. {
  11314. pow10 = 100000000;
  11315. return 9;
  11316. }
  11317. else if (n >= 10000000)
  11318. {
  11319. pow10 = 10000000;
  11320. return 8;
  11321. }
  11322. else if (n >= 1000000)
  11323. {
  11324. pow10 = 1000000;
  11325. return 7;
  11326. }
  11327. else if (n >= 100000)
  11328. {
  11329. pow10 = 100000;
  11330. return 6;
  11331. }
  11332. else if (n >= 10000)
  11333. {
  11334. pow10 = 10000;
  11335. return 5;
  11336. }
  11337. else if (n >= 1000)
  11338. {
  11339. pow10 = 1000;
  11340. return 4;
  11341. }
  11342. else if (n >= 100)
  11343. {
  11344. pow10 = 100;
  11345. return 3;
  11346. }
  11347. else if (n >= 10)
  11348. {
  11349. pow10 = 10;
  11350. return 2;
  11351. }
  11352. else
  11353. {
  11354. pow10 = 1;
  11355. return 1;
  11356. }
  11357. }
  11358. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  11359. std::uint64_t rest, std::uint64_t ten_k)
  11360. {
  11361. assert(len >= 1);
  11362. assert(dist <= delta);
  11363. assert(rest <= delta);
  11364. assert(ten_k > 0);
  11365. // <--------------------------- delta ---->
  11366. // <---- dist --------->
  11367. // --------------[------------------+-------------------]--------------
  11368. // M- w M+
  11369. //
  11370. // ten_k
  11371. // <------>
  11372. // <---- rest ---->
  11373. // --------------[------------------+----+--------------]--------------
  11374. // w V
  11375. // = buf * 10^k
  11376. //
  11377. // ten_k represents a unit-in-the-last-place in the decimal representation
  11378. // stored in buf.
  11379. // Decrement buf by ten_k while this takes buf closer to w.
  11380. // The tests are written in this order to avoid overflow in unsigned
  11381. // integer arithmetic.
  11382. while (rest < dist
  11383. and delta - rest >= ten_k
  11384. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  11385. {
  11386. assert(buf[len - 1] != '0');
  11387. buf[len - 1]--;
  11388. rest += ten_k;
  11389. }
  11390. }
  11391. /*!
  11392. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  11393. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  11394. */
  11395. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  11396. diyfp M_minus, diyfp w, diyfp M_plus)
  11397. {
  11398. static_assert(kAlpha >= -60, "internal error");
  11399. static_assert(kGamma <= -32, "internal error");
  11400. // Generates the digits (and the exponent) of a decimal floating-point
  11401. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  11402. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  11403. //
  11404. // <--------------------------- delta ---->
  11405. // <---- dist --------->
  11406. // --------------[------------------+-------------------]--------------
  11407. // M- w M+
  11408. //
  11409. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  11410. // V is in [M-,M+].
  11411. assert(M_plus.e >= kAlpha);
  11412. assert(M_plus.e <= kGamma);
  11413. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  11414. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  11415. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  11416. //
  11417. // M+ = f * 2^e
  11418. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  11419. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  11420. // = p1 + p2 * 2^e
  11421. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  11422. 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.)
  11423. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  11424. // 1)
  11425. //
  11426. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  11427. assert(p1 > 0);
  11428. std::uint32_t pow10;
  11429. const int k = find_largest_pow10(p1, pow10);
  11430. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  11431. //
  11432. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  11433. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  11434. //
  11435. // M+ = p1 + p2 * 2^e
  11436. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  11437. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  11438. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  11439. //
  11440. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  11441. //
  11442. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  11443. //
  11444. // but stop as soon as
  11445. //
  11446. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  11447. int n = k;
  11448. while (n > 0)
  11449. {
  11450. // Invariants:
  11451. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  11452. // pow10 = 10^(n-1) <= p1 < 10^n
  11453. //
  11454. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  11455. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  11456. //
  11457. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  11458. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  11459. //
  11460. assert(d <= 9);
  11461. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  11462. //
  11463. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  11464. //
  11465. p1 = r;
  11466. n--;
  11467. //
  11468. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  11469. // pow10 = 10^n
  11470. //
  11471. // Now check if enough digits have been generated.
  11472. // Compute
  11473. //
  11474. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  11475. //
  11476. // Note:
  11477. // Since rest and delta share the same exponent e, it suffices to
  11478. // compare the significands.
  11479. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  11480. if (rest <= delta)
  11481. {
  11482. // V = buffer * 10^n, with M- <= V <= M+.
  11483. decimal_exponent += n;
  11484. // We may now just stop. But instead look if the buffer could be
  11485. // decremented to bring V closer to w.
  11486. //
  11487. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  11488. // The rounding procedure works with diyfp's with an implicit
  11489. // exponent of e.
  11490. //
  11491. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  11492. //
  11493. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  11494. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  11495. return;
  11496. }
  11497. pow10 /= 10;
  11498. //
  11499. // pow10 = 10^(n-1) <= p1 < 10^n
  11500. // Invariants restored.
  11501. }
  11502. // 2)
  11503. //
  11504. // The digits of the integral part have been generated:
  11505. //
  11506. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  11507. // = buffer + p2 * 2^e
  11508. //
  11509. // Now generate the digits of the fractional part p2 * 2^e.
  11510. //
  11511. // Note:
  11512. // No decimal point is generated: the exponent is adjusted instead.
  11513. //
  11514. // p2 actually represents the fraction
  11515. //
  11516. // p2 * 2^e
  11517. // = p2 / 2^-e
  11518. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  11519. //
  11520. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  11521. //
  11522. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  11523. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  11524. //
  11525. // using
  11526. //
  11527. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  11528. // = ( d) * 2^-e + ( r)
  11529. //
  11530. // or
  11531. // 10^m * p2 * 2^e = d + r * 2^e
  11532. //
  11533. // i.e.
  11534. //
  11535. // M+ = buffer + p2 * 2^e
  11536. // = buffer + 10^-m * (d + r * 2^e)
  11537. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  11538. //
  11539. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  11540. assert(p2 > delta);
  11541. int m = 0;
  11542. for (;;)
  11543. {
  11544. // Invariant:
  11545. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  11546. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  11547. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  11548. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  11549. //
  11550. assert(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  11551. p2 *= 10;
  11552. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  11553. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  11554. //
  11555. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  11556. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  11557. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  11558. //
  11559. assert(d <= 9);
  11560. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  11561. //
  11562. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  11563. //
  11564. p2 = r;
  11565. m++;
  11566. //
  11567. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  11568. // Invariant restored.
  11569. // Check if enough digits have been generated.
  11570. //
  11571. // 10^-m * p2 * 2^e <= delta * 2^e
  11572. // p2 * 2^e <= 10^m * delta * 2^e
  11573. // p2 <= 10^m * delta
  11574. delta *= 10;
  11575. dist *= 10;
  11576. if (p2 <= delta)
  11577. {
  11578. break;
  11579. }
  11580. }
  11581. // V = buffer * 10^-m, with M- <= V <= M+.
  11582. decimal_exponent -= m;
  11583. // 1 ulp in the decimal representation is now 10^-m.
  11584. // Since delta and dist are now scaled by 10^m, we need to do the
  11585. // same with ulp in order to keep the units in sync.
  11586. //
  11587. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  11588. //
  11589. const std::uint64_t ten_m = one.f;
  11590. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  11591. // By construction this algorithm generates the shortest possible decimal
  11592. // number (Loitsch, Theorem 6.2) which rounds back to w.
  11593. // For an input number of precision p, at least
  11594. //
  11595. // N = 1 + ceil(p * log_10(2))
  11596. //
  11597. // decimal digits are sufficient to identify all binary floating-point
  11598. // numbers (Matula, "In-and-Out conversions").
  11599. // This implies that the algorithm does not produce more than N decimal
  11600. // digits.
  11601. //
  11602. // N = 17 for p = 53 (IEEE double precision)
  11603. // N = 9 for p = 24 (IEEE single precision)
  11604. }
  11605. /*!
  11606. v = buf * 10^decimal_exponent
  11607. len is the length of the buffer (number of decimal digits)
  11608. The buffer must be large enough, i.e. >= max_digits10.
  11609. */
  11610. JSON_HEDLEY_NON_NULL(1)
  11611. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  11612. diyfp m_minus, diyfp v, diyfp m_plus)
  11613. {
  11614. assert(m_plus.e == m_minus.e);
  11615. assert(m_plus.e == v.e);
  11616. // --------(-----------------------+-----------------------)-------- (A)
  11617. // m- v m+
  11618. //
  11619. // --------------------(-----------+-----------------------)-------- (B)
  11620. // m- v m+
  11621. //
  11622. // First scale v (and m- and m+) such that the exponent is in the range
  11623. // [alpha, gamma].
  11624. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  11625. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  11626. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  11627. const diyfp w = diyfp::mul(v, c_minus_k);
  11628. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  11629. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  11630. // ----(---+---)---------------(---+---)---------------(---+---)----
  11631. // w- w w+
  11632. // = c*m- = c*v = c*m+
  11633. //
  11634. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  11635. // w+ are now off by a small amount.
  11636. // In fact:
  11637. //
  11638. // w - v * 10^k < 1 ulp
  11639. //
  11640. // To account for this inaccuracy, add resp. subtract 1 ulp.
  11641. //
  11642. // --------+---[---------------(---+---)---------------]---+--------
  11643. // w- M- w M+ w+
  11644. //
  11645. // Now any number in [M-, M+] (bounds included) will round to w when input,
  11646. // regardless of how the input rounding algorithm breaks ties.
  11647. //
  11648. // And digit_gen generates the shortest possible such number in [M-, M+].
  11649. // Note that this does not mean that Grisu2 always generates the shortest
  11650. // possible number in the interval (m-, m+).
  11651. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  11652. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  11653. decimal_exponent = -cached.k; // = -(-k) = k
  11654. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  11655. }
  11656. /*!
  11657. v = buf * 10^decimal_exponent
  11658. len is the length of the buffer (number of decimal digits)
  11659. The buffer must be large enough, i.e. >= max_digits10.
  11660. */
  11661. template <typename FloatType>
  11662. JSON_HEDLEY_NON_NULL(1)
  11663. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  11664. {
  11665. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  11666. "internal error: not enough precision");
  11667. assert(std::isfinite(value));
  11668. assert(value > 0);
  11669. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  11670. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  11671. // decimal representations are not exactly "short".
  11672. //
  11673. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  11674. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  11675. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  11676. // does.
  11677. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  11678. // representation using the corresponding std::from_chars function recovers value exactly". That
  11679. // indicates that single precision floating-point numbers should be recovered using
  11680. // 'std::strtof'.
  11681. //
  11682. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  11683. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  11684. // value is off by 1 ulp.
  11685. #if 0
  11686. const boundaries w = compute_boundaries(static_cast<double>(value));
  11687. #else
  11688. const boundaries w = compute_boundaries(value);
  11689. #endif
  11690. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  11691. }
  11692. /*!
  11693. @brief appends a decimal representation of e to buf
  11694. @return a pointer to the element following the exponent.
  11695. @pre -1000 < e < 1000
  11696. */
  11697. JSON_HEDLEY_NON_NULL(1)
  11698. JSON_HEDLEY_RETURNS_NON_NULL
  11699. inline char* append_exponent(char* buf, int e)
  11700. {
  11701. assert(e > -1000);
  11702. assert(e < 1000);
  11703. if (e < 0)
  11704. {
  11705. e = -e;
  11706. *buf++ = '-';
  11707. }
  11708. else
  11709. {
  11710. *buf++ = '+';
  11711. }
  11712. auto k = static_cast<std::uint32_t>(e);
  11713. if (k < 10)
  11714. {
  11715. // Always print at least two digits in the exponent.
  11716. // This is for compatibility with printf("%g").
  11717. *buf++ = '0';
  11718. *buf++ = static_cast<char>('0' + k);
  11719. }
  11720. else if (k < 100)
  11721. {
  11722. *buf++ = static_cast<char>('0' + k / 10);
  11723. k %= 10;
  11724. *buf++ = static_cast<char>('0' + k);
  11725. }
  11726. else
  11727. {
  11728. *buf++ = static_cast<char>('0' + k / 100);
  11729. k %= 100;
  11730. *buf++ = static_cast<char>('0' + k / 10);
  11731. k %= 10;
  11732. *buf++ = static_cast<char>('0' + k);
  11733. }
  11734. return buf;
  11735. }
  11736. /*!
  11737. @brief prettify v = buf * 10^decimal_exponent
  11738. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  11739. notation. Otherwise it will be printed in exponential notation.
  11740. @pre min_exp < 0
  11741. @pre max_exp > 0
  11742. */
  11743. JSON_HEDLEY_NON_NULL(1)
  11744. JSON_HEDLEY_RETURNS_NON_NULL
  11745. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  11746. int min_exp, int max_exp)
  11747. {
  11748. assert(min_exp < 0);
  11749. assert(max_exp > 0);
  11750. const int k = len;
  11751. const int n = len + decimal_exponent;
  11752. // v = buf * 10^(n-k)
  11753. // k is the length of the buffer (number of decimal digits)
  11754. // n is the position of the decimal point relative to the start of the buffer.
  11755. if (k <= n and n <= max_exp)
  11756. {
  11757. // digits[000]
  11758. // len <= max_exp + 2
  11759. std::memset(buf + k, '0', static_cast<size_t>(n - k));
  11760. // Make it look like a floating-point number (#362, #378)
  11761. buf[n + 0] = '.';
  11762. buf[n + 1] = '0';
  11763. return buf + (n + 2);
  11764. }
  11765. if (0 < n and n <= max_exp)
  11766. {
  11767. // dig.its
  11768. // len <= max_digits10 + 1
  11769. assert(k > n);
  11770. std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
  11771. buf[n] = '.';
  11772. return buf + (k + 1);
  11773. }
  11774. if (min_exp < n and n <= 0)
  11775. {
  11776. // 0.[000]digits
  11777. // len <= 2 + (-min_exp - 1) + max_digits10
  11778. std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
  11779. buf[0] = '0';
  11780. buf[1] = '.';
  11781. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  11782. return buf + (2 + (-n) + k);
  11783. }
  11784. if (k == 1)
  11785. {
  11786. // dE+123
  11787. // len <= 1 + 5
  11788. buf += 1;
  11789. }
  11790. else
  11791. {
  11792. // d.igitsE+123
  11793. // len <= max_digits10 + 1 + 5
  11794. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
  11795. buf[1] = '.';
  11796. buf += 1 + k;
  11797. }
  11798. *buf++ = 'e';
  11799. return append_exponent(buf, n - 1);
  11800. }
  11801. } // namespace dtoa_impl
  11802. /*!
  11803. @brief generates a decimal representation of the floating-point number value in [first, last).
  11804. The format of the resulting decimal representation is similar to printf's %g
  11805. format. Returns an iterator pointing past-the-end of the decimal representation.
  11806. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  11807. @note The buffer must be large enough.
  11808. @note The result is NOT null-terminated.
  11809. */
  11810. template <typename FloatType>
  11811. JSON_HEDLEY_NON_NULL(1, 2)
  11812. JSON_HEDLEY_RETURNS_NON_NULL
  11813. char* to_chars(char* first, const char* last, FloatType value)
  11814. {
  11815. static_cast<void>(last); // maybe unused - fix warning
  11816. assert(std::isfinite(value));
  11817. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  11818. if (std::signbit(value))
  11819. {
  11820. value = -value;
  11821. *first++ = '-';
  11822. }
  11823. if (value == 0) // +-0
  11824. {
  11825. *first++ = '0';
  11826. // Make it look like a floating-point number (#362, #378)
  11827. *first++ = '.';
  11828. *first++ = '0';
  11829. return first;
  11830. }
  11831. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  11832. // Compute v = buffer * 10^decimal_exponent.
  11833. // The decimal digits are stored in the buffer, which needs to be interpreted
  11834. // as an unsigned decimal integer.
  11835. // len is the length of the buffer, i.e. the number of decimal digits.
  11836. int len = 0;
  11837. int decimal_exponent = 0;
  11838. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  11839. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  11840. // Format the buffer like printf("%.*g", prec, value)
  11841. constexpr int kMinExp = -4;
  11842. // Use digits10 here to increase compatibility with version 2.
  11843. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  11844. assert(last - first >= kMaxExp + 2);
  11845. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  11846. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  11847. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  11848. }
  11849. } // namespace detail
  11850. } // namespace nlohmann
  11851. // #include <nlohmann/detail/exceptions.hpp>
  11852. // #include <nlohmann/detail/macro_scope.hpp>
  11853. // #include <nlohmann/detail/meta/cpp_future.hpp>
  11854. // #include <nlohmann/detail/output/binary_writer.hpp>
  11855. // #include <nlohmann/detail/output/output_adapters.hpp>
  11856. // #include <nlohmann/detail/value_t.hpp>
  11857. namespace nlohmann
  11858. {
  11859. namespace detail
  11860. {
  11861. ///////////////////
  11862. // serialization //
  11863. ///////////////////
  11864. /// how to treat decoding errors
  11865. enum class error_handler_t
  11866. {
  11867. strict, ///< throw a type_error exception in case of invalid UTF-8
  11868. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  11869. ignore ///< ignore invalid UTF-8 sequences
  11870. };
  11871. template<typename BasicJsonType>
  11872. class serializer
  11873. {
  11874. using string_t = typename BasicJsonType::string_t;
  11875. using number_float_t = typename BasicJsonType::number_float_t;
  11876. using number_integer_t = typename BasicJsonType::number_integer_t;
  11877. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  11878. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  11879. static constexpr std::uint8_t UTF8_REJECT = 1;
  11880. public:
  11881. /*!
  11882. @param[in] s output stream to serialize to
  11883. @param[in] ichar indentation character to use
  11884. @param[in] error_handler_ how to react on decoding errors
  11885. */
  11886. serializer(output_adapter_t<char> s, const char ichar,
  11887. error_handler_t error_handler_ = error_handler_t::strict)
  11888. : o(std::move(s))
  11889. , loc(std::localeconv())
  11890. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep))
  11891. , decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point))
  11892. , indent_char(ichar)
  11893. , indent_string(512, indent_char)
  11894. , error_handler(error_handler_)
  11895. {}
  11896. // delete because of pointer members
  11897. serializer(const serializer&) = delete;
  11898. serializer& operator=(const serializer&) = delete;
  11899. serializer(serializer&&) = delete;
  11900. serializer& operator=(serializer&&) = delete;
  11901. ~serializer() = default;
  11902. /*!
  11903. @brief internal implementation of the serialization function
  11904. This function is called by the public member function dump and organizes
  11905. the serialization internally. The indentation level is propagated as
  11906. additional parameter. In case of arrays and objects, the function is
  11907. called recursively.
  11908. - strings and object keys are escaped using `escape_string()`
  11909. - integer numbers are converted implicitly via `operator<<`
  11910. - floating-point numbers are converted to a string using `"%g"` format
  11911. @param[in] val value to serialize
  11912. @param[in] pretty_print whether the output shall be pretty-printed
  11913. @param[in] indent_step the indent level
  11914. @param[in] current_indent the current indent level (only used internally)
  11915. */
  11916. void dump(const BasicJsonType& val, const bool pretty_print,
  11917. const bool ensure_ascii,
  11918. const unsigned int indent_step,
  11919. const unsigned int current_indent = 0)
  11920. {
  11921. switch (val.m_type)
  11922. {
  11923. case value_t::object:
  11924. {
  11925. if (val.m_value.object->empty())
  11926. {
  11927. o->write_characters("{}", 2);
  11928. return;
  11929. }
  11930. if (pretty_print)
  11931. {
  11932. o->write_characters("{\n", 2);
  11933. // variable to hold indentation for recursive calls
  11934. const auto new_indent = current_indent + indent_step;
  11935. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  11936. {
  11937. indent_string.resize(indent_string.size() * 2, ' ');
  11938. }
  11939. // first n-1 elements
  11940. auto i = val.m_value.object->cbegin();
  11941. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  11942. {
  11943. o->write_characters(indent_string.c_str(), new_indent);
  11944. o->write_character('\"');
  11945. dump_escaped(i->first, ensure_ascii);
  11946. o->write_characters("\": ", 3);
  11947. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  11948. o->write_characters(",\n", 2);
  11949. }
  11950. // last element
  11951. assert(i != val.m_value.object->cend());
  11952. assert(std::next(i) == val.m_value.object->cend());
  11953. o->write_characters(indent_string.c_str(), new_indent);
  11954. o->write_character('\"');
  11955. dump_escaped(i->first, ensure_ascii);
  11956. o->write_characters("\": ", 3);
  11957. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  11958. o->write_character('\n');
  11959. o->write_characters(indent_string.c_str(), current_indent);
  11960. o->write_character('}');
  11961. }
  11962. else
  11963. {
  11964. o->write_character('{');
  11965. // first n-1 elements
  11966. auto i = val.m_value.object->cbegin();
  11967. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  11968. {
  11969. o->write_character('\"');
  11970. dump_escaped(i->first, ensure_ascii);
  11971. o->write_characters("\":", 2);
  11972. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  11973. o->write_character(',');
  11974. }
  11975. // last element
  11976. assert(i != val.m_value.object->cend());
  11977. assert(std::next(i) == val.m_value.object->cend());
  11978. o->write_character('\"');
  11979. dump_escaped(i->first, ensure_ascii);
  11980. o->write_characters("\":", 2);
  11981. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  11982. o->write_character('}');
  11983. }
  11984. return;
  11985. }
  11986. case value_t::array:
  11987. {
  11988. if (val.m_value.array->empty())
  11989. {
  11990. o->write_characters("[]", 2);
  11991. return;
  11992. }
  11993. if (pretty_print)
  11994. {
  11995. o->write_characters("[\n", 2);
  11996. // variable to hold indentation for recursive calls
  11997. const auto new_indent = current_indent + indent_step;
  11998. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  11999. {
  12000. indent_string.resize(indent_string.size() * 2, ' ');
  12001. }
  12002. // first n-1 elements
  12003. for (auto i = val.m_value.array->cbegin();
  12004. i != val.m_value.array->cend() - 1; ++i)
  12005. {
  12006. o->write_characters(indent_string.c_str(), new_indent);
  12007. dump(*i, true, ensure_ascii, indent_step, new_indent);
  12008. o->write_characters(",\n", 2);
  12009. }
  12010. // last element
  12011. assert(not val.m_value.array->empty());
  12012. o->write_characters(indent_string.c_str(), new_indent);
  12013. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  12014. o->write_character('\n');
  12015. o->write_characters(indent_string.c_str(), current_indent);
  12016. o->write_character(']');
  12017. }
  12018. else
  12019. {
  12020. o->write_character('[');
  12021. // first n-1 elements
  12022. for (auto i = val.m_value.array->cbegin();
  12023. i != val.m_value.array->cend() - 1; ++i)
  12024. {
  12025. dump(*i, false, ensure_ascii, indent_step, current_indent);
  12026. o->write_character(',');
  12027. }
  12028. // last element
  12029. assert(not val.m_value.array->empty());
  12030. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  12031. o->write_character(']');
  12032. }
  12033. return;
  12034. }
  12035. case value_t::string:
  12036. {
  12037. o->write_character('\"');
  12038. dump_escaped(*val.m_value.string, ensure_ascii);
  12039. o->write_character('\"');
  12040. return;
  12041. }
  12042. case value_t::boolean:
  12043. {
  12044. if (val.m_value.boolean)
  12045. {
  12046. o->write_characters("true", 4);
  12047. }
  12048. else
  12049. {
  12050. o->write_characters("false", 5);
  12051. }
  12052. return;
  12053. }
  12054. case value_t::number_integer:
  12055. {
  12056. dump_integer(val.m_value.number_integer);
  12057. return;
  12058. }
  12059. case value_t::number_unsigned:
  12060. {
  12061. dump_integer(val.m_value.number_unsigned);
  12062. return;
  12063. }
  12064. case value_t::number_float:
  12065. {
  12066. dump_float(val.m_value.number_float);
  12067. return;
  12068. }
  12069. case value_t::discarded:
  12070. {
  12071. o->write_characters("<discarded>", 11);
  12072. return;
  12073. }
  12074. case value_t::null:
  12075. {
  12076. o->write_characters("null", 4);
  12077. return;
  12078. }
  12079. default: // LCOV_EXCL_LINE
  12080. assert(false); // LCOV_EXCL_LINE
  12081. }
  12082. }
  12083. private:
  12084. /*!
  12085. @brief dump escaped string
  12086. Escape a string by replacing certain special characters by a sequence of an
  12087. escape character (backslash) and another character and other control
  12088. characters by a sequence of "\u" followed by a four-digit hex
  12089. representation. The escaped string is written to output stream @a o.
  12090. @param[in] s the string to escape
  12091. @param[in] ensure_ascii whether to escape non-ASCII characters with
  12092. \uXXXX sequences
  12093. @complexity Linear in the length of string @a s.
  12094. */
  12095. void dump_escaped(const string_t& s, const bool ensure_ascii)
  12096. {
  12097. std::uint32_t codepoint;
  12098. std::uint8_t state = UTF8_ACCEPT;
  12099. std::size_t bytes = 0; // number of bytes written to string_buffer
  12100. // number of bytes written at the point of the last valid byte
  12101. std::size_t bytes_after_last_accept = 0;
  12102. std::size_t undumped_chars = 0;
  12103. for (std::size_t i = 0; i < s.size(); ++i)
  12104. {
  12105. const auto byte = static_cast<uint8_t>(s[i]);
  12106. switch (decode(state, codepoint, byte))
  12107. {
  12108. case UTF8_ACCEPT: // decode found a new code point
  12109. {
  12110. switch (codepoint)
  12111. {
  12112. case 0x08: // backspace
  12113. {
  12114. string_buffer[bytes++] = '\\';
  12115. string_buffer[bytes++] = 'b';
  12116. break;
  12117. }
  12118. case 0x09: // horizontal tab
  12119. {
  12120. string_buffer[bytes++] = '\\';
  12121. string_buffer[bytes++] = 't';
  12122. break;
  12123. }
  12124. case 0x0A: // newline
  12125. {
  12126. string_buffer[bytes++] = '\\';
  12127. string_buffer[bytes++] = 'n';
  12128. break;
  12129. }
  12130. case 0x0C: // formfeed
  12131. {
  12132. string_buffer[bytes++] = '\\';
  12133. string_buffer[bytes++] = 'f';
  12134. break;
  12135. }
  12136. case 0x0D: // carriage return
  12137. {
  12138. string_buffer[bytes++] = '\\';
  12139. string_buffer[bytes++] = 'r';
  12140. break;
  12141. }
  12142. case 0x22: // quotation mark
  12143. {
  12144. string_buffer[bytes++] = '\\';
  12145. string_buffer[bytes++] = '\"';
  12146. break;
  12147. }
  12148. case 0x5C: // reverse solidus
  12149. {
  12150. string_buffer[bytes++] = '\\';
  12151. string_buffer[bytes++] = '\\';
  12152. break;
  12153. }
  12154. default:
  12155. {
  12156. // escape control characters (0x00..0x1F) or, if
  12157. // ensure_ascii parameter is used, non-ASCII characters
  12158. if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
  12159. {
  12160. if (codepoint <= 0xFFFF)
  12161. {
  12162. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  12163. static_cast<std::uint16_t>(codepoint));
  12164. bytes += 6;
  12165. }
  12166. else
  12167. {
  12168. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  12169. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  12170. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  12171. bytes += 12;
  12172. }
  12173. }
  12174. else
  12175. {
  12176. // copy byte to buffer (all previous bytes
  12177. // been copied have in default case above)
  12178. string_buffer[bytes++] = s[i];
  12179. }
  12180. break;
  12181. }
  12182. }
  12183. // write buffer and reset index; there must be 13 bytes
  12184. // left, as this is the maximal number of bytes to be
  12185. // written ("\uxxxx\uxxxx\0") for one code point
  12186. if (string_buffer.size() - bytes < 13)
  12187. {
  12188. o->write_characters(string_buffer.data(), bytes);
  12189. bytes = 0;
  12190. }
  12191. // remember the byte position of this accept
  12192. bytes_after_last_accept = bytes;
  12193. undumped_chars = 0;
  12194. break;
  12195. }
  12196. case UTF8_REJECT: // decode found invalid UTF-8 byte
  12197. {
  12198. switch (error_handler)
  12199. {
  12200. case error_handler_t::strict:
  12201. {
  12202. std::string sn(3, '\0');
  12203. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  12204. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  12205. }
  12206. case error_handler_t::ignore:
  12207. case error_handler_t::replace:
  12208. {
  12209. // in case we saw this character the first time, we
  12210. // would like to read it again, because the byte
  12211. // may be OK for itself, but just not OK for the
  12212. // previous sequence
  12213. if (undumped_chars > 0)
  12214. {
  12215. --i;
  12216. }
  12217. // reset length buffer to the last accepted index;
  12218. // thus removing/ignoring the invalid characters
  12219. bytes = bytes_after_last_accept;
  12220. if (error_handler == error_handler_t::replace)
  12221. {
  12222. // add a replacement character
  12223. if (ensure_ascii)
  12224. {
  12225. string_buffer[bytes++] = '\\';
  12226. string_buffer[bytes++] = 'u';
  12227. string_buffer[bytes++] = 'f';
  12228. string_buffer[bytes++] = 'f';
  12229. string_buffer[bytes++] = 'f';
  12230. string_buffer[bytes++] = 'd';
  12231. }
  12232. else
  12233. {
  12234. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  12235. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  12236. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  12237. }
  12238. // write buffer and reset index; there must be 13 bytes
  12239. // left, as this is the maximal number of bytes to be
  12240. // written ("\uxxxx\uxxxx\0") for one code point
  12241. if (string_buffer.size() - bytes < 13)
  12242. {
  12243. o->write_characters(string_buffer.data(), bytes);
  12244. bytes = 0;
  12245. }
  12246. bytes_after_last_accept = bytes;
  12247. }
  12248. undumped_chars = 0;
  12249. // continue processing the string
  12250. state = UTF8_ACCEPT;
  12251. break;
  12252. }
  12253. default: // LCOV_EXCL_LINE
  12254. assert(false); // LCOV_EXCL_LINE
  12255. }
  12256. break;
  12257. }
  12258. default: // decode found yet incomplete multi-byte code point
  12259. {
  12260. if (not ensure_ascii)
  12261. {
  12262. // code point will not be escaped - copy byte to buffer
  12263. string_buffer[bytes++] = s[i];
  12264. }
  12265. ++undumped_chars;
  12266. break;
  12267. }
  12268. }
  12269. }
  12270. // we finished processing the string
  12271. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  12272. {
  12273. // write buffer
  12274. if (bytes > 0)
  12275. {
  12276. o->write_characters(string_buffer.data(), bytes);
  12277. }
  12278. }
  12279. else
  12280. {
  12281. // we finish reading, but do not accept: string was incomplete
  12282. switch (error_handler)
  12283. {
  12284. case error_handler_t::strict:
  12285. {
  12286. std::string sn(3, '\0');
  12287. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  12288. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  12289. }
  12290. case error_handler_t::ignore:
  12291. {
  12292. // write all accepted bytes
  12293. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  12294. break;
  12295. }
  12296. case error_handler_t::replace:
  12297. {
  12298. // write all accepted bytes
  12299. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  12300. // add a replacement character
  12301. if (ensure_ascii)
  12302. {
  12303. o->write_characters("\\ufffd", 6);
  12304. }
  12305. else
  12306. {
  12307. o->write_characters("\xEF\xBF\xBD", 3);
  12308. }
  12309. break;
  12310. }
  12311. default: // LCOV_EXCL_LINE
  12312. assert(false); // LCOV_EXCL_LINE
  12313. }
  12314. }
  12315. }
  12316. /*!
  12317. @brief count digits
  12318. Count the number of decimal (base 10) digits for an input unsigned integer.
  12319. @param[in] x unsigned integer number to count its digits
  12320. @return number of decimal digits
  12321. */
  12322. inline unsigned int count_digits(number_unsigned_t x) noexcept
  12323. {
  12324. unsigned int n_digits = 1;
  12325. for (;;)
  12326. {
  12327. if (x < 10)
  12328. {
  12329. return n_digits;
  12330. }
  12331. if (x < 100)
  12332. {
  12333. return n_digits + 1;
  12334. }
  12335. if (x < 1000)
  12336. {
  12337. return n_digits + 2;
  12338. }
  12339. if (x < 10000)
  12340. {
  12341. return n_digits + 3;
  12342. }
  12343. x = x / 10000u;
  12344. n_digits += 4;
  12345. }
  12346. }
  12347. /*!
  12348. @brief dump an integer
  12349. Dump a given integer to output stream @a o. Works internally with
  12350. @a number_buffer.
  12351. @param[in] x integer number (signed or unsigned) to dump
  12352. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  12353. */
  12354. template<typename NumberType, detail::enable_if_t<
  12355. std::is_same<NumberType, number_unsigned_t>::value or
  12356. std::is_same<NumberType, number_integer_t>::value,
  12357. int> = 0>
  12358. void dump_integer(NumberType x)
  12359. {
  12360. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  12361. {
  12362. {
  12363. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  12364. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  12365. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  12366. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  12367. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  12368. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  12369. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  12370. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  12371. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  12372. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  12373. }
  12374. };
  12375. // special case for "0"
  12376. if (x == 0)
  12377. {
  12378. o->write_character('0');
  12379. return;
  12380. }
  12381. // use a pointer to fill the buffer
  12382. auto buffer_ptr = number_buffer.begin();
  12383. const bool is_negative = std::is_same<NumberType, number_integer_t>::value and not(x >= 0); // see issue #755
  12384. number_unsigned_t abs_value;
  12385. unsigned int n_chars;
  12386. if (is_negative)
  12387. {
  12388. *buffer_ptr = '-';
  12389. abs_value = static_cast<number_unsigned_t>(std::abs(static_cast<std::intmax_t>(x)));
  12390. // account one more byte for the minus sign
  12391. n_chars = 1 + count_digits(abs_value);
  12392. }
  12393. else
  12394. {
  12395. abs_value = static_cast<number_unsigned_t>(x);
  12396. n_chars = count_digits(abs_value);
  12397. }
  12398. // spare 1 byte for '\0'
  12399. assert(n_chars < number_buffer.size() - 1);
  12400. // jump to the end to generate the string from backward
  12401. // so we later avoid reversing the result
  12402. buffer_ptr += n_chars;
  12403. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  12404. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  12405. while (abs_value >= 100)
  12406. {
  12407. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  12408. abs_value /= 100;
  12409. *(--buffer_ptr) = digits_to_99[digits_index][1];
  12410. *(--buffer_ptr) = digits_to_99[digits_index][0];
  12411. }
  12412. if (abs_value >= 10)
  12413. {
  12414. const auto digits_index = static_cast<unsigned>(abs_value);
  12415. *(--buffer_ptr) = digits_to_99[digits_index][1];
  12416. *(--buffer_ptr) = digits_to_99[digits_index][0];
  12417. }
  12418. else
  12419. {
  12420. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  12421. }
  12422. o->write_characters(number_buffer.data(), n_chars);
  12423. }
  12424. /*!
  12425. @brief dump a floating-point number
  12426. Dump a given floating-point number to output stream @a o. Works internally
  12427. with @a number_buffer.
  12428. @param[in] x floating-point number to dump
  12429. */
  12430. void dump_float(number_float_t x)
  12431. {
  12432. // NaN / inf
  12433. if (not std::isfinite(x))
  12434. {
  12435. o->write_characters("null", 4);
  12436. return;
  12437. }
  12438. // If number_float_t is an IEEE-754 single or double precision number,
  12439. // use the Grisu2 algorithm to produce short numbers which are
  12440. // guaranteed to round-trip, using strtof and strtod, resp.
  12441. //
  12442. // NB: The test below works if <long double> == <double>.
  12443. static constexpr bool is_ieee_single_or_double
  12444. = (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 24 and std::numeric_limits<number_float_t>::max_exponent == 128) or
  12445. (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 53 and std::numeric_limits<number_float_t>::max_exponent == 1024);
  12446. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  12447. }
  12448. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  12449. {
  12450. char* begin = number_buffer.data();
  12451. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  12452. o->write_characters(begin, static_cast<size_t>(end - begin));
  12453. }
  12454. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  12455. {
  12456. // get number of digits for a float -> text -> float round-trip
  12457. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  12458. // the actual conversion
  12459. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  12460. // negative value indicates an error
  12461. assert(len > 0);
  12462. // check if buffer was large enough
  12463. assert(static_cast<std::size_t>(len) < number_buffer.size());
  12464. // erase thousands separator
  12465. if (thousands_sep != '\0')
  12466. {
  12467. const auto end = std::remove(number_buffer.begin(),
  12468. number_buffer.begin() + len, thousands_sep);
  12469. std::fill(end, number_buffer.end(), '\0');
  12470. assert((end - number_buffer.begin()) <= len);
  12471. len = (end - number_buffer.begin());
  12472. }
  12473. // convert decimal point to '.'
  12474. if (decimal_point != '\0' and decimal_point != '.')
  12475. {
  12476. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  12477. if (dec_pos != number_buffer.end())
  12478. {
  12479. *dec_pos = '.';
  12480. }
  12481. }
  12482. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  12483. // determine if need to append ".0"
  12484. const bool value_is_int_like =
  12485. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  12486. [](char c)
  12487. {
  12488. return c == '.' or c == 'e';
  12489. });
  12490. if (value_is_int_like)
  12491. {
  12492. o->write_characters(".0", 2);
  12493. }
  12494. }
  12495. /*!
  12496. @brief check whether a string is UTF-8 encoded
  12497. The function checks each byte of a string whether it is UTF-8 encoded. The
  12498. result of the check is stored in the @a state parameter. The function must
  12499. be called initially with state 0 (accept). State 1 means the string must
  12500. be rejected, because the current byte is not allowed. If the string is
  12501. completely processed, but the state is non-zero, the string ended
  12502. prematurely; that is, the last byte indicated more bytes should have
  12503. followed.
  12504. @param[in,out] state the state of the decoding
  12505. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  12506. @param[in] byte next byte to decode
  12507. @return new state
  12508. @note The function has been edited: a std::array is used.
  12509. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  12510. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  12511. */
  12512. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  12513. {
  12514. static const std::array<std::uint8_t, 400> utf8d =
  12515. {
  12516. {
  12517. 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
  12518. 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
  12519. 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
  12520. 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
  12521. 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
  12522. 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
  12523. 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
  12524. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  12525. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  12526. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  12527. 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
  12528. 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
  12529. 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
  12530. 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
  12531. }
  12532. };
  12533. const std::uint8_t type = utf8d[byte];
  12534. codep = (state != UTF8_ACCEPT)
  12535. ? (byte & 0x3fu) | (codep << 6u)
  12536. : (0xFFu >> type) & (byte);
  12537. state = utf8d[256u + state * 16u + type];
  12538. return state;
  12539. }
  12540. private:
  12541. /// the output of the serializer
  12542. output_adapter_t<char> o = nullptr;
  12543. /// a (hopefully) large enough character buffer
  12544. std::array<char, 64> number_buffer{{}};
  12545. /// the locale
  12546. const std::lconv* loc = nullptr;
  12547. /// the locale's thousand separator character
  12548. const char thousands_sep = '\0';
  12549. /// the locale's decimal point character
  12550. const char decimal_point = '\0';
  12551. /// string buffer
  12552. std::array<char, 512> string_buffer{{}};
  12553. /// the indentation character
  12554. const char indent_char;
  12555. /// the indentation string
  12556. string_t indent_string;
  12557. /// error_handler how to react on decoding errors
  12558. const error_handler_t error_handler;
  12559. };
  12560. } // namespace detail
  12561. } // namespace nlohmann
  12562. // #include <nlohmann/detail/value_t.hpp>
  12563. // #include <nlohmann/json_fwd.hpp>
  12564. /*!
  12565. @brief namespace for Niels Lohmann
  12566. @see https://github.com/nlohmann
  12567. @since version 1.0.0
  12568. */
  12569. namespace nlohmann
  12570. {
  12571. /*!
  12572. @brief a class to store JSON values
  12573. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  12574. in @ref object_t)
  12575. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  12576. in @ref array_t)
  12577. @tparam StringType type for JSON strings and object keys (`std::string` by
  12578. default; will be used in @ref string_t)
  12579. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  12580. in @ref boolean_t)
  12581. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  12582. default; will be used in @ref number_integer_t)
  12583. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  12584. `uint64_t` by default; will be used in @ref number_unsigned_t)
  12585. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  12586. default; will be used in @ref number_float_t)
  12587. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  12588. default)
  12589. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  12590. and `from_json()` (@ref adl_serializer by default)
  12591. @requirement The class satisfies the following concept requirements:
  12592. - Basic
  12593. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  12594. JSON values can be default constructed. The result will be a JSON null
  12595. value.
  12596. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  12597. A JSON value can be constructed from an rvalue argument.
  12598. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  12599. A JSON value can be copy-constructed from an lvalue expression.
  12600. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  12601. A JSON value van be assigned from an rvalue argument.
  12602. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  12603. A JSON value can be copy-assigned from an lvalue expression.
  12604. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  12605. JSON values can be destructed.
  12606. - Layout
  12607. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  12608. JSON values have
  12609. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  12610. All non-static data members are private and standard layout types, the
  12611. class has no virtual functions or (virtual) base classes.
  12612. - Library-wide
  12613. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  12614. JSON values can be compared with `==`, see @ref
  12615. operator==(const_reference,const_reference).
  12616. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  12617. JSON values can be compared with `<`, see @ref
  12618. operator<(const_reference,const_reference).
  12619. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  12620. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  12621. other compatible types, using unqualified function call @ref swap().
  12622. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  12623. JSON values can be compared against `std::nullptr_t` objects which are used
  12624. to model the `null` value.
  12625. - Container
  12626. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  12627. JSON values can be used like STL containers and provide iterator access.
  12628. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  12629. JSON values can be used like STL containers and provide reverse iterator
  12630. access.
  12631. @invariant The member variables @a m_value and @a m_type have the following
  12632. relationship:
  12633. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  12634. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  12635. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  12636. The invariants are checked by member function assert_invariant().
  12637. @internal
  12638. @note ObjectType trick from http://stackoverflow.com/a/9860911
  12639. @endinternal
  12640. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  12641. Format](http://rfc7159.net/rfc7159)
  12642. @since version 1.0.0
  12643. @nosubgrouping
  12644. */
  12645. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12646. class basic_json
  12647. {
  12648. private:
  12649. template<detail::value_t> friend struct detail::external_constructor;
  12650. friend ::nlohmann::json_pointer<basic_json>;
  12651. friend ::nlohmann::detail::parser<basic_json>;
  12652. friend ::nlohmann::detail::serializer<basic_json>;
  12653. template<typename BasicJsonType>
  12654. friend class ::nlohmann::detail::iter_impl;
  12655. template<typename BasicJsonType, typename CharType>
  12656. friend class ::nlohmann::detail::binary_writer;
  12657. template<typename BasicJsonType, typename SAX>
  12658. friend class ::nlohmann::detail::binary_reader;
  12659. template<typename BasicJsonType>
  12660. friend class ::nlohmann::detail::json_sax_dom_parser;
  12661. template<typename BasicJsonType>
  12662. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  12663. /// workaround type for MSVC
  12664. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  12665. // convenience aliases for types residing in namespace detail;
  12666. using lexer = ::nlohmann::detail::lexer<basic_json>;
  12667. using parser = ::nlohmann::detail::parser<basic_json>;
  12668. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  12669. template<typename BasicJsonType>
  12670. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  12671. template<typename BasicJsonType>
  12672. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  12673. template<typename Iterator>
  12674. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  12675. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  12676. template<typename CharType>
  12677. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  12678. using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
  12679. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  12680. using serializer = ::nlohmann::detail::serializer<basic_json>;
  12681. public:
  12682. using value_t = detail::value_t;
  12683. /// JSON Pointer, see @ref nlohmann::json_pointer
  12684. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  12685. template<typename T, typename SFINAE>
  12686. using json_serializer = JSONSerializer<T, SFINAE>;
  12687. /// how to treat decoding errors
  12688. using error_handler_t = detail::error_handler_t;
  12689. /// helper type for initializer lists of basic_json values
  12690. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  12691. using input_format_t = detail::input_format_t;
  12692. /// SAX interface type, see @ref nlohmann::json_sax
  12693. using json_sax_t = json_sax<basic_json>;
  12694. ////////////////
  12695. // exceptions //
  12696. ////////////////
  12697. /// @name exceptions
  12698. /// Classes to implement user-defined exceptions.
  12699. /// @{
  12700. /// @copydoc detail::exception
  12701. using exception = detail::exception;
  12702. /// @copydoc detail::parse_error
  12703. using parse_error = detail::parse_error;
  12704. /// @copydoc detail::invalid_iterator
  12705. using invalid_iterator = detail::invalid_iterator;
  12706. /// @copydoc detail::type_error
  12707. using type_error = detail::type_error;
  12708. /// @copydoc detail::out_of_range
  12709. using out_of_range = detail::out_of_range;
  12710. /// @copydoc detail::other_error
  12711. using other_error = detail::other_error;
  12712. /// @}
  12713. /////////////////////
  12714. // container types //
  12715. /////////////////////
  12716. /// @name container types
  12717. /// The canonic container types to use @ref basic_json like any other STL
  12718. /// container.
  12719. /// @{
  12720. /// the type of elements in a basic_json container
  12721. using value_type = basic_json;
  12722. /// the type of an element reference
  12723. using reference = value_type&;
  12724. /// the type of an element const reference
  12725. using const_reference = const value_type&;
  12726. /// a type to represent differences between iterators
  12727. using difference_type = std::ptrdiff_t;
  12728. /// a type to represent container sizes
  12729. using size_type = std::size_t;
  12730. /// the allocator type
  12731. using allocator_type = AllocatorType<basic_json>;
  12732. /// the type of an element pointer
  12733. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  12734. /// the type of an element const pointer
  12735. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  12736. /// an iterator for a basic_json container
  12737. using iterator = iter_impl<basic_json>;
  12738. /// a const iterator for a basic_json container
  12739. using const_iterator = iter_impl<const basic_json>;
  12740. /// a reverse iterator for a basic_json container
  12741. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  12742. /// a const reverse iterator for a basic_json container
  12743. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  12744. /// @}
  12745. /*!
  12746. @brief returns the allocator associated with the container
  12747. */
  12748. static allocator_type get_allocator()
  12749. {
  12750. return allocator_type();
  12751. }
  12752. /*!
  12753. @brief returns version information on the library
  12754. This function returns a JSON object with information about the library,
  12755. including the version number and information on the platform and compiler.
  12756. @return JSON object holding version information
  12757. key | description
  12758. ----------- | ---------------
  12759. `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).
  12760. `copyright` | The copyright line for the library as string.
  12761. `name` | The name of the library as string.
  12762. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  12763. `url` | The URL of the project as string.
  12764. `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).
  12765. @liveexample{The following code shows an example output of the `meta()`
  12766. function.,meta}
  12767. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12768. changes to any JSON value.
  12769. @complexity Constant.
  12770. @since 2.1.0
  12771. */
  12772. JSON_HEDLEY_WARN_UNUSED_RESULT
  12773. static basic_json meta()
  12774. {
  12775. basic_json result;
  12776. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  12777. result["name"] = "JSON for Modern C++";
  12778. result["url"] = "https://github.com/nlohmann/json";
  12779. result["version"]["string"] =
  12780. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  12781. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  12782. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  12783. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  12784. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  12785. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  12786. #ifdef _WIN32
  12787. result["platform"] = "win32";
  12788. #elif defined __linux__
  12789. result["platform"] = "linux";
  12790. #elif defined __APPLE__
  12791. result["platform"] = "apple";
  12792. #elif defined __unix__
  12793. result["platform"] = "unix";
  12794. #else
  12795. result["platform"] = "unknown";
  12796. #endif
  12797. #if defined(__ICC) || defined(__INTEL_COMPILER)
  12798. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  12799. #elif defined(__clang__)
  12800. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  12801. #elif defined(__GNUC__) || defined(__GNUG__)
  12802. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  12803. #elif defined(__HP_cc) || defined(__HP_aCC)
  12804. result["compiler"] = "hp"
  12805. #elif defined(__IBMCPP__)
  12806. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  12807. #elif defined(_MSC_VER)
  12808. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  12809. #elif defined(__PGI)
  12810. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  12811. #elif defined(__SUNPRO_CC)
  12812. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  12813. #else
  12814. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  12815. #endif
  12816. #ifdef __cplusplus
  12817. result["compiler"]["c++"] = std::to_string(__cplusplus);
  12818. #else
  12819. result["compiler"]["c++"] = "unknown";
  12820. #endif
  12821. return result;
  12822. }
  12823. ///////////////////////////
  12824. // JSON value data types //
  12825. ///////////////////////////
  12826. /// @name JSON value data types
  12827. /// The data types to store a JSON value. These types are derived from
  12828. /// the template arguments passed to class @ref basic_json.
  12829. /// @{
  12830. #if defined(JSON_HAS_CPP_14)
  12831. // Use transparent comparator if possible, combined with perfect forwarding
  12832. // on find() and count() calls prevents unnecessary string construction.
  12833. using object_comparator_t = std::less<>;
  12834. #else
  12835. using object_comparator_t = std::less<StringType>;
  12836. #endif
  12837. /*!
  12838. @brief a type for an object
  12839. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  12840. > An object is an unordered collection of zero or more name/value pairs,
  12841. > where a name is a string and a value is a string, number, boolean, null,
  12842. > object, or array.
  12843. To store objects in C++, a type is defined by the template parameters
  12844. described below.
  12845. @tparam ObjectType the container to store objects (e.g., `std::map` or
  12846. `std::unordered_map`)
  12847. @tparam StringType the type of the keys or names (e.g., `std::string`).
  12848. The comparison function `std::less<StringType>` is used to order elements
  12849. inside the container.
  12850. @tparam AllocatorType the allocator to use for objects (e.g.,
  12851. `std::allocator`)
  12852. #### Default type
  12853. With the default values for @a ObjectType (`std::map`), @a StringType
  12854. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  12855. value for @a object_t is:
  12856. @code {.cpp}
  12857. std::map<
  12858. std::string, // key_type
  12859. basic_json, // value_type
  12860. std::less<std::string>, // key_compare
  12861. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  12862. >
  12863. @endcode
  12864. #### Behavior
  12865. The choice of @a object_t influences the behavior of the JSON class. With
  12866. the default type, objects have the following behavior:
  12867. - When all names are unique, objects will be interoperable in the sense
  12868. that all software implementations receiving that object will agree on
  12869. the name-value mappings.
  12870. - When the names within an object are not unique, it is unspecified which
  12871. one of the values for a given key will be chosen. For instance,
  12872. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  12873. `{"key": 2}`.
  12874. - Internally, name/value pairs are stored in lexicographical order of the
  12875. names. Objects will also be serialized (see @ref dump) in this order.
  12876. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  12877. and serialized as `{"a": 2, "b": 1}`.
  12878. - When comparing objects, the order of the name/value pairs is irrelevant.
  12879. This makes objects interoperable in the sense that they will not be
  12880. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  12881. `{"a": 2, "b": 1}` will be treated as equal.
  12882. #### Limits
  12883. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  12884. > An implementation may set limits on the maximum depth of nesting.
  12885. In this class, the object's limit of nesting is not explicitly constrained.
  12886. However, a maximum depth of nesting may be introduced by the compiler or
  12887. runtime environment. A theoretical limit can be queried by calling the
  12888. @ref max_size function of a JSON object.
  12889. #### Storage
  12890. Objects are stored as pointers in a @ref basic_json type. That is, for any
  12891. access to object values, a pointer of type `object_t*` must be
  12892. dereferenced.
  12893. @sa @ref array_t -- type for an array value
  12894. @since version 1.0.0
  12895. @note The order name/value pairs are added to the object is *not*
  12896. preserved by the library. Therefore, iterating an object may return
  12897. name/value pairs in a different order than they were originally stored. In
  12898. fact, keys will be traversed in alphabetical order as `std::map` with
  12899. `std::less` is used by default. Please note this behavior conforms to [RFC
  12900. 7159](http://rfc7159.net/rfc7159), because any order implements the
  12901. specified "unordered" nature of JSON objects.
  12902. */
  12903. using object_t = ObjectType<StringType,
  12904. basic_json,
  12905. object_comparator_t,
  12906. AllocatorType<std::pair<const StringType,
  12907. basic_json>>>;
  12908. /*!
  12909. @brief a type for an array
  12910. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  12911. > An array is an ordered sequence of zero or more values.
  12912. To store objects in C++, a type is defined by the template parameters
  12913. explained below.
  12914. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  12915. `std::list`)
  12916. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  12917. #### Default type
  12918. With the default values for @a ArrayType (`std::vector`) and @a
  12919. AllocatorType (`std::allocator`), the default value for @a array_t is:
  12920. @code {.cpp}
  12921. std::vector<
  12922. basic_json, // value_type
  12923. std::allocator<basic_json> // allocator_type
  12924. >
  12925. @endcode
  12926. #### Limits
  12927. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  12928. > An implementation may set limits on the maximum depth of nesting.
  12929. In this class, the array's limit of nesting is not explicitly constrained.
  12930. However, a maximum depth of nesting may be introduced by the compiler or
  12931. runtime environment. A theoretical limit can be queried by calling the
  12932. @ref max_size function of a JSON array.
  12933. #### Storage
  12934. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  12935. access to array values, a pointer of type `array_t*` must be dereferenced.
  12936. @sa @ref object_t -- type for an object value
  12937. @since version 1.0.0
  12938. */
  12939. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  12940. /*!
  12941. @brief a type for a string
  12942. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  12943. > A string is a sequence of zero or more Unicode characters.
  12944. To store objects in C++, a type is defined by the template parameter
  12945. described below. Unicode values are split by the JSON class into
  12946. byte-sized characters during deserialization.
  12947. @tparam StringType the container to store strings (e.g., `std::string`).
  12948. Note this container is used for keys/names in objects, see @ref object_t.
  12949. #### Default type
  12950. With the default values for @a StringType (`std::string`), the default
  12951. value for @a string_t is:
  12952. @code {.cpp}
  12953. std::string
  12954. @endcode
  12955. #### Encoding
  12956. Strings are stored in UTF-8 encoding. Therefore, functions like
  12957. `std::string::size()` or `std::string::length()` return the number of
  12958. bytes in the string rather than the number of characters or glyphs.
  12959. #### String comparison
  12960. [RFC 7159](http://rfc7159.net/rfc7159) states:
  12961. > Software implementations are typically required to test names of object
  12962. > members for equality. Implementations that transform the textual
  12963. > representation into sequences of Unicode code units and then perform the
  12964. > comparison numerically, code unit by code unit, are interoperable in the
  12965. > sense that implementations will agree in all cases on equality or
  12966. > inequality of two strings. For example, implementations that compare
  12967. > strings with escaped characters unconverted may incorrectly find that
  12968. > `"a\\b"` and `"a\u005Cb"` are not equal.
  12969. This implementation is interoperable as it does compare strings code unit
  12970. by code unit.
  12971. #### Storage
  12972. String values are stored as pointers in a @ref basic_json type. That is,
  12973. for any access to string values, a pointer of type `string_t*` must be
  12974. dereferenced.
  12975. @since version 1.0.0
  12976. */
  12977. using string_t = StringType;
  12978. /*!
  12979. @brief a type for a boolean
  12980. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  12981. type which differentiates the two literals `true` and `false`.
  12982. To store objects in C++, a type is defined by the template parameter @a
  12983. BooleanType which chooses the type to use.
  12984. #### Default type
  12985. With the default values for @a BooleanType (`bool`), the default value for
  12986. @a boolean_t is:
  12987. @code {.cpp}
  12988. bool
  12989. @endcode
  12990. #### Storage
  12991. Boolean values are stored directly inside a @ref basic_json type.
  12992. @since version 1.0.0
  12993. */
  12994. using boolean_t = BooleanType;
  12995. /*!
  12996. @brief a type for a number (integer)
  12997. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  12998. > The representation of numbers is similar to that used in most
  12999. > programming languages. A number is represented in base 10 using decimal
  13000. > digits. It contains an integer component that may be prefixed with an
  13001. > optional minus sign, which may be followed by a fraction part and/or an
  13002. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  13003. > cannot be represented in the grammar below (such as Infinity and NaN)
  13004. > are not permitted.
  13005. This description includes both integer and floating-point numbers.
  13006. However, C++ allows more precise storage if it is known whether the number
  13007. is a signed integer, an unsigned integer or a floating-point number.
  13008. Therefore, three different types, @ref number_integer_t, @ref
  13009. number_unsigned_t and @ref number_float_t are used.
  13010. To store integer numbers in C++, a type is defined by the template
  13011. parameter @a NumberIntegerType which chooses the type to use.
  13012. #### Default type
  13013. With the default values for @a NumberIntegerType (`int64_t`), the default
  13014. value for @a number_integer_t is:
  13015. @code {.cpp}
  13016. int64_t
  13017. @endcode
  13018. #### Default behavior
  13019. - The restrictions about leading zeros is not enforced in C++. Instead,
  13020. leading zeros in integer literals lead to an interpretation as octal
  13021. number. Internally, the value will be stored as decimal number. For
  13022. instance, the C++ integer literal `010` will be serialized to `8`.
  13023. During deserialization, leading zeros yield an error.
  13024. - Not-a-number (NaN) values will be serialized to `null`.
  13025. #### Limits
  13026. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13027. > An implementation may set limits on the range and precision of numbers.
  13028. When the default type is used, the maximal integer number that can be
  13029. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  13030. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  13031. that are out of range will yield over/underflow when used in a
  13032. constructor. During deserialization, too large or small integer numbers
  13033. will be automatically be stored as @ref number_unsigned_t or @ref
  13034. number_float_t.
  13035. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  13036. > Note that when such software is used, numbers that are integers and are
  13037. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  13038. > that implementations will agree exactly on their numeric values.
  13039. As this range is a subrange of the exactly supported range [INT64_MIN,
  13040. INT64_MAX], this class's integer type is interoperable.
  13041. #### Storage
  13042. Integer number values are stored directly inside a @ref basic_json type.
  13043. @sa @ref number_float_t -- type for number values (floating-point)
  13044. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  13045. @since version 1.0.0
  13046. */
  13047. using number_integer_t = NumberIntegerType;
  13048. /*!
  13049. @brief a type for a number (unsigned)
  13050. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  13051. > The representation of numbers is similar to that used in most
  13052. > programming languages. A number is represented in base 10 using decimal
  13053. > digits. It contains an integer component that may be prefixed with an
  13054. > optional minus sign, which may be followed by a fraction part and/or an
  13055. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  13056. > cannot be represented in the grammar below (such as Infinity and NaN)
  13057. > are not permitted.
  13058. This description includes both integer and floating-point numbers.
  13059. However, C++ allows more precise storage if it is known whether the number
  13060. is a signed integer, an unsigned integer or a floating-point number.
  13061. Therefore, three different types, @ref number_integer_t, @ref
  13062. number_unsigned_t and @ref number_float_t are used.
  13063. To store unsigned integer numbers in C++, a type is defined by the
  13064. template parameter @a NumberUnsignedType which chooses the type to use.
  13065. #### Default type
  13066. With the default values for @a NumberUnsignedType (`uint64_t`), the
  13067. default value for @a number_unsigned_t is:
  13068. @code {.cpp}
  13069. uint64_t
  13070. @endcode
  13071. #### Default behavior
  13072. - The restrictions about leading zeros is not enforced in C++. Instead,
  13073. leading zeros in integer literals lead to an interpretation as octal
  13074. number. Internally, the value will be stored as decimal number. For
  13075. instance, the C++ integer literal `010` will be serialized to `8`.
  13076. During deserialization, leading zeros yield an error.
  13077. - Not-a-number (NaN) values will be serialized to `null`.
  13078. #### Limits
  13079. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13080. > An implementation may set limits on the range and precision of numbers.
  13081. When the default type is used, the maximal integer number that can be
  13082. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  13083. number that can be stored is `0`. Integer numbers that are out of range
  13084. will yield over/underflow when used in a constructor. During
  13085. deserialization, too large or small integer numbers will be automatically
  13086. be stored as @ref number_integer_t or @ref number_float_t.
  13087. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  13088. > Note that when such software is used, numbers that are integers and are
  13089. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  13090. > that implementations will agree exactly on their numeric values.
  13091. As this range is a subrange (when considered in conjunction with the
  13092. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  13093. this class's integer type is interoperable.
  13094. #### Storage
  13095. Integer number values are stored directly inside a @ref basic_json type.
  13096. @sa @ref number_float_t -- type for number values (floating-point)
  13097. @sa @ref number_integer_t -- type for number values (integer)
  13098. @since version 2.0.0
  13099. */
  13100. using number_unsigned_t = NumberUnsignedType;
  13101. /*!
  13102. @brief a type for a number (floating-point)
  13103. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  13104. > The representation of numbers is similar to that used in most
  13105. > programming languages. A number is represented in base 10 using decimal
  13106. > digits. It contains an integer component that may be prefixed with an
  13107. > optional minus sign, which may be followed by a fraction part and/or an
  13108. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  13109. > cannot be represented in the grammar below (such as Infinity and NaN)
  13110. > are not permitted.
  13111. This description includes both integer and floating-point numbers.
  13112. However, C++ allows more precise storage if it is known whether the number
  13113. is a signed integer, an unsigned integer or a floating-point number.
  13114. Therefore, three different types, @ref number_integer_t, @ref
  13115. number_unsigned_t and @ref number_float_t are used.
  13116. To store floating-point numbers in C++, a type is defined by the template
  13117. parameter @a NumberFloatType which chooses the type to use.
  13118. #### Default type
  13119. With the default values for @a NumberFloatType (`double`), the default
  13120. value for @a number_float_t is:
  13121. @code {.cpp}
  13122. double
  13123. @endcode
  13124. #### Default behavior
  13125. - The restrictions about leading zeros is not enforced in C++. Instead,
  13126. leading zeros in floating-point literals will be ignored. Internally,
  13127. the value will be stored as decimal number. For instance, the C++
  13128. floating-point literal `01.2` will be serialized to `1.2`. During
  13129. deserialization, leading zeros yield an error.
  13130. - Not-a-number (NaN) values will be serialized to `null`.
  13131. #### Limits
  13132. [RFC 7159](http://rfc7159.net/rfc7159) states:
  13133. > This specification allows implementations to set limits on the range and
  13134. > precision of numbers accepted. Since software that implements IEEE
  13135. > 754-2008 binary64 (double precision) numbers is generally available and
  13136. > widely used, good interoperability can be achieved by implementations
  13137. > that expect no more precision or range than these provide, in the sense
  13138. > that implementations will approximate JSON numbers within the expected
  13139. > precision.
  13140. This implementation does exactly follow this approach, as it uses double
  13141. precision floating-point numbers. Note values smaller than
  13142. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  13143. will be stored as NaN internally and be serialized to `null`.
  13144. #### Storage
  13145. Floating-point number values are stored directly inside a @ref basic_json
  13146. type.
  13147. @sa @ref number_integer_t -- type for number values (integer)
  13148. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  13149. @since version 1.0.0
  13150. */
  13151. using number_float_t = NumberFloatType;
  13152. /// @}
  13153. private:
  13154. /// helper for exception-safe object creation
  13155. template<typename T, typename... Args>
  13156. JSON_HEDLEY_RETURNS_NON_NULL
  13157. static T* create(Args&& ... args)
  13158. {
  13159. AllocatorType<T> alloc;
  13160. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  13161. auto deleter = [&](T * object)
  13162. {
  13163. AllocatorTraits::deallocate(alloc, object, 1);
  13164. };
  13165. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  13166. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  13167. assert(object != nullptr);
  13168. return object.release();
  13169. }
  13170. ////////////////////////
  13171. // JSON value storage //
  13172. ////////////////////////
  13173. /*!
  13174. @brief a JSON value
  13175. The actual storage for a JSON value of the @ref basic_json class. This
  13176. union combines the different storage types for the JSON value types
  13177. defined in @ref value_t.
  13178. JSON type | value_t type | used type
  13179. --------- | --------------- | ------------------------
  13180. object | object | pointer to @ref object_t
  13181. array | array | pointer to @ref array_t
  13182. string | string | pointer to @ref string_t
  13183. boolean | boolean | @ref boolean_t
  13184. number | number_integer | @ref number_integer_t
  13185. number | number_unsigned | @ref number_unsigned_t
  13186. number | number_float | @ref number_float_t
  13187. null | null | *no value is stored*
  13188. @note Variable-length types (objects, arrays, and strings) are stored as
  13189. pointers. The size of the union should not exceed 64 bits if the default
  13190. value types are used.
  13191. @since version 1.0.0
  13192. */
  13193. union json_value
  13194. {
  13195. /// object (stored with pointer to save storage)
  13196. object_t* object;
  13197. /// array (stored with pointer to save storage)
  13198. array_t* array;
  13199. /// string (stored with pointer to save storage)
  13200. string_t* string;
  13201. /// boolean
  13202. boolean_t boolean;
  13203. /// number (integer)
  13204. number_integer_t number_integer;
  13205. /// number (unsigned integer)
  13206. number_unsigned_t number_unsigned;
  13207. /// number (floating-point)
  13208. number_float_t number_float;
  13209. /// default constructor (for null values)
  13210. json_value() = default;
  13211. /// constructor for booleans
  13212. json_value(boolean_t v) noexcept : boolean(v) {}
  13213. /// constructor for numbers (integer)
  13214. json_value(number_integer_t v) noexcept : number_integer(v) {}
  13215. /// constructor for numbers (unsigned)
  13216. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  13217. /// constructor for numbers (floating-point)
  13218. json_value(number_float_t v) noexcept : number_float(v) {}
  13219. /// constructor for empty values of a given type
  13220. json_value(value_t t)
  13221. {
  13222. switch (t)
  13223. {
  13224. case value_t::object:
  13225. {
  13226. object = create<object_t>();
  13227. break;
  13228. }
  13229. case value_t::array:
  13230. {
  13231. array = create<array_t>();
  13232. break;
  13233. }
  13234. case value_t::string:
  13235. {
  13236. string = create<string_t>("");
  13237. break;
  13238. }
  13239. case value_t::boolean:
  13240. {
  13241. boolean = boolean_t(false);
  13242. break;
  13243. }
  13244. case value_t::number_integer:
  13245. {
  13246. number_integer = number_integer_t(0);
  13247. break;
  13248. }
  13249. case value_t::number_unsigned:
  13250. {
  13251. number_unsigned = number_unsigned_t(0);
  13252. break;
  13253. }
  13254. case value_t::number_float:
  13255. {
  13256. number_float = number_float_t(0.0);
  13257. break;
  13258. }
  13259. case value_t::null:
  13260. {
  13261. object = nullptr; // silence warning, see #821
  13262. break;
  13263. }
  13264. default:
  13265. {
  13266. object = nullptr; // silence warning, see #821
  13267. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  13268. {
  13269. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.7.0")); // LCOV_EXCL_LINE
  13270. }
  13271. break;
  13272. }
  13273. }
  13274. }
  13275. /// constructor for strings
  13276. json_value(const string_t& value)
  13277. {
  13278. string = create<string_t>(value);
  13279. }
  13280. /// constructor for rvalue strings
  13281. json_value(string_t&& value)
  13282. {
  13283. string = create<string_t>(std::move(value));
  13284. }
  13285. /// constructor for objects
  13286. json_value(const object_t& value)
  13287. {
  13288. object = create<object_t>(value);
  13289. }
  13290. /// constructor for rvalue objects
  13291. json_value(object_t&& value)
  13292. {
  13293. object = create<object_t>(std::move(value));
  13294. }
  13295. /// constructor for arrays
  13296. json_value(const array_t& value)
  13297. {
  13298. array = create<array_t>(value);
  13299. }
  13300. /// constructor for rvalue arrays
  13301. json_value(array_t&& value)
  13302. {
  13303. array = create<array_t>(std::move(value));
  13304. }
  13305. void destroy(value_t t) noexcept
  13306. {
  13307. switch (t)
  13308. {
  13309. case value_t::object:
  13310. {
  13311. AllocatorType<object_t> alloc;
  13312. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  13313. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  13314. break;
  13315. }
  13316. case value_t::array:
  13317. {
  13318. AllocatorType<array_t> alloc;
  13319. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  13320. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  13321. break;
  13322. }
  13323. case value_t::string:
  13324. {
  13325. AllocatorType<string_t> alloc;
  13326. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  13327. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  13328. break;
  13329. }
  13330. default:
  13331. {
  13332. break;
  13333. }
  13334. }
  13335. }
  13336. };
  13337. /*!
  13338. @brief checks the class invariants
  13339. This function asserts the class invariants. It needs to be called at the
  13340. end of every constructor to make sure that created objects respect the
  13341. invariant. Furthermore, it has to be called each time the type of a JSON
  13342. value is changed, because the invariant expresses a relationship between
  13343. @a m_type and @a m_value.
  13344. */
  13345. void assert_invariant() const noexcept
  13346. {
  13347. assert(m_type != value_t::object or m_value.object != nullptr);
  13348. assert(m_type != value_t::array or m_value.array != nullptr);
  13349. assert(m_type != value_t::string or m_value.string != nullptr);
  13350. }
  13351. public:
  13352. //////////////////////////
  13353. // JSON parser callback //
  13354. //////////////////////////
  13355. /*!
  13356. @brief parser event types
  13357. The parser callback distinguishes the following events:
  13358. - `object_start`: the parser read `{` and started to process a JSON object
  13359. - `key`: the parser read a key of a value in an object
  13360. - `object_end`: the parser read `}` and finished processing a JSON object
  13361. - `array_start`: the parser read `[` and started to process a JSON array
  13362. - `array_end`: the parser read `]` and finished processing a JSON array
  13363. - `value`: the parser finished reading a JSON value
  13364. @image html callback_events.png "Example when certain parse events are triggered"
  13365. @sa @ref parser_callback_t for more information and examples
  13366. */
  13367. using parse_event_t = typename parser::parse_event_t;
  13368. /*!
  13369. @brief per-element parser callback type
  13370. With a parser callback function, the result of parsing a JSON text can be
  13371. influenced. When passed to @ref parse, it is called on certain events
  13372. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  13373. depth @a depth and context JSON value @a parsed. The return value of the
  13374. callback function is a boolean indicating whether the element that emitted
  13375. the callback shall be kept or not.
  13376. We distinguish six scenarios (determined by the event type) in which the
  13377. callback function can be called. The following table describes the values
  13378. of the parameters @a depth, @a event, and @a parsed.
  13379. parameter @a event | description | parameter @a depth | parameter @a parsed
  13380. ------------------ | ----------- | ------------------ | -------------------
  13381. 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
  13382. 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
  13383. 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
  13384. 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
  13385. 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
  13386. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  13387. @image html callback_events.png "Example when certain parse events are triggered"
  13388. Discarding a value (i.e., returning `false`) has different effects
  13389. depending on the context in which function was called:
  13390. - Discarded values in structured types are skipped. That is, the parser
  13391. will behave as if the discarded value was never read.
  13392. - In case a value outside a structured type is skipped, it is replaced
  13393. with `null`. This case happens if the top-level element is skipped.
  13394. @param[in] depth the depth of the recursion during parsing
  13395. @param[in] event an event of type parse_event_t indicating the context in
  13396. the callback function has been called
  13397. @param[in,out] parsed the current intermediate parse result; note that
  13398. writing to this value has no effect for parse_event_t::key events
  13399. @return Whether the JSON value which called the function during parsing
  13400. should be kept (`true`) or not (`false`). In the latter case, it is either
  13401. skipped completely or replaced by an empty discarded object.
  13402. @sa @ref parse for examples
  13403. @since version 1.0.0
  13404. */
  13405. using parser_callback_t = typename parser::parser_callback_t;
  13406. //////////////////
  13407. // constructors //
  13408. //////////////////
  13409. /// @name constructors and destructors
  13410. /// Constructors of class @ref basic_json, copy/move constructor, copy
  13411. /// assignment, static functions creating objects, and the destructor.
  13412. /// @{
  13413. /*!
  13414. @brief create an empty value with a given type
  13415. Create an empty JSON value with a given type. The value will be default
  13416. initialized with an empty value which depends on the type:
  13417. Value type | initial value
  13418. ----------- | -------------
  13419. null | `null`
  13420. boolean | `false`
  13421. string | `""`
  13422. number | `0`
  13423. object | `{}`
  13424. array | `[]`
  13425. @param[in] v the type of the value to create
  13426. @complexity Constant.
  13427. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13428. changes to any JSON value.
  13429. @liveexample{The following code shows the constructor for different @ref
  13430. value_t values,basic_json__value_t}
  13431. @sa @ref clear() -- restores the postcondition of this constructor
  13432. @since version 1.0.0
  13433. */
  13434. basic_json(const value_t v)
  13435. : m_type(v), m_value(v)
  13436. {
  13437. assert_invariant();
  13438. }
  13439. /*!
  13440. @brief create a null object
  13441. Create a `null` JSON value. It either takes a null pointer as parameter
  13442. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  13443. The passed null pointer itself is not read -- it is only used to choose
  13444. the right constructor.
  13445. @complexity Constant.
  13446. @exceptionsafety No-throw guarantee: this constructor never throws
  13447. exceptions.
  13448. @liveexample{The following code shows the constructor with and without a
  13449. null pointer parameter.,basic_json__nullptr_t}
  13450. @since version 1.0.0
  13451. */
  13452. basic_json(std::nullptr_t = nullptr) noexcept
  13453. : basic_json(value_t::null)
  13454. {
  13455. assert_invariant();
  13456. }
  13457. /*!
  13458. @brief create a JSON value
  13459. This is a "catch all" constructor for all compatible JSON types; that is,
  13460. types for which a `to_json()` method exists. The constructor forwards the
  13461. parameter @a val to that method (to `json_serializer<U>::to_json` method
  13462. with `U = uncvref_t<CompatibleType>`, to be exact).
  13463. Template type @a CompatibleType includes, but is not limited to, the
  13464. following types:
  13465. - **arrays**: @ref array_t and all kinds of compatible containers such as
  13466. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  13467. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  13468. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  13469. which a @ref basic_json value can be constructed.
  13470. - **objects**: @ref object_t and all kinds of compatible associative
  13471. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  13472. and `std::unordered_multimap` with a `key_type` compatible to
  13473. @ref string_t and a `value_type` from which a @ref basic_json value can
  13474. be constructed.
  13475. - **strings**: @ref string_t, string literals, and all compatible string
  13476. containers can be used.
  13477. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  13478. @ref number_float_t, and all convertible number types such as `int`,
  13479. `size_t`, `int64_t`, `float` or `double` can be used.
  13480. - **boolean**: @ref boolean_t / `bool` can be used.
  13481. See the examples below.
  13482. @tparam CompatibleType a type such that:
  13483. - @a CompatibleType is not derived from `std::istream`,
  13484. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  13485. constructors),
  13486. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  13487. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  13488. @ref json_pointer, @ref iterator, etc ...)
  13489. - @ref @ref json_serializer<U> has a
  13490. `to_json(basic_json_t&, CompatibleType&&)` method
  13491. @tparam U = `uncvref_t<CompatibleType>`
  13492. @param[in] val the value to be forwarded to the respective constructor
  13493. @complexity Usually linear in the size of the passed @a val, also
  13494. depending on the implementation of the called `to_json()`
  13495. method.
  13496. @exceptionsafety Depends on the called constructor. For types directly
  13497. supported by the library (i.e., all types for which no `to_json()` function
  13498. was provided), strong guarantee holds: if an exception is thrown, there are
  13499. no changes to any JSON value.
  13500. @liveexample{The following code shows the constructor with several
  13501. compatible types.,basic_json__CompatibleType}
  13502. @since version 2.1.0
  13503. */
  13504. template <typename CompatibleType,
  13505. typename U = detail::uncvref_t<CompatibleType>,
  13506. detail::enable_if_t<
  13507. not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  13508. basic_json(CompatibleType && val) noexcept(noexcept(
  13509. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  13510. std::forward<CompatibleType>(val))))
  13511. {
  13512. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  13513. assert_invariant();
  13514. }
  13515. /*!
  13516. @brief create a JSON value from an existing one
  13517. This is a constructor for existing @ref basic_json types.
  13518. It does not hijack copy/move constructors, since the parameter has different
  13519. template arguments than the current ones.
  13520. The constructor tries to convert the internal @ref m_value of the parameter.
  13521. @tparam BasicJsonType a type such that:
  13522. - @a BasicJsonType is a @ref basic_json type.
  13523. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  13524. @param[in] val the @ref basic_json value to be converted.
  13525. @complexity Usually linear in the size of the passed @a val, also
  13526. depending on the implementation of the called `to_json()`
  13527. method.
  13528. @exceptionsafety Depends on the called constructor. For types directly
  13529. supported by the library (i.e., all types for which no `to_json()` function
  13530. was provided), strong guarantee holds: if an exception is thrown, there are
  13531. no changes to any JSON value.
  13532. @since version 3.2.0
  13533. */
  13534. template <typename BasicJsonType,
  13535. detail::enable_if_t<
  13536. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  13537. basic_json(const BasicJsonType& val)
  13538. {
  13539. using other_boolean_t = typename BasicJsonType::boolean_t;
  13540. using other_number_float_t = typename BasicJsonType::number_float_t;
  13541. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  13542. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  13543. using other_string_t = typename BasicJsonType::string_t;
  13544. using other_object_t = typename BasicJsonType::object_t;
  13545. using other_array_t = typename BasicJsonType::array_t;
  13546. switch (val.type())
  13547. {
  13548. case value_t::boolean:
  13549. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  13550. break;
  13551. case value_t::number_float:
  13552. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  13553. break;
  13554. case value_t::number_integer:
  13555. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  13556. break;
  13557. case value_t::number_unsigned:
  13558. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  13559. break;
  13560. case value_t::string:
  13561. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  13562. break;
  13563. case value_t::object:
  13564. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  13565. break;
  13566. case value_t::array:
  13567. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  13568. break;
  13569. case value_t::null:
  13570. *this = nullptr;
  13571. break;
  13572. case value_t::discarded:
  13573. m_type = value_t::discarded;
  13574. break;
  13575. default: // LCOV_EXCL_LINE
  13576. assert(false); // LCOV_EXCL_LINE
  13577. }
  13578. assert_invariant();
  13579. }
  13580. /*!
  13581. @brief create a container (array or object) from an initializer list
  13582. Creates a JSON value of type array or object from the passed initializer
  13583. list @a init. In case @a type_deduction is `true` (default), the type of
  13584. the JSON value to be created is deducted from the initializer list @a init
  13585. according to the following rules:
  13586. 1. If the list is empty, an empty JSON object value `{}` is created.
  13587. 2. If the list consists of pairs whose first element is a string, a JSON
  13588. object value is created where the first elements of the pairs are
  13589. treated as keys and the second elements are as values.
  13590. 3. In all other cases, an array is created.
  13591. The rules aim to create the best fit between a C++ initializer list and
  13592. JSON values. The rationale is as follows:
  13593. 1. The empty initializer list is written as `{}` which is exactly an empty
  13594. JSON object.
  13595. 2. C++ has no way of describing mapped types other than to list a list of
  13596. pairs. As JSON requires that keys must be of type string, rule 2 is the
  13597. weakest constraint one can pose on initializer lists to interpret them
  13598. as an object.
  13599. 3. In all other cases, the initializer list could not be interpreted as
  13600. JSON object type, so interpreting it as JSON array type is safe.
  13601. With the rules described above, the following JSON values cannot be
  13602. expressed by an initializer list:
  13603. - the empty array (`[]`): use @ref array(initializer_list_t)
  13604. with an empty initializer list in this case
  13605. - arrays whose elements satisfy rule 2: use @ref
  13606. array(initializer_list_t) with the same initializer list
  13607. in this case
  13608. @note When used without parentheses around an empty initializer list, @ref
  13609. basic_json() is called instead of this function, yielding the JSON null
  13610. value.
  13611. @param[in] init initializer list with JSON values
  13612. @param[in] type_deduction internal parameter; when set to `true`, the type
  13613. of the JSON value is deducted from the initializer list @a init; when set
  13614. to `false`, the type provided via @a manual_type is forced. This mode is
  13615. used by the functions @ref array(initializer_list_t) and
  13616. @ref object(initializer_list_t).
  13617. @param[in] manual_type internal parameter; when @a type_deduction is set
  13618. to `false`, the created JSON value will use the provided type (only @ref
  13619. value_t::array and @ref value_t::object are valid); when @a type_deduction
  13620. is set to `true`, this parameter has no effect
  13621. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  13622. `value_t::object`, but @a init contains an element which is not a pair
  13623. whose first element is a string. In this case, the constructor could not
  13624. create an object. If @a type_deduction would have be `true`, an array
  13625. would have been created. See @ref object(initializer_list_t)
  13626. for an example.
  13627. @complexity Linear in the size of the initializer list @a init.
  13628. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13629. changes to any JSON value.
  13630. @liveexample{The example below shows how JSON values are created from
  13631. initializer lists.,basic_json__list_init_t}
  13632. @sa @ref array(initializer_list_t) -- create a JSON array
  13633. value from an initializer list
  13634. @sa @ref object(initializer_list_t) -- create a JSON object
  13635. value from an initializer list
  13636. @since version 1.0.0
  13637. */
  13638. basic_json(initializer_list_t init,
  13639. bool type_deduction = true,
  13640. value_t manual_type = value_t::array)
  13641. {
  13642. // check if each element is an array with two elements whose first
  13643. // element is a string
  13644. bool is_an_object = std::all_of(init.begin(), init.end(),
  13645. [](const detail::json_ref<basic_json>& element_ref)
  13646. {
  13647. return element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string();
  13648. });
  13649. // adjust type if type deduction is not wanted
  13650. if (not type_deduction)
  13651. {
  13652. // if array is wanted, do not create an object though possible
  13653. if (manual_type == value_t::array)
  13654. {
  13655. is_an_object = false;
  13656. }
  13657. // if object is wanted but impossible, throw an exception
  13658. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object and not is_an_object))
  13659. {
  13660. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  13661. }
  13662. }
  13663. if (is_an_object)
  13664. {
  13665. // the initializer list is a list of pairs -> create object
  13666. m_type = value_t::object;
  13667. m_value = value_t::object;
  13668. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  13669. {
  13670. auto element = element_ref.moved_or_copied();
  13671. m_value.object->emplace(
  13672. std::move(*((*element.m_value.array)[0].m_value.string)),
  13673. std::move((*element.m_value.array)[1]));
  13674. });
  13675. }
  13676. else
  13677. {
  13678. // the initializer list describes an array -> create array
  13679. m_type = value_t::array;
  13680. m_value.array = create<array_t>(init.begin(), init.end());
  13681. }
  13682. assert_invariant();
  13683. }
  13684. /*!
  13685. @brief explicitly create an array from an initializer list
  13686. Creates a JSON array value from a given initializer list. That is, given a
  13687. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  13688. initializer list is empty, the empty array `[]` is created.
  13689. @note This function is only needed to express two edge cases that cannot
  13690. be realized with the initializer list constructor (@ref
  13691. basic_json(initializer_list_t, bool, value_t)). These cases
  13692. are:
  13693. 1. creating an array whose elements are all pairs whose first element is a
  13694. string -- in this case, the initializer list constructor would create an
  13695. object, taking the first elements as keys
  13696. 2. creating an empty array -- passing the empty initializer list to the
  13697. initializer list constructor yields an empty object
  13698. @param[in] init initializer list with JSON values to create an array from
  13699. (optional)
  13700. @return JSON array value
  13701. @complexity Linear in the size of @a init.
  13702. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13703. changes to any JSON value.
  13704. @liveexample{The following code shows an example for the `array`
  13705. function.,array}
  13706. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  13707. create a JSON value from an initializer list
  13708. @sa @ref object(initializer_list_t) -- create a JSON object
  13709. value from an initializer list
  13710. @since version 1.0.0
  13711. */
  13712. JSON_HEDLEY_WARN_UNUSED_RESULT
  13713. static basic_json array(initializer_list_t init = {})
  13714. {
  13715. return basic_json(init, false, value_t::array);
  13716. }
  13717. /*!
  13718. @brief explicitly create an object from an initializer list
  13719. Creates a JSON object value from a given initializer list. The initializer
  13720. lists elements must be pairs, and their first elements must be strings. If
  13721. the initializer list is empty, the empty object `{}` is created.
  13722. @note This function is only added for symmetry reasons. In contrast to the
  13723. related function @ref array(initializer_list_t), there are
  13724. no cases which can only be expressed by this function. That is, any
  13725. initializer list @a init can also be passed to the initializer list
  13726. constructor @ref basic_json(initializer_list_t, bool, value_t).
  13727. @param[in] init initializer list to create an object from (optional)
  13728. @return JSON object value
  13729. @throw type_error.301 if @a init is not a list of pairs whose first
  13730. elements are strings. In this case, no object can be created. When such a
  13731. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  13732. an array would have been created from the passed initializer list @a init.
  13733. See example below.
  13734. @complexity Linear in the size of @a init.
  13735. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13736. changes to any JSON value.
  13737. @liveexample{The following code shows an example for the `object`
  13738. function.,object}
  13739. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  13740. create a JSON value from an initializer list
  13741. @sa @ref array(initializer_list_t) -- create a JSON array
  13742. value from an initializer list
  13743. @since version 1.0.0
  13744. */
  13745. JSON_HEDLEY_WARN_UNUSED_RESULT
  13746. static basic_json object(initializer_list_t init = {})
  13747. {
  13748. return basic_json(init, false, value_t::object);
  13749. }
  13750. /*!
  13751. @brief construct an array with count copies of given value
  13752. Constructs a JSON array value by creating @a cnt copies of a passed value.
  13753. In case @a cnt is `0`, an empty array is created.
  13754. @param[in] cnt the number of JSON copies of @a val to create
  13755. @param[in] val the JSON value to copy
  13756. @post `std::distance(begin(),end()) == cnt` holds.
  13757. @complexity Linear in @a cnt.
  13758. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13759. changes to any JSON value.
  13760. @liveexample{The following code shows examples for the @ref
  13761. basic_json(size_type\, const basic_json&)
  13762. constructor.,basic_json__size_type_basic_json}
  13763. @since version 1.0.0
  13764. */
  13765. basic_json(size_type cnt, const basic_json& val)
  13766. : m_type(value_t::array)
  13767. {
  13768. m_value.array = create<array_t>(cnt, val);
  13769. assert_invariant();
  13770. }
  13771. /*!
  13772. @brief construct a JSON container given an iterator range
  13773. Constructs the JSON value with the contents of the range `[first, last)`.
  13774. The semantics depends on the different types a JSON value can have:
  13775. - In case of a null type, invalid_iterator.206 is thrown.
  13776. - In case of other primitive types (number, boolean, or string), @a first
  13777. must be `begin()` and @a last must be `end()`. In this case, the value is
  13778. copied. Otherwise, invalid_iterator.204 is thrown.
  13779. - In case of structured types (array, object), the constructor behaves as
  13780. similar versions for `std::vector` or `std::map`; that is, a JSON array
  13781. or object is constructed from the values in the range.
  13782. @tparam InputIT an input iterator type (@ref iterator or @ref
  13783. const_iterator)
  13784. @param[in] first begin of the range to copy from (included)
  13785. @param[in] last end of the range to copy from (excluded)
  13786. @pre Iterators @a first and @a last must be initialized. **This
  13787. precondition is enforced with an assertion (see warning).** If
  13788. assertions are switched off, a violation of this precondition yields
  13789. undefined behavior.
  13790. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  13791. checked efficiently. Only certain edge cases are detected; see the
  13792. description of the exceptions below. A violation of this precondition
  13793. yields undefined behavior.
  13794. @warning A precondition is enforced with a runtime assertion that will
  13795. result in calling `std::abort` if this precondition is not met.
  13796. Assertions can be disabled by defining `NDEBUG` at compile time.
  13797. See https://en.cppreference.com/w/cpp/error/assert for more
  13798. information.
  13799. @throw invalid_iterator.201 if iterators @a first and @a last are not
  13800. compatible (i.e., do not belong to the same JSON value). In this case,
  13801. the range `[first, last)` is undefined.
  13802. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  13803. primitive type (number, boolean, or string), but @a first does not point
  13804. to the first element any more. In this case, the range `[first, last)` is
  13805. undefined. See example code below.
  13806. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  13807. null value. In this case, the range `[first, last)` is undefined.
  13808. @complexity Linear in distance between @a first and @a last.
  13809. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13810. changes to any JSON value.
  13811. @liveexample{The example below shows several ways to create JSON values by
  13812. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  13813. @since version 1.0.0
  13814. */
  13815. template<class InputIT, typename std::enable_if<
  13816. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  13817. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  13818. basic_json(InputIT first, InputIT last)
  13819. {
  13820. assert(first.m_object != nullptr);
  13821. assert(last.m_object != nullptr);
  13822. // make sure iterator fits the current value
  13823. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  13824. {
  13825. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  13826. }
  13827. // copy type from first iterator
  13828. m_type = first.m_object->m_type;
  13829. // check if iterator range is complete for primitive values
  13830. switch (m_type)
  13831. {
  13832. case value_t::boolean:
  13833. case value_t::number_float:
  13834. case value_t::number_integer:
  13835. case value_t::number_unsigned:
  13836. case value_t::string:
  13837. {
  13838. if (JSON_HEDLEY_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  13839. or not last.m_it.primitive_iterator.is_end()))
  13840. {
  13841. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  13842. }
  13843. break;
  13844. }
  13845. default:
  13846. break;
  13847. }
  13848. switch (m_type)
  13849. {
  13850. case value_t::number_integer:
  13851. {
  13852. m_value.number_integer = first.m_object->m_value.number_integer;
  13853. break;
  13854. }
  13855. case value_t::number_unsigned:
  13856. {
  13857. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  13858. break;
  13859. }
  13860. case value_t::number_float:
  13861. {
  13862. m_value.number_float = first.m_object->m_value.number_float;
  13863. break;
  13864. }
  13865. case value_t::boolean:
  13866. {
  13867. m_value.boolean = first.m_object->m_value.boolean;
  13868. break;
  13869. }
  13870. case value_t::string:
  13871. {
  13872. m_value = *first.m_object->m_value.string;
  13873. break;
  13874. }
  13875. case value_t::object:
  13876. {
  13877. m_value.object = create<object_t>(first.m_it.object_iterator,
  13878. last.m_it.object_iterator);
  13879. break;
  13880. }
  13881. case value_t::array:
  13882. {
  13883. m_value.array = create<array_t>(first.m_it.array_iterator,
  13884. last.m_it.array_iterator);
  13885. break;
  13886. }
  13887. default:
  13888. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  13889. std::string(first.m_object->type_name())));
  13890. }
  13891. assert_invariant();
  13892. }
  13893. ///////////////////////////////////////
  13894. // other constructors and destructor //
  13895. ///////////////////////////////////////
  13896. /// @private
  13897. basic_json(const detail::json_ref<basic_json>& ref)
  13898. : basic_json(ref.moved_or_copied())
  13899. {}
  13900. /*!
  13901. @brief copy constructor
  13902. Creates a copy of a given JSON value.
  13903. @param[in] other the JSON value to copy
  13904. @post `*this == other`
  13905. @complexity Linear in the size of @a other.
  13906. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13907. changes to any JSON value.
  13908. @requirement This function helps `basic_json` satisfying the
  13909. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  13910. requirements:
  13911. - The complexity is linear.
  13912. - As postcondition, it holds: `other == basic_json(other)`.
  13913. @liveexample{The following code shows an example for the copy
  13914. constructor.,basic_json__basic_json}
  13915. @since version 1.0.0
  13916. */
  13917. basic_json(const basic_json& other)
  13918. : m_type(other.m_type)
  13919. {
  13920. // check of passed value is valid
  13921. other.assert_invariant();
  13922. switch (m_type)
  13923. {
  13924. case value_t::object:
  13925. {
  13926. m_value = *other.m_value.object;
  13927. break;
  13928. }
  13929. case value_t::array:
  13930. {
  13931. m_value = *other.m_value.array;
  13932. break;
  13933. }
  13934. case value_t::string:
  13935. {
  13936. m_value = *other.m_value.string;
  13937. break;
  13938. }
  13939. case value_t::boolean:
  13940. {
  13941. m_value = other.m_value.boolean;
  13942. break;
  13943. }
  13944. case value_t::number_integer:
  13945. {
  13946. m_value = other.m_value.number_integer;
  13947. break;
  13948. }
  13949. case value_t::number_unsigned:
  13950. {
  13951. m_value = other.m_value.number_unsigned;
  13952. break;
  13953. }
  13954. case value_t::number_float:
  13955. {
  13956. m_value = other.m_value.number_float;
  13957. break;
  13958. }
  13959. default:
  13960. break;
  13961. }
  13962. assert_invariant();
  13963. }
  13964. /*!
  13965. @brief move constructor
  13966. Move constructor. Constructs a JSON value with the contents of the given
  13967. value @a other using move semantics. It "steals" the resources from @a
  13968. other and leaves it as JSON null value.
  13969. @param[in,out] other value to move to this object
  13970. @post `*this` has the same value as @a other before the call.
  13971. @post @a other is a JSON null value.
  13972. @complexity Constant.
  13973. @exceptionsafety No-throw guarantee: this constructor never throws
  13974. exceptions.
  13975. @requirement This function helps `basic_json` satisfying the
  13976. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  13977. requirements.
  13978. @liveexample{The code below shows the move constructor explicitly called
  13979. via std::move.,basic_json__moveconstructor}
  13980. @since version 1.0.0
  13981. */
  13982. basic_json(basic_json&& other) noexcept
  13983. : m_type(std::move(other.m_type)),
  13984. m_value(std::move(other.m_value))
  13985. {
  13986. // check that passed value is valid
  13987. other.assert_invariant();
  13988. // invalidate payload
  13989. other.m_type = value_t::null;
  13990. other.m_value = {};
  13991. assert_invariant();
  13992. }
  13993. /*!
  13994. @brief copy assignment
  13995. Copy assignment operator. Copies a JSON value via the "copy and swap"
  13996. strategy: It is expressed in terms of the copy constructor, destructor,
  13997. and the `swap()` member function.
  13998. @param[in] other value to copy from
  13999. @complexity Linear.
  14000. @requirement This function helps `basic_json` satisfying the
  14001. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14002. requirements:
  14003. - The complexity is linear.
  14004. @liveexample{The code below shows and example for the copy assignment. It
  14005. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  14006. copy of `a` (which is the null value after the swap) is
  14007. destroyed.,basic_json__copyassignment}
  14008. @since version 1.0.0
  14009. */
  14010. basic_json& operator=(basic_json other) noexcept (
  14011. std::is_nothrow_move_constructible<value_t>::value and
  14012. std::is_nothrow_move_assignable<value_t>::value and
  14013. std::is_nothrow_move_constructible<json_value>::value and
  14014. std::is_nothrow_move_assignable<json_value>::value
  14015. )
  14016. {
  14017. // check that passed value is valid
  14018. other.assert_invariant();
  14019. using std::swap;
  14020. swap(m_type, other.m_type);
  14021. swap(m_value, other.m_value);
  14022. assert_invariant();
  14023. return *this;
  14024. }
  14025. /*!
  14026. @brief destructor
  14027. Destroys the JSON value and frees all allocated memory.
  14028. @complexity Linear.
  14029. @requirement This function helps `basic_json` satisfying the
  14030. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14031. requirements:
  14032. - The complexity is linear.
  14033. - All stored elements are destroyed and all memory is freed.
  14034. @since version 1.0.0
  14035. */
  14036. ~basic_json() noexcept
  14037. {
  14038. assert_invariant();
  14039. m_value.destroy(m_type);
  14040. }
  14041. /// @}
  14042. public:
  14043. ///////////////////////
  14044. // object inspection //
  14045. ///////////////////////
  14046. /// @name object inspection
  14047. /// Functions to inspect the type of a JSON value.
  14048. /// @{
  14049. /*!
  14050. @brief serialization
  14051. Serialization function for JSON values. The function tries to mimic
  14052. Python's `json.dumps()` function, and currently supports its @a indent
  14053. and @a ensure_ascii parameters.
  14054. @param[in] indent If indent is nonnegative, then array elements and object
  14055. members will be pretty-printed with that indent level. An indent level of
  14056. `0` will only insert newlines. `-1` (the default) selects the most compact
  14057. representation.
  14058. @param[in] indent_char The character to use for indentation if @a indent is
  14059. greater than `0`. The default is ` ` (space).
  14060. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  14061. in the output are escaped with `\uXXXX` sequences, and the result consists
  14062. of ASCII characters only.
  14063. @param[in] error_handler how to react on decoding errors; there are three
  14064. possible values: `strict` (throws and exception in case a decoding error
  14065. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  14066. and `ignore` (ignore invalid UTF-8 sequences during serialization).
  14067. @return string containing the serialization of the JSON value
  14068. @throw type_error.316 if a string stored inside the JSON value is not
  14069. UTF-8 encoded
  14070. @complexity Linear.
  14071. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14072. changes in the JSON value.
  14073. @liveexample{The following example shows the effect of different @a indent\,
  14074. @a indent_char\, and @a ensure_ascii parameters to the result of the
  14075. serialization.,dump}
  14076. @see https://docs.python.org/2/library/json.html#json.dump
  14077. @since version 1.0.0; indentation character @a indent_char, option
  14078. @a ensure_ascii and exceptions added in version 3.0.0; error
  14079. handlers added in version 3.4.0.
  14080. */
  14081. string_t dump(const int indent = -1,
  14082. const char indent_char = ' ',
  14083. const bool ensure_ascii = false,
  14084. const error_handler_t error_handler = error_handler_t::strict) const
  14085. {
  14086. string_t result;
  14087. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  14088. if (indent >= 0)
  14089. {
  14090. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  14091. }
  14092. else
  14093. {
  14094. s.dump(*this, false, ensure_ascii, 0);
  14095. }
  14096. return result;
  14097. }
  14098. /*!
  14099. @brief return the type of the JSON value (explicit)
  14100. Return the type of the JSON value as a value from the @ref value_t
  14101. enumeration.
  14102. @return the type of the JSON value
  14103. Value type | return value
  14104. ------------------------- | -------------------------
  14105. null | value_t::null
  14106. boolean | value_t::boolean
  14107. string | value_t::string
  14108. number (integer) | value_t::number_integer
  14109. number (unsigned integer) | value_t::number_unsigned
  14110. number (floating-point) | value_t::number_float
  14111. object | value_t::object
  14112. array | value_t::array
  14113. discarded | value_t::discarded
  14114. @complexity Constant.
  14115. @exceptionsafety No-throw guarantee: this member function never throws
  14116. exceptions.
  14117. @liveexample{The following code exemplifies `type()` for all JSON
  14118. types.,type}
  14119. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  14120. @sa @ref type_name() -- return the type as string
  14121. @since version 1.0.0
  14122. */
  14123. constexpr value_t type() const noexcept
  14124. {
  14125. return m_type;
  14126. }
  14127. /*!
  14128. @brief return whether type is primitive
  14129. This function returns true if and only if the JSON type is primitive
  14130. (string, number, boolean, or null).
  14131. @return `true` if type is primitive (string, number, boolean, or null),
  14132. `false` otherwise.
  14133. @complexity Constant.
  14134. @exceptionsafety No-throw guarantee: this member function never throws
  14135. exceptions.
  14136. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  14137. types.,is_primitive}
  14138. @sa @ref is_structured() -- returns whether JSON value is structured
  14139. @sa @ref is_null() -- returns whether JSON value is `null`
  14140. @sa @ref is_string() -- returns whether JSON value is a string
  14141. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  14142. @sa @ref is_number() -- returns whether JSON value is a number
  14143. @since version 1.0.0
  14144. */
  14145. constexpr bool is_primitive() const noexcept
  14146. {
  14147. return is_null() or is_string() or is_boolean() or is_number();
  14148. }
  14149. /*!
  14150. @brief return whether type is structured
  14151. This function returns true if and only if the JSON type is structured
  14152. (array or object).
  14153. @return `true` if type is structured (array or object), `false` otherwise.
  14154. @complexity Constant.
  14155. @exceptionsafety No-throw guarantee: this member function never throws
  14156. exceptions.
  14157. @liveexample{The following code exemplifies `is_structured()` for all JSON
  14158. types.,is_structured}
  14159. @sa @ref is_primitive() -- returns whether value is primitive
  14160. @sa @ref is_array() -- returns whether value is an array
  14161. @sa @ref is_object() -- returns whether value is an object
  14162. @since version 1.0.0
  14163. */
  14164. constexpr bool is_structured() const noexcept
  14165. {
  14166. return is_array() or is_object();
  14167. }
  14168. /*!
  14169. @brief return whether value is null
  14170. This function returns true if and only if the JSON value is null.
  14171. @return `true` if type is null, `false` otherwise.
  14172. @complexity Constant.
  14173. @exceptionsafety No-throw guarantee: this member function never throws
  14174. exceptions.
  14175. @liveexample{The following code exemplifies `is_null()` for all JSON
  14176. types.,is_null}
  14177. @since version 1.0.0
  14178. */
  14179. constexpr bool is_null() const noexcept
  14180. {
  14181. return m_type == value_t::null;
  14182. }
  14183. /*!
  14184. @brief return whether value is a boolean
  14185. This function returns true if and only if the JSON value is a boolean.
  14186. @return `true` if type is boolean, `false` otherwise.
  14187. @complexity Constant.
  14188. @exceptionsafety No-throw guarantee: this member function never throws
  14189. exceptions.
  14190. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  14191. types.,is_boolean}
  14192. @since version 1.0.0
  14193. */
  14194. constexpr bool is_boolean() const noexcept
  14195. {
  14196. return m_type == value_t::boolean;
  14197. }
  14198. /*!
  14199. @brief return whether value is a number
  14200. This function returns true if and only if the JSON value is a number. This
  14201. includes both integer (signed and unsigned) and floating-point values.
  14202. @return `true` if type is number (regardless whether integer, unsigned
  14203. integer or floating-type), `false` otherwise.
  14204. @complexity Constant.
  14205. @exceptionsafety No-throw guarantee: this member function never throws
  14206. exceptions.
  14207. @liveexample{The following code exemplifies `is_number()` for all JSON
  14208. types.,is_number}
  14209. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  14210. integer number
  14211. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  14212. number
  14213. @sa @ref is_number_float() -- check if value is a floating-point number
  14214. @since version 1.0.0
  14215. */
  14216. constexpr bool is_number() const noexcept
  14217. {
  14218. return is_number_integer() or is_number_float();
  14219. }
  14220. /*!
  14221. @brief return whether value is an integer number
  14222. This function returns true if and only if the JSON value is a signed or
  14223. unsigned integer number. This excludes floating-point values.
  14224. @return `true` if type is an integer or unsigned integer number, `false`
  14225. otherwise.
  14226. @complexity Constant.
  14227. @exceptionsafety No-throw guarantee: this member function never throws
  14228. exceptions.
  14229. @liveexample{The following code exemplifies `is_number_integer()` for all
  14230. JSON types.,is_number_integer}
  14231. @sa @ref is_number() -- check if value is a number
  14232. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  14233. number
  14234. @sa @ref is_number_float() -- check if value is a floating-point number
  14235. @since version 1.0.0
  14236. */
  14237. constexpr bool is_number_integer() const noexcept
  14238. {
  14239. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  14240. }
  14241. /*!
  14242. @brief return whether value is an unsigned integer number
  14243. This function returns true if and only if the JSON value is an unsigned
  14244. integer number. This excludes floating-point and signed integer values.
  14245. @return `true` if type is an unsigned integer number, `false` otherwise.
  14246. @complexity Constant.
  14247. @exceptionsafety No-throw guarantee: this member function never throws
  14248. exceptions.
  14249. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  14250. JSON types.,is_number_unsigned}
  14251. @sa @ref is_number() -- check if value is a number
  14252. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  14253. integer number
  14254. @sa @ref is_number_float() -- check if value is a floating-point number
  14255. @since version 2.0.0
  14256. */
  14257. constexpr bool is_number_unsigned() const noexcept
  14258. {
  14259. return m_type == value_t::number_unsigned;
  14260. }
  14261. /*!
  14262. @brief return whether value is a floating-point number
  14263. This function returns true if and only if the JSON value is a
  14264. floating-point number. This excludes signed and unsigned integer values.
  14265. @return `true` if type is a floating-point number, `false` otherwise.
  14266. @complexity Constant.
  14267. @exceptionsafety No-throw guarantee: this member function never throws
  14268. exceptions.
  14269. @liveexample{The following code exemplifies `is_number_float()` for all
  14270. JSON types.,is_number_float}
  14271. @sa @ref is_number() -- check if value is number
  14272. @sa @ref is_number_integer() -- check if value is an integer number
  14273. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  14274. number
  14275. @since version 1.0.0
  14276. */
  14277. constexpr bool is_number_float() const noexcept
  14278. {
  14279. return m_type == value_t::number_float;
  14280. }
  14281. /*!
  14282. @brief return whether value is an object
  14283. This function returns true if and only if the JSON value is an object.
  14284. @return `true` if type is object, `false` otherwise.
  14285. @complexity Constant.
  14286. @exceptionsafety No-throw guarantee: this member function never throws
  14287. exceptions.
  14288. @liveexample{The following code exemplifies `is_object()` for all JSON
  14289. types.,is_object}
  14290. @since version 1.0.0
  14291. */
  14292. constexpr bool is_object() const noexcept
  14293. {
  14294. return m_type == value_t::object;
  14295. }
  14296. /*!
  14297. @brief return whether value is an array
  14298. This function returns true if and only if the JSON value is an array.
  14299. @return `true` if type is array, `false` otherwise.
  14300. @complexity Constant.
  14301. @exceptionsafety No-throw guarantee: this member function never throws
  14302. exceptions.
  14303. @liveexample{The following code exemplifies `is_array()` for all JSON
  14304. types.,is_array}
  14305. @since version 1.0.0
  14306. */
  14307. constexpr bool is_array() const noexcept
  14308. {
  14309. return m_type == value_t::array;
  14310. }
  14311. /*!
  14312. @brief return whether value is a string
  14313. This function returns true if and only if the JSON value is a string.
  14314. @return `true` if type is string, `false` otherwise.
  14315. @complexity Constant.
  14316. @exceptionsafety No-throw guarantee: this member function never throws
  14317. exceptions.
  14318. @liveexample{The following code exemplifies `is_string()` for all JSON
  14319. types.,is_string}
  14320. @since version 1.0.0
  14321. */
  14322. constexpr bool is_string() const noexcept
  14323. {
  14324. return m_type == value_t::string;
  14325. }
  14326. /*!
  14327. @brief return whether value is discarded
  14328. This function returns true if and only if the JSON value was discarded
  14329. during parsing with a callback function (see @ref parser_callback_t).
  14330. @note This function will always be `false` for JSON values after parsing.
  14331. That is, discarded values can only occur during parsing, but will be
  14332. removed when inside a structured value or replaced by null in other cases.
  14333. @return `true` if type is discarded, `false` otherwise.
  14334. @complexity Constant.
  14335. @exceptionsafety No-throw guarantee: this member function never throws
  14336. exceptions.
  14337. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  14338. types.,is_discarded}
  14339. @since version 1.0.0
  14340. */
  14341. constexpr bool is_discarded() const noexcept
  14342. {
  14343. return m_type == value_t::discarded;
  14344. }
  14345. /*!
  14346. @brief return the type of the JSON value (implicit)
  14347. Implicitly return the type of the JSON value as a value from the @ref
  14348. value_t enumeration.
  14349. @return the type of the JSON value
  14350. @complexity Constant.
  14351. @exceptionsafety No-throw guarantee: this member function never throws
  14352. exceptions.
  14353. @liveexample{The following code exemplifies the @ref value_t operator for
  14354. all JSON types.,operator__value_t}
  14355. @sa @ref type() -- return the type of the JSON value (explicit)
  14356. @sa @ref type_name() -- return the type as string
  14357. @since version 1.0.0
  14358. */
  14359. constexpr operator value_t() const noexcept
  14360. {
  14361. return m_type;
  14362. }
  14363. /// @}
  14364. private:
  14365. //////////////////
  14366. // value access //
  14367. //////////////////
  14368. /// get a boolean (explicit)
  14369. boolean_t get_impl(boolean_t* /*unused*/) const
  14370. {
  14371. if (JSON_HEDLEY_LIKELY(is_boolean()))
  14372. {
  14373. return m_value.boolean;
  14374. }
  14375. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  14376. }
  14377. /// get a pointer to the value (object)
  14378. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  14379. {
  14380. return is_object() ? m_value.object : nullptr;
  14381. }
  14382. /// get a pointer to the value (object)
  14383. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  14384. {
  14385. return is_object() ? m_value.object : nullptr;
  14386. }
  14387. /// get a pointer to the value (array)
  14388. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  14389. {
  14390. return is_array() ? m_value.array : nullptr;
  14391. }
  14392. /// get a pointer to the value (array)
  14393. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  14394. {
  14395. return is_array() ? m_value.array : nullptr;
  14396. }
  14397. /// get a pointer to the value (string)
  14398. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  14399. {
  14400. return is_string() ? m_value.string : nullptr;
  14401. }
  14402. /// get a pointer to the value (string)
  14403. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  14404. {
  14405. return is_string() ? m_value.string : nullptr;
  14406. }
  14407. /// get a pointer to the value (boolean)
  14408. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  14409. {
  14410. return is_boolean() ? &m_value.boolean : nullptr;
  14411. }
  14412. /// get a pointer to the value (boolean)
  14413. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  14414. {
  14415. return is_boolean() ? &m_value.boolean : nullptr;
  14416. }
  14417. /// get a pointer to the value (integer number)
  14418. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  14419. {
  14420. return is_number_integer() ? &m_value.number_integer : nullptr;
  14421. }
  14422. /// get a pointer to the value (integer number)
  14423. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  14424. {
  14425. return is_number_integer() ? &m_value.number_integer : nullptr;
  14426. }
  14427. /// get a pointer to the value (unsigned number)
  14428. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  14429. {
  14430. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  14431. }
  14432. /// get a pointer to the value (unsigned number)
  14433. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  14434. {
  14435. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  14436. }
  14437. /// get a pointer to the value (floating-point number)
  14438. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  14439. {
  14440. return is_number_float() ? &m_value.number_float : nullptr;
  14441. }
  14442. /// get a pointer to the value (floating-point number)
  14443. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  14444. {
  14445. return is_number_float() ? &m_value.number_float : nullptr;
  14446. }
  14447. /*!
  14448. @brief helper function to implement get_ref()
  14449. This function helps to implement get_ref() without code duplication for
  14450. const and non-const overloads
  14451. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  14452. @throw type_error.303 if ReferenceType does not match underlying value
  14453. type of the current JSON
  14454. */
  14455. template<typename ReferenceType, typename ThisType>
  14456. static ReferenceType get_ref_impl(ThisType& obj)
  14457. {
  14458. // delegate the call to get_ptr<>()
  14459. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  14460. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  14461. {
  14462. return *ptr;
  14463. }
  14464. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  14465. }
  14466. public:
  14467. /// @name value access
  14468. /// Direct access to the stored value of a JSON value.
  14469. /// @{
  14470. /*!
  14471. @brief get special-case overload
  14472. This overloads avoids a lot of template boilerplate, it can be seen as the
  14473. identity method
  14474. @tparam BasicJsonType == @ref basic_json
  14475. @return a copy of *this
  14476. @complexity Constant.
  14477. @since version 2.1.0
  14478. */
  14479. template<typename BasicJsonType, detail::enable_if_t<
  14480. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  14481. int> = 0>
  14482. basic_json get() const
  14483. {
  14484. return *this;
  14485. }
  14486. /*!
  14487. @brief get special-case overload
  14488. This overloads converts the current @ref basic_json in a different
  14489. @ref basic_json type
  14490. @tparam BasicJsonType == @ref basic_json
  14491. @return a copy of *this, converted into @tparam BasicJsonType
  14492. @complexity Depending on the implementation of the called `from_json()`
  14493. method.
  14494. @since version 3.2.0
  14495. */
  14496. template<typename BasicJsonType, detail::enable_if_t<
  14497. not std::is_same<BasicJsonType, basic_json>::value and
  14498. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  14499. BasicJsonType get() const
  14500. {
  14501. return *this;
  14502. }
  14503. /*!
  14504. @brief get a value (explicit)
  14505. Explicit type conversion between the JSON value and a compatible value
  14506. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  14507. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  14508. The value is converted by calling the @ref json_serializer<ValueType>
  14509. `from_json()` method.
  14510. The function is equivalent to executing
  14511. @code {.cpp}
  14512. ValueType ret;
  14513. JSONSerializer<ValueType>::from_json(*this, ret);
  14514. return ret;
  14515. @endcode
  14516. This overloads is chosen if:
  14517. - @a ValueType is not @ref basic_json,
  14518. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  14519. `void from_json(const basic_json&, ValueType&)`, and
  14520. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  14521. the form `ValueType from_json(const basic_json&)`
  14522. @tparam ValueTypeCV the provided value type
  14523. @tparam ValueType the returned value type
  14524. @return copy of the JSON value, converted to @a ValueType
  14525. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  14526. @liveexample{The example below shows several conversions from JSON values
  14527. to other types. There a few things to note: (1) Floating-point numbers can
  14528. be converted to integers\, (2) A JSON array can be converted to a standard
  14529. `std::vector<short>`\, (3) A JSON object can be converted to C++
  14530. associative containers such as `std::unordered_map<std::string\,
  14531. json>`.,get__ValueType_const}
  14532. @since version 2.1.0
  14533. */
  14534. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  14535. detail::enable_if_t <
  14536. not detail::is_basic_json<ValueType>::value and
  14537. detail::has_from_json<basic_json_t, ValueType>::value and
  14538. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  14539. int> = 0>
  14540. ValueType get() const noexcept(noexcept(
  14541. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  14542. {
  14543. // we cannot static_assert on ValueTypeCV being non-const, because
  14544. // there is support for get<const basic_json_t>(), which is why we
  14545. // still need the uncvref
  14546. static_assert(not std::is_reference<ValueTypeCV>::value,
  14547. "get() cannot be used with reference types, you might want to use get_ref()");
  14548. static_assert(std::is_default_constructible<ValueType>::value,
  14549. "types must be DefaultConstructible when used with get()");
  14550. ValueType ret;
  14551. JSONSerializer<ValueType>::from_json(*this, ret);
  14552. return ret;
  14553. }
  14554. /*!
  14555. @brief get a value (explicit); special case
  14556. Explicit type conversion between the JSON value and a compatible value
  14557. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  14558. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  14559. The value is converted by calling the @ref json_serializer<ValueType>
  14560. `from_json()` method.
  14561. The function is equivalent to executing
  14562. @code {.cpp}
  14563. return JSONSerializer<ValueTypeCV>::from_json(*this);
  14564. @endcode
  14565. This overloads is chosen if:
  14566. - @a ValueType is not @ref basic_json and
  14567. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  14568. `ValueType from_json(const basic_json&)`
  14569. @note If @ref json_serializer<ValueType> has both overloads of
  14570. `from_json()`, this one is chosen.
  14571. @tparam ValueTypeCV the provided value type
  14572. @tparam ValueType the returned value type
  14573. @return copy of the JSON value, converted to @a ValueType
  14574. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  14575. @since version 2.1.0
  14576. */
  14577. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  14578. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  14579. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  14580. int> = 0>
  14581. ValueType get() const noexcept(noexcept(
  14582. JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
  14583. {
  14584. static_assert(not std::is_reference<ValueTypeCV>::value,
  14585. "get() cannot be used with reference types, you might want to use get_ref()");
  14586. return JSONSerializer<ValueTypeCV>::from_json(*this);
  14587. }
  14588. /*!
  14589. @brief get a value (explicit)
  14590. Explicit type conversion between the JSON value and a compatible value.
  14591. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  14592. `from_json()` method.
  14593. The function is equivalent to executing
  14594. @code {.cpp}
  14595. ValueType v;
  14596. JSONSerializer<ValueType>::from_json(*this, v);
  14597. @endcode
  14598. This overloads is chosen if:
  14599. - @a ValueType is not @ref basic_json,
  14600. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  14601. `void from_json(const basic_json&, ValueType&)`, and
  14602. @tparam ValueType the input parameter type.
  14603. @return the input parameter, allowing chaining calls.
  14604. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  14605. @liveexample{The example below shows several conversions from JSON values
  14606. to other types. There a few things to note: (1) Floating-point numbers can
  14607. be converted to integers\, (2) A JSON array can be converted to a standard
  14608. `std::vector<short>`\, (3) A JSON object can be converted to C++
  14609. associative containers such as `std::unordered_map<std::string\,
  14610. json>`.,get_to}
  14611. @since version 3.3.0
  14612. */
  14613. template<typename ValueType,
  14614. detail::enable_if_t <
  14615. not detail::is_basic_json<ValueType>::value and
  14616. detail::has_from_json<basic_json_t, ValueType>::value,
  14617. int> = 0>
  14618. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  14619. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  14620. {
  14621. JSONSerializer<ValueType>::from_json(*this, v);
  14622. return v;
  14623. }
  14624. template <
  14625. typename T, std::size_t N,
  14626. typename Array = T (&)[N],
  14627. detail::enable_if_t <
  14628. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  14629. Array get_to(T (&v)[N]) const
  14630. noexcept(noexcept(JSONSerializer<Array>::from_json(
  14631. std::declval<const basic_json_t&>(), v)))
  14632. {
  14633. JSONSerializer<Array>::from_json(*this, v);
  14634. return v;
  14635. }
  14636. /*!
  14637. @brief get a pointer value (implicit)
  14638. Implicit pointer access to the internally stored JSON value. No copies are
  14639. made.
  14640. @warning Writing data to the pointee of the result yields an undefined
  14641. state.
  14642. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  14643. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  14644. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  14645. assertion.
  14646. @return pointer to the internally stored JSON value if the requested
  14647. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  14648. @complexity Constant.
  14649. @liveexample{The example below shows how pointers to internal values of a
  14650. JSON value can be requested. Note that no type conversions are made and a
  14651. `nullptr` is returned if the value and the requested pointer type does not
  14652. match.,get_ptr}
  14653. @since version 1.0.0
  14654. */
  14655. template<typename PointerType, typename std::enable_if<
  14656. std::is_pointer<PointerType>::value, int>::type = 0>
  14657. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  14658. {
  14659. // delegate the call to get_impl_ptr<>()
  14660. return get_impl_ptr(static_cast<PointerType>(nullptr));
  14661. }
  14662. /*!
  14663. @brief get a pointer value (implicit)
  14664. @copydoc get_ptr()
  14665. */
  14666. template<typename PointerType, typename std::enable_if<
  14667. std::is_pointer<PointerType>::value and
  14668. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  14669. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  14670. {
  14671. // delegate the call to get_impl_ptr<>() const
  14672. return get_impl_ptr(static_cast<PointerType>(nullptr));
  14673. }
  14674. /*!
  14675. @brief get a pointer value (explicit)
  14676. Explicit pointer access to the internally stored JSON value. No copies are
  14677. made.
  14678. @warning The pointer becomes invalid if the underlying JSON object
  14679. changes.
  14680. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  14681. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  14682. @ref number_unsigned_t, or @ref number_float_t.
  14683. @return pointer to the internally stored JSON value if the requested
  14684. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  14685. @complexity Constant.
  14686. @liveexample{The example below shows how pointers to internal values of a
  14687. JSON value can be requested. Note that no type conversions are made and a
  14688. `nullptr` is returned if the value and the requested pointer type does not
  14689. match.,get__PointerType}
  14690. @sa @ref get_ptr() for explicit pointer-member access
  14691. @since version 1.0.0
  14692. */
  14693. template<typename PointerType, typename std::enable_if<
  14694. std::is_pointer<PointerType>::value, int>::type = 0>
  14695. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  14696. {
  14697. // delegate the call to get_ptr
  14698. return get_ptr<PointerType>();
  14699. }
  14700. /*!
  14701. @brief get a pointer value (explicit)
  14702. @copydoc get()
  14703. */
  14704. template<typename PointerType, typename std::enable_if<
  14705. std::is_pointer<PointerType>::value, int>::type = 0>
  14706. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  14707. {
  14708. // delegate the call to get_ptr
  14709. return get_ptr<PointerType>();
  14710. }
  14711. /*!
  14712. @brief get a reference value (implicit)
  14713. Implicit reference access to the internally stored JSON value. No copies
  14714. are made.
  14715. @warning Writing data to the referee of the result yields an undefined
  14716. state.
  14717. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  14718. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  14719. @ref number_float_t. Enforced by static assertion.
  14720. @return reference to the internally stored JSON value if the requested
  14721. reference type @a ReferenceType fits to the JSON value; throws
  14722. type_error.303 otherwise
  14723. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  14724. with the stored JSON value; see example below
  14725. @complexity Constant.
  14726. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  14727. @since version 1.1.0
  14728. */
  14729. template<typename ReferenceType, typename std::enable_if<
  14730. std::is_reference<ReferenceType>::value, int>::type = 0>
  14731. ReferenceType get_ref()
  14732. {
  14733. // delegate call to get_ref_impl
  14734. return get_ref_impl<ReferenceType>(*this);
  14735. }
  14736. /*!
  14737. @brief get a reference value (implicit)
  14738. @copydoc get_ref()
  14739. */
  14740. template<typename ReferenceType, typename std::enable_if<
  14741. std::is_reference<ReferenceType>::value and
  14742. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  14743. ReferenceType get_ref() const
  14744. {
  14745. // delegate call to get_ref_impl
  14746. return get_ref_impl<ReferenceType>(*this);
  14747. }
  14748. /*!
  14749. @brief get a value (implicit)
  14750. Implicit type conversion between the JSON value and a compatible value.
  14751. The call is realized by calling @ref get() const.
  14752. @tparam ValueType non-pointer type compatible to the JSON value, for
  14753. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  14754. `std::vector` types for JSON arrays. The character type of @ref string_t
  14755. as well as an initializer list of this type is excluded to avoid
  14756. ambiguities as these types implicitly convert to `std::string`.
  14757. @return copy of the JSON value, converted to type @a ValueType
  14758. @throw type_error.302 in case passed type @a ValueType is incompatible
  14759. to the JSON value type (e.g., the JSON value is of type boolean, but a
  14760. string is requested); see example below
  14761. @complexity Linear in the size of the JSON value.
  14762. @liveexample{The example below shows several conversions from JSON values
  14763. to other types. There a few things to note: (1) Floating-point numbers can
  14764. be converted to integers\, (2) A JSON array can be converted to a standard
  14765. `std::vector<short>`\, (3) A JSON object can be converted to C++
  14766. associative containers such as `std::unordered_map<std::string\,
  14767. json>`.,operator__ValueType}
  14768. @since version 1.0.0
  14769. */
  14770. template < typename ValueType, typename std::enable_if <
  14771. not std::is_pointer<ValueType>::value and
  14772. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  14773. not std::is_same<ValueType, typename string_t::value_type>::value and
  14774. not detail::is_basic_json<ValueType>::value
  14775. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  14776. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  14777. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) and _MSC_VER <= 1914))
  14778. and not std::is_same<ValueType, typename std::string_view>::value
  14779. #endif
  14780. #endif
  14781. and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  14782. , int >::type = 0 >
  14783. operator ValueType() const
  14784. {
  14785. // delegate the call to get<>() const
  14786. return get<ValueType>();
  14787. }
  14788. /// @}
  14789. ////////////////////
  14790. // element access //
  14791. ////////////////////
  14792. /// @name element access
  14793. /// Access to the JSON value.
  14794. /// @{
  14795. /*!
  14796. @brief access specified array element with bounds checking
  14797. Returns a reference to the element at specified location @a idx, with
  14798. bounds checking.
  14799. @param[in] idx index of the element to access
  14800. @return reference to the element at index @a idx
  14801. @throw type_error.304 if the JSON value is not an array; in this case,
  14802. calling `at` with an index makes no sense. See example below.
  14803. @throw out_of_range.401 if the index @a idx is out of range of the array;
  14804. that is, `idx >= size()`. See example below.
  14805. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14806. changes in the JSON value.
  14807. @complexity Constant.
  14808. @since version 1.0.0
  14809. @liveexample{The example below shows how array elements can be read and
  14810. written using `at()`. It also demonstrates the different exceptions that
  14811. can be thrown.,at__size_type}
  14812. */
  14813. reference at(size_type idx)
  14814. {
  14815. // at only works for arrays
  14816. if (JSON_HEDLEY_LIKELY(is_array()))
  14817. {
  14818. JSON_TRY
  14819. {
  14820. return m_value.array->at(idx);
  14821. }
  14822. JSON_CATCH (std::out_of_range&)
  14823. {
  14824. // create better exception explanation
  14825. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  14826. }
  14827. }
  14828. else
  14829. {
  14830. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  14831. }
  14832. }
  14833. /*!
  14834. @brief access specified array element with bounds checking
  14835. Returns a const reference to the element at specified location @a idx,
  14836. with bounds checking.
  14837. @param[in] idx index of the element to access
  14838. @return const reference to the element at index @a idx
  14839. @throw type_error.304 if the JSON value is not an array; in this case,
  14840. calling `at` with an index makes no sense. See example below.
  14841. @throw out_of_range.401 if the index @a idx is out of range of the array;
  14842. that is, `idx >= size()`. See example below.
  14843. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14844. changes in the JSON value.
  14845. @complexity Constant.
  14846. @since version 1.0.0
  14847. @liveexample{The example below shows how array elements can be read using
  14848. `at()`. It also demonstrates the different exceptions that can be thrown.,
  14849. at__size_type_const}
  14850. */
  14851. const_reference at(size_type idx) const
  14852. {
  14853. // at only works for arrays
  14854. if (JSON_HEDLEY_LIKELY(is_array()))
  14855. {
  14856. JSON_TRY
  14857. {
  14858. return m_value.array->at(idx);
  14859. }
  14860. JSON_CATCH (std::out_of_range&)
  14861. {
  14862. // create better exception explanation
  14863. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  14864. }
  14865. }
  14866. else
  14867. {
  14868. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  14869. }
  14870. }
  14871. /*!
  14872. @brief access specified object element with bounds checking
  14873. Returns a reference to the element at with specified key @a key, with
  14874. bounds checking.
  14875. @param[in] key key of the element to access
  14876. @return reference to the element at key @a key
  14877. @throw type_error.304 if the JSON value is not an object; in this case,
  14878. calling `at` with a key makes no sense. See example below.
  14879. @throw out_of_range.403 if the key @a key is is not stored in the object;
  14880. that is, `find(key) == end()`. See example below.
  14881. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14882. changes in the JSON value.
  14883. @complexity Logarithmic in the size of the container.
  14884. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  14885. access by reference
  14886. @sa @ref value() for access by value with a default value
  14887. @since version 1.0.0
  14888. @liveexample{The example below shows how object elements can be read and
  14889. written using `at()`. It also demonstrates the different exceptions that
  14890. can be thrown.,at__object_t_key_type}
  14891. */
  14892. reference at(const typename object_t::key_type& key)
  14893. {
  14894. // at only works for objects
  14895. if (JSON_HEDLEY_LIKELY(is_object()))
  14896. {
  14897. JSON_TRY
  14898. {
  14899. return m_value.object->at(key);
  14900. }
  14901. JSON_CATCH (std::out_of_range&)
  14902. {
  14903. // create better exception explanation
  14904. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  14905. }
  14906. }
  14907. else
  14908. {
  14909. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  14910. }
  14911. }
  14912. /*!
  14913. @brief access specified object element with bounds checking
  14914. Returns a const reference to the element at with specified key @a key,
  14915. with bounds checking.
  14916. @param[in] key key of the element to access
  14917. @return const reference to the element at key @a key
  14918. @throw type_error.304 if the JSON value is not an object; in this case,
  14919. calling `at` with a key makes no sense. See example below.
  14920. @throw out_of_range.403 if the key @a key is is not stored in the object;
  14921. that is, `find(key) == end()`. See example below.
  14922. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14923. changes in the JSON value.
  14924. @complexity Logarithmic in the size of the container.
  14925. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  14926. access by reference
  14927. @sa @ref value() for access by value with a default value
  14928. @since version 1.0.0
  14929. @liveexample{The example below shows how object elements can be read using
  14930. `at()`. It also demonstrates the different exceptions that can be thrown.,
  14931. at__object_t_key_type_const}
  14932. */
  14933. const_reference at(const typename object_t::key_type& key) const
  14934. {
  14935. // at only works for objects
  14936. if (JSON_HEDLEY_LIKELY(is_object()))
  14937. {
  14938. JSON_TRY
  14939. {
  14940. return m_value.object->at(key);
  14941. }
  14942. JSON_CATCH (std::out_of_range&)
  14943. {
  14944. // create better exception explanation
  14945. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  14946. }
  14947. }
  14948. else
  14949. {
  14950. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  14951. }
  14952. }
  14953. /*!
  14954. @brief access specified array element
  14955. Returns a reference to the element at specified location @a idx.
  14956. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  14957. then the array is silently filled up with `null` values to make `idx` a
  14958. valid reference to the last stored element.
  14959. @param[in] idx index of the element to access
  14960. @return reference to the element at index @a idx
  14961. @throw type_error.305 if the JSON value is not an array or null; in that
  14962. cases, using the [] operator with an index makes no sense.
  14963. @complexity Constant if @a idx is in the range of the array. Otherwise
  14964. linear in `idx - size()`.
  14965. @liveexample{The example below shows how array elements can be read and
  14966. written using `[]` operator. Note the addition of `null`
  14967. values.,operatorarray__size_type}
  14968. @since version 1.0.0
  14969. */
  14970. reference operator[](size_type idx)
  14971. {
  14972. // implicitly convert null value to an empty array
  14973. if (is_null())
  14974. {
  14975. m_type = value_t::array;
  14976. m_value.array = create<array_t>();
  14977. assert_invariant();
  14978. }
  14979. // operator[] only works for arrays
  14980. if (JSON_HEDLEY_LIKELY(is_array()))
  14981. {
  14982. // fill up array with null values if given idx is outside range
  14983. if (idx >= m_value.array->size())
  14984. {
  14985. m_value.array->insert(m_value.array->end(),
  14986. idx - m_value.array->size() + 1,
  14987. basic_json());
  14988. }
  14989. return m_value.array->operator[](idx);
  14990. }
  14991. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  14992. }
  14993. /*!
  14994. @brief access specified array element
  14995. Returns a const reference to the element at specified location @a idx.
  14996. @param[in] idx index of the element to access
  14997. @return const reference to the element at index @a idx
  14998. @throw type_error.305 if the JSON value is not an array; in that case,
  14999. using the [] operator with an index makes no sense.
  15000. @complexity Constant.
  15001. @liveexample{The example below shows how array elements can be read using
  15002. the `[]` operator.,operatorarray__size_type_const}
  15003. @since version 1.0.0
  15004. */
  15005. const_reference operator[](size_type idx) const
  15006. {
  15007. // const operator[] only works for arrays
  15008. if (JSON_HEDLEY_LIKELY(is_array()))
  15009. {
  15010. return m_value.array->operator[](idx);
  15011. }
  15012. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  15013. }
  15014. /*!
  15015. @brief access specified object element
  15016. Returns a reference to the element at with specified key @a key.
  15017. @note If @a key is not found in the object, then it is silently added to
  15018. the object and filled with a `null` value to make `key` a valid reference.
  15019. In case the value was `null` before, it is converted to an object.
  15020. @param[in] key key of the element to access
  15021. @return reference to the element at key @a key
  15022. @throw type_error.305 if the JSON value is not an object or null; in that
  15023. cases, using the [] operator with a key makes no sense.
  15024. @complexity Logarithmic in the size of the container.
  15025. @liveexample{The example below shows how object elements can be read and
  15026. written using the `[]` operator.,operatorarray__key_type}
  15027. @sa @ref at(const typename object_t::key_type&) for access by reference
  15028. with range checking
  15029. @sa @ref value() for access by value with a default value
  15030. @since version 1.0.0
  15031. */
  15032. reference operator[](const typename object_t::key_type& key)
  15033. {
  15034. // implicitly convert null value to an empty object
  15035. if (is_null())
  15036. {
  15037. m_type = value_t::object;
  15038. m_value.object = create<object_t>();
  15039. assert_invariant();
  15040. }
  15041. // operator[] only works for objects
  15042. if (JSON_HEDLEY_LIKELY(is_object()))
  15043. {
  15044. return m_value.object->operator[](key);
  15045. }
  15046. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15047. }
  15048. /*!
  15049. @brief read-only access specified object element
  15050. Returns a const reference to the element at with specified key @a key. No
  15051. bounds checking is performed.
  15052. @warning If the element with key @a key does not exist, the behavior is
  15053. undefined.
  15054. @param[in] key key of the element to access
  15055. @return const reference to the element at key @a key
  15056. @pre The element with key @a key must exist. **This precondition is
  15057. enforced with an assertion.**
  15058. @throw type_error.305 if the JSON value is not an object; in that case,
  15059. using the [] operator with a key makes no sense.
  15060. @complexity Logarithmic in the size of the container.
  15061. @liveexample{The example below shows how object elements can be read using
  15062. the `[]` operator.,operatorarray__key_type_const}
  15063. @sa @ref at(const typename object_t::key_type&) for access by reference
  15064. with range checking
  15065. @sa @ref value() for access by value with a default value
  15066. @since version 1.0.0
  15067. */
  15068. const_reference operator[](const typename object_t::key_type& key) const
  15069. {
  15070. // const operator[] only works for objects
  15071. if (JSON_HEDLEY_LIKELY(is_object()))
  15072. {
  15073. assert(m_value.object->find(key) != m_value.object->end());
  15074. return m_value.object->find(key)->second;
  15075. }
  15076. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15077. }
  15078. /*!
  15079. @brief access specified object element
  15080. Returns a reference to the element at with specified key @a key.
  15081. @note If @a key is not found in the object, then it is silently added to
  15082. the object and filled with a `null` value to make `key` a valid reference.
  15083. In case the value was `null` before, it is converted to an object.
  15084. @param[in] key key of the element to access
  15085. @return reference to the element at key @a key
  15086. @throw type_error.305 if the JSON value is not an object or null; in that
  15087. cases, using the [] operator with a key makes no sense.
  15088. @complexity Logarithmic in the size of the container.
  15089. @liveexample{The example below shows how object elements can be read and
  15090. written using the `[]` operator.,operatorarray__key_type}
  15091. @sa @ref at(const typename object_t::key_type&) for access by reference
  15092. with range checking
  15093. @sa @ref value() for access by value with a default value
  15094. @since version 1.1.0
  15095. */
  15096. template<typename T>
  15097. JSON_HEDLEY_NON_NULL(2)
  15098. reference operator[](T* key)
  15099. {
  15100. // implicitly convert null to object
  15101. if (is_null())
  15102. {
  15103. m_type = value_t::object;
  15104. m_value = value_t::object;
  15105. assert_invariant();
  15106. }
  15107. // at only works for objects
  15108. if (JSON_HEDLEY_LIKELY(is_object()))
  15109. {
  15110. return m_value.object->operator[](key);
  15111. }
  15112. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15113. }
  15114. /*!
  15115. @brief read-only access specified object element
  15116. Returns a const reference to the element at with specified key @a key. No
  15117. bounds checking is performed.
  15118. @warning If the element with key @a key does not exist, the behavior is
  15119. undefined.
  15120. @param[in] key key of the element to access
  15121. @return const reference to the element at key @a key
  15122. @pre The element with key @a key must exist. **This precondition is
  15123. enforced with an assertion.**
  15124. @throw type_error.305 if the JSON value is not an object; in that case,
  15125. using the [] operator with a key makes no sense.
  15126. @complexity Logarithmic in the size of the container.
  15127. @liveexample{The example below shows how object elements can be read using
  15128. the `[]` operator.,operatorarray__key_type_const}
  15129. @sa @ref at(const typename object_t::key_type&) for access by reference
  15130. with range checking
  15131. @sa @ref value() for access by value with a default value
  15132. @since version 1.1.0
  15133. */
  15134. template<typename T>
  15135. JSON_HEDLEY_NON_NULL(2)
  15136. const_reference operator[](T* key) const
  15137. {
  15138. // at only works for objects
  15139. if (JSON_HEDLEY_LIKELY(is_object()))
  15140. {
  15141. assert(m_value.object->find(key) != m_value.object->end());
  15142. return m_value.object->find(key)->second;
  15143. }
  15144. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15145. }
  15146. /*!
  15147. @brief access specified object element with default value
  15148. Returns either a copy of an object's element at the specified key @a key
  15149. or a given default value if no element with key @a key exists.
  15150. The function is basically equivalent to executing
  15151. @code {.cpp}
  15152. try {
  15153. return at(key);
  15154. } catch(out_of_range) {
  15155. return default_value;
  15156. }
  15157. @endcode
  15158. @note Unlike @ref at(const typename object_t::key_type&), this function
  15159. does not throw if the given key @a key was not found.
  15160. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  15161. function does not implicitly add an element to the position defined by @a
  15162. key. This function is furthermore also applicable to const objects.
  15163. @param[in] key key of the element to access
  15164. @param[in] default_value the value to return if @a key is not found
  15165. @tparam ValueType type compatible to JSON values, for instance `int` for
  15166. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  15167. JSON arrays. Note the type of the expected value at @a key and the default
  15168. value @a default_value must be compatible.
  15169. @return copy of the element at key @a key or @a default_value if @a key
  15170. is not found
  15171. @throw type_error.302 if @a default_value does not match the type of the
  15172. value at @a key
  15173. @throw type_error.306 if the JSON value is not an object; in that case,
  15174. using `value()` with a key makes no sense.
  15175. @complexity Logarithmic in the size of the container.
  15176. @liveexample{The example below shows how object elements can be queried
  15177. with a default value.,basic_json__value}
  15178. @sa @ref at(const typename object_t::key_type&) for access by reference
  15179. with range checking
  15180. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  15181. access by reference
  15182. @since version 1.0.0
  15183. */
  15184. template<class ValueType, typename std::enable_if<
  15185. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  15186. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  15187. {
  15188. // at only works for objects
  15189. if (JSON_HEDLEY_LIKELY(is_object()))
  15190. {
  15191. // if key is found, return value and given default value otherwise
  15192. const auto it = find(key);
  15193. if (it != end())
  15194. {
  15195. return *it;
  15196. }
  15197. return default_value;
  15198. }
  15199. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  15200. }
  15201. /*!
  15202. @brief overload for a default value of type const char*
  15203. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  15204. */
  15205. string_t value(const typename object_t::key_type& key, const char* default_value) const
  15206. {
  15207. return value(key, string_t(default_value));
  15208. }
  15209. /*!
  15210. @brief access specified object element via JSON Pointer with default value
  15211. Returns either a copy of an object's element at the specified key @a key
  15212. or a given default value if no element with key @a key exists.
  15213. The function is basically equivalent to executing
  15214. @code {.cpp}
  15215. try {
  15216. return at(ptr);
  15217. } catch(out_of_range) {
  15218. return default_value;
  15219. }
  15220. @endcode
  15221. @note Unlike @ref at(const json_pointer&), this function does not throw
  15222. if the given key @a key was not found.
  15223. @param[in] ptr a JSON pointer to the element to access
  15224. @param[in] default_value the value to return if @a ptr found no value
  15225. @tparam ValueType type compatible to JSON values, for instance `int` for
  15226. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  15227. JSON arrays. Note the type of the expected value at @a key and the default
  15228. value @a default_value must be compatible.
  15229. @return copy of the element at key @a key or @a default_value if @a key
  15230. is not found
  15231. @throw type_error.302 if @a default_value does not match the type of the
  15232. value at @a ptr
  15233. @throw type_error.306 if the JSON value is not an object; in that case,
  15234. using `value()` with a key makes no sense.
  15235. @complexity Logarithmic in the size of the container.
  15236. @liveexample{The example below shows how object elements can be queried
  15237. with a default value.,basic_json__value_ptr}
  15238. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  15239. @since version 2.0.2
  15240. */
  15241. template<class ValueType, typename std::enable_if<
  15242. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  15243. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  15244. {
  15245. // at only works for objects
  15246. if (JSON_HEDLEY_LIKELY(is_object()))
  15247. {
  15248. // if pointer resolves a value, return it or use default value
  15249. JSON_TRY
  15250. {
  15251. return ptr.get_checked(this);
  15252. }
  15253. JSON_INTERNAL_CATCH (out_of_range&)
  15254. {
  15255. return default_value;
  15256. }
  15257. }
  15258. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  15259. }
  15260. /*!
  15261. @brief overload for a default value of type const char*
  15262. @copydoc basic_json::value(const json_pointer&, ValueType) const
  15263. */
  15264. JSON_HEDLEY_NON_NULL(3)
  15265. string_t value(const json_pointer& ptr, const char* default_value) const
  15266. {
  15267. return value(ptr, string_t(default_value));
  15268. }
  15269. /*!
  15270. @brief access the first element
  15271. Returns a reference to the first element in the container. For a JSON
  15272. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  15273. @return In case of a structured type (array or object), a reference to the
  15274. first element is returned. In case of number, string, or boolean values, a
  15275. reference to the value is returned.
  15276. @complexity Constant.
  15277. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  15278. or an empty array or object (undefined behavior, **guarded by
  15279. assertions**).
  15280. @post The JSON value remains unchanged.
  15281. @throw invalid_iterator.214 when called on `null` value
  15282. @liveexample{The following code shows an example for `front()`.,front}
  15283. @sa @ref back() -- access the last element
  15284. @since version 1.0.0
  15285. */
  15286. reference front()
  15287. {
  15288. return *begin();
  15289. }
  15290. /*!
  15291. @copydoc basic_json::front()
  15292. */
  15293. const_reference front() const
  15294. {
  15295. return *cbegin();
  15296. }
  15297. /*!
  15298. @brief access the last element
  15299. Returns a reference to the last element in the container. For a JSON
  15300. container `c`, the expression `c.back()` is equivalent to
  15301. @code {.cpp}
  15302. auto tmp = c.end();
  15303. --tmp;
  15304. return *tmp;
  15305. @endcode
  15306. @return In case of a structured type (array or object), a reference to the
  15307. last element is returned. In case of number, string, or boolean values, a
  15308. reference to the value is returned.
  15309. @complexity Constant.
  15310. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  15311. or an empty array or object (undefined behavior, **guarded by
  15312. assertions**).
  15313. @post The JSON value remains unchanged.
  15314. @throw invalid_iterator.214 when called on a `null` value. See example
  15315. below.
  15316. @liveexample{The following code shows an example for `back()`.,back}
  15317. @sa @ref front() -- access the first element
  15318. @since version 1.0.0
  15319. */
  15320. reference back()
  15321. {
  15322. auto tmp = end();
  15323. --tmp;
  15324. return *tmp;
  15325. }
  15326. /*!
  15327. @copydoc basic_json::back()
  15328. */
  15329. const_reference back() const
  15330. {
  15331. auto tmp = cend();
  15332. --tmp;
  15333. return *tmp;
  15334. }
  15335. /*!
  15336. @brief remove element given an iterator
  15337. Removes the element specified by iterator @a pos. The iterator @a pos must
  15338. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  15339. but is not dereferenceable) cannot be used as a value for @a pos.
  15340. If called on a primitive type other than `null`, the resulting JSON value
  15341. will be `null`.
  15342. @param[in] pos iterator to the element to remove
  15343. @return Iterator following the last removed element. If the iterator @a
  15344. pos refers to the last element, the `end()` iterator is returned.
  15345. @tparam IteratorType an @ref iterator or @ref const_iterator
  15346. @post Invalidates iterators and references at or after the point of the
  15347. erase, including the `end()` iterator.
  15348. @throw type_error.307 if called on a `null` value; example: `"cannot use
  15349. erase() with null"`
  15350. @throw invalid_iterator.202 if called on an iterator which does not belong
  15351. to the current JSON value; example: `"iterator does not fit current
  15352. value"`
  15353. @throw invalid_iterator.205 if called on a primitive type with invalid
  15354. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  15355. out of range"`
  15356. @complexity The complexity depends on the type:
  15357. - objects: amortized constant
  15358. - arrays: linear in distance between @a pos and the end of the container
  15359. - strings: linear in the length of the string
  15360. - other types: constant
  15361. @liveexample{The example shows the result of `erase()` for different JSON
  15362. types.,erase__IteratorType}
  15363. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  15364. the given range
  15365. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  15366. from an object at the given key
  15367. @sa @ref erase(const size_type) -- removes the element from an array at
  15368. the given index
  15369. @since version 1.0.0
  15370. */
  15371. template<class IteratorType, typename std::enable_if<
  15372. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  15373. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  15374. = 0>
  15375. IteratorType erase(IteratorType pos)
  15376. {
  15377. // make sure iterator fits the current value
  15378. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  15379. {
  15380. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  15381. }
  15382. IteratorType result = end();
  15383. switch (m_type)
  15384. {
  15385. case value_t::boolean:
  15386. case value_t::number_float:
  15387. case value_t::number_integer:
  15388. case value_t::number_unsigned:
  15389. case value_t::string:
  15390. {
  15391. if (JSON_HEDLEY_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  15392. {
  15393. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  15394. }
  15395. if (is_string())
  15396. {
  15397. AllocatorType<string_t> alloc;
  15398. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  15399. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  15400. m_value.string = nullptr;
  15401. }
  15402. m_type = value_t::null;
  15403. assert_invariant();
  15404. break;
  15405. }
  15406. case value_t::object:
  15407. {
  15408. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  15409. break;
  15410. }
  15411. case value_t::array:
  15412. {
  15413. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  15414. break;
  15415. }
  15416. default:
  15417. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15418. }
  15419. return result;
  15420. }
  15421. /*!
  15422. @brief remove elements given an iterator range
  15423. Removes the element specified by the range `[first; last)`. The iterator
  15424. @a first does not need to be dereferenceable if `first == last`: erasing
  15425. an empty range is a no-op.
  15426. If called on a primitive type other than `null`, the resulting JSON value
  15427. will be `null`.
  15428. @param[in] first iterator to the beginning of the range to remove
  15429. @param[in] last iterator past the end of the range to remove
  15430. @return Iterator following the last removed element. If the iterator @a
  15431. second refers to the last element, the `end()` iterator is returned.
  15432. @tparam IteratorType an @ref iterator or @ref const_iterator
  15433. @post Invalidates iterators and references at or after the point of the
  15434. erase, including the `end()` iterator.
  15435. @throw type_error.307 if called on a `null` value; example: `"cannot use
  15436. erase() with null"`
  15437. @throw invalid_iterator.203 if called on iterators which does not belong
  15438. to the current JSON value; example: `"iterators do not fit current value"`
  15439. @throw invalid_iterator.204 if called on a primitive type with invalid
  15440. iterators (i.e., if `first != begin()` and `last != end()`); example:
  15441. `"iterators out of range"`
  15442. @complexity The complexity depends on the type:
  15443. - objects: `log(size()) + std::distance(first, last)`
  15444. - arrays: linear in the distance between @a first and @a last, plus linear
  15445. in the distance between @a last and end of the container
  15446. - strings: linear in the length of the string
  15447. - other types: constant
  15448. @liveexample{The example shows the result of `erase()` for different JSON
  15449. types.,erase__IteratorType_IteratorType}
  15450. @sa @ref erase(IteratorType) -- removes the element at a given position
  15451. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  15452. from an object at the given key
  15453. @sa @ref erase(const size_type) -- removes the element from an array at
  15454. the given index
  15455. @since version 1.0.0
  15456. */
  15457. template<class IteratorType, typename std::enable_if<
  15458. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  15459. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  15460. = 0>
  15461. IteratorType erase(IteratorType first, IteratorType last)
  15462. {
  15463. // make sure iterator fits the current value
  15464. if (JSON_HEDLEY_UNLIKELY(this != first.m_object or this != last.m_object))
  15465. {
  15466. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  15467. }
  15468. IteratorType result = end();
  15469. switch (m_type)
  15470. {
  15471. case value_t::boolean:
  15472. case value_t::number_float:
  15473. case value_t::number_integer:
  15474. case value_t::number_unsigned:
  15475. case value_t::string:
  15476. {
  15477. if (JSON_HEDLEY_LIKELY(not first.m_it.primitive_iterator.is_begin()
  15478. or not last.m_it.primitive_iterator.is_end()))
  15479. {
  15480. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  15481. }
  15482. if (is_string())
  15483. {
  15484. AllocatorType<string_t> alloc;
  15485. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  15486. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  15487. m_value.string = nullptr;
  15488. }
  15489. m_type = value_t::null;
  15490. assert_invariant();
  15491. break;
  15492. }
  15493. case value_t::object:
  15494. {
  15495. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  15496. last.m_it.object_iterator);
  15497. break;
  15498. }
  15499. case value_t::array:
  15500. {
  15501. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  15502. last.m_it.array_iterator);
  15503. break;
  15504. }
  15505. default:
  15506. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15507. }
  15508. return result;
  15509. }
  15510. /*!
  15511. @brief remove element from a JSON object given a key
  15512. Removes elements from a JSON object with the key value @a key.
  15513. @param[in] key value of the elements to remove
  15514. @return Number of elements removed. If @a ObjectType is the default
  15515. `std::map` type, the return value will always be `0` (@a key was not
  15516. found) or `1` (@a key was found).
  15517. @post References and iterators to the erased elements are invalidated.
  15518. Other references and iterators are not affected.
  15519. @throw type_error.307 when called on a type other than JSON object;
  15520. example: `"cannot use erase() with null"`
  15521. @complexity `log(size()) + count(key)`
  15522. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  15523. @sa @ref erase(IteratorType) -- removes the element at a given position
  15524. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  15525. the given range
  15526. @sa @ref erase(const size_type) -- removes the element from an array at
  15527. the given index
  15528. @since version 1.0.0
  15529. */
  15530. size_type erase(const typename object_t::key_type& key)
  15531. {
  15532. // this erase only works for objects
  15533. if (JSON_HEDLEY_LIKELY(is_object()))
  15534. {
  15535. return m_value.object->erase(key);
  15536. }
  15537. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15538. }
  15539. /*!
  15540. @brief remove element from a JSON array given an index
  15541. Removes element from a JSON array at the index @a idx.
  15542. @param[in] idx index of the element to remove
  15543. @throw type_error.307 when called on a type other than JSON object;
  15544. example: `"cannot use erase() with null"`
  15545. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  15546. is out of range"`
  15547. @complexity Linear in distance between @a idx and the end of the container.
  15548. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  15549. @sa @ref erase(IteratorType) -- removes the element at a given position
  15550. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  15551. the given range
  15552. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  15553. from an object at the given key
  15554. @since version 1.0.0
  15555. */
  15556. void erase(const size_type idx)
  15557. {
  15558. // this erase only works for arrays
  15559. if (JSON_HEDLEY_LIKELY(is_array()))
  15560. {
  15561. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  15562. {
  15563. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  15564. }
  15565. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  15566. }
  15567. else
  15568. {
  15569. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15570. }
  15571. }
  15572. /// @}
  15573. ////////////
  15574. // lookup //
  15575. ////////////
  15576. /// @name lookup
  15577. /// @{
  15578. /*!
  15579. @brief find an element in a JSON object
  15580. Finds an element in a JSON object with key equivalent to @a key. If the
  15581. element is not found or the JSON value is not an object, end() is
  15582. returned.
  15583. @note This method always returns @ref end() when executed on a JSON type
  15584. that is not an object.
  15585. @param[in] key key value of the element to search for.
  15586. @return Iterator to an element with key equivalent to @a key. If no such
  15587. element is found or the JSON value is not an object, past-the-end (see
  15588. @ref end()) iterator is returned.
  15589. @complexity Logarithmic in the size of the JSON object.
  15590. @liveexample{The example shows how `find()` is used.,find__key_type}
  15591. @sa @ref contains(KeyT&&) const -- checks whether a key exists
  15592. @since version 1.0.0
  15593. */
  15594. template<typename KeyT>
  15595. iterator find(KeyT&& key)
  15596. {
  15597. auto result = end();
  15598. if (is_object())
  15599. {
  15600. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  15601. }
  15602. return result;
  15603. }
  15604. /*!
  15605. @brief find an element in a JSON object
  15606. @copydoc find(KeyT&&)
  15607. */
  15608. template<typename KeyT>
  15609. const_iterator find(KeyT&& key) const
  15610. {
  15611. auto result = cend();
  15612. if (is_object())
  15613. {
  15614. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  15615. }
  15616. return result;
  15617. }
  15618. /*!
  15619. @brief returns the number of occurrences of a key in a JSON object
  15620. Returns the number of elements with key @a key. If ObjectType is the
  15621. default `std::map` type, the return value will always be `0` (@a key was
  15622. not found) or `1` (@a key was found).
  15623. @note This method always returns `0` when executed on a JSON type that is
  15624. not an object.
  15625. @param[in] key key value of the element to count
  15626. @return Number of elements with key @a key. If the JSON value is not an
  15627. object, the return value will be `0`.
  15628. @complexity Logarithmic in the size of the JSON object.
  15629. @liveexample{The example shows how `count()` is used.,count}
  15630. @since version 1.0.0
  15631. */
  15632. template<typename KeyT>
  15633. size_type count(KeyT&& key) const
  15634. {
  15635. // return 0 for all nonobject types
  15636. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  15637. }
  15638. /*!
  15639. @brief check the existence of an element in a JSON object
  15640. Check whether an element exists in a JSON object with key equivalent to
  15641. @a key. If the element is not found or the JSON value is not an object,
  15642. false is returned.
  15643. @note This method always returns false when executed on a JSON type
  15644. that is not an object.
  15645. @param[in] key key value to check its existence.
  15646. @return true if an element with specified @a key exists. If no such
  15647. element with such key is found or the JSON value is not an object,
  15648. false is returned.
  15649. @complexity Logarithmic in the size of the JSON object.
  15650. @liveexample{The following code shows an example for `contains()`.,contains}
  15651. @sa @ref find(KeyT&&) -- returns an iterator to an object element
  15652. @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  15653. @since version 3.6.0
  15654. */
  15655. template<typename KeyT, typename std::enable_if<
  15656. not std::is_same<KeyT, json_pointer>::value, int>::type = 0>
  15657. bool contains(KeyT && key) const
  15658. {
  15659. return is_object() and m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  15660. }
  15661. /*!
  15662. @brief check the existence of an element in a JSON object given a JSON pointer
  15663. Check wehther the given JSON pointer @a ptr can be resolved in the current
  15664. JSON value.
  15665. @note This method can be executed on any JSON value type.
  15666. @param[in] ptr JSON pointer to check its existence.
  15667. @return true if the JSON pointer can be resolved to a stored value, false
  15668. otherwise.
  15669. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  15670. @throw parse_error.106 if an array index begins with '0'
  15671. @throw parse_error.109 if an array index was not a number
  15672. @complexity Logarithmic in the size of the JSON object.
  15673. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  15674. @sa @ref contains(KeyT &&) const -- checks the existence of a key
  15675. @since version 3.7.0
  15676. */
  15677. bool contains(const json_pointer& ptr) const
  15678. {
  15679. return ptr.contains(this);
  15680. }
  15681. /// @}
  15682. ///////////////
  15683. // iterators //
  15684. ///////////////
  15685. /// @name iterators
  15686. /// @{
  15687. /*!
  15688. @brief returns an iterator to the first element
  15689. Returns an iterator to the first element.
  15690. @image html range-begin-end.svg "Illustration from cppreference.com"
  15691. @return iterator to the first element
  15692. @complexity Constant.
  15693. @requirement This function helps `basic_json` satisfying the
  15694. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15695. requirements:
  15696. - The complexity is constant.
  15697. @liveexample{The following code shows an example for `begin()`.,begin}
  15698. @sa @ref cbegin() -- returns a const iterator to the beginning
  15699. @sa @ref end() -- returns an iterator to the end
  15700. @sa @ref cend() -- returns a const iterator to the end
  15701. @since version 1.0.0
  15702. */
  15703. iterator begin() noexcept
  15704. {
  15705. iterator result(this);
  15706. result.set_begin();
  15707. return result;
  15708. }
  15709. /*!
  15710. @copydoc basic_json::cbegin()
  15711. */
  15712. const_iterator begin() const noexcept
  15713. {
  15714. return cbegin();
  15715. }
  15716. /*!
  15717. @brief returns a const iterator to the first element
  15718. Returns a const iterator to the first element.
  15719. @image html range-begin-end.svg "Illustration from cppreference.com"
  15720. @return const iterator to the first element
  15721. @complexity Constant.
  15722. @requirement This function helps `basic_json` satisfying the
  15723. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15724. requirements:
  15725. - The complexity is constant.
  15726. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  15727. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  15728. @sa @ref begin() -- returns an iterator to the beginning
  15729. @sa @ref end() -- returns an iterator to the end
  15730. @sa @ref cend() -- returns a const iterator to the end
  15731. @since version 1.0.0
  15732. */
  15733. const_iterator cbegin() const noexcept
  15734. {
  15735. const_iterator result(this);
  15736. result.set_begin();
  15737. return result;
  15738. }
  15739. /*!
  15740. @brief returns an iterator to one past the last element
  15741. Returns an iterator to one past the last element.
  15742. @image html range-begin-end.svg "Illustration from cppreference.com"
  15743. @return iterator one past the last element
  15744. @complexity Constant.
  15745. @requirement This function helps `basic_json` satisfying the
  15746. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15747. requirements:
  15748. - The complexity is constant.
  15749. @liveexample{The following code shows an example for `end()`.,end}
  15750. @sa @ref cend() -- returns a const iterator to the end
  15751. @sa @ref begin() -- returns an iterator to the beginning
  15752. @sa @ref cbegin() -- returns a const iterator to the beginning
  15753. @since version 1.0.0
  15754. */
  15755. iterator end() noexcept
  15756. {
  15757. iterator result(this);
  15758. result.set_end();
  15759. return result;
  15760. }
  15761. /*!
  15762. @copydoc basic_json::cend()
  15763. */
  15764. const_iterator end() const noexcept
  15765. {
  15766. return cend();
  15767. }
  15768. /*!
  15769. @brief returns a const iterator to one past the last element
  15770. Returns a const iterator to one past the last element.
  15771. @image html range-begin-end.svg "Illustration from cppreference.com"
  15772. @return const iterator one past the last element
  15773. @complexity Constant.
  15774. @requirement This function helps `basic_json` satisfying the
  15775. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15776. requirements:
  15777. - The complexity is constant.
  15778. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  15779. @liveexample{The following code shows an example for `cend()`.,cend}
  15780. @sa @ref end() -- returns an iterator to the end
  15781. @sa @ref begin() -- returns an iterator to the beginning
  15782. @sa @ref cbegin() -- returns a const iterator to the beginning
  15783. @since version 1.0.0
  15784. */
  15785. const_iterator cend() const noexcept
  15786. {
  15787. const_iterator result(this);
  15788. result.set_end();
  15789. return result;
  15790. }
  15791. /*!
  15792. @brief returns an iterator to the reverse-beginning
  15793. Returns an iterator to the reverse-beginning; that is, the last element.
  15794. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15795. @complexity Constant.
  15796. @requirement This function helps `basic_json` satisfying the
  15797. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15798. requirements:
  15799. - The complexity is constant.
  15800. - Has the semantics of `reverse_iterator(end())`.
  15801. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  15802. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  15803. @sa @ref rend() -- returns a reverse iterator to the end
  15804. @sa @ref crend() -- returns a const reverse iterator to the end
  15805. @since version 1.0.0
  15806. */
  15807. reverse_iterator rbegin() noexcept
  15808. {
  15809. return reverse_iterator(end());
  15810. }
  15811. /*!
  15812. @copydoc basic_json::crbegin()
  15813. */
  15814. const_reverse_iterator rbegin() const noexcept
  15815. {
  15816. return crbegin();
  15817. }
  15818. /*!
  15819. @brief returns an iterator to the reverse-end
  15820. Returns an iterator to the reverse-end; that is, one before the first
  15821. element.
  15822. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15823. @complexity Constant.
  15824. @requirement This function helps `basic_json` satisfying the
  15825. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15826. requirements:
  15827. - The complexity is constant.
  15828. - Has the semantics of `reverse_iterator(begin())`.
  15829. @liveexample{The following code shows an example for `rend()`.,rend}
  15830. @sa @ref crend() -- returns a const reverse iterator to the end
  15831. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  15832. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  15833. @since version 1.0.0
  15834. */
  15835. reverse_iterator rend() noexcept
  15836. {
  15837. return reverse_iterator(begin());
  15838. }
  15839. /*!
  15840. @copydoc basic_json::crend()
  15841. */
  15842. const_reverse_iterator rend() const noexcept
  15843. {
  15844. return crend();
  15845. }
  15846. /*!
  15847. @brief returns a const reverse iterator to the last element
  15848. Returns a const iterator to the reverse-beginning; that is, the last
  15849. element.
  15850. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15851. @complexity Constant.
  15852. @requirement This function helps `basic_json` satisfying the
  15853. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15854. requirements:
  15855. - The complexity is constant.
  15856. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  15857. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  15858. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  15859. @sa @ref rend() -- returns a reverse iterator to the end
  15860. @sa @ref crend() -- returns a const reverse iterator to the end
  15861. @since version 1.0.0
  15862. */
  15863. const_reverse_iterator crbegin() const noexcept
  15864. {
  15865. return const_reverse_iterator(cend());
  15866. }
  15867. /*!
  15868. @brief returns a const reverse iterator to one before the first
  15869. Returns a const reverse iterator to the reverse-end; that is, one before
  15870. the first element.
  15871. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15872. @complexity Constant.
  15873. @requirement This function helps `basic_json` satisfying the
  15874. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15875. requirements:
  15876. - The complexity is constant.
  15877. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  15878. @liveexample{The following code shows an example for `crend()`.,crend}
  15879. @sa @ref rend() -- returns a reverse iterator to the end
  15880. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  15881. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  15882. @since version 1.0.0
  15883. */
  15884. const_reverse_iterator crend() const noexcept
  15885. {
  15886. return const_reverse_iterator(cbegin());
  15887. }
  15888. public:
  15889. /*!
  15890. @brief wrapper to access iterator member functions in range-based for
  15891. This function allows to access @ref iterator::key() and @ref
  15892. iterator::value() during range-based for loops. In these loops, a
  15893. reference to the JSON values is returned, so there is no access to the
  15894. underlying iterator.
  15895. For loop without iterator_wrapper:
  15896. @code{cpp}
  15897. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  15898. {
  15899. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  15900. }
  15901. @endcode
  15902. Range-based for loop without iterator proxy:
  15903. @code{cpp}
  15904. for (auto it : j_object)
  15905. {
  15906. // "it" is of type json::reference and has no key() member
  15907. std::cout << "value: " << it << '\n';
  15908. }
  15909. @endcode
  15910. Range-based for loop with iterator proxy:
  15911. @code{cpp}
  15912. for (auto it : json::iterator_wrapper(j_object))
  15913. {
  15914. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  15915. }
  15916. @endcode
  15917. @note When iterating over an array, `key()` will return the index of the
  15918. element as string (see example).
  15919. @param[in] ref reference to a JSON value
  15920. @return iteration proxy object wrapping @a ref with an interface to use in
  15921. range-based for loops
  15922. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  15923. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15924. changes in the JSON value.
  15925. @complexity Constant.
  15926. @note The name of this function is not yet final and may change in the
  15927. future.
  15928. @deprecated This stream operator is deprecated and will be removed in
  15929. future 4.0.0 of the library. Please use @ref items() instead;
  15930. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  15931. */
  15932. JSON_HEDLEY_DEPRECATED(3.1.0)
  15933. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  15934. {
  15935. return ref.items();
  15936. }
  15937. /*!
  15938. @copydoc iterator_wrapper(reference)
  15939. */
  15940. JSON_HEDLEY_DEPRECATED(3.1.0)
  15941. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  15942. {
  15943. return ref.items();
  15944. }
  15945. /*!
  15946. @brief helper to access iterator member functions in range-based for
  15947. This function allows to access @ref iterator::key() and @ref
  15948. iterator::value() during range-based for loops. In these loops, a
  15949. reference to the JSON values is returned, so there is no access to the
  15950. underlying iterator.
  15951. For loop without `items()` function:
  15952. @code{cpp}
  15953. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  15954. {
  15955. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  15956. }
  15957. @endcode
  15958. Range-based for loop without `items()` function:
  15959. @code{cpp}
  15960. for (auto it : j_object)
  15961. {
  15962. // "it" is of type json::reference and has no key() member
  15963. std::cout << "value: " << it << '\n';
  15964. }
  15965. @endcode
  15966. Range-based for loop with `items()` function:
  15967. @code{cpp}
  15968. for (auto& el : j_object.items())
  15969. {
  15970. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  15971. }
  15972. @endcode
  15973. The `items()` function also allows to use
  15974. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  15975. (C++17):
  15976. @code{cpp}
  15977. for (auto& [key, val] : j_object.items())
  15978. {
  15979. std::cout << "key: " << key << ", value:" << val << '\n';
  15980. }
  15981. @endcode
  15982. @note When iterating over an array, `key()` will return the index of the
  15983. element as string (see example). For primitive types (e.g., numbers),
  15984. `key()` returns an empty string.
  15985. @return iteration proxy object wrapping @a ref with an interface to use in
  15986. range-based for loops
  15987. @liveexample{The following code shows how the function is used.,items}
  15988. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15989. changes in the JSON value.
  15990. @complexity Constant.
  15991. @since version 3.1.0, structured bindings support since 3.5.0.
  15992. */
  15993. iteration_proxy<iterator> items() noexcept
  15994. {
  15995. return iteration_proxy<iterator>(*this);
  15996. }
  15997. /*!
  15998. @copydoc items()
  15999. */
  16000. iteration_proxy<const_iterator> items() const noexcept
  16001. {
  16002. return iteration_proxy<const_iterator>(*this);
  16003. }
  16004. /// @}
  16005. //////////////
  16006. // capacity //
  16007. //////////////
  16008. /// @name capacity
  16009. /// @{
  16010. /*!
  16011. @brief checks whether the container is empty.
  16012. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  16013. @return The return value depends on the different types and is
  16014. defined as follows:
  16015. Value type | return value
  16016. ----------- | -------------
  16017. null | `true`
  16018. boolean | `false`
  16019. string | `false`
  16020. number | `false`
  16021. object | result of function `object_t::empty()`
  16022. array | result of function `array_t::empty()`
  16023. @liveexample{The following code uses `empty()` to check if a JSON
  16024. object contains any elements.,empty}
  16025. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  16026. the Container concept; that is, their `empty()` functions have constant
  16027. complexity.
  16028. @iterators No changes.
  16029. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16030. @note This function does not return whether a string stored as JSON value
  16031. is empty - it returns whether the JSON container itself is empty which is
  16032. false in the case of a string.
  16033. @requirement This function helps `basic_json` satisfying the
  16034. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16035. requirements:
  16036. - The complexity is constant.
  16037. - Has the semantics of `begin() == end()`.
  16038. @sa @ref size() -- returns the number of elements
  16039. @since version 1.0.0
  16040. */
  16041. bool empty() const noexcept
  16042. {
  16043. switch (m_type)
  16044. {
  16045. case value_t::null:
  16046. {
  16047. // null values are empty
  16048. return true;
  16049. }
  16050. case value_t::array:
  16051. {
  16052. // delegate call to array_t::empty()
  16053. return m_value.array->empty();
  16054. }
  16055. case value_t::object:
  16056. {
  16057. // delegate call to object_t::empty()
  16058. return m_value.object->empty();
  16059. }
  16060. default:
  16061. {
  16062. // all other types are nonempty
  16063. return false;
  16064. }
  16065. }
  16066. }
  16067. /*!
  16068. @brief returns the number of elements
  16069. Returns the number of elements in a JSON value.
  16070. @return The return value depends on the different types and is
  16071. defined as follows:
  16072. Value type | return value
  16073. ----------- | -------------
  16074. null | `0`
  16075. boolean | `1`
  16076. string | `1`
  16077. number | `1`
  16078. object | result of function object_t::size()
  16079. array | result of function array_t::size()
  16080. @liveexample{The following code calls `size()` on the different value
  16081. types.,size}
  16082. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  16083. the Container concept; that is, their size() functions have constant
  16084. complexity.
  16085. @iterators No changes.
  16086. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16087. @note This function does not return the length of a string stored as JSON
  16088. value - it returns the number of elements in the JSON value which is 1 in
  16089. the case of a string.
  16090. @requirement This function helps `basic_json` satisfying the
  16091. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16092. requirements:
  16093. - The complexity is constant.
  16094. - Has the semantics of `std::distance(begin(), end())`.
  16095. @sa @ref empty() -- checks whether the container is empty
  16096. @sa @ref max_size() -- returns the maximal number of elements
  16097. @since version 1.0.0
  16098. */
  16099. size_type size() const noexcept
  16100. {
  16101. switch (m_type)
  16102. {
  16103. case value_t::null:
  16104. {
  16105. // null values are empty
  16106. return 0;
  16107. }
  16108. case value_t::array:
  16109. {
  16110. // delegate call to array_t::size()
  16111. return m_value.array->size();
  16112. }
  16113. case value_t::object:
  16114. {
  16115. // delegate call to object_t::size()
  16116. return m_value.object->size();
  16117. }
  16118. default:
  16119. {
  16120. // all other types have size 1
  16121. return 1;
  16122. }
  16123. }
  16124. }
  16125. /*!
  16126. @brief returns the maximum possible number of elements
  16127. Returns the maximum number of elements a JSON value is able to hold due to
  16128. system or library implementation limitations, i.e. `std::distance(begin(),
  16129. end())` for the JSON value.
  16130. @return The return value depends on the different types and is
  16131. defined as follows:
  16132. Value type | return value
  16133. ----------- | -------------
  16134. null | `0` (same as `size()`)
  16135. boolean | `1` (same as `size()`)
  16136. string | `1` (same as `size()`)
  16137. number | `1` (same as `size()`)
  16138. object | result of function `object_t::max_size()`
  16139. array | result of function `array_t::max_size()`
  16140. @liveexample{The following code calls `max_size()` on the different value
  16141. types. Note the output is implementation specific.,max_size}
  16142. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  16143. the Container concept; that is, their `max_size()` functions have constant
  16144. complexity.
  16145. @iterators No changes.
  16146. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16147. @requirement This function helps `basic_json` satisfying the
  16148. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16149. requirements:
  16150. - The complexity is constant.
  16151. - Has the semantics of returning `b.size()` where `b` is the largest
  16152. possible JSON value.
  16153. @sa @ref size() -- returns the number of elements
  16154. @since version 1.0.0
  16155. */
  16156. size_type max_size() const noexcept
  16157. {
  16158. switch (m_type)
  16159. {
  16160. case value_t::array:
  16161. {
  16162. // delegate call to array_t::max_size()
  16163. return m_value.array->max_size();
  16164. }
  16165. case value_t::object:
  16166. {
  16167. // delegate call to object_t::max_size()
  16168. return m_value.object->max_size();
  16169. }
  16170. default:
  16171. {
  16172. // all other types have max_size() == size()
  16173. return size();
  16174. }
  16175. }
  16176. }
  16177. /// @}
  16178. ///////////////
  16179. // modifiers //
  16180. ///////////////
  16181. /// @name modifiers
  16182. /// @{
  16183. /*!
  16184. @brief clears the contents
  16185. Clears the content of a JSON value and resets it to the default value as
  16186. if @ref basic_json(value_t) would have been called with the current value
  16187. type from @ref type():
  16188. Value type | initial value
  16189. ----------- | -------------
  16190. null | `null`
  16191. boolean | `false`
  16192. string | `""`
  16193. number | `0`
  16194. object | `{}`
  16195. array | `[]`
  16196. @post Has the same effect as calling
  16197. @code {.cpp}
  16198. *this = basic_json(type());
  16199. @endcode
  16200. @liveexample{The example below shows the effect of `clear()` to different
  16201. JSON types.,clear}
  16202. @complexity Linear in the size of the JSON value.
  16203. @iterators All iterators, pointers and references related to this container
  16204. are invalidated.
  16205. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16206. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  16207. same value than calling `clear()`
  16208. @since version 1.0.0
  16209. */
  16210. void clear() noexcept
  16211. {
  16212. switch (m_type)
  16213. {
  16214. case value_t::number_integer:
  16215. {
  16216. m_value.number_integer = 0;
  16217. break;
  16218. }
  16219. case value_t::number_unsigned:
  16220. {
  16221. m_value.number_unsigned = 0;
  16222. break;
  16223. }
  16224. case value_t::number_float:
  16225. {
  16226. m_value.number_float = 0.0;
  16227. break;
  16228. }
  16229. case value_t::boolean:
  16230. {
  16231. m_value.boolean = false;
  16232. break;
  16233. }
  16234. case value_t::string:
  16235. {
  16236. m_value.string->clear();
  16237. break;
  16238. }
  16239. case value_t::array:
  16240. {
  16241. m_value.array->clear();
  16242. break;
  16243. }
  16244. case value_t::object:
  16245. {
  16246. m_value.object->clear();
  16247. break;
  16248. }
  16249. default:
  16250. break;
  16251. }
  16252. }
  16253. /*!
  16254. @brief add an object to an array
  16255. Appends the given element @a val to the end of the JSON value. If the
  16256. function is called on a JSON null value, an empty array is created before
  16257. appending @a val.
  16258. @param[in] val the value to add to the JSON array
  16259. @throw type_error.308 when called on a type other than JSON array or
  16260. null; example: `"cannot use push_back() with number"`
  16261. @complexity Amortized constant.
  16262. @liveexample{The example shows how `push_back()` and `+=` can be used to
  16263. add elements to a JSON array. Note how the `null` value was silently
  16264. converted to a JSON array.,push_back}
  16265. @since version 1.0.0
  16266. */
  16267. void push_back(basic_json&& val)
  16268. {
  16269. // push_back only works for null objects or arrays
  16270. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  16271. {
  16272. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  16273. }
  16274. // transform null object into an array
  16275. if (is_null())
  16276. {
  16277. m_type = value_t::array;
  16278. m_value = value_t::array;
  16279. assert_invariant();
  16280. }
  16281. // add element to array (move semantics)
  16282. m_value.array->push_back(std::move(val));
  16283. // invalidate object: mark it null so we do not call the destructor
  16284. // cppcheck-suppress accessMoved
  16285. val.m_type = value_t::null;
  16286. }
  16287. /*!
  16288. @brief add an object to an array
  16289. @copydoc push_back(basic_json&&)
  16290. */
  16291. reference operator+=(basic_json&& val)
  16292. {
  16293. push_back(std::move(val));
  16294. return *this;
  16295. }
  16296. /*!
  16297. @brief add an object to an array
  16298. @copydoc push_back(basic_json&&)
  16299. */
  16300. void push_back(const basic_json& val)
  16301. {
  16302. // push_back only works for null objects or arrays
  16303. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  16304. {
  16305. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  16306. }
  16307. // transform null object into an array
  16308. if (is_null())
  16309. {
  16310. m_type = value_t::array;
  16311. m_value = value_t::array;
  16312. assert_invariant();
  16313. }
  16314. // add element to array
  16315. m_value.array->push_back(val);
  16316. }
  16317. /*!
  16318. @brief add an object to an array
  16319. @copydoc push_back(basic_json&&)
  16320. */
  16321. reference operator+=(const basic_json& val)
  16322. {
  16323. push_back(val);
  16324. return *this;
  16325. }
  16326. /*!
  16327. @brief add an object to an object
  16328. Inserts the given element @a val to the JSON object. If the function is
  16329. called on a JSON null value, an empty object is created before inserting
  16330. @a val.
  16331. @param[in] val the value to add to the JSON object
  16332. @throw type_error.308 when called on a type other than JSON object or
  16333. null; example: `"cannot use push_back() with number"`
  16334. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  16335. @liveexample{The example shows how `push_back()` and `+=` can be used to
  16336. add elements to a JSON object. Note how the `null` value was silently
  16337. converted to a JSON object.,push_back__object_t__value}
  16338. @since version 1.0.0
  16339. */
  16340. void push_back(const typename object_t::value_type& val)
  16341. {
  16342. // push_back only works for null objects or objects
  16343. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  16344. {
  16345. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  16346. }
  16347. // transform null object into an object
  16348. if (is_null())
  16349. {
  16350. m_type = value_t::object;
  16351. m_value = value_t::object;
  16352. assert_invariant();
  16353. }
  16354. // add element to array
  16355. m_value.object->insert(val);
  16356. }
  16357. /*!
  16358. @brief add an object to an object
  16359. @copydoc push_back(const typename object_t::value_type&)
  16360. */
  16361. reference operator+=(const typename object_t::value_type& val)
  16362. {
  16363. push_back(val);
  16364. return *this;
  16365. }
  16366. /*!
  16367. @brief add an object to an object
  16368. This function allows to use `push_back` with an initializer list. In case
  16369. 1. the current value is an object,
  16370. 2. the initializer list @a init contains only two elements, and
  16371. 3. the first element of @a init is a string,
  16372. @a init is converted into an object element and added using
  16373. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  16374. is converted to a JSON value and added using @ref push_back(basic_json&&).
  16375. @param[in] init an initializer list
  16376. @complexity Linear in the size of the initializer list @a init.
  16377. @note This function is required to resolve an ambiguous overload error,
  16378. because pairs like `{"key", "value"}` can be both interpreted as
  16379. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  16380. https://github.com/nlohmann/json/issues/235 for more information.
  16381. @liveexample{The example shows how initializer lists are treated as
  16382. objects when possible.,push_back__initializer_list}
  16383. */
  16384. void push_back(initializer_list_t init)
  16385. {
  16386. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  16387. {
  16388. basic_json&& key = init.begin()->moved_or_copied();
  16389. push_back(typename object_t::value_type(
  16390. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  16391. }
  16392. else
  16393. {
  16394. push_back(basic_json(init));
  16395. }
  16396. }
  16397. /*!
  16398. @brief add an object to an object
  16399. @copydoc push_back(initializer_list_t)
  16400. */
  16401. reference operator+=(initializer_list_t init)
  16402. {
  16403. push_back(init);
  16404. return *this;
  16405. }
  16406. /*!
  16407. @brief add an object to an array
  16408. Creates a JSON value from the passed parameters @a args to the end of the
  16409. JSON value. If the function is called on a JSON null value, an empty array
  16410. is created before appending the value created from @a args.
  16411. @param[in] args arguments to forward to a constructor of @ref basic_json
  16412. @tparam Args compatible types to create a @ref basic_json object
  16413. @return reference to the inserted element
  16414. @throw type_error.311 when called on a type other than JSON array or
  16415. null; example: `"cannot use emplace_back() with number"`
  16416. @complexity Amortized constant.
  16417. @liveexample{The example shows how `push_back()` can be used to add
  16418. elements to a JSON array. Note how the `null` value was silently converted
  16419. to a JSON array.,emplace_back}
  16420. @since version 2.0.8, returns reference since 3.7.0
  16421. */
  16422. template<class... Args>
  16423. reference emplace_back(Args&& ... args)
  16424. {
  16425. // emplace_back only works for null objects or arrays
  16426. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  16427. {
  16428. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  16429. }
  16430. // transform null object into an array
  16431. if (is_null())
  16432. {
  16433. m_type = value_t::array;
  16434. m_value = value_t::array;
  16435. assert_invariant();
  16436. }
  16437. // add element to array (perfect forwarding)
  16438. #ifdef JSON_HAS_CPP_17
  16439. return m_value.array->emplace_back(std::forward<Args>(args)...);
  16440. #else
  16441. m_value.array->emplace_back(std::forward<Args>(args)...);
  16442. return m_value.array->back();
  16443. #endif
  16444. }
  16445. /*!
  16446. @brief add an object to an object if key does not exist
  16447. Inserts a new element into a JSON object constructed in-place with the
  16448. given @a args if there is no element with the key in the container. If the
  16449. function is called on a JSON null value, an empty object is created before
  16450. appending the value created from @a args.
  16451. @param[in] args arguments to forward to a constructor of @ref basic_json
  16452. @tparam Args compatible types to create a @ref basic_json object
  16453. @return a pair consisting of an iterator to the inserted element, or the
  16454. already-existing element if no insertion happened, and a bool
  16455. denoting whether the insertion took place.
  16456. @throw type_error.311 when called on a type other than JSON object or
  16457. null; example: `"cannot use emplace() with number"`
  16458. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  16459. @liveexample{The example shows how `emplace()` can be used to add elements
  16460. to a JSON object. Note how the `null` value was silently converted to a
  16461. JSON object. Further note how no value is added if there was already one
  16462. value stored with the same key.,emplace}
  16463. @since version 2.0.8
  16464. */
  16465. template<class... Args>
  16466. std::pair<iterator, bool> emplace(Args&& ... args)
  16467. {
  16468. // emplace only works for null objects or arrays
  16469. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  16470. {
  16471. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  16472. }
  16473. // transform null object into an object
  16474. if (is_null())
  16475. {
  16476. m_type = value_t::object;
  16477. m_value = value_t::object;
  16478. assert_invariant();
  16479. }
  16480. // add element to array (perfect forwarding)
  16481. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  16482. // create result iterator and set iterator to the result of emplace
  16483. auto it = begin();
  16484. it.m_it.object_iterator = res.first;
  16485. // return pair of iterator and boolean
  16486. return {it, res.second};
  16487. }
  16488. /// Helper for insertion of an iterator
  16489. /// @note: This uses std::distance to support GCC 4.8,
  16490. /// see https://github.com/nlohmann/json/pull/1257
  16491. template<typename... Args>
  16492. iterator insert_iterator(const_iterator pos, Args&& ... args)
  16493. {
  16494. iterator result(this);
  16495. assert(m_value.array != nullptr);
  16496. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  16497. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  16498. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  16499. // This could have been written as:
  16500. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  16501. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  16502. return result;
  16503. }
  16504. /*!
  16505. @brief inserts element
  16506. Inserts element @a val before iterator @a pos.
  16507. @param[in] pos iterator before which the content will be inserted; may be
  16508. the end() iterator
  16509. @param[in] val element to insert
  16510. @return iterator pointing to the inserted @a val.
  16511. @throw type_error.309 if called on JSON values other than arrays;
  16512. example: `"cannot use insert() with string"`
  16513. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16514. example: `"iterator does not fit current value"`
  16515. @complexity Constant plus linear in the distance between @a pos and end of
  16516. the container.
  16517. @liveexample{The example shows how `insert()` is used.,insert}
  16518. @since version 1.0.0
  16519. */
  16520. iterator insert(const_iterator pos, const basic_json& val)
  16521. {
  16522. // insert only works for arrays
  16523. if (JSON_HEDLEY_LIKELY(is_array()))
  16524. {
  16525. // check if iterator pos fits to this JSON value
  16526. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16527. {
  16528. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16529. }
  16530. // insert to array and return iterator
  16531. return insert_iterator(pos, val);
  16532. }
  16533. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16534. }
  16535. /*!
  16536. @brief inserts element
  16537. @copydoc insert(const_iterator, const basic_json&)
  16538. */
  16539. iterator insert(const_iterator pos, basic_json&& val)
  16540. {
  16541. return insert(pos, val);
  16542. }
  16543. /*!
  16544. @brief inserts elements
  16545. Inserts @a cnt copies of @a val before iterator @a pos.
  16546. @param[in] pos iterator before which the content will be inserted; may be
  16547. the end() iterator
  16548. @param[in] cnt number of copies of @a val to insert
  16549. @param[in] val element to insert
  16550. @return iterator pointing to the first element inserted, or @a pos if
  16551. `cnt==0`
  16552. @throw type_error.309 if called on JSON values other than arrays; example:
  16553. `"cannot use insert() with string"`
  16554. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16555. example: `"iterator does not fit current value"`
  16556. @complexity Linear in @a cnt plus linear in the distance between @a pos
  16557. and end of the container.
  16558. @liveexample{The example shows how `insert()` is used.,insert__count}
  16559. @since version 1.0.0
  16560. */
  16561. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  16562. {
  16563. // insert only works for arrays
  16564. if (JSON_HEDLEY_LIKELY(is_array()))
  16565. {
  16566. // check if iterator pos fits to this JSON value
  16567. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16568. {
  16569. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16570. }
  16571. // insert to array and return iterator
  16572. return insert_iterator(pos, cnt, val);
  16573. }
  16574. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16575. }
  16576. /*!
  16577. @brief inserts elements
  16578. Inserts elements from range `[first, last)` before iterator @a pos.
  16579. @param[in] pos iterator before which the content will be inserted; may be
  16580. the end() iterator
  16581. @param[in] first begin of the range of elements to insert
  16582. @param[in] last end of the range of elements to insert
  16583. @throw type_error.309 if called on JSON values other than arrays; example:
  16584. `"cannot use insert() with string"`
  16585. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16586. example: `"iterator does not fit current value"`
  16587. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  16588. same JSON value; example: `"iterators do not fit"`
  16589. @throw invalid_iterator.211 if @a first or @a last are iterators into
  16590. container for which insert is called; example: `"passed iterators may not
  16591. belong to container"`
  16592. @return iterator pointing to the first element inserted, or @a pos if
  16593. `first==last`
  16594. @complexity Linear in `std::distance(first, last)` plus linear in the
  16595. distance between @a pos and end of the container.
  16596. @liveexample{The example shows how `insert()` is used.,insert__range}
  16597. @since version 1.0.0
  16598. */
  16599. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  16600. {
  16601. // insert only works for arrays
  16602. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  16603. {
  16604. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16605. }
  16606. // check if iterator pos fits to this JSON value
  16607. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16608. {
  16609. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16610. }
  16611. // check if range iterators belong to the same JSON object
  16612. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16613. {
  16614. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  16615. }
  16616. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  16617. {
  16618. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  16619. }
  16620. // insert to array and return iterator
  16621. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  16622. }
  16623. /*!
  16624. @brief inserts elements
  16625. Inserts elements from initializer list @a ilist before iterator @a pos.
  16626. @param[in] pos iterator before which the content will be inserted; may be
  16627. the end() iterator
  16628. @param[in] ilist initializer list to insert the values from
  16629. @throw type_error.309 if called on JSON values other than arrays; example:
  16630. `"cannot use insert() with string"`
  16631. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16632. example: `"iterator does not fit current value"`
  16633. @return iterator pointing to the first element inserted, or @a pos if
  16634. `ilist` is empty
  16635. @complexity Linear in `ilist.size()` plus linear in the distance between
  16636. @a pos and end of the container.
  16637. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  16638. @since version 1.0.0
  16639. */
  16640. iterator insert(const_iterator pos, initializer_list_t ilist)
  16641. {
  16642. // insert only works for arrays
  16643. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  16644. {
  16645. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16646. }
  16647. // check if iterator pos fits to this JSON value
  16648. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16649. {
  16650. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16651. }
  16652. // insert to array and return iterator
  16653. return insert_iterator(pos, ilist.begin(), ilist.end());
  16654. }
  16655. /*!
  16656. @brief inserts elements
  16657. Inserts elements from range `[first, last)`.
  16658. @param[in] first begin of the range of elements to insert
  16659. @param[in] last end of the range of elements to insert
  16660. @throw type_error.309 if called on JSON values other than objects; example:
  16661. `"cannot use insert() with string"`
  16662. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  16663. point to an object; example: `"iterators first and last must point to
  16664. objects"`
  16665. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  16666. same JSON value; example: `"iterators do not fit"`
  16667. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  16668. of elements to insert.
  16669. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  16670. @since version 3.0.0
  16671. */
  16672. void insert(const_iterator first, const_iterator last)
  16673. {
  16674. // insert only works for objects
  16675. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  16676. {
  16677. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16678. }
  16679. // check if range iterators belong to the same JSON object
  16680. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16681. {
  16682. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  16683. }
  16684. // passed iterators must belong to objects
  16685. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()))
  16686. {
  16687. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  16688. }
  16689. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  16690. }
  16691. /*!
  16692. @brief updates a JSON object from another object, overwriting existing keys
  16693. Inserts all values from JSON object @a j and overwrites existing keys.
  16694. @param[in] j JSON object to read values from
  16695. @throw type_error.312 if called on JSON values other than objects; example:
  16696. `"cannot use update() with string"`
  16697. @complexity O(N*log(size() + N)), where N is the number of elements to
  16698. insert.
  16699. @liveexample{The example shows how `update()` is used.,update}
  16700. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  16701. @since version 3.0.0
  16702. */
  16703. void update(const_reference j)
  16704. {
  16705. // implicitly convert null value to an empty object
  16706. if (is_null())
  16707. {
  16708. m_type = value_t::object;
  16709. m_value.object = create<object_t>();
  16710. assert_invariant();
  16711. }
  16712. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  16713. {
  16714. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  16715. }
  16716. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  16717. {
  16718. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  16719. }
  16720. for (auto it = j.cbegin(); it != j.cend(); ++it)
  16721. {
  16722. m_value.object->operator[](it.key()) = it.value();
  16723. }
  16724. }
  16725. /*!
  16726. @brief updates a JSON object from another object, overwriting existing keys
  16727. Inserts all values from from range `[first, last)` and overwrites existing
  16728. keys.
  16729. @param[in] first begin of the range of elements to insert
  16730. @param[in] last end of the range of elements to insert
  16731. @throw type_error.312 if called on JSON values other than objects; example:
  16732. `"cannot use update() with string"`
  16733. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  16734. point to an object; example: `"iterators first and last must point to
  16735. objects"`
  16736. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  16737. same JSON value; example: `"iterators do not fit"`
  16738. @complexity O(N*log(size() + N)), where N is the number of elements to
  16739. insert.
  16740. @liveexample{The example shows how `update()` is used__range.,update}
  16741. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  16742. @since version 3.0.0
  16743. */
  16744. void update(const_iterator first, const_iterator last)
  16745. {
  16746. // implicitly convert null value to an empty object
  16747. if (is_null())
  16748. {
  16749. m_type = value_t::object;
  16750. m_value.object = create<object_t>();
  16751. assert_invariant();
  16752. }
  16753. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  16754. {
  16755. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  16756. }
  16757. // check if range iterators belong to the same JSON object
  16758. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16759. {
  16760. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  16761. }
  16762. // passed iterators must belong to objects
  16763. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()
  16764. or not last.m_object->is_object()))
  16765. {
  16766. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  16767. }
  16768. for (auto it = first; it != last; ++it)
  16769. {
  16770. m_value.object->operator[](it.key()) = it.value();
  16771. }
  16772. }
  16773. /*!
  16774. @brief exchanges the values
  16775. Exchanges the contents of the JSON value with those of @a other. Does not
  16776. invoke any move, copy, or swap operations on individual elements. All
  16777. iterators and references remain valid. The past-the-end iterator is
  16778. invalidated.
  16779. @param[in,out] other JSON value to exchange the contents with
  16780. @complexity Constant.
  16781. @liveexample{The example below shows how JSON values can be swapped with
  16782. `swap()`.,swap__reference}
  16783. @since version 1.0.0
  16784. */
  16785. void swap(reference other) noexcept (
  16786. std::is_nothrow_move_constructible<value_t>::value and
  16787. std::is_nothrow_move_assignable<value_t>::value and
  16788. std::is_nothrow_move_constructible<json_value>::value and
  16789. std::is_nothrow_move_assignable<json_value>::value
  16790. )
  16791. {
  16792. std::swap(m_type, other.m_type);
  16793. std::swap(m_value, other.m_value);
  16794. assert_invariant();
  16795. }
  16796. /*!
  16797. @brief exchanges the values
  16798. Exchanges the contents of a JSON array with those of @a other. Does not
  16799. invoke any move, copy, or swap operations on individual elements. All
  16800. iterators and references remain valid. The past-the-end iterator is
  16801. invalidated.
  16802. @param[in,out] other array to exchange the contents with
  16803. @throw type_error.310 when JSON value is not an array; example: `"cannot
  16804. use swap() with string"`
  16805. @complexity Constant.
  16806. @liveexample{The example below shows how arrays can be swapped with
  16807. `swap()`.,swap__array_t}
  16808. @since version 1.0.0
  16809. */
  16810. void swap(array_t& other)
  16811. {
  16812. // swap only works for arrays
  16813. if (JSON_HEDLEY_LIKELY(is_array()))
  16814. {
  16815. std::swap(*(m_value.array), other);
  16816. }
  16817. else
  16818. {
  16819. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  16820. }
  16821. }
  16822. /*!
  16823. @brief exchanges the values
  16824. Exchanges the contents of a JSON object with those of @a other. Does not
  16825. invoke any move, copy, or swap operations on individual elements. All
  16826. iterators and references remain valid. The past-the-end iterator is
  16827. invalidated.
  16828. @param[in,out] other object to exchange the contents with
  16829. @throw type_error.310 when JSON value is not an object; example:
  16830. `"cannot use swap() with string"`
  16831. @complexity Constant.
  16832. @liveexample{The example below shows how objects can be swapped with
  16833. `swap()`.,swap__object_t}
  16834. @since version 1.0.0
  16835. */
  16836. void swap(object_t& other)
  16837. {
  16838. // swap only works for objects
  16839. if (JSON_HEDLEY_LIKELY(is_object()))
  16840. {
  16841. std::swap(*(m_value.object), other);
  16842. }
  16843. else
  16844. {
  16845. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  16846. }
  16847. }
  16848. /*!
  16849. @brief exchanges the values
  16850. Exchanges the contents of a JSON string with those of @a other. Does not
  16851. invoke any move, copy, or swap operations on individual elements. All
  16852. iterators and references remain valid. The past-the-end iterator is
  16853. invalidated.
  16854. @param[in,out] other string to exchange the contents with
  16855. @throw type_error.310 when JSON value is not a string; example: `"cannot
  16856. use swap() with boolean"`
  16857. @complexity Constant.
  16858. @liveexample{The example below shows how strings can be swapped with
  16859. `swap()`.,swap__string_t}
  16860. @since version 1.0.0
  16861. */
  16862. void swap(string_t& other)
  16863. {
  16864. // swap only works for strings
  16865. if (JSON_HEDLEY_LIKELY(is_string()))
  16866. {
  16867. std::swap(*(m_value.string), other);
  16868. }
  16869. else
  16870. {
  16871. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  16872. }
  16873. }
  16874. /// @}
  16875. public:
  16876. //////////////////////////////////////////
  16877. // lexicographical comparison operators //
  16878. //////////////////////////////////////////
  16879. /// @name lexicographical comparison operators
  16880. /// @{
  16881. /*!
  16882. @brief comparison: equal
  16883. Compares two JSON values for equality according to the following rules:
  16884. - Two JSON values are equal if (1) they are from the same type and (2)
  16885. their stored values are the same according to their respective
  16886. `operator==`.
  16887. - Integer and floating-point numbers are automatically converted before
  16888. comparison. Note than two NaN values are always treated as unequal.
  16889. - Two JSON null values are equal.
  16890. @note Floating-point inside JSON values numbers are compared with
  16891. `json::number_float_t::operator==` which is `double::operator==` by
  16892. default. To compare floating-point while respecting an epsilon, an alternative
  16893. [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
  16894. could be used, for instance
  16895. @code {.cpp}
  16896. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  16897. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  16898. {
  16899. return std::abs(a - b) <= epsilon;
  16900. }
  16901. @endcode
  16902. @note NaN values never compare equal to themselves or to other NaN values.
  16903. @param[in] lhs first JSON value to consider
  16904. @param[in] rhs second JSON value to consider
  16905. @return whether the values @a lhs and @a rhs are equal
  16906. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16907. @complexity Linear.
  16908. @liveexample{The example demonstrates comparing several JSON
  16909. types.,operator__equal}
  16910. @since version 1.0.0
  16911. */
  16912. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  16913. {
  16914. const auto lhs_type = lhs.type();
  16915. const auto rhs_type = rhs.type();
  16916. if (lhs_type == rhs_type)
  16917. {
  16918. switch (lhs_type)
  16919. {
  16920. case value_t::array:
  16921. return *lhs.m_value.array == *rhs.m_value.array;
  16922. case value_t::object:
  16923. return *lhs.m_value.object == *rhs.m_value.object;
  16924. case value_t::null:
  16925. return true;
  16926. case value_t::string:
  16927. return *lhs.m_value.string == *rhs.m_value.string;
  16928. case value_t::boolean:
  16929. return lhs.m_value.boolean == rhs.m_value.boolean;
  16930. case value_t::number_integer:
  16931. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  16932. case value_t::number_unsigned:
  16933. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  16934. case value_t::number_float:
  16935. return lhs.m_value.number_float == rhs.m_value.number_float;
  16936. default:
  16937. return false;
  16938. }
  16939. }
  16940. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  16941. {
  16942. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  16943. }
  16944. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  16945. {
  16946. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  16947. }
  16948. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  16949. {
  16950. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  16951. }
  16952. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  16953. {
  16954. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  16955. }
  16956. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  16957. {
  16958. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  16959. }
  16960. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  16961. {
  16962. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  16963. }
  16964. return false;
  16965. }
  16966. /*!
  16967. @brief comparison: equal
  16968. @copydoc operator==(const_reference, const_reference)
  16969. */
  16970. template<typename ScalarType, typename std::enable_if<
  16971. std::is_scalar<ScalarType>::value, int>::type = 0>
  16972. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  16973. {
  16974. return lhs == basic_json(rhs);
  16975. }
  16976. /*!
  16977. @brief comparison: equal
  16978. @copydoc operator==(const_reference, const_reference)
  16979. */
  16980. template<typename ScalarType, typename std::enable_if<
  16981. std::is_scalar<ScalarType>::value, int>::type = 0>
  16982. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  16983. {
  16984. return basic_json(lhs) == rhs;
  16985. }
  16986. /*!
  16987. @brief comparison: not equal
  16988. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  16989. @param[in] lhs first JSON value to consider
  16990. @param[in] rhs second JSON value to consider
  16991. @return whether the values @a lhs and @a rhs are not equal
  16992. @complexity Linear.
  16993. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16994. @liveexample{The example demonstrates comparing several JSON
  16995. types.,operator__notequal}
  16996. @since version 1.0.0
  16997. */
  16998. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  16999. {
  17000. return not (lhs == rhs);
  17001. }
  17002. /*!
  17003. @brief comparison: not equal
  17004. @copydoc operator!=(const_reference, const_reference)
  17005. */
  17006. template<typename ScalarType, typename std::enable_if<
  17007. std::is_scalar<ScalarType>::value, int>::type = 0>
  17008. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  17009. {
  17010. return lhs != basic_json(rhs);
  17011. }
  17012. /*!
  17013. @brief comparison: not equal
  17014. @copydoc operator!=(const_reference, const_reference)
  17015. */
  17016. template<typename ScalarType, typename std::enable_if<
  17017. std::is_scalar<ScalarType>::value, int>::type = 0>
  17018. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  17019. {
  17020. return basic_json(lhs) != rhs;
  17021. }
  17022. /*!
  17023. @brief comparison: less than
  17024. Compares whether one JSON value @a lhs is less than another JSON value @a
  17025. rhs according to the following rules:
  17026. - If @a lhs and @a rhs have the same type, the values are compared using
  17027. the default `<` operator.
  17028. - Integer and floating-point numbers are automatically converted before
  17029. comparison
  17030. - In case @a lhs and @a rhs have different types, the values are ignored
  17031. and the order of the types is considered, see
  17032. @ref operator<(const value_t, const value_t).
  17033. @param[in] lhs first JSON value to consider
  17034. @param[in] rhs second JSON value to consider
  17035. @return whether @a lhs is less than @a rhs
  17036. @complexity Linear.
  17037. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17038. @liveexample{The example demonstrates comparing several JSON
  17039. types.,operator__less}
  17040. @since version 1.0.0
  17041. */
  17042. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  17043. {
  17044. const auto lhs_type = lhs.type();
  17045. const auto rhs_type = rhs.type();
  17046. if (lhs_type == rhs_type)
  17047. {
  17048. switch (lhs_type)
  17049. {
  17050. case value_t::array:
  17051. // note parentheses are necessary, see
  17052. // https://github.com/nlohmann/json/issues/1530
  17053. return (*lhs.m_value.array) < (*rhs.m_value.array);
  17054. case value_t::object:
  17055. return (*lhs.m_value.object) < (*rhs.m_value.object);
  17056. case value_t::null:
  17057. return false;
  17058. case value_t::string:
  17059. return (*lhs.m_value.string) < (*rhs.m_value.string);
  17060. case value_t::boolean:
  17061. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  17062. case value_t::number_integer:
  17063. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  17064. case value_t::number_unsigned:
  17065. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  17066. case value_t::number_float:
  17067. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  17068. default:
  17069. return false;
  17070. }
  17071. }
  17072. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  17073. {
  17074. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  17075. }
  17076. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  17077. {
  17078. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  17079. }
  17080. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  17081. {
  17082. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  17083. }
  17084. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  17085. {
  17086. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  17087. }
  17088. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  17089. {
  17090. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  17091. }
  17092. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  17093. {
  17094. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  17095. }
  17096. // We only reach this line if we cannot compare values. In that case,
  17097. // we compare types. Note we have to call the operator explicitly,
  17098. // because MSVC has problems otherwise.
  17099. return operator<(lhs_type, rhs_type);
  17100. }
  17101. /*!
  17102. @brief comparison: less than
  17103. @copydoc operator<(const_reference, const_reference)
  17104. */
  17105. template<typename ScalarType, typename std::enable_if<
  17106. std::is_scalar<ScalarType>::value, int>::type = 0>
  17107. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  17108. {
  17109. return lhs < basic_json(rhs);
  17110. }
  17111. /*!
  17112. @brief comparison: less than
  17113. @copydoc operator<(const_reference, const_reference)
  17114. */
  17115. template<typename ScalarType, typename std::enable_if<
  17116. std::is_scalar<ScalarType>::value, int>::type = 0>
  17117. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  17118. {
  17119. return basic_json(lhs) < rhs;
  17120. }
  17121. /*!
  17122. @brief comparison: less than or equal
  17123. Compares whether one JSON value @a lhs is less than or equal to another
  17124. JSON value by calculating `not (rhs < lhs)`.
  17125. @param[in] lhs first JSON value to consider
  17126. @param[in] rhs second JSON value to consider
  17127. @return whether @a lhs is less than or equal to @a rhs
  17128. @complexity Linear.
  17129. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17130. @liveexample{The example demonstrates comparing several JSON
  17131. types.,operator__greater}
  17132. @since version 1.0.0
  17133. */
  17134. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  17135. {
  17136. return not (rhs < lhs);
  17137. }
  17138. /*!
  17139. @brief comparison: less than or equal
  17140. @copydoc operator<=(const_reference, const_reference)
  17141. */
  17142. template<typename ScalarType, typename std::enable_if<
  17143. std::is_scalar<ScalarType>::value, int>::type = 0>
  17144. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  17145. {
  17146. return lhs <= basic_json(rhs);
  17147. }
  17148. /*!
  17149. @brief comparison: less than or equal
  17150. @copydoc operator<=(const_reference, const_reference)
  17151. */
  17152. template<typename ScalarType, typename std::enable_if<
  17153. std::is_scalar<ScalarType>::value, int>::type = 0>
  17154. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  17155. {
  17156. return basic_json(lhs) <= rhs;
  17157. }
  17158. /*!
  17159. @brief comparison: greater than
  17160. Compares whether one JSON value @a lhs is greater than another
  17161. JSON value by calculating `not (lhs <= rhs)`.
  17162. @param[in] lhs first JSON value to consider
  17163. @param[in] rhs second JSON value to consider
  17164. @return whether @a lhs is greater than to @a rhs
  17165. @complexity Linear.
  17166. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17167. @liveexample{The example demonstrates comparing several JSON
  17168. types.,operator__lessequal}
  17169. @since version 1.0.0
  17170. */
  17171. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  17172. {
  17173. return not (lhs <= rhs);
  17174. }
  17175. /*!
  17176. @brief comparison: greater than
  17177. @copydoc operator>(const_reference, const_reference)
  17178. */
  17179. template<typename ScalarType, typename std::enable_if<
  17180. std::is_scalar<ScalarType>::value, int>::type = 0>
  17181. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  17182. {
  17183. return lhs > basic_json(rhs);
  17184. }
  17185. /*!
  17186. @brief comparison: greater than
  17187. @copydoc operator>(const_reference, const_reference)
  17188. */
  17189. template<typename ScalarType, typename std::enable_if<
  17190. std::is_scalar<ScalarType>::value, int>::type = 0>
  17191. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  17192. {
  17193. return basic_json(lhs) > rhs;
  17194. }
  17195. /*!
  17196. @brief comparison: greater than or equal
  17197. Compares whether one JSON value @a lhs is greater than or equal to another
  17198. JSON value by calculating `not (lhs < rhs)`.
  17199. @param[in] lhs first JSON value to consider
  17200. @param[in] rhs second JSON value to consider
  17201. @return whether @a lhs is greater than or equal to @a rhs
  17202. @complexity Linear.
  17203. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17204. @liveexample{The example demonstrates comparing several JSON
  17205. types.,operator__greaterequal}
  17206. @since version 1.0.0
  17207. */
  17208. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  17209. {
  17210. return not (lhs < rhs);
  17211. }
  17212. /*!
  17213. @brief comparison: greater than or equal
  17214. @copydoc operator>=(const_reference, const_reference)
  17215. */
  17216. template<typename ScalarType, typename std::enable_if<
  17217. std::is_scalar<ScalarType>::value, int>::type = 0>
  17218. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  17219. {
  17220. return lhs >= basic_json(rhs);
  17221. }
  17222. /*!
  17223. @brief comparison: greater than or equal
  17224. @copydoc operator>=(const_reference, const_reference)
  17225. */
  17226. template<typename ScalarType, typename std::enable_if<
  17227. std::is_scalar<ScalarType>::value, int>::type = 0>
  17228. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  17229. {
  17230. return basic_json(lhs) >= rhs;
  17231. }
  17232. /// @}
  17233. ///////////////////
  17234. // serialization //
  17235. ///////////////////
  17236. /// @name serialization
  17237. /// @{
  17238. /*!
  17239. @brief serialize to stream
  17240. Serialize the given JSON value @a j to the output stream @a o. The JSON
  17241. value will be serialized using the @ref dump member function.
  17242. - The indentation of the output can be controlled with the member variable
  17243. `width` of the output stream @a o. For instance, using the manipulator
  17244. `std::setw(4)` on @a o sets the indentation level to `4` and the
  17245. serialization result is the same as calling `dump(4)`.
  17246. - The indentation character can be controlled with the member variable
  17247. `fill` of the output stream @a o. For instance, the manipulator
  17248. `std::setfill('\\t')` sets indentation to use a tab character rather than
  17249. the default space character.
  17250. @param[in,out] o stream to serialize to
  17251. @param[in] j JSON value to serialize
  17252. @return the stream @a o
  17253. @throw type_error.316 if a string stored inside the JSON value is not
  17254. UTF-8 encoded
  17255. @complexity Linear.
  17256. @liveexample{The example below shows the serialization with different
  17257. parameters to `width` to adjust the indentation level.,operator_serialize}
  17258. @since version 1.0.0; indentation character added in version 3.0.0
  17259. */
  17260. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  17261. {
  17262. // read width member and use it as indentation parameter if nonzero
  17263. const bool pretty_print = o.width() > 0;
  17264. const auto indentation = pretty_print ? o.width() : 0;
  17265. // reset width to 0 for subsequent calls to this stream
  17266. o.width(0);
  17267. // do the actual serialization
  17268. serializer s(detail::output_adapter<char>(o), o.fill());
  17269. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  17270. return o;
  17271. }
  17272. /*!
  17273. @brief serialize to stream
  17274. @deprecated This stream operator is deprecated and will be removed in
  17275. future 4.0.0 of the library. Please use
  17276. @ref operator<<(std::ostream&, const basic_json&)
  17277. instead; that is, replace calls like `j >> o;` with `o << j;`.
  17278. @since version 1.0.0; deprecated since version 3.0.0
  17279. */
  17280. JSON_HEDLEY_DEPRECATED(3.0.0)
  17281. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  17282. {
  17283. return o << j;
  17284. }
  17285. /// @}
  17286. /////////////////////
  17287. // deserialization //
  17288. /////////////////////
  17289. /// @name deserialization
  17290. /// @{
  17291. /*!
  17292. @brief deserialize from a compatible input
  17293. This function reads from a compatible input. Examples are:
  17294. - an array of 1-byte values
  17295. - strings with character/literal type with size of 1 byte
  17296. - input streams
  17297. - container with contiguous storage of 1-byte values. Compatible container
  17298. types include `std::vector`, `std::string`, `std::array`,
  17299. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  17300. arrays can be used with `std::begin()`/`std::end()`. User-defined
  17301. containers can be used as long as they implement random-access iterators
  17302. and a contiguous storage.
  17303. @pre Each element of the container has a size of 1 byte. Violating this
  17304. precondition yields undefined behavior. **This precondition is enforced
  17305. with a static assertion.**
  17306. @pre The container storage is contiguous. Violating this precondition
  17307. yields undefined behavior. **This precondition is enforced with an
  17308. assertion.**
  17309. @warning There is no way to enforce all preconditions at compile-time. If
  17310. the function is called with a noncompliant container and with
  17311. assertions switched off, the behavior is undefined and will most
  17312. likely yield segmentation violation.
  17313. @param[in] i input to read from
  17314. @param[in] cb a parser callback function of type @ref parser_callback_t
  17315. which is used to control the deserialization by filtering unwanted values
  17316. (optional)
  17317. @param[in] allow_exceptions whether to throw exceptions in case of a
  17318. parse error (optional, true by default)
  17319. @return deserialized JSON value; in case of a parse error and
  17320. @a allow_exceptions set to `false`, the return value will be
  17321. value_t::discarded.
  17322. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  17323. of input; expected string literal""`
  17324. @throw parse_error.102 if to_unicode fails or surrogate error
  17325. @throw parse_error.103 if to_unicode fails
  17326. @complexity Linear in the length of the input. The parser is a predictive
  17327. LL(1) parser. The complexity can be higher if the parser callback function
  17328. @a cb has a super-linear complexity.
  17329. @note A UTF-8 byte order mark is silently ignored.
  17330. @liveexample{The example below demonstrates the `parse()` function reading
  17331. from an array.,parse__array__parser_callback_t}
  17332. @liveexample{The example below demonstrates the `parse()` function with
  17333. and without callback function.,parse__string__parser_callback_t}
  17334. @liveexample{The example below demonstrates the `parse()` function with
  17335. and without callback function.,parse__istream__parser_callback_t}
  17336. @liveexample{The example below demonstrates the `parse()` function reading
  17337. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  17338. @since version 2.0.3 (contiguous containers)
  17339. */
  17340. JSON_HEDLEY_WARN_UNUSED_RESULT
  17341. static basic_json parse(detail::input_adapter&& i,
  17342. const parser_callback_t cb = nullptr,
  17343. const bool allow_exceptions = true)
  17344. {
  17345. basic_json result;
  17346. parser(i, cb, allow_exceptions).parse(true, result);
  17347. return result;
  17348. }
  17349. static bool accept(detail::input_adapter&& i)
  17350. {
  17351. return parser(i).accept(true);
  17352. }
  17353. /*!
  17354. @brief generate SAX events
  17355. The SAX event lister must follow the interface of @ref json_sax.
  17356. This function reads from a compatible input. Examples are:
  17357. - an array of 1-byte values
  17358. - strings with character/literal type with size of 1 byte
  17359. - input streams
  17360. - container with contiguous storage of 1-byte values. Compatible container
  17361. types include `std::vector`, `std::string`, `std::array`,
  17362. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  17363. arrays can be used with `std::begin()`/`std::end()`. User-defined
  17364. containers can be used as long as they implement random-access iterators
  17365. and a contiguous storage.
  17366. @pre Each element of the container has a size of 1 byte. Violating this
  17367. precondition yields undefined behavior. **This precondition is enforced
  17368. with a static assertion.**
  17369. @pre The container storage is contiguous. Violating this precondition
  17370. yields undefined behavior. **This precondition is enforced with an
  17371. assertion.**
  17372. @warning There is no way to enforce all preconditions at compile-time. If
  17373. the function is called with a noncompliant container and with
  17374. assertions switched off, the behavior is undefined and will most
  17375. likely yield segmentation violation.
  17376. @param[in] i input to read from
  17377. @param[in,out] sax SAX event listener
  17378. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  17379. @param[in] strict whether the input has to be consumed completely
  17380. @return return value of the last processed SAX event
  17381. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  17382. of input; expected string literal""`
  17383. @throw parse_error.102 if to_unicode fails or surrogate error
  17384. @throw parse_error.103 if to_unicode fails
  17385. @complexity Linear in the length of the input. The parser is a predictive
  17386. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  17387. a super-linear complexity.
  17388. @note A UTF-8 byte order mark is silently ignored.
  17389. @liveexample{The example below demonstrates the `sax_parse()` function
  17390. reading from string and processing the events with a user-defined SAX
  17391. event consumer.,sax_parse}
  17392. @since version 3.2.0
  17393. */
  17394. template <typename SAX>
  17395. JSON_HEDLEY_NON_NULL(2)
  17396. static bool sax_parse(detail::input_adapter&& i, SAX* sax,
  17397. input_format_t format = input_format_t::json,
  17398. const bool strict = true)
  17399. {
  17400. assert(sax);
  17401. return format == input_format_t::json
  17402. ? parser(std::move(i)).sax_parse(sax, strict)
  17403. : detail::binary_reader<basic_json, SAX>(std::move(i)).sax_parse(format, sax, strict);
  17404. }
  17405. /*!
  17406. @brief deserialize from an iterator range with contiguous storage
  17407. This function reads from an iterator range of a container with contiguous
  17408. storage of 1-byte values. Compatible container types include
  17409. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  17410. `std::initializer_list`. Furthermore, C-style arrays can be used with
  17411. `std::begin()`/`std::end()`. User-defined containers can be used as long
  17412. as they implement random-access iterators and a contiguous storage.
  17413. @pre The iterator range is contiguous. Violating this precondition yields
  17414. undefined behavior. **This precondition is enforced with an assertion.**
  17415. @pre Each element in the range has a size of 1 byte. Violating this
  17416. precondition yields undefined behavior. **This precondition is enforced
  17417. with a static assertion.**
  17418. @warning There is no way to enforce all preconditions at compile-time. If
  17419. the function is called with noncompliant iterators and with
  17420. assertions switched off, the behavior is undefined and will most
  17421. likely yield segmentation violation.
  17422. @tparam IteratorType iterator of container with contiguous storage
  17423. @param[in] first begin of the range to parse (included)
  17424. @param[in] last end of the range to parse (excluded)
  17425. @param[in] cb a parser callback function of type @ref parser_callback_t
  17426. which is used to control the deserialization by filtering unwanted values
  17427. (optional)
  17428. @param[in] allow_exceptions whether to throw exceptions in case of a
  17429. parse error (optional, true by default)
  17430. @return deserialized JSON value; in case of a parse error and
  17431. @a allow_exceptions set to `false`, the return value will be
  17432. value_t::discarded.
  17433. @throw parse_error.101 in case of an unexpected token
  17434. @throw parse_error.102 if to_unicode fails or surrogate error
  17435. @throw parse_error.103 if to_unicode fails
  17436. @complexity Linear in the length of the input. The parser is a predictive
  17437. LL(1) parser. The complexity can be higher if the parser callback function
  17438. @a cb has a super-linear complexity.
  17439. @note A UTF-8 byte order mark is silently ignored.
  17440. @liveexample{The example below demonstrates the `parse()` function reading
  17441. from an iterator range.,parse__iteratortype__parser_callback_t}
  17442. @since version 2.0.3
  17443. */
  17444. template<class IteratorType, typename std::enable_if<
  17445. std::is_base_of<
  17446. std::random_access_iterator_tag,
  17447. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  17448. static basic_json parse(IteratorType first, IteratorType last,
  17449. const parser_callback_t cb = nullptr,
  17450. const bool allow_exceptions = true)
  17451. {
  17452. basic_json result;
  17453. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  17454. return result;
  17455. }
  17456. template<class IteratorType, typename std::enable_if<
  17457. std::is_base_of<
  17458. std::random_access_iterator_tag,
  17459. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  17460. static bool accept(IteratorType first, IteratorType last)
  17461. {
  17462. return parser(detail::input_adapter(first, last)).accept(true);
  17463. }
  17464. template<class IteratorType, class SAX, typename std::enable_if<
  17465. std::is_base_of<
  17466. std::random_access_iterator_tag,
  17467. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  17468. JSON_HEDLEY_NON_NULL(3)
  17469. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
  17470. {
  17471. return parser(detail::input_adapter(first, last)).sax_parse(sax);
  17472. }
  17473. /*!
  17474. @brief deserialize from stream
  17475. @deprecated This stream operator is deprecated and will be removed in
  17476. version 4.0.0 of the library. Please use
  17477. @ref operator>>(std::istream&, basic_json&)
  17478. instead; that is, replace calls like `j << i;` with `i >> j;`.
  17479. @since version 1.0.0; deprecated since version 3.0.0
  17480. */
  17481. JSON_HEDLEY_DEPRECATED(3.0.0)
  17482. friend std::istream& operator<<(basic_json& j, std::istream& i)
  17483. {
  17484. return operator>>(i, j);
  17485. }
  17486. /*!
  17487. @brief deserialize from stream
  17488. Deserializes an input stream to a JSON value.
  17489. @param[in,out] i input stream to read a serialized JSON value from
  17490. @param[in,out] j JSON value to write the deserialized input to
  17491. @throw parse_error.101 in case of an unexpected token
  17492. @throw parse_error.102 if to_unicode fails or surrogate error
  17493. @throw parse_error.103 if to_unicode fails
  17494. @complexity Linear in the length of the input. The parser is a predictive
  17495. LL(1) parser.
  17496. @note A UTF-8 byte order mark is silently ignored.
  17497. @liveexample{The example below shows how a JSON value is constructed by
  17498. reading a serialization from a stream.,operator_deserialize}
  17499. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  17500. parser callback function to filter values while parsing
  17501. @since version 1.0.0
  17502. */
  17503. friend std::istream& operator>>(std::istream& i, basic_json& j)
  17504. {
  17505. parser(detail::input_adapter(i)).parse(false, j);
  17506. return i;
  17507. }
  17508. /// @}
  17509. ///////////////////////////
  17510. // convenience functions //
  17511. ///////////////////////////
  17512. /*!
  17513. @brief return the type as string
  17514. Returns the type name as string to be used in error messages - usually to
  17515. indicate that a function was called on a wrong JSON type.
  17516. @return a string representation of a the @a m_type member:
  17517. Value type | return value
  17518. ----------- | -------------
  17519. null | `"null"`
  17520. boolean | `"boolean"`
  17521. string | `"string"`
  17522. number | `"number"` (for all number types)
  17523. object | `"object"`
  17524. array | `"array"`
  17525. discarded | `"discarded"`
  17526. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17527. @complexity Constant.
  17528. @liveexample{The following code exemplifies `type_name()` for all JSON
  17529. types.,type_name}
  17530. @sa @ref type() -- return the type of the JSON value
  17531. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  17532. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  17533. since 3.0.0
  17534. */
  17535. JSON_HEDLEY_RETURNS_NON_NULL
  17536. const char* type_name() const noexcept
  17537. {
  17538. {
  17539. switch (m_type)
  17540. {
  17541. case value_t::null:
  17542. return "null";
  17543. case value_t::object:
  17544. return "object";
  17545. case value_t::array:
  17546. return "array";
  17547. case value_t::string:
  17548. return "string";
  17549. case value_t::boolean:
  17550. return "boolean";
  17551. case value_t::discarded:
  17552. return "discarded";
  17553. default:
  17554. return "number";
  17555. }
  17556. }
  17557. }
  17558. private:
  17559. //////////////////////
  17560. // member variables //
  17561. //////////////////////
  17562. /// the type of the current element
  17563. value_t m_type = value_t::null;
  17564. /// the value of the current element
  17565. json_value m_value = {};
  17566. //////////////////////////////////////////
  17567. // binary serialization/deserialization //
  17568. //////////////////////////////////////////
  17569. /// @name binary serialization/deserialization support
  17570. /// @{
  17571. public:
  17572. /*!
  17573. @brief create a CBOR serialization of a given JSON value
  17574. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  17575. Binary Object Representation) serialization format. CBOR is a binary
  17576. serialization format which aims to be more compact than JSON itself, yet
  17577. more efficient to parse.
  17578. The library uses the following mapping from JSON values types to
  17579. CBOR types according to the CBOR specification (RFC 7049):
  17580. JSON value type | value/range | CBOR type | first byte
  17581. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  17582. null | `null` | Null | 0xF6
  17583. boolean | `true` | True | 0xF5
  17584. boolean | `false` | False | 0xF4
  17585. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  17586. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  17587. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  17588. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  17589. number_integer | -24..-1 | Negative integer | 0x20..0x37
  17590. number_integer | 0..23 | Integer | 0x00..0x17
  17591. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  17592. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  17593. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  17594. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  17595. number_unsigned | 0..23 | Integer | 0x00..0x17
  17596. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  17597. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  17598. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  17599. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  17600. number_float | *any value* | Double-Precision Float | 0xFB
  17601. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  17602. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  17603. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  17604. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  17605. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  17606. array | *size*: 0..23 | array | 0x80..0x97
  17607. array | *size*: 23..255 | array (1 byte follow) | 0x98
  17608. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  17609. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  17610. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  17611. object | *size*: 0..23 | map | 0xA0..0xB7
  17612. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  17613. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  17614. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  17615. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  17616. @note The mapping is **complete** in the sense that any JSON value type
  17617. can be converted to a CBOR value.
  17618. @note If NaN or Infinity are stored inside a JSON number, they are
  17619. serialized properly. This behavior differs from the @ref dump()
  17620. function which serializes NaN or Infinity to `null`.
  17621. @note The following CBOR types are not used in the conversion:
  17622. - byte strings (0x40..0x5F)
  17623. - UTF-8 strings terminated by "break" (0x7F)
  17624. - arrays terminated by "break" (0x9F)
  17625. - maps terminated by "break" (0xBF)
  17626. - date/time (0xC0..0xC1)
  17627. - bignum (0xC2..0xC3)
  17628. - decimal fraction (0xC4)
  17629. - bigfloat (0xC5)
  17630. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  17631. - expected conversions (0xD5..0xD7)
  17632. - simple values (0xE0..0xF3, 0xF8)
  17633. - undefined (0xF7)
  17634. - half and single-precision floats (0xF9-0xFA)
  17635. - break (0xFF)
  17636. @param[in] j JSON value to serialize
  17637. @return MessagePack serialization as byte vector
  17638. @complexity Linear in the size of the JSON value @a j.
  17639. @liveexample{The example shows the serialization of a JSON value to a byte
  17640. vector in CBOR format.,to_cbor}
  17641. @sa http://cbor.io
  17642. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  17643. analogous deserialization
  17644. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  17645. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  17646. related UBJSON format
  17647. @since version 2.0.9
  17648. */
  17649. static std::vector<uint8_t> to_cbor(const basic_json& j)
  17650. {
  17651. std::vector<uint8_t> result;
  17652. to_cbor(j, result);
  17653. return result;
  17654. }
  17655. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  17656. {
  17657. binary_writer<uint8_t>(o).write_cbor(j);
  17658. }
  17659. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  17660. {
  17661. binary_writer<char>(o).write_cbor(j);
  17662. }
  17663. /*!
  17664. @brief create a MessagePack serialization of a given JSON value
  17665. Serializes a given JSON value @a j to a byte vector using the MessagePack
  17666. serialization format. MessagePack is a binary serialization format which
  17667. aims to be more compact than JSON itself, yet more efficient to parse.
  17668. The library uses the following mapping from JSON values types to
  17669. MessagePack types according to the MessagePack specification:
  17670. JSON value type | value/range | MessagePack type | first byte
  17671. --------------- | --------------------------------- | ---------------- | ----------
  17672. null | `null` | nil | 0xC0
  17673. boolean | `true` | true | 0xC3
  17674. boolean | `false` | false | 0xC2
  17675. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  17676. number_integer | -2147483648..-32769 | int32 | 0xD2
  17677. number_integer | -32768..-129 | int16 | 0xD1
  17678. number_integer | -128..-33 | int8 | 0xD0
  17679. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  17680. number_integer | 0..127 | positive fixint | 0x00..0x7F
  17681. number_integer | 128..255 | uint 8 | 0xCC
  17682. number_integer | 256..65535 | uint 16 | 0xCD
  17683. number_integer | 65536..4294967295 | uint 32 | 0xCE
  17684. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  17685. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  17686. number_unsigned | 128..255 | uint 8 | 0xCC
  17687. number_unsigned | 256..65535 | uint 16 | 0xCD
  17688. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  17689. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  17690. number_float | *any value* | float 64 | 0xCB
  17691. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  17692. string | *length*: 32..255 | str 8 | 0xD9
  17693. string | *length*: 256..65535 | str 16 | 0xDA
  17694. string | *length*: 65536..4294967295 | str 32 | 0xDB
  17695. array | *size*: 0..15 | fixarray | 0x90..0x9F
  17696. array | *size*: 16..65535 | array 16 | 0xDC
  17697. array | *size*: 65536..4294967295 | array 32 | 0xDD
  17698. object | *size*: 0..15 | fix map | 0x80..0x8F
  17699. object | *size*: 16..65535 | map 16 | 0xDE
  17700. object | *size*: 65536..4294967295 | map 32 | 0xDF
  17701. @note The mapping is **complete** in the sense that any JSON value type
  17702. can be converted to a MessagePack value.
  17703. @note The following values can **not** be converted to a MessagePack value:
  17704. - strings with more than 4294967295 bytes
  17705. - arrays with more than 4294967295 elements
  17706. - objects with more than 4294967295 elements
  17707. @note The following MessagePack types are not used in the conversion:
  17708. - bin 8 - bin 32 (0xC4..0xC6)
  17709. - ext 8 - ext 32 (0xC7..0xC9)
  17710. - float 32 (0xCA)
  17711. - fixext 1 - fixext 16 (0xD4..0xD8)
  17712. @note Any MessagePack output created @ref to_msgpack can be successfully
  17713. parsed by @ref from_msgpack.
  17714. @note If NaN or Infinity are stored inside a JSON number, they are
  17715. serialized properly. This behavior differs from the @ref dump()
  17716. function which serializes NaN or Infinity to `null`.
  17717. @param[in] j JSON value to serialize
  17718. @return MessagePack serialization as byte vector
  17719. @complexity Linear in the size of the JSON value @a j.
  17720. @liveexample{The example shows the serialization of a JSON value to a byte
  17721. vector in MessagePack format.,to_msgpack}
  17722. @sa http://msgpack.org
  17723. @sa @ref from_msgpack for the analogous deserialization
  17724. @sa @ref to_cbor(const basic_json& for the related CBOR format
  17725. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  17726. related UBJSON format
  17727. @since version 2.0.9
  17728. */
  17729. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  17730. {
  17731. std::vector<uint8_t> result;
  17732. to_msgpack(j, result);
  17733. return result;
  17734. }
  17735. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  17736. {
  17737. binary_writer<uint8_t>(o).write_msgpack(j);
  17738. }
  17739. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  17740. {
  17741. binary_writer<char>(o).write_msgpack(j);
  17742. }
  17743. /*!
  17744. @brief create a UBJSON serialization of a given JSON value
  17745. Serializes a given JSON value @a j to a byte vector using the UBJSON
  17746. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  17747. than JSON itself, yet more efficient to parse.
  17748. The library uses the following mapping from JSON values types to
  17749. UBJSON types according to the UBJSON specification:
  17750. JSON value type | value/range | UBJSON type | marker
  17751. --------------- | --------------------------------- | ----------- | ------
  17752. null | `null` | null | `Z`
  17753. boolean | `true` | true | `T`
  17754. boolean | `false` | false | `F`
  17755. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  17756. number_integer | -2147483648..-32769 | int32 | `l`
  17757. number_integer | -32768..-129 | int16 | `I`
  17758. number_integer | -128..127 | int8 | `i`
  17759. number_integer | 128..255 | uint8 | `U`
  17760. number_integer | 256..32767 | int16 | `I`
  17761. number_integer | 32768..2147483647 | int32 | `l`
  17762. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  17763. number_unsigned | 0..127 | int8 | `i`
  17764. number_unsigned | 128..255 | uint8 | `U`
  17765. number_unsigned | 256..32767 | int16 | `I`
  17766. number_unsigned | 32768..2147483647 | int32 | `l`
  17767. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  17768. number_float | *any value* | float64 | `D`
  17769. string | *with shortest length indicator* | string | `S`
  17770. array | *see notes on optimized format* | array | `[`
  17771. object | *see notes on optimized format* | map | `{`
  17772. @note The mapping is **complete** in the sense that any JSON value type
  17773. can be converted to a UBJSON value.
  17774. @note The following values can **not** be converted to a UBJSON value:
  17775. - strings with more than 9223372036854775807 bytes (theoretical)
  17776. - unsigned integer numbers above 9223372036854775807
  17777. @note The following markers are not used in the conversion:
  17778. - `Z`: no-op values are not created.
  17779. - `C`: single-byte strings are serialized with `S` markers.
  17780. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  17781. by @ref from_ubjson.
  17782. @note If NaN or Infinity are stored inside a JSON number, they are
  17783. serialized properly. This behavior differs from the @ref dump()
  17784. function which serializes NaN or Infinity to `null`.
  17785. @note The optimized formats for containers are supported: Parameter
  17786. @a use_size adds size information to the beginning of a container and
  17787. removes the closing marker. Parameter @a use_type further checks
  17788. whether all elements of a container have the same type and adds the
  17789. type marker to the beginning of the container. The @a use_type
  17790. parameter must only be used together with @a use_size = true. Note
  17791. that @a use_size = true alone may result in larger representations -
  17792. the benefit of this parameter is that the receiving side is
  17793. immediately informed on the number of elements of the container.
  17794. @param[in] j JSON value to serialize
  17795. @param[in] use_size whether to add size annotations to container types
  17796. @param[in] use_type whether to add type annotations to container types
  17797. (must be combined with @a use_size = true)
  17798. @return UBJSON serialization as byte vector
  17799. @complexity Linear in the size of the JSON value @a j.
  17800. @liveexample{The example shows the serialization of a JSON value to a byte
  17801. vector in UBJSON format.,to_ubjson}
  17802. @sa http://ubjson.org
  17803. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  17804. analogous deserialization
  17805. @sa @ref to_cbor(const basic_json& for the related CBOR format
  17806. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  17807. @since version 3.1.0
  17808. */
  17809. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  17810. const bool use_size = false,
  17811. const bool use_type = false)
  17812. {
  17813. std::vector<uint8_t> result;
  17814. to_ubjson(j, result, use_size, use_type);
  17815. return result;
  17816. }
  17817. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  17818. const bool use_size = false, const bool use_type = false)
  17819. {
  17820. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  17821. }
  17822. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  17823. const bool use_size = false, const bool use_type = false)
  17824. {
  17825. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  17826. }
  17827. /*!
  17828. @brief Serializes the given JSON object `j` to BSON and returns a vector
  17829. containing the corresponding BSON-representation.
  17830. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  17831. stored as a single entity (a so-called document).
  17832. The library uses the following mapping from JSON values types to BSON types:
  17833. JSON value type | value/range | BSON type | marker
  17834. --------------- | --------------------------------- | ----------- | ------
  17835. null | `null` | null | 0x0A
  17836. boolean | `true`, `false` | boolean | 0x08
  17837. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  17838. number_integer | -2147483648..2147483647 | int32 | 0x10
  17839. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  17840. number_unsigned | 0..2147483647 | int32 | 0x10
  17841. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  17842. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  17843. number_float | *any value* | double | 0x01
  17844. string | *any value* | string | 0x02
  17845. array | *any value* | document | 0x04
  17846. object | *any value* | document | 0x03
  17847. @warning The mapping is **incomplete**, since only JSON-objects (and things
  17848. contained therein) can be serialized to BSON.
  17849. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  17850. and the keys may not contain U+0000, since they are serialized a
  17851. zero-terminated c-strings.
  17852. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  17853. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  17854. @throw type_error.317 if `!j.is_object()`
  17855. @pre The input `j` is required to be an object: `j.is_object() == true`.
  17856. @note Any BSON output created via @ref to_bson can be successfully parsed
  17857. by @ref from_bson.
  17858. @param[in] j JSON value to serialize
  17859. @return BSON serialization as byte vector
  17860. @complexity Linear in the size of the JSON value @a j.
  17861. @liveexample{The example shows the serialization of a JSON value to a byte
  17862. vector in BSON format.,to_bson}
  17863. @sa http://bsonspec.org/spec.html
  17864. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  17865. analogous deserialization
  17866. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  17867. related UBJSON format
  17868. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  17869. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  17870. */
  17871. static std::vector<uint8_t> to_bson(const basic_json& j)
  17872. {
  17873. std::vector<uint8_t> result;
  17874. to_bson(j, result);
  17875. return result;
  17876. }
  17877. /*!
  17878. @brief Serializes the given JSON object `j` to BSON and forwards the
  17879. corresponding BSON-representation to the given output_adapter `o`.
  17880. @param j The JSON object to convert to BSON.
  17881. @param o The output adapter that receives the binary BSON representation.
  17882. @pre The input `j` shall be an object: `j.is_object() == true`
  17883. @sa @ref to_bson(const basic_json&)
  17884. */
  17885. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  17886. {
  17887. binary_writer<uint8_t>(o).write_bson(j);
  17888. }
  17889. /*!
  17890. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  17891. */
  17892. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  17893. {
  17894. binary_writer<char>(o).write_bson(j);
  17895. }
  17896. /*!
  17897. @brief create a JSON value from an input in CBOR format
  17898. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  17899. Binary Object Representation) serialization format.
  17900. The library maps CBOR types to JSON value types as follows:
  17901. CBOR type | JSON value type | first byte
  17902. ---------------------- | --------------- | ----------
  17903. Integer | number_unsigned | 0x00..0x17
  17904. Unsigned integer | number_unsigned | 0x18
  17905. Unsigned integer | number_unsigned | 0x19
  17906. Unsigned integer | number_unsigned | 0x1A
  17907. Unsigned integer | number_unsigned | 0x1B
  17908. Negative integer | number_integer | 0x20..0x37
  17909. Negative integer | number_integer | 0x38
  17910. Negative integer | number_integer | 0x39
  17911. Negative integer | number_integer | 0x3A
  17912. Negative integer | number_integer | 0x3B
  17913. Negative integer | number_integer | 0x40..0x57
  17914. UTF-8 string | string | 0x60..0x77
  17915. UTF-8 string | string | 0x78
  17916. UTF-8 string | string | 0x79
  17917. UTF-8 string | string | 0x7A
  17918. UTF-8 string | string | 0x7B
  17919. UTF-8 string | string | 0x7F
  17920. array | array | 0x80..0x97
  17921. array | array | 0x98
  17922. array | array | 0x99
  17923. array | array | 0x9A
  17924. array | array | 0x9B
  17925. array | array | 0x9F
  17926. map | object | 0xA0..0xB7
  17927. map | object | 0xB8
  17928. map | object | 0xB9
  17929. map | object | 0xBA
  17930. map | object | 0xBB
  17931. map | object | 0xBF
  17932. False | `false` | 0xF4
  17933. True | `true` | 0xF5
  17934. Null | `null` | 0xF6
  17935. Half-Precision Float | number_float | 0xF9
  17936. Single-Precision Float | number_float | 0xFA
  17937. Double-Precision Float | number_float | 0xFB
  17938. @warning The mapping is **incomplete** in the sense that not all CBOR
  17939. types can be converted to a JSON value. The following CBOR types
  17940. are not supported and will yield parse errors (parse_error.112):
  17941. - byte strings (0x40..0x5F)
  17942. - date/time (0xC0..0xC1)
  17943. - bignum (0xC2..0xC3)
  17944. - decimal fraction (0xC4)
  17945. - bigfloat (0xC5)
  17946. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  17947. - expected conversions (0xD5..0xD7)
  17948. - simple values (0xE0..0xF3, 0xF8)
  17949. - undefined (0xF7)
  17950. @warning CBOR allows map keys of any type, whereas JSON only allows
  17951. strings as keys in object values. Therefore, CBOR maps with keys
  17952. other than UTF-8 strings are rejected (parse_error.113).
  17953. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  17954. @ref from_cbor.
  17955. @param[in] i an input in CBOR format convertible to an input adapter
  17956. @param[in] strict whether to expect the input to be consumed until EOF
  17957. (true by default)
  17958. @param[in] allow_exceptions whether to throw exceptions in case of a
  17959. parse error (optional, true by default)
  17960. @return deserialized JSON value; in case of a parse error and
  17961. @a allow_exceptions set to `false`, the return value will be
  17962. value_t::discarded.
  17963. @throw parse_error.110 if the given input ends prematurely or the end of
  17964. file was not reached when @a strict was set to true
  17965. @throw parse_error.112 if unsupported features from CBOR were
  17966. used in the given input @a v or if the input is not valid CBOR
  17967. @throw parse_error.113 if a string was expected as map key, but not found
  17968. @complexity Linear in the size of the input @a i.
  17969. @liveexample{The example shows the deserialization of a byte vector in CBOR
  17970. format to a JSON value.,from_cbor}
  17971. @sa http://cbor.io
  17972. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  17973. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  17974. related MessagePack format
  17975. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  17976. related UBJSON format
  17977. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  17978. consume input adapters, removed start_index parameter, and added
  17979. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  17980. since 3.2.0
  17981. */
  17982. JSON_HEDLEY_WARN_UNUSED_RESULT
  17983. static basic_json from_cbor(detail::input_adapter&& i,
  17984. const bool strict = true,
  17985. const bool allow_exceptions = true)
  17986. {
  17987. basic_json result;
  17988. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  17989. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict);
  17990. return res ? result : basic_json(value_t::discarded);
  17991. }
  17992. /*!
  17993. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
  17994. */
  17995. template<typename A1, typename A2,
  17996. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  17997. JSON_HEDLEY_WARN_UNUSED_RESULT
  17998. static basic_json from_cbor(A1 && a1, A2 && a2,
  17999. const bool strict = true,
  18000. const bool allow_exceptions = true)
  18001. {
  18002. basic_json result;
  18003. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18004. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::cbor, &sdp, strict);
  18005. return res ? result : basic_json(value_t::discarded);
  18006. }
  18007. /*!
  18008. @brief create a JSON value from an input in MessagePack format
  18009. Deserializes a given input @a i to a JSON value using the MessagePack
  18010. serialization format.
  18011. The library maps MessagePack types to JSON value types as follows:
  18012. MessagePack type | JSON value type | first byte
  18013. ---------------- | --------------- | ----------
  18014. positive fixint | number_unsigned | 0x00..0x7F
  18015. fixmap | object | 0x80..0x8F
  18016. fixarray | array | 0x90..0x9F
  18017. fixstr | string | 0xA0..0xBF
  18018. nil | `null` | 0xC0
  18019. false | `false` | 0xC2
  18020. true | `true` | 0xC3
  18021. float 32 | number_float | 0xCA
  18022. float 64 | number_float | 0xCB
  18023. uint 8 | number_unsigned | 0xCC
  18024. uint 16 | number_unsigned | 0xCD
  18025. uint 32 | number_unsigned | 0xCE
  18026. uint 64 | number_unsigned | 0xCF
  18027. int 8 | number_integer | 0xD0
  18028. int 16 | number_integer | 0xD1
  18029. int 32 | number_integer | 0xD2
  18030. int 64 | number_integer | 0xD3
  18031. str 8 | string | 0xD9
  18032. str 16 | string | 0xDA
  18033. str 32 | string | 0xDB
  18034. array 16 | array | 0xDC
  18035. array 32 | array | 0xDD
  18036. map 16 | object | 0xDE
  18037. map 32 | object | 0xDF
  18038. negative fixint | number_integer | 0xE0-0xFF
  18039. @warning The mapping is **incomplete** in the sense that not all
  18040. MessagePack types can be converted to a JSON value. The following
  18041. MessagePack types are not supported and will yield parse errors:
  18042. - bin 8 - bin 32 (0xC4..0xC6)
  18043. - ext 8 - ext 32 (0xC7..0xC9)
  18044. - fixext 1 - fixext 16 (0xD4..0xD8)
  18045. @note Any MessagePack output created @ref to_msgpack can be successfully
  18046. parsed by @ref from_msgpack.
  18047. @param[in] i an input in MessagePack format convertible to an input
  18048. adapter
  18049. @param[in] strict whether to expect the input to be consumed until EOF
  18050. (true by default)
  18051. @param[in] allow_exceptions whether to throw exceptions in case of a
  18052. parse error (optional, true by default)
  18053. @return deserialized JSON value; in case of a parse error and
  18054. @a allow_exceptions set to `false`, the return value will be
  18055. value_t::discarded.
  18056. @throw parse_error.110 if the given input ends prematurely or the end of
  18057. file was not reached when @a strict was set to true
  18058. @throw parse_error.112 if unsupported features from MessagePack were
  18059. used in the given input @a i or if the input is not valid MessagePack
  18060. @throw parse_error.113 if a string was expected as map key, but not found
  18061. @complexity Linear in the size of the input @a i.
  18062. @liveexample{The example shows the deserialization of a byte vector in
  18063. MessagePack format to a JSON value.,from_msgpack}
  18064. @sa http://msgpack.org
  18065. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  18066. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  18067. related CBOR format
  18068. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  18069. the related UBJSON format
  18070. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  18071. the related BSON format
  18072. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  18073. consume input adapters, removed start_index parameter, and added
  18074. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  18075. since 3.2.0
  18076. */
  18077. JSON_HEDLEY_WARN_UNUSED_RESULT
  18078. static basic_json from_msgpack(detail::input_adapter&& i,
  18079. const bool strict = true,
  18080. const bool allow_exceptions = true)
  18081. {
  18082. basic_json result;
  18083. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18084. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict);
  18085. return res ? result : basic_json(value_t::discarded);
  18086. }
  18087. /*!
  18088. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  18089. */
  18090. template<typename A1, typename A2,
  18091. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18092. JSON_HEDLEY_WARN_UNUSED_RESULT
  18093. static basic_json from_msgpack(A1 && a1, A2 && a2,
  18094. const bool strict = true,
  18095. const bool allow_exceptions = true)
  18096. {
  18097. basic_json result;
  18098. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18099. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::msgpack, &sdp, strict);
  18100. return res ? result : basic_json(value_t::discarded);
  18101. }
  18102. /*!
  18103. @brief create a JSON value from an input in UBJSON format
  18104. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  18105. Binary JSON) serialization format.
  18106. The library maps UBJSON types to JSON value types as follows:
  18107. UBJSON type | JSON value type | marker
  18108. ----------- | --------------------------------------- | ------
  18109. no-op | *no value, next value is read* | `N`
  18110. null | `null` | `Z`
  18111. false | `false` | `F`
  18112. true | `true` | `T`
  18113. float32 | number_float | `d`
  18114. float64 | number_float | `D`
  18115. uint8 | number_unsigned | `U`
  18116. int8 | number_integer | `i`
  18117. int16 | number_integer | `I`
  18118. int32 | number_integer | `l`
  18119. int64 | number_integer | `L`
  18120. string | string | `S`
  18121. char | string | `C`
  18122. array | array (optimized values are supported) | `[`
  18123. object | object (optimized values are supported) | `{`
  18124. @note The mapping is **complete** in the sense that any UBJSON value can
  18125. be converted to a JSON value.
  18126. @param[in] i an input in UBJSON format convertible to an input adapter
  18127. @param[in] strict whether to expect the input to be consumed until EOF
  18128. (true by default)
  18129. @param[in] allow_exceptions whether to throw exceptions in case of a
  18130. parse error (optional, true by default)
  18131. @return deserialized JSON value; in case of a parse error and
  18132. @a allow_exceptions set to `false`, the return value will be
  18133. value_t::discarded.
  18134. @throw parse_error.110 if the given input ends prematurely or the end of
  18135. file was not reached when @a strict was set to true
  18136. @throw parse_error.112 if a parse error occurs
  18137. @throw parse_error.113 if a string could not be parsed successfully
  18138. @complexity Linear in the size of the input @a i.
  18139. @liveexample{The example shows the deserialization of a byte vector in
  18140. UBJSON format to a JSON value.,from_ubjson}
  18141. @sa http://ubjson.org
  18142. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  18143. analogous serialization
  18144. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  18145. related CBOR format
  18146. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  18147. the related MessagePack format
  18148. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  18149. the related BSON format
  18150. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  18151. */
  18152. JSON_HEDLEY_WARN_UNUSED_RESULT
  18153. static basic_json from_ubjson(detail::input_adapter&& i,
  18154. const bool strict = true,
  18155. const bool allow_exceptions = true)
  18156. {
  18157. basic_json result;
  18158. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18159. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict);
  18160. return res ? result : basic_json(value_t::discarded);
  18161. }
  18162. /*!
  18163. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  18164. */
  18165. template<typename A1, typename A2,
  18166. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18167. JSON_HEDLEY_WARN_UNUSED_RESULT
  18168. static basic_json from_ubjson(A1 && a1, A2 && a2,
  18169. const bool strict = true,
  18170. const bool allow_exceptions = true)
  18171. {
  18172. basic_json result;
  18173. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18174. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::ubjson, &sdp, strict);
  18175. return res ? result : basic_json(value_t::discarded);
  18176. }
  18177. /*!
  18178. @brief Create a JSON value from an input in BSON format
  18179. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  18180. serialization format.
  18181. The library maps BSON record types to JSON value types as follows:
  18182. BSON type | BSON marker byte | JSON value type
  18183. --------------- | ---------------- | ---------------------------
  18184. double | 0x01 | number_float
  18185. string | 0x02 | string
  18186. document | 0x03 | object
  18187. array | 0x04 | array
  18188. binary | 0x05 | still unsupported
  18189. undefined | 0x06 | still unsupported
  18190. ObjectId | 0x07 | still unsupported
  18191. boolean | 0x08 | boolean
  18192. UTC Date-Time | 0x09 | still unsupported
  18193. null | 0x0A | null
  18194. Regular Expr. | 0x0B | still unsupported
  18195. DB Pointer | 0x0C | still unsupported
  18196. JavaScript Code | 0x0D | still unsupported
  18197. Symbol | 0x0E | still unsupported
  18198. JavaScript Code | 0x0F | still unsupported
  18199. int32 | 0x10 | number_integer
  18200. Timestamp | 0x11 | still unsupported
  18201. 128-bit decimal float | 0x13 | still unsupported
  18202. Max Key | 0x7F | still unsupported
  18203. Min Key | 0xFF | still unsupported
  18204. @warning The mapping is **incomplete**. The unsupported mappings
  18205. are indicated in the table above.
  18206. @param[in] i an input in BSON format convertible to an input adapter
  18207. @param[in] strict whether to expect the input to be consumed until EOF
  18208. (true by default)
  18209. @param[in] allow_exceptions whether to throw exceptions in case of a
  18210. parse error (optional, true by default)
  18211. @return deserialized JSON value; in case of a parse error and
  18212. @a allow_exceptions set to `false`, the return value will be
  18213. value_t::discarded.
  18214. @throw parse_error.114 if an unsupported BSON record type is encountered
  18215. @complexity Linear in the size of the input @a i.
  18216. @liveexample{The example shows the deserialization of a byte vector in
  18217. BSON format to a JSON value.,from_bson}
  18218. @sa http://bsonspec.org/spec.html
  18219. @sa @ref to_bson(const basic_json&) for the analogous serialization
  18220. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  18221. related CBOR format
  18222. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  18223. the related MessagePack format
  18224. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  18225. related UBJSON format
  18226. */
  18227. JSON_HEDLEY_WARN_UNUSED_RESULT
  18228. static basic_json from_bson(detail::input_adapter&& i,
  18229. const bool strict = true,
  18230. const bool allow_exceptions = true)
  18231. {
  18232. basic_json result;
  18233. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18234. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::bson, &sdp, strict);
  18235. return res ? result : basic_json(value_t::discarded);
  18236. }
  18237. /*!
  18238. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  18239. */
  18240. template<typename A1, typename A2,
  18241. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18242. JSON_HEDLEY_WARN_UNUSED_RESULT
  18243. static basic_json from_bson(A1 && a1, A2 && a2,
  18244. const bool strict = true,
  18245. const bool allow_exceptions = true)
  18246. {
  18247. basic_json result;
  18248. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18249. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::bson, &sdp, strict);
  18250. return res ? result : basic_json(value_t::discarded);
  18251. }
  18252. /// @}
  18253. //////////////////////////
  18254. // JSON Pointer support //
  18255. //////////////////////////
  18256. /// @name JSON Pointer functions
  18257. /// @{
  18258. /*!
  18259. @brief access specified element via JSON Pointer
  18260. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  18261. No bound checking is performed. Similar to @ref operator[](const typename
  18262. object_t::key_type&), `null` values are created in arrays and objects if
  18263. necessary.
  18264. In particular:
  18265. - If the JSON pointer points to an object key that does not exist, it
  18266. is created an filled with a `null` value before a reference to it
  18267. is returned.
  18268. - If the JSON pointer points to an array index that does not exist, it
  18269. is created an filled with a `null` value before a reference to it
  18270. is returned. All indices between the current maximum and the given
  18271. index are also filled with `null`.
  18272. - The special value `-` is treated as a synonym for the index past the
  18273. end.
  18274. @param[in] ptr a JSON pointer
  18275. @return reference to the element pointed to by @a ptr
  18276. @complexity Constant.
  18277. @throw parse_error.106 if an array index begins with '0'
  18278. @throw parse_error.109 if an array index was not a number
  18279. @throw out_of_range.404 if the JSON pointer can not be resolved
  18280. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  18281. @since version 2.0.0
  18282. */
  18283. reference operator[](const json_pointer& ptr)
  18284. {
  18285. return ptr.get_unchecked(this);
  18286. }
  18287. /*!
  18288. @brief access specified element via JSON Pointer
  18289. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  18290. No bound checking is performed. The function does not change the JSON
  18291. value; no `null` values are created. In particular, the the special value
  18292. `-` yields an exception.
  18293. @param[in] ptr JSON pointer to the desired element
  18294. @return const reference to the element pointed to by @a ptr
  18295. @complexity Constant.
  18296. @throw parse_error.106 if an array index begins with '0'
  18297. @throw parse_error.109 if an array index was not a number
  18298. @throw out_of_range.402 if the array index '-' is used
  18299. @throw out_of_range.404 if the JSON pointer can not be resolved
  18300. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  18301. @since version 2.0.0
  18302. */
  18303. const_reference operator[](const json_pointer& ptr) const
  18304. {
  18305. return ptr.get_unchecked(this);
  18306. }
  18307. /*!
  18308. @brief access specified element via JSON Pointer
  18309. Returns a reference to the element at with specified JSON pointer @a ptr,
  18310. with bounds checking.
  18311. @param[in] ptr JSON pointer to the desired element
  18312. @return reference to the element pointed to by @a ptr
  18313. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  18314. begins with '0'. See example below.
  18315. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  18316. is not a number. See example below.
  18317. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  18318. is out of range. See example below.
  18319. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  18320. pointer @a ptr. As `at` provides checked access (and no elements are
  18321. implicitly inserted), the index '-' is always invalid. See example below.
  18322. @throw out_of_range.403 if the JSON pointer describes a key of an object
  18323. which cannot be found. See example below.
  18324. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  18325. See example below.
  18326. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18327. changes in the JSON value.
  18328. @complexity Constant.
  18329. @since version 2.0.0
  18330. @liveexample{The behavior is shown in the example.,at_json_pointer}
  18331. */
  18332. reference at(const json_pointer& ptr)
  18333. {
  18334. return ptr.get_checked(this);
  18335. }
  18336. /*!
  18337. @brief access specified element via JSON Pointer
  18338. Returns a const reference to the element at with specified JSON pointer @a
  18339. ptr, with bounds checking.
  18340. @param[in] ptr JSON pointer to the desired element
  18341. @return reference to the element pointed to by @a ptr
  18342. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  18343. begins with '0'. See example below.
  18344. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  18345. is not a number. See example below.
  18346. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  18347. is out of range. See example below.
  18348. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  18349. pointer @a ptr. As `at` provides checked access (and no elements are
  18350. implicitly inserted), the index '-' is always invalid. See example below.
  18351. @throw out_of_range.403 if the JSON pointer describes a key of an object
  18352. which cannot be found. See example below.
  18353. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  18354. See example below.
  18355. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18356. changes in the JSON value.
  18357. @complexity Constant.
  18358. @since version 2.0.0
  18359. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  18360. */
  18361. const_reference at(const json_pointer& ptr) const
  18362. {
  18363. return ptr.get_checked(this);
  18364. }
  18365. /*!
  18366. @brief return flattened JSON value
  18367. The function creates a JSON object whose keys are JSON pointers (see [RFC
  18368. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  18369. primitive. The original JSON value can be restored using the @ref
  18370. unflatten() function.
  18371. @return an object that maps JSON pointers to primitive values
  18372. @note Empty objects and arrays are flattened to `null` and will not be
  18373. reconstructed correctly by the @ref unflatten() function.
  18374. @complexity Linear in the size the JSON value.
  18375. @liveexample{The following code shows how a JSON object is flattened to an
  18376. object whose keys consist of JSON pointers.,flatten}
  18377. @sa @ref unflatten() for the reverse function
  18378. @since version 2.0.0
  18379. */
  18380. basic_json flatten() const
  18381. {
  18382. basic_json result(value_t::object);
  18383. json_pointer::flatten("", *this, result);
  18384. return result;
  18385. }
  18386. /*!
  18387. @brief unflatten a previously flattened JSON value
  18388. The function restores the arbitrary nesting of a JSON value that has been
  18389. flattened before using the @ref flatten() function. The JSON value must
  18390. meet certain constraints:
  18391. 1. The value must be an object.
  18392. 2. The keys must be JSON pointers (see
  18393. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  18394. 3. The mapped values must be primitive JSON types.
  18395. @return the original JSON from a flattened version
  18396. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  18397. values and can not unflattened to their original type. Apart from
  18398. this example, for a JSON value `j`, the following is always true:
  18399. `j == j.flatten().unflatten()`.
  18400. @complexity Linear in the size the JSON value.
  18401. @throw type_error.314 if value is not an object
  18402. @throw type_error.315 if object values are not primitive
  18403. @liveexample{The following code shows how a flattened JSON object is
  18404. unflattened into the original nested JSON object.,unflatten}
  18405. @sa @ref flatten() for the reverse function
  18406. @since version 2.0.0
  18407. */
  18408. basic_json unflatten() const
  18409. {
  18410. return json_pointer::unflatten(*this);
  18411. }
  18412. /// @}
  18413. //////////////////////////
  18414. // JSON Patch functions //
  18415. //////////////////////////
  18416. /// @name JSON Patch functions
  18417. /// @{
  18418. /*!
  18419. @brief applies a JSON patch
  18420. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  18421. expressing a sequence of operations to apply to a JSON) document. With
  18422. this function, a JSON Patch is applied to the current JSON value by
  18423. executing all operations from the patch.
  18424. @param[in] json_patch JSON patch document
  18425. @return patched document
  18426. @note The application of a patch is atomic: Either all operations succeed
  18427. and the patched document is returned or an exception is thrown. In
  18428. any case, the original value is not changed: the patch is applied
  18429. to a copy of the value.
  18430. @throw parse_error.104 if the JSON patch does not consist of an array of
  18431. objects
  18432. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  18433. attributes are missing); example: `"operation add must have member path"`
  18434. @throw out_of_range.401 if an array index is out of range.
  18435. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  18436. resolved successfully in the current JSON value; example: `"key baz not
  18437. found"`
  18438. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  18439. "move")
  18440. @throw other_error.501 if "test" operation was unsuccessful
  18441. @complexity Linear in the size of the JSON value and the length of the
  18442. JSON patch. As usually only a fraction of the JSON value is affected by
  18443. the patch, the complexity can usually be neglected.
  18444. @liveexample{The following code shows how a JSON patch is applied to a
  18445. value.,patch}
  18446. @sa @ref diff -- create a JSON patch by comparing two JSON values
  18447. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  18448. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  18449. @since version 2.0.0
  18450. */
  18451. basic_json patch(const basic_json& json_patch) const
  18452. {
  18453. // make a working copy to apply the patch to
  18454. basic_json result = *this;
  18455. // the valid JSON Patch operations
  18456. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  18457. const auto get_op = [](const std::string & op)
  18458. {
  18459. if (op == "add")
  18460. {
  18461. return patch_operations::add;
  18462. }
  18463. if (op == "remove")
  18464. {
  18465. return patch_operations::remove;
  18466. }
  18467. if (op == "replace")
  18468. {
  18469. return patch_operations::replace;
  18470. }
  18471. if (op == "move")
  18472. {
  18473. return patch_operations::move;
  18474. }
  18475. if (op == "copy")
  18476. {
  18477. return patch_operations::copy;
  18478. }
  18479. if (op == "test")
  18480. {
  18481. return patch_operations::test;
  18482. }
  18483. return patch_operations::invalid;
  18484. };
  18485. // wrapper for "add" operation; add value at ptr
  18486. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  18487. {
  18488. // adding to the root of the target document means replacing it
  18489. if (ptr.empty())
  18490. {
  18491. result = val;
  18492. return;
  18493. }
  18494. // make sure the top element of the pointer exists
  18495. json_pointer top_pointer = ptr.top();
  18496. if (top_pointer != ptr)
  18497. {
  18498. result.at(top_pointer);
  18499. }
  18500. // get reference to parent of JSON pointer ptr
  18501. const auto last_path = ptr.back();
  18502. ptr.pop_back();
  18503. basic_json& parent = result[ptr];
  18504. switch (parent.m_type)
  18505. {
  18506. case value_t::null:
  18507. case value_t::object:
  18508. {
  18509. // use operator[] to add value
  18510. parent[last_path] = val;
  18511. break;
  18512. }
  18513. case value_t::array:
  18514. {
  18515. if (last_path == "-")
  18516. {
  18517. // special case: append to back
  18518. parent.push_back(val);
  18519. }
  18520. else
  18521. {
  18522. const auto idx = json_pointer::array_index(last_path);
  18523. if (JSON_HEDLEY_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  18524. {
  18525. // avoid undefined behavior
  18526. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  18527. }
  18528. // default case: insert add offset
  18529. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  18530. }
  18531. break;
  18532. }
  18533. // if there exists a parent it cannot be primitive
  18534. default: // LCOV_EXCL_LINE
  18535. assert(false); // LCOV_EXCL_LINE
  18536. }
  18537. };
  18538. // wrapper for "remove" operation; remove value at ptr
  18539. const auto operation_remove = [&result](json_pointer & ptr)
  18540. {
  18541. // get reference to parent of JSON pointer ptr
  18542. const auto last_path = ptr.back();
  18543. ptr.pop_back();
  18544. basic_json& parent = result.at(ptr);
  18545. // remove child
  18546. if (parent.is_object())
  18547. {
  18548. // perform range check
  18549. auto it = parent.find(last_path);
  18550. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  18551. {
  18552. parent.erase(it);
  18553. }
  18554. else
  18555. {
  18556. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  18557. }
  18558. }
  18559. else if (parent.is_array())
  18560. {
  18561. // note erase performs range check
  18562. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  18563. }
  18564. };
  18565. // type check: top level value must be an array
  18566. if (JSON_HEDLEY_UNLIKELY(not json_patch.is_array()))
  18567. {
  18568. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  18569. }
  18570. // iterate and apply the operations
  18571. for (const auto& val : json_patch)
  18572. {
  18573. // wrapper to get a value for an operation
  18574. const auto get_value = [&val](const std::string & op,
  18575. const std::string & member,
  18576. bool string_type) -> basic_json &
  18577. {
  18578. // find value
  18579. auto it = val.m_value.object->find(member);
  18580. // context-sensitive error message
  18581. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  18582. // check if desired value is present
  18583. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  18584. {
  18585. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  18586. }
  18587. // check if result is of type string
  18588. if (JSON_HEDLEY_UNLIKELY(string_type and not it->second.is_string()))
  18589. {
  18590. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  18591. }
  18592. // no error: return value
  18593. return it->second;
  18594. };
  18595. // type check: every element of the array must be an object
  18596. if (JSON_HEDLEY_UNLIKELY(not val.is_object()))
  18597. {
  18598. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  18599. }
  18600. // collect mandatory members
  18601. const std::string op = get_value("op", "op", true);
  18602. const std::string path = get_value(op, "path", true);
  18603. json_pointer ptr(path);
  18604. switch (get_op(op))
  18605. {
  18606. case patch_operations::add:
  18607. {
  18608. operation_add(ptr, get_value("add", "value", false));
  18609. break;
  18610. }
  18611. case patch_operations::remove:
  18612. {
  18613. operation_remove(ptr);
  18614. break;
  18615. }
  18616. case patch_operations::replace:
  18617. {
  18618. // the "path" location must exist - use at()
  18619. result.at(ptr) = get_value("replace", "value", false);
  18620. break;
  18621. }
  18622. case patch_operations::move:
  18623. {
  18624. const std::string from_path = get_value("move", "from", true);
  18625. json_pointer from_ptr(from_path);
  18626. // the "from" location must exist - use at()
  18627. basic_json v = result.at(from_ptr);
  18628. // The move operation is functionally identical to a
  18629. // "remove" operation on the "from" location, followed
  18630. // immediately by an "add" operation at the target
  18631. // location with the value that was just removed.
  18632. operation_remove(from_ptr);
  18633. operation_add(ptr, v);
  18634. break;
  18635. }
  18636. case patch_operations::copy:
  18637. {
  18638. const std::string from_path = get_value("copy", "from", true);
  18639. const json_pointer from_ptr(from_path);
  18640. // the "from" location must exist - use at()
  18641. basic_json v = result.at(from_ptr);
  18642. // The copy is functionally identical to an "add"
  18643. // operation at the target location using the value
  18644. // specified in the "from" member.
  18645. operation_add(ptr, v);
  18646. break;
  18647. }
  18648. case patch_operations::test:
  18649. {
  18650. bool success = false;
  18651. JSON_TRY
  18652. {
  18653. // check if "value" matches the one at "path"
  18654. // the "path" location must exist - use at()
  18655. success = (result.at(ptr) == get_value("test", "value", false));
  18656. }
  18657. JSON_INTERNAL_CATCH (out_of_range&)
  18658. {
  18659. // ignore out of range errors: success remains false
  18660. }
  18661. // throw an exception if test fails
  18662. if (JSON_HEDLEY_UNLIKELY(not success))
  18663. {
  18664. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  18665. }
  18666. break;
  18667. }
  18668. default:
  18669. {
  18670. // op must be "add", "remove", "replace", "move", "copy", or
  18671. // "test"
  18672. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  18673. }
  18674. }
  18675. }
  18676. return result;
  18677. }
  18678. /*!
  18679. @brief creates a diff as a JSON patch
  18680. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  18681. be changed into the value @a target by calling @ref patch function.
  18682. @invariant For two JSON values @a source and @a target, the following code
  18683. yields always `true`:
  18684. @code {.cpp}
  18685. source.patch(diff(source, target)) == target;
  18686. @endcode
  18687. @note Currently, only `remove`, `add`, and `replace` operations are
  18688. generated.
  18689. @param[in] source JSON value to compare from
  18690. @param[in] target JSON value to compare against
  18691. @param[in] path helper value to create JSON pointers
  18692. @return a JSON patch to convert the @a source to @a target
  18693. @complexity Linear in the lengths of @a source and @a target.
  18694. @liveexample{The following code shows how a JSON patch is created as a
  18695. diff for two JSON values.,diff}
  18696. @sa @ref patch -- apply a JSON patch
  18697. @sa @ref merge_patch -- apply a JSON Merge Patch
  18698. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  18699. @since version 2.0.0
  18700. */
  18701. JSON_HEDLEY_WARN_UNUSED_RESULT
  18702. static basic_json diff(const basic_json& source, const basic_json& target,
  18703. const std::string& path = "")
  18704. {
  18705. // the patch
  18706. basic_json result(value_t::array);
  18707. // if the values are the same, return empty patch
  18708. if (source == target)
  18709. {
  18710. return result;
  18711. }
  18712. if (source.type() != target.type())
  18713. {
  18714. // different types: replace value
  18715. result.push_back(
  18716. {
  18717. {"op", "replace"}, {"path", path}, {"value", target}
  18718. });
  18719. return result;
  18720. }
  18721. switch (source.type())
  18722. {
  18723. case value_t::array:
  18724. {
  18725. // first pass: traverse common elements
  18726. std::size_t i = 0;
  18727. while (i < source.size() and i < target.size())
  18728. {
  18729. // recursive call to compare array values at index i
  18730. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  18731. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  18732. ++i;
  18733. }
  18734. // i now reached the end of at least one array
  18735. // in a second pass, traverse the remaining elements
  18736. // remove my remaining elements
  18737. const auto end_index = static_cast<difference_type>(result.size());
  18738. while (i < source.size())
  18739. {
  18740. // add operations in reverse order to avoid invalid
  18741. // indices
  18742. result.insert(result.begin() + end_index, object(
  18743. {
  18744. {"op", "remove"},
  18745. {"path", path + "/" + std::to_string(i)}
  18746. }));
  18747. ++i;
  18748. }
  18749. // add other remaining elements
  18750. while (i < target.size())
  18751. {
  18752. result.push_back(
  18753. {
  18754. {"op", "add"},
  18755. {"path", path + "/" + std::to_string(i)},
  18756. {"value", target[i]}
  18757. });
  18758. ++i;
  18759. }
  18760. break;
  18761. }
  18762. case value_t::object:
  18763. {
  18764. // first pass: traverse this object's elements
  18765. for (auto it = source.cbegin(); it != source.cend(); ++it)
  18766. {
  18767. // escape the key name to be used in a JSON patch
  18768. const auto key = json_pointer::escape(it.key());
  18769. if (target.find(it.key()) != target.end())
  18770. {
  18771. // recursive call to compare object values at key it
  18772. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  18773. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  18774. }
  18775. else
  18776. {
  18777. // found a key that is not in o -> remove it
  18778. result.push_back(object(
  18779. {
  18780. {"op", "remove"}, {"path", path + "/" + key}
  18781. }));
  18782. }
  18783. }
  18784. // second pass: traverse other object's elements
  18785. for (auto it = target.cbegin(); it != target.cend(); ++it)
  18786. {
  18787. if (source.find(it.key()) == source.end())
  18788. {
  18789. // found a key that is not in this -> add it
  18790. const auto key = json_pointer::escape(it.key());
  18791. result.push_back(
  18792. {
  18793. {"op", "add"}, {"path", path + "/" + key},
  18794. {"value", it.value()}
  18795. });
  18796. }
  18797. }
  18798. break;
  18799. }
  18800. default:
  18801. {
  18802. // both primitive type: replace value
  18803. result.push_back(
  18804. {
  18805. {"op", "replace"}, {"path", path}, {"value", target}
  18806. });
  18807. break;
  18808. }
  18809. }
  18810. return result;
  18811. }
  18812. /// @}
  18813. ////////////////////////////////
  18814. // JSON Merge Patch functions //
  18815. ////////////////////////////////
  18816. /// @name JSON Merge Patch functions
  18817. /// @{
  18818. /*!
  18819. @brief applies a JSON Merge Patch
  18820. The merge patch format is primarily intended for use with the HTTP PATCH
  18821. method as a means of describing a set of modifications to a target
  18822. resource's content. This function applies a merge patch to the current
  18823. JSON value.
  18824. The function implements the following algorithm from Section 2 of
  18825. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  18826. ```
  18827. define MergePatch(Target, Patch):
  18828. if Patch is an Object:
  18829. if Target is not an Object:
  18830. Target = {} // Ignore the contents and set it to an empty Object
  18831. for each Name/Value pair in Patch:
  18832. if Value is null:
  18833. if Name exists in Target:
  18834. remove the Name/Value pair from Target
  18835. else:
  18836. Target[Name] = MergePatch(Target[Name], Value)
  18837. return Target
  18838. else:
  18839. return Patch
  18840. ```
  18841. Thereby, `Target` is the current object; that is, the patch is applied to
  18842. the current value.
  18843. @param[in] apply_patch the patch to apply
  18844. @complexity Linear in the lengths of @a patch.
  18845. @liveexample{The following code shows how a JSON Merge Patch is applied to
  18846. a JSON document.,merge_patch}
  18847. @sa @ref patch -- apply a JSON patch
  18848. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  18849. @since version 3.0.0
  18850. */
  18851. void merge_patch(const basic_json& apply_patch)
  18852. {
  18853. if (apply_patch.is_object())
  18854. {
  18855. if (not is_object())
  18856. {
  18857. *this = object();
  18858. }
  18859. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  18860. {
  18861. if (it.value().is_null())
  18862. {
  18863. erase(it.key());
  18864. }
  18865. else
  18866. {
  18867. operator[](it.key()).merge_patch(it.value());
  18868. }
  18869. }
  18870. }
  18871. else
  18872. {
  18873. *this = apply_patch;
  18874. }
  18875. }
  18876. /// @}
  18877. };
  18878. /*!
  18879. @brief user-defined to_string function for JSON values
  18880. This function implements a user-defined to_string for JSON objects.
  18881. @param[in] j a JSON object
  18882. @return a std::string object
  18883. */
  18884. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  18885. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  18886. {
  18887. return j.dump();
  18888. }
  18889. } // namespace nlohmann
  18890. ///////////////////////
  18891. // nonmember support //
  18892. ///////////////////////
  18893. // specialization of std::swap, and std::hash
  18894. namespace std
  18895. {
  18896. /// hash value for JSON objects
  18897. template<>
  18898. struct hash<nlohmann::json>
  18899. {
  18900. /*!
  18901. @brief return a hash value for a JSON object
  18902. @since version 1.0.0
  18903. */
  18904. std::size_t operator()(const nlohmann::json& j) const
  18905. {
  18906. // a naive hashing via the string representation
  18907. const auto& h = hash<nlohmann::json::string_t>();
  18908. return h(j.dump());
  18909. }
  18910. };
  18911. /// specialization for std::less<value_t>
  18912. /// @note: do not remove the space after '<',
  18913. /// see https://github.com/nlohmann/json/pull/679
  18914. template<>
  18915. struct less< ::nlohmann::detail::value_t>
  18916. {
  18917. /*!
  18918. @brief compare two value_t enum values
  18919. @since version 3.0.0
  18920. */
  18921. bool operator()(nlohmann::detail::value_t lhs,
  18922. nlohmann::detail::value_t rhs) const noexcept
  18923. {
  18924. return nlohmann::detail::operator<(lhs, rhs);
  18925. }
  18926. };
  18927. /*!
  18928. @brief exchanges the values of two JSON objects
  18929. @since version 1.0.0
  18930. */
  18931. template<>
  18932. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  18933. is_nothrow_move_constructible<nlohmann::json>::value and
  18934. is_nothrow_move_assignable<nlohmann::json>::value
  18935. )
  18936. {
  18937. j1.swap(j2);
  18938. }
  18939. } // namespace std
  18940. /*!
  18941. @brief user-defined string literal for JSON values
  18942. This operator implements a user-defined string literal for JSON objects. It
  18943. can be used by adding `"_json"` to a string literal and returns a JSON object
  18944. if no parse error occurred.
  18945. @param[in] s a string representation of a JSON object
  18946. @param[in] n the length of string @a s
  18947. @return a JSON object
  18948. @since version 1.0.0
  18949. */
  18950. JSON_HEDLEY_NON_NULL(1)
  18951. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  18952. {
  18953. return nlohmann::json::parse(s, s + n);
  18954. }
  18955. /*!
  18956. @brief user-defined string literal for JSON pointer
  18957. This operator implements a user-defined string literal for JSON Pointers. It
  18958. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  18959. object if no parse error occurred.
  18960. @param[in] s a string representation of a JSON Pointer
  18961. @param[in] n the length of string @a s
  18962. @return a JSON pointer object
  18963. @since version 2.0.0
  18964. */
  18965. JSON_HEDLEY_NON_NULL(1)
  18966. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  18967. {
  18968. return nlohmann::json::json_pointer(std::string(s, n));
  18969. }
  18970. // #include <nlohmann/detail/macro_unscope.hpp>
  18971. // restore GCC/clang diagnostic settings
  18972. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  18973. #pragma GCC diagnostic pop
  18974. #endif
  18975. #if defined(__clang__)
  18976. #pragma GCC diagnostic pop
  18977. #endif
  18978. // clean up
  18979. #undef JSON_INTERNAL_CATCH
  18980. #undef JSON_CATCH
  18981. #undef JSON_THROW
  18982. #undef JSON_TRY
  18983. #undef JSON_HAS_CPP_14
  18984. #undef JSON_HAS_CPP_17
  18985. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  18986. #undef NLOHMANN_BASIC_JSON_TPL
  18987. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  18988. #undef JSON_HEDLEY_ALWAYS_INLINE
  18989. #undef JSON_HEDLEY_ARM_VERSION
  18990. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  18991. #undef JSON_HEDLEY_ARRAY_PARAM
  18992. #undef JSON_HEDLEY_ASSUME
  18993. #undef JSON_HEDLEY_BEGIN_C_DECLS
  18994. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  18995. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  18996. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  18997. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  18998. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  18999. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  19000. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  19001. #undef JSON_HEDLEY_COMPCERT_VERSION
  19002. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  19003. #undef JSON_HEDLEY_CONCAT
  19004. #undef JSON_HEDLEY_CONCAT_EX
  19005. #undef JSON_HEDLEY_CONST
  19006. #undef JSON_HEDLEY_CONSTEXPR
  19007. #undef JSON_HEDLEY_CONST_CAST
  19008. #undef JSON_HEDLEY_CPP_CAST
  19009. #undef JSON_HEDLEY_CRAY_VERSION
  19010. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  19011. #undef JSON_HEDLEY_C_DECL
  19012. #undef JSON_HEDLEY_DEPRECATED
  19013. #undef JSON_HEDLEY_DEPRECATED_FOR
  19014. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  19015. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  19016. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  19017. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  19018. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  19019. #undef JSON_HEDLEY_DMC_VERSION
  19020. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  19021. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  19022. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  19023. #undef JSON_HEDLEY_END_C_DECLS
  19024. #undef JSON_HEDLEY_FALL_THROUGH
  19025. #undef JSON_HEDLEY_FLAGS
  19026. #undef JSON_HEDLEY_FLAGS_CAST
  19027. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  19028. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  19029. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  19030. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  19031. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  19032. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  19033. #undef JSON_HEDLEY_GCC_HAS_WARNING
  19034. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  19035. #undef JSON_HEDLEY_GCC_VERSION
  19036. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  19037. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  19038. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  19039. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  19040. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  19041. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  19042. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  19043. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  19044. #undef JSON_HEDLEY_GNUC_VERSION
  19045. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  19046. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  19047. #undef JSON_HEDLEY_HAS_BUILTIN
  19048. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  19049. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  19050. #undef JSON_HEDLEY_HAS_EXTENSION
  19051. #undef JSON_HEDLEY_HAS_FEATURE
  19052. #undef JSON_HEDLEY_HAS_WARNING
  19053. #undef JSON_HEDLEY_IAR_VERSION
  19054. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  19055. #undef JSON_HEDLEY_IBM_VERSION
  19056. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  19057. #undef JSON_HEDLEY_IMPORT
  19058. #undef JSON_HEDLEY_INLINE
  19059. #undef JSON_HEDLEY_INTEL_VERSION
  19060. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  19061. #undef JSON_HEDLEY_IS_CONSTANT
  19062. #undef JSON_HEDLEY_LIKELY
  19063. #undef JSON_HEDLEY_MALLOC
  19064. #undef JSON_HEDLEY_MESSAGE
  19065. #undef JSON_HEDLEY_MSVC_VERSION
  19066. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  19067. #undef JSON_HEDLEY_NEVER_INLINE
  19068. #undef JSON_HEDLEY_NON_NULL
  19069. #undef JSON_HEDLEY_NO_RETURN
  19070. #undef JSON_HEDLEY_NO_THROW
  19071. #undef JSON_HEDLEY_PELLES_VERSION
  19072. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  19073. #undef JSON_HEDLEY_PGI_VERSION
  19074. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  19075. #undef JSON_HEDLEY_PREDICT
  19076. #undef JSON_HEDLEY_PRINTF_FORMAT
  19077. #undef JSON_HEDLEY_PRIVATE
  19078. #undef JSON_HEDLEY_PUBLIC
  19079. #undef JSON_HEDLEY_PURE
  19080. #undef JSON_HEDLEY_REINTERPRET_CAST
  19081. #undef JSON_HEDLEY_REQUIRE
  19082. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  19083. #undef JSON_HEDLEY_REQUIRE_MSG
  19084. #undef JSON_HEDLEY_RESTRICT
  19085. #undef JSON_HEDLEY_RETURNS_NON_NULL
  19086. #undef JSON_HEDLEY_SENTINEL
  19087. #undef JSON_HEDLEY_STATIC_ASSERT
  19088. #undef JSON_HEDLEY_STATIC_CAST
  19089. #undef JSON_HEDLEY_STRINGIFY
  19090. #undef JSON_HEDLEY_STRINGIFY_EX
  19091. #undef JSON_HEDLEY_SUNPRO_VERSION
  19092. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  19093. #undef JSON_HEDLEY_TINYC_VERSION
  19094. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  19095. #undef JSON_HEDLEY_TI_VERSION
  19096. #undef JSON_HEDLEY_TI_VERSION_CHECK
  19097. #undef JSON_HEDLEY_UNAVAILABLE
  19098. #undef JSON_HEDLEY_UNLIKELY
  19099. #undef JSON_HEDLEY_UNPREDICTABLE
  19100. #undef JSON_HEDLEY_UNREACHABLE
  19101. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  19102. #undef JSON_HEDLEY_VERSION
  19103. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  19104. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  19105. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  19106. #undef JSON_HEDLEY_VERSION_ENCODE
  19107. #undef JSON_HEDLEY_WARNING
  19108. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  19109. #endif // INCLUDE_NLOHMANN_JSON_HPP_