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.

20911 lines
713 KiB

  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.6.1
  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 6
  29. #define NLOHMANN_JSON_VERSION_PATCH 1
  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. namespace nlohmann
  86. {
  87. namespace detail
  88. {
  89. ////////////////
  90. // exceptions //
  91. ////////////////
  92. /*!
  93. @brief general exception of the @ref basic_json class
  94. This class is an extension of `std::exception` objects with a member @a id for
  95. exception ids. It is used as the base class for all exceptions thrown by the
  96. @ref basic_json class. This class can hence be used as "wildcard" to catch
  97. exceptions.
  98. Subclasses:
  99. - @ref parse_error for exceptions indicating a parse error
  100. - @ref invalid_iterator for exceptions indicating errors with iterators
  101. - @ref type_error for exceptions indicating executing a member function with
  102. a wrong type
  103. - @ref out_of_range for exceptions indicating access out of the defined range
  104. - @ref other_error for exceptions indicating other library errors
  105. @internal
  106. @note To have nothrow-copy-constructible exceptions, we internally use
  107. `std::runtime_error` which can cope with arbitrary-length error messages.
  108. Intermediate strings are built with static functions and then passed to
  109. the actual constructor.
  110. @endinternal
  111. @liveexample{The following code shows how arbitrary library exceptions can be
  112. caught.,exception}
  113. @since version 3.0.0
  114. */
  115. class exception : public std::exception
  116. {
  117. public:
  118. /// returns the explanatory string
  119. const char* what() const noexcept override
  120. {
  121. return m.what();
  122. }
  123. /// the id of the exception
  124. const int id;
  125. protected:
  126. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  127. static std::string name(const std::string& ename, int id_)
  128. {
  129. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  130. }
  131. private:
  132. /// an exception object as storage for error messages
  133. std::runtime_error m;
  134. };
  135. /*!
  136. @brief exception indicating a parse error
  137. This exception is thrown by the library when a parse error occurs. Parse errors
  138. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  139. as when using JSON Patch.
  140. Member @a byte holds the byte index of the last read character in the input
  141. file.
  142. Exceptions have ids 1xx.
  143. name / id | example message | description
  144. ------------------------------ | --------------- | -------------------------
  145. 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.
  146. 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.
  147. 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.
  148. 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.
  149. 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.
  150. 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`.
  151. 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.
  152. 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.
  153. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  154. 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.
  155. 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.
  156. 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.
  157. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  158. @note For an input with n bytes, 1 is the index of the first character and n+1
  159. is the index of the terminating null byte or the end of file. This also
  160. holds true when reading a byte vector (CBOR or MessagePack).
  161. @liveexample{The following code shows how a `parse_error` exception can be
  162. caught.,parse_error}
  163. @sa - @ref exception for the base class of the library exceptions
  164. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  165. @sa - @ref type_error for exceptions indicating executing a member function with
  166. a wrong type
  167. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  168. @sa - @ref other_error for exceptions indicating other library errors
  169. @since version 3.0.0
  170. */
  171. class parse_error : public exception
  172. {
  173. public:
  174. /*!
  175. @brief create a parse error exception
  176. @param[in] id_ the id of the exception
  177. @param[in] pos the position where the error occurred (or with
  178. chars_read_total=0 if the position cannot be
  179. determined)
  180. @param[in] what_arg the explanatory string
  181. @return parse_error object
  182. */
  183. static parse_error create(int id_, const position_t& pos, const std::string& what_arg)
  184. {
  185. std::string w = exception::name("parse_error", id_) + "parse error" +
  186. position_string(pos) + ": " + what_arg;
  187. return parse_error(id_, pos.chars_read_total, w.c_str());
  188. }
  189. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  190. {
  191. std::string w = exception::name("parse_error", id_) + "parse error" +
  192. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  193. ": " + what_arg;
  194. return parse_error(id_, byte_, w.c_str());
  195. }
  196. /*!
  197. @brief byte index of the parse error
  198. The byte index of the last read character in the input file.
  199. @note For an input with n bytes, 1 is the index of the first character and
  200. n+1 is the index of the terminating null byte or the end of file.
  201. This also holds true when reading a byte vector (CBOR or MessagePack).
  202. */
  203. const std::size_t byte;
  204. private:
  205. parse_error(int id_, std::size_t byte_, const char* what_arg)
  206. : exception(id_, what_arg), byte(byte_) {}
  207. static std::string position_string(const position_t& pos)
  208. {
  209. return " at line " + std::to_string(pos.lines_read + 1) +
  210. ", column " + std::to_string(pos.chars_read_current_line);
  211. }
  212. };
  213. /*!
  214. @brief exception indicating errors with iterators
  215. This exception is thrown if iterators passed to a library function do not match
  216. the expected semantics.
  217. Exceptions have ids 2xx.
  218. name / id | example message | description
  219. ----------------------------------- | --------------- | -------------------------
  220. 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.
  221. 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.
  222. 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.
  223. 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.
  224. 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.
  225. 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.
  226. 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.
  227. 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.
  228. 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.
  229. 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.
  230. 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.
  231. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  232. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  233. 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().
  234. @liveexample{The following code shows how an `invalid_iterator` exception can be
  235. caught.,invalid_iterator}
  236. @sa - @ref exception for the base class of the library exceptions
  237. @sa - @ref parse_error for exceptions indicating a parse error
  238. @sa - @ref type_error for exceptions indicating executing a member function with
  239. a wrong type
  240. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  241. @sa - @ref other_error for exceptions indicating other library errors
  242. @since version 3.0.0
  243. */
  244. class invalid_iterator : public exception
  245. {
  246. public:
  247. static invalid_iterator create(int id_, const std::string& what_arg)
  248. {
  249. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  250. return invalid_iterator(id_, w.c_str());
  251. }
  252. private:
  253. invalid_iterator(int id_, const char* what_arg)
  254. : exception(id_, what_arg) {}
  255. };
  256. /*!
  257. @brief exception indicating executing a member function with a wrong type
  258. This exception is thrown in case of a type error; that is, a library function is
  259. executed on a JSON value whose type does not match the expected semantics.
  260. Exceptions have ids 3xx.
  261. name / id | example message | description
  262. ----------------------------- | --------------- | -------------------------
  263. 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.
  264. 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.
  265. 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 &.
  266. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  267. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  268. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  269. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  270. 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.
  271. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  272. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  273. 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.
  274. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  275. 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.
  276. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  277. 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.
  278. 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. |
  279. 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) |
  280. @liveexample{The following code shows how a `type_error` exception can be
  281. caught.,type_error}
  282. @sa - @ref exception for the base class of the library exceptions
  283. @sa - @ref parse_error for exceptions indicating a parse error
  284. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  285. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  286. @sa - @ref other_error for exceptions indicating other library errors
  287. @since version 3.0.0
  288. */
  289. class type_error : public exception
  290. {
  291. public:
  292. static type_error create(int id_, const std::string& what_arg)
  293. {
  294. std::string w = exception::name("type_error", id_) + what_arg;
  295. return type_error(id_, w.c_str());
  296. }
  297. private:
  298. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  299. };
  300. /*!
  301. @brief exception indicating access out of the defined range
  302. This exception is thrown in case a library function is called on an input
  303. parameter that exceeds the expected range, for instance in case of array
  304. indices or nonexisting object keys.
  305. Exceptions have ids 4xx.
  306. name / id | example message | description
  307. ------------------------------- | --------------- | -------------------------
  308. 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.
  309. 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.
  310. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  311. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  312. 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.
  313. 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.
  314. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. |
  315. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  316. 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 |
  317. @liveexample{The following code shows how an `out_of_range` exception can be
  318. caught.,out_of_range}
  319. @sa - @ref exception for the base class of the library exceptions
  320. @sa - @ref parse_error for exceptions indicating a parse error
  321. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  322. @sa - @ref type_error for exceptions indicating executing a member function with
  323. a wrong type
  324. @sa - @ref other_error for exceptions indicating other library errors
  325. @since version 3.0.0
  326. */
  327. class out_of_range : public exception
  328. {
  329. public:
  330. static out_of_range create(int id_, const std::string& what_arg)
  331. {
  332. std::string w = exception::name("out_of_range", id_) + what_arg;
  333. return out_of_range(id_, w.c_str());
  334. }
  335. private:
  336. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  337. };
  338. /*!
  339. @brief exception indicating other library errors
  340. This exception is thrown in case of errors that cannot be classified with the
  341. other exception types.
  342. Exceptions have ids 5xx.
  343. name / id | example message | description
  344. ------------------------------ | --------------- | -------------------------
  345. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  346. @sa - @ref exception for the base class of the library exceptions
  347. @sa - @ref parse_error for exceptions indicating a parse error
  348. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  349. @sa - @ref type_error for exceptions indicating executing a member function with
  350. a wrong type
  351. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  352. @liveexample{The following code shows how an `other_error` exception can be
  353. caught.,other_error}
  354. @since version 3.0.0
  355. */
  356. class other_error : public exception
  357. {
  358. public:
  359. static other_error create(int id_, const std::string& what_arg)
  360. {
  361. std::string w = exception::name("other_error", id_) + what_arg;
  362. return other_error(id_, w.c_str());
  363. }
  364. private:
  365. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  366. };
  367. } // namespace detail
  368. } // namespace nlohmann
  369. // #include <nlohmann/detail/macro_scope.hpp>
  370. #include <utility> // pair
  371. // This file contains all internal macro definitions
  372. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  373. // exclude unsupported compilers
  374. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  375. #if defined(__clang__)
  376. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  377. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  378. #endif
  379. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  380. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  381. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  382. #endif
  383. #endif
  384. #endif
  385. // C++ language standard detection
  386. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  387. #define JSON_HAS_CPP_17
  388. #define JSON_HAS_CPP_14
  389. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  390. #define JSON_HAS_CPP_14
  391. #endif
  392. // disable float-equal warnings on GCC/clang
  393. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  394. #pragma GCC diagnostic push
  395. #pragma GCC diagnostic ignored "-Wfloat-equal"
  396. #endif
  397. // disable documentation warnings on clang
  398. #if defined(__clang__)
  399. #pragma GCC diagnostic push
  400. #pragma GCC diagnostic ignored "-Wdocumentation"
  401. #endif
  402. // allow for portable deprecation warnings
  403. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  404. #define JSON_DEPRECATED __attribute__((deprecated))
  405. #elif defined(_MSC_VER)
  406. #define JSON_DEPRECATED __declspec(deprecated)
  407. #else
  408. #define JSON_DEPRECATED
  409. #endif
  410. // allow for portable nodiscard warnings
  411. #if defined(__has_cpp_attribute)
  412. #if __has_cpp_attribute(nodiscard)
  413. #if defined(__clang__) && !defined(JSON_HAS_CPP_17) // issue #1535
  414. #define JSON_NODISCARD
  415. #else
  416. #define JSON_NODISCARD [[nodiscard]]
  417. #endif
  418. #elif __has_cpp_attribute(gnu::warn_unused_result)
  419. #define JSON_NODISCARD [[gnu::warn_unused_result]]
  420. #else
  421. #define JSON_NODISCARD
  422. #endif
  423. #else
  424. #define JSON_NODISCARD
  425. #endif
  426. // allow to disable exceptions
  427. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  428. #define JSON_THROW(exception) throw exception
  429. #define JSON_TRY try
  430. #define JSON_CATCH(exception) catch(exception)
  431. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  432. #else
  433. #include <cstdlib>
  434. #define JSON_THROW(exception) std::abort()
  435. #define JSON_TRY if(true)
  436. #define JSON_CATCH(exception) if(false)
  437. #define JSON_INTERNAL_CATCH(exception) if(false)
  438. #endif
  439. // override exception macros
  440. #if defined(JSON_THROW_USER)
  441. #undef JSON_THROW
  442. #define JSON_THROW JSON_THROW_USER
  443. #endif
  444. #if defined(JSON_TRY_USER)
  445. #undef JSON_TRY
  446. #define JSON_TRY JSON_TRY_USER
  447. #endif
  448. #if defined(JSON_CATCH_USER)
  449. #undef JSON_CATCH
  450. #define JSON_CATCH JSON_CATCH_USER
  451. #undef JSON_INTERNAL_CATCH
  452. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  453. #endif
  454. #if defined(JSON_INTERNAL_CATCH_USER)
  455. #undef JSON_INTERNAL_CATCH
  456. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  457. #endif
  458. // manual branch prediction
  459. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  460. #define JSON_LIKELY(x) __builtin_expect(x, 1)
  461. #define JSON_UNLIKELY(x) __builtin_expect(x, 0)
  462. #else
  463. #define JSON_LIKELY(x) x
  464. #define JSON_UNLIKELY(x) x
  465. #endif
  466. /*!
  467. @brief macro to briefly define a mapping between an enum and JSON
  468. @def NLOHMANN_JSON_SERIALIZE_ENUM
  469. @since version 3.4.0
  470. */
  471. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  472. template<typename BasicJsonType> \
  473. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  474. { \
  475. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  476. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  477. auto it = std::find_if(std::begin(m), std::end(m), \
  478. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  479. { \
  480. return ej_pair.first == e; \
  481. }); \
  482. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  483. } \
  484. template<typename BasicJsonType> \
  485. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  486. { \
  487. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  488. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  489. auto it = std::find_if(std::begin(m), std::end(m), \
  490. [j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  491. { \
  492. return ej_pair.second == j; \
  493. }); \
  494. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  495. }
  496. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  497. // may be removed in the future once the class is split.
  498. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  499. template<template<typename, typename, typename...> class ObjectType, \
  500. template<typename, typename...> class ArrayType, \
  501. class StringType, class BooleanType, class NumberIntegerType, \
  502. class NumberUnsignedType, class NumberFloatType, \
  503. template<typename> class AllocatorType, \
  504. template<typename, typename = void> class JSONSerializer>
  505. #define NLOHMANN_BASIC_JSON_TPL \
  506. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  507. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  508. AllocatorType, JSONSerializer>
  509. // #include <nlohmann/detail/meta/cpp_future.hpp>
  510. #include <ciso646> // not
  511. #include <cstddef> // size_t
  512. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  513. namespace nlohmann
  514. {
  515. namespace detail
  516. {
  517. // alias templates to reduce boilerplate
  518. template<bool B, typename T = void>
  519. using enable_if_t = typename std::enable_if<B, T>::type;
  520. template<typename T>
  521. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  522. // implementation of C++14 index_sequence and affiliates
  523. // source: https://stackoverflow.com/a/32223343
  524. template<std::size_t... Ints>
  525. struct index_sequence
  526. {
  527. using type = index_sequence;
  528. using value_type = std::size_t;
  529. static constexpr std::size_t size() noexcept
  530. {
  531. return sizeof...(Ints);
  532. }
  533. };
  534. template<class Sequence1, class Sequence2>
  535. struct merge_and_renumber;
  536. template<std::size_t... I1, std::size_t... I2>
  537. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  538. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  539. template<std::size_t N>
  540. struct make_index_sequence
  541. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  542. typename make_index_sequence < N - N / 2 >::type > {};
  543. template<> struct make_index_sequence<0> : index_sequence<> {};
  544. template<> struct make_index_sequence<1> : index_sequence<0> {};
  545. template<typename... Ts>
  546. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  547. // dispatch utility (taken from ranges-v3)
  548. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  549. template<> struct priority_tag<0> {};
  550. // taken from ranges-v3
  551. template<typename T>
  552. struct static_const
  553. {
  554. static constexpr T value{};
  555. };
  556. template<typename T>
  557. constexpr T static_const<T>::value;
  558. } // namespace detail
  559. } // namespace nlohmann
  560. // #include <nlohmann/detail/meta/type_traits.hpp>
  561. #include <ciso646> // not
  562. #include <limits> // numeric_limits
  563. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  564. #include <utility> // declval
  565. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  566. #include <iterator> // random_access_iterator_tag
  567. // #include <nlohmann/detail/meta/void_t.hpp>
  568. namespace nlohmann
  569. {
  570. namespace detail
  571. {
  572. template <typename ...Ts> struct make_void
  573. {
  574. using type = void;
  575. };
  576. template <typename ...Ts> using void_t = typename make_void<Ts...>::type;
  577. } // namespace detail
  578. } // namespace nlohmann
  579. // #include <nlohmann/detail/meta/cpp_future.hpp>
  580. namespace nlohmann
  581. {
  582. namespace detail
  583. {
  584. template <typename It, typename = void>
  585. struct iterator_types {};
  586. template <typename It>
  587. struct iterator_types <
  588. It,
  589. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  590. typename It::reference, typename It::iterator_category >>
  591. {
  592. using difference_type = typename It::difference_type;
  593. using value_type = typename It::value_type;
  594. using pointer = typename It::pointer;
  595. using reference = typename It::reference;
  596. using iterator_category = typename It::iterator_category;
  597. };
  598. // This is required as some compilers implement std::iterator_traits in a way that
  599. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  600. template <typename T, typename = void>
  601. struct iterator_traits
  602. {
  603. };
  604. template <typename T>
  605. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  606. : iterator_types<T>
  607. {
  608. };
  609. template <typename T>
  610. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  611. {
  612. using iterator_category = std::random_access_iterator_tag;
  613. using value_type = T;
  614. using difference_type = ptrdiff_t;
  615. using pointer = T*;
  616. using reference = T&;
  617. };
  618. } // namespace detail
  619. } // namespace nlohmann
  620. // #include <nlohmann/detail/macro_scope.hpp>
  621. // #include <nlohmann/detail/meta/cpp_future.hpp>
  622. // #include <nlohmann/detail/meta/detected.hpp>
  623. #include <type_traits>
  624. // #include <nlohmann/detail/meta/void_t.hpp>
  625. // http://en.cppreference.com/w/cpp/experimental/is_detected
  626. namespace nlohmann
  627. {
  628. namespace detail
  629. {
  630. struct nonesuch
  631. {
  632. nonesuch() = delete;
  633. ~nonesuch() = delete;
  634. nonesuch(nonesuch const&) = delete;
  635. nonesuch(nonesuch const&&) = delete;
  636. void operator=(nonesuch const&) = delete;
  637. void operator=(nonesuch&&) = delete;
  638. };
  639. template <class Default,
  640. class AlwaysVoid,
  641. template <class...> class Op,
  642. class... Args>
  643. struct detector
  644. {
  645. using value_t = std::false_type;
  646. using type = Default;
  647. };
  648. template <class Default, template <class...> class Op, class... Args>
  649. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  650. {
  651. using value_t = std::true_type;
  652. using type = Op<Args...>;
  653. };
  654. template <template <class...> class Op, class... Args>
  655. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  656. template <template <class...> class Op, class... Args>
  657. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  658. template <class Default, template <class...> class Op, class... Args>
  659. using detected_or = detector<Default, void, Op, Args...>;
  660. template <class Default, template <class...> class Op, class... Args>
  661. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  662. template <class Expected, template <class...> class Op, class... Args>
  663. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  664. template <class To, template <class...> class Op, class... Args>
  665. using is_detected_convertible =
  666. std::is_convertible<detected_t<Op, Args...>, To>;
  667. } // namespace detail
  668. } // namespace nlohmann
  669. // #include <nlohmann/json_fwd.hpp>
  670. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  671. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  672. #include <cstdint> // int64_t, uint64_t
  673. #include <map> // map
  674. #include <memory> // allocator
  675. #include <string> // string
  676. #include <vector> // vector
  677. /*!
  678. @brief namespace for Niels Lohmann
  679. @see https://github.com/nlohmann
  680. @since version 1.0.0
  681. */
  682. namespace nlohmann
  683. {
  684. /*!
  685. @brief default JSONSerializer template argument
  686. This serializer ignores the template arguments and uses ADL
  687. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  688. for serialization.
  689. */
  690. template<typename T = void, typename SFINAE = void>
  691. struct adl_serializer;
  692. template<template<typename U, typename V, typename... Args> class ObjectType =
  693. std::map,
  694. template<typename U, typename... Args> class ArrayType = std::vector,
  695. class StringType = std::string, class BooleanType = bool,
  696. class NumberIntegerType = std::int64_t,
  697. class NumberUnsignedType = std::uint64_t,
  698. class NumberFloatType = double,
  699. template<typename U> class AllocatorType = std::allocator,
  700. template<typename T, typename SFINAE = void> class JSONSerializer =
  701. adl_serializer>
  702. class basic_json;
  703. /*!
  704. @brief JSON Pointer
  705. A JSON pointer defines a string syntax for identifying a specific value
  706. within a JSON document. It can be used with functions `at` and
  707. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  708. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  709. @since version 2.0.0
  710. */
  711. template<typename BasicJsonType>
  712. class json_pointer;
  713. /*!
  714. @brief default JSON class
  715. This type is the default specialization of the @ref basic_json class which
  716. uses the standard template types.
  717. @since version 1.0.0
  718. */
  719. using json = basic_json<>;
  720. } // namespace nlohmann
  721. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  722. namespace nlohmann
  723. {
  724. /*!
  725. @brief detail namespace with internal helper functions
  726. This namespace collects functions that should not be exposed,
  727. implementations of some @ref basic_json methods, and meta-programming helpers.
  728. @since version 2.1.0
  729. */
  730. namespace detail
  731. {
  732. /////////////
  733. // helpers //
  734. /////////////
  735. // Note to maintainers:
  736. //
  737. // Every trait in this file expects a non CV-qualified type.
  738. // The only exceptions are in the 'aliases for detected' section
  739. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  740. //
  741. // In this case, T has to be properly CV-qualified to constraint the function arguments
  742. // (e.g. to_json(BasicJsonType&, const T&))
  743. template<typename> struct is_basic_json : std::false_type {};
  744. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  745. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  746. //////////////////////////
  747. // aliases for detected //
  748. //////////////////////////
  749. template <typename T>
  750. using mapped_type_t = typename T::mapped_type;
  751. template <typename T>
  752. using key_type_t = typename T::key_type;
  753. template <typename T>
  754. using value_type_t = typename T::value_type;
  755. template <typename T>
  756. using difference_type_t = typename T::difference_type;
  757. template <typename T>
  758. using pointer_t = typename T::pointer;
  759. template <typename T>
  760. using reference_t = typename T::reference;
  761. template <typename T>
  762. using iterator_category_t = typename T::iterator_category;
  763. template <typename T>
  764. using iterator_t = typename T::iterator;
  765. template <typename T, typename... Args>
  766. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  767. template <typename T, typename... Args>
  768. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  769. template <typename T, typename U>
  770. using get_template_function = decltype(std::declval<T>().template get<U>());
  771. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  772. template <typename BasicJsonType, typename T, typename = void>
  773. struct has_from_json : std::false_type {};
  774. template <typename BasicJsonType, typename T>
  775. struct has_from_json<BasicJsonType, T,
  776. enable_if_t<not is_basic_json<T>::value>>
  777. {
  778. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  779. static constexpr bool value =
  780. is_detected_exact<void, from_json_function, serializer,
  781. const BasicJsonType&, T&>::value;
  782. };
  783. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  784. // this overload is used for non-default-constructible user-defined-types
  785. template <typename BasicJsonType, typename T, typename = void>
  786. struct has_non_default_from_json : std::false_type {};
  787. template<typename BasicJsonType, typename T>
  788. struct has_non_default_from_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  789. {
  790. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  791. static constexpr bool value =
  792. is_detected_exact<T, from_json_function, serializer,
  793. const BasicJsonType&>::value;
  794. };
  795. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  796. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  797. template <typename BasicJsonType, typename T, typename = void>
  798. struct has_to_json : std::false_type {};
  799. template <typename BasicJsonType, typename T>
  800. struct has_to_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  801. {
  802. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  803. static constexpr bool value =
  804. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  805. T>::value;
  806. };
  807. ///////////////////
  808. // is_ functions //
  809. ///////////////////
  810. template <typename T, typename = void>
  811. struct is_iterator_traits : std::false_type {};
  812. template <typename T>
  813. struct is_iterator_traits<iterator_traits<T>>
  814. {
  815. private:
  816. using traits = iterator_traits<T>;
  817. public:
  818. static constexpr auto value =
  819. is_detected<value_type_t, traits>::value &&
  820. is_detected<difference_type_t, traits>::value &&
  821. is_detected<pointer_t, traits>::value &&
  822. is_detected<iterator_category_t, traits>::value &&
  823. is_detected<reference_t, traits>::value;
  824. };
  825. // source: https://stackoverflow.com/a/37193089/4116453
  826. template <typename T, typename = void>
  827. struct is_complete_type : std::false_type {};
  828. template <typename T>
  829. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  830. template <typename BasicJsonType, typename CompatibleObjectType,
  831. typename = void>
  832. struct is_compatible_object_type_impl : std::false_type {};
  833. template <typename BasicJsonType, typename CompatibleObjectType>
  834. struct is_compatible_object_type_impl <
  835. BasicJsonType, CompatibleObjectType,
  836. enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value and
  837. is_detected<key_type_t, CompatibleObjectType>::value >>
  838. {
  839. using object_t = typename BasicJsonType::object_t;
  840. // macOS's is_constructible does not play well with nonesuch...
  841. static constexpr bool value =
  842. std::is_constructible<typename object_t::key_type,
  843. typename CompatibleObjectType::key_type>::value and
  844. std::is_constructible<typename object_t::mapped_type,
  845. typename CompatibleObjectType::mapped_type>::value;
  846. };
  847. template <typename BasicJsonType, typename CompatibleObjectType>
  848. struct is_compatible_object_type
  849. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  850. template <typename BasicJsonType, typename ConstructibleObjectType,
  851. typename = void>
  852. struct is_constructible_object_type_impl : std::false_type {};
  853. template <typename BasicJsonType, typename ConstructibleObjectType>
  854. struct is_constructible_object_type_impl <
  855. BasicJsonType, ConstructibleObjectType,
  856. enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value and
  857. is_detected<key_type_t, ConstructibleObjectType>::value >>
  858. {
  859. using object_t = typename BasicJsonType::object_t;
  860. static constexpr bool value =
  861. (std::is_default_constructible<ConstructibleObjectType>::value and
  862. (std::is_move_assignable<ConstructibleObjectType>::value or
  863. std::is_copy_assignable<ConstructibleObjectType>::value) and
  864. (std::is_constructible<typename ConstructibleObjectType::key_type,
  865. typename object_t::key_type>::value and
  866. std::is_same <
  867. typename object_t::mapped_type,
  868. typename ConstructibleObjectType::mapped_type >::value)) or
  869. (has_from_json<BasicJsonType,
  870. typename ConstructibleObjectType::mapped_type>::value or
  871. has_non_default_from_json <
  872. BasicJsonType,
  873. typename ConstructibleObjectType::mapped_type >::value);
  874. };
  875. template <typename BasicJsonType, typename ConstructibleObjectType>
  876. struct is_constructible_object_type
  877. : is_constructible_object_type_impl<BasicJsonType,
  878. ConstructibleObjectType> {};
  879. template <typename BasicJsonType, typename CompatibleStringType,
  880. typename = void>
  881. struct is_compatible_string_type_impl : std::false_type {};
  882. template <typename BasicJsonType, typename CompatibleStringType>
  883. struct is_compatible_string_type_impl <
  884. BasicJsonType, CompatibleStringType,
  885. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  886. value_type_t, CompatibleStringType>::value >>
  887. {
  888. static constexpr auto value =
  889. std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  890. };
  891. template <typename BasicJsonType, typename ConstructibleStringType>
  892. struct is_compatible_string_type
  893. : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  894. template <typename BasicJsonType, typename ConstructibleStringType,
  895. typename = void>
  896. struct is_constructible_string_type_impl : std::false_type {};
  897. template <typename BasicJsonType, typename ConstructibleStringType>
  898. struct is_constructible_string_type_impl <
  899. BasicJsonType, ConstructibleStringType,
  900. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  901. value_type_t, ConstructibleStringType>::value >>
  902. {
  903. static constexpr auto value =
  904. std::is_constructible<ConstructibleStringType,
  905. typename BasicJsonType::string_t>::value;
  906. };
  907. template <typename BasicJsonType, typename ConstructibleStringType>
  908. struct is_constructible_string_type
  909. : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  910. template <typename BasicJsonType, typename CompatibleArrayType, typename = void>
  911. struct is_compatible_array_type_impl : std::false_type {};
  912. template <typename BasicJsonType, typename CompatibleArrayType>
  913. struct is_compatible_array_type_impl <
  914. BasicJsonType, CompatibleArrayType,
  915. enable_if_t<is_detected<value_type_t, CompatibleArrayType>::value and
  916. is_detected<iterator_t, CompatibleArrayType>::value and
  917. // This is needed because json_reverse_iterator has a ::iterator type...
  918. // Therefore it is detected as a CompatibleArrayType.
  919. // The real fix would be to have an Iterable concept.
  920. not is_iterator_traits<
  921. iterator_traits<CompatibleArrayType>>::value >>
  922. {
  923. static constexpr bool value =
  924. std::is_constructible<BasicJsonType,
  925. typename CompatibleArrayType::value_type>::value;
  926. };
  927. template <typename BasicJsonType, typename CompatibleArrayType>
  928. struct is_compatible_array_type
  929. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  930. template <typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  931. struct is_constructible_array_type_impl : std::false_type {};
  932. template <typename BasicJsonType, typename ConstructibleArrayType>
  933. struct is_constructible_array_type_impl <
  934. BasicJsonType, ConstructibleArrayType,
  935. enable_if_t<std::is_same<ConstructibleArrayType,
  936. typename BasicJsonType::value_type>::value >>
  937. : std::true_type {};
  938. template <typename BasicJsonType, typename ConstructibleArrayType>
  939. struct is_constructible_array_type_impl <
  940. BasicJsonType, ConstructibleArrayType,
  941. enable_if_t<not std::is_same<ConstructibleArrayType,
  942. typename BasicJsonType::value_type>::value and
  943. std::is_default_constructible<ConstructibleArrayType>::value and
  944. (std::is_move_assignable<ConstructibleArrayType>::value or
  945. std::is_copy_assignable<ConstructibleArrayType>::value) and
  946. is_detected<value_type_t, ConstructibleArrayType>::value and
  947. is_detected<iterator_t, ConstructibleArrayType>::value and
  948. is_complete_type<
  949. detected_t<value_type_t, ConstructibleArrayType>>::value >>
  950. {
  951. static constexpr bool value =
  952. // This is needed because json_reverse_iterator has a ::iterator type,
  953. // furthermore, std::back_insert_iterator (and other iterators) have a
  954. // base class `iterator`... Therefore it is detected as a
  955. // ConstructibleArrayType. The real fix would be to have an Iterable
  956. // concept.
  957. not is_iterator_traits<iterator_traits<ConstructibleArrayType>>::value and
  958. (std::is_same<typename ConstructibleArrayType::value_type,
  959. typename BasicJsonType::array_t::value_type>::value or
  960. has_from_json<BasicJsonType,
  961. typename ConstructibleArrayType::value_type>::value or
  962. has_non_default_from_json <
  963. BasicJsonType, typename ConstructibleArrayType::value_type >::value);
  964. };
  965. template <typename BasicJsonType, typename ConstructibleArrayType>
  966. struct is_constructible_array_type
  967. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  968. template <typename RealIntegerType, typename CompatibleNumberIntegerType,
  969. typename = void>
  970. struct is_compatible_integer_type_impl : std::false_type {};
  971. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  972. struct is_compatible_integer_type_impl <
  973. RealIntegerType, CompatibleNumberIntegerType,
  974. enable_if_t<std::is_integral<RealIntegerType>::value and
  975. std::is_integral<CompatibleNumberIntegerType>::value and
  976. not std::is_same<bool, CompatibleNumberIntegerType>::value >>
  977. {
  978. // is there an assert somewhere on overflows?
  979. using RealLimits = std::numeric_limits<RealIntegerType>;
  980. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  981. static constexpr auto value =
  982. std::is_constructible<RealIntegerType,
  983. CompatibleNumberIntegerType>::value and
  984. CompatibleLimits::is_integer and
  985. RealLimits::is_signed == CompatibleLimits::is_signed;
  986. };
  987. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  988. struct is_compatible_integer_type
  989. : is_compatible_integer_type_impl<RealIntegerType,
  990. CompatibleNumberIntegerType> {};
  991. template <typename BasicJsonType, typename CompatibleType, typename = void>
  992. struct is_compatible_type_impl: std::false_type {};
  993. template <typename BasicJsonType, typename CompatibleType>
  994. struct is_compatible_type_impl <
  995. BasicJsonType, CompatibleType,
  996. enable_if_t<is_complete_type<CompatibleType>::value >>
  997. {
  998. static constexpr bool value =
  999. has_to_json<BasicJsonType, CompatibleType>::value;
  1000. };
  1001. template <typename BasicJsonType, typename CompatibleType>
  1002. struct is_compatible_type
  1003. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  1004. } // namespace detail
  1005. } // namespace nlohmann
  1006. // #include <nlohmann/detail/value_t.hpp>
  1007. #include <array> // array
  1008. #include <ciso646> // and
  1009. #include <cstddef> // size_t
  1010. #include <cstdint> // uint8_t
  1011. #include <string> // string
  1012. namespace nlohmann
  1013. {
  1014. namespace detail
  1015. {
  1016. ///////////////////////////
  1017. // JSON type enumeration //
  1018. ///////////////////////////
  1019. /*!
  1020. @brief the JSON type enumeration
  1021. This enumeration collects the different JSON types. It is internally used to
  1022. distinguish the stored values, and the functions @ref basic_json::is_null(),
  1023. @ref basic_json::is_object(), @ref basic_json::is_array(),
  1024. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  1025. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  1026. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  1027. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  1028. @ref basic_json::is_structured() rely on it.
  1029. @note There are three enumeration entries (number_integer, number_unsigned, and
  1030. number_float), because the library distinguishes these three types for numbers:
  1031. @ref basic_json::number_unsigned_t is used for unsigned integers,
  1032. @ref basic_json::number_integer_t is used for signed integers, and
  1033. @ref basic_json::number_float_t is used for floating-point numbers or to
  1034. approximate integers which do not fit in the limits of their respective type.
  1035. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  1036. value with the default value for a given type
  1037. @since version 1.0.0
  1038. */
  1039. enum class value_t : std::uint8_t
  1040. {
  1041. null, ///< null value
  1042. object, ///< object (unordered set of name/value pairs)
  1043. array, ///< array (ordered collection of values)
  1044. string, ///< string value
  1045. boolean, ///< boolean value
  1046. number_integer, ///< number value (signed integer)
  1047. number_unsigned, ///< number value (unsigned integer)
  1048. number_float, ///< number value (floating-point)
  1049. discarded ///< discarded by the the parser callback function
  1050. };
  1051. /*!
  1052. @brief comparison operator for JSON types
  1053. Returns an ordering that is similar to Python:
  1054. - order: null < boolean < number < object < array < string
  1055. - furthermore, each type is not smaller than itself
  1056. - discarded values are not comparable
  1057. @since version 1.0.0
  1058. */
  1059. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  1060. {
  1061. static constexpr std::array<std::uint8_t, 8> order = {{
  1062. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  1063. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
  1064. }
  1065. };
  1066. const auto l_index = static_cast<std::size_t>(lhs);
  1067. const auto r_index = static_cast<std::size_t>(rhs);
  1068. return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
  1069. }
  1070. } // namespace detail
  1071. } // namespace nlohmann
  1072. namespace nlohmann
  1073. {
  1074. namespace detail
  1075. {
  1076. template<typename BasicJsonType>
  1077. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  1078. {
  1079. if (JSON_UNLIKELY(not j.is_null()))
  1080. {
  1081. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
  1082. }
  1083. n = nullptr;
  1084. }
  1085. // overloads for basic_json template parameters
  1086. template<typename BasicJsonType, typename ArithmeticType,
  1087. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  1088. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  1089. int> = 0>
  1090. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  1091. {
  1092. switch (static_cast<value_t>(j))
  1093. {
  1094. case value_t::number_unsigned:
  1095. {
  1096. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  1097. break;
  1098. }
  1099. case value_t::number_integer:
  1100. {
  1101. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  1102. break;
  1103. }
  1104. case value_t::number_float:
  1105. {
  1106. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  1107. break;
  1108. }
  1109. default:
  1110. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  1111. }
  1112. }
  1113. template<typename BasicJsonType>
  1114. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  1115. {
  1116. if (JSON_UNLIKELY(not j.is_boolean()))
  1117. {
  1118. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  1119. }
  1120. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  1121. }
  1122. template<typename BasicJsonType>
  1123. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  1124. {
  1125. if (JSON_UNLIKELY(not j.is_string()))
  1126. {
  1127. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  1128. }
  1129. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  1130. }
  1131. template <
  1132. typename BasicJsonType, typename ConstructibleStringType,
  1133. enable_if_t <
  1134. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value and
  1135. not std::is_same<typename BasicJsonType::string_t,
  1136. ConstructibleStringType>::value,
  1137. int > = 0 >
  1138. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  1139. {
  1140. if (JSON_UNLIKELY(not j.is_string()))
  1141. {
  1142. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  1143. }
  1144. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  1145. }
  1146. template<typename BasicJsonType>
  1147. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  1148. {
  1149. get_arithmetic_value(j, val);
  1150. }
  1151. template<typename BasicJsonType>
  1152. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  1153. {
  1154. get_arithmetic_value(j, val);
  1155. }
  1156. template<typename BasicJsonType>
  1157. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  1158. {
  1159. get_arithmetic_value(j, val);
  1160. }
  1161. template<typename BasicJsonType, typename EnumType,
  1162. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  1163. void from_json(const BasicJsonType& j, EnumType& e)
  1164. {
  1165. typename std::underlying_type<EnumType>::type val;
  1166. get_arithmetic_value(j, val);
  1167. e = static_cast<EnumType>(val);
  1168. }
  1169. // forward_list doesn't have an insert method
  1170. template<typename BasicJsonType, typename T, typename Allocator,
  1171. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  1172. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  1173. {
  1174. if (JSON_UNLIKELY(not j.is_array()))
  1175. {
  1176. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1177. }
  1178. l.clear();
  1179. std::transform(j.rbegin(), j.rend(),
  1180. std::front_inserter(l), [](const BasicJsonType & i)
  1181. {
  1182. return i.template get<T>();
  1183. });
  1184. }
  1185. // valarray doesn't have an insert method
  1186. template<typename BasicJsonType, typename T,
  1187. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  1188. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  1189. {
  1190. if (JSON_UNLIKELY(not j.is_array()))
  1191. {
  1192. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1193. }
  1194. l.resize(j.size());
  1195. std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
  1196. }
  1197. template <typename BasicJsonType, typename T, std::size_t N>
  1198. auto from_json(const BasicJsonType& j, T (&arr)[N])
  1199. -> decltype(j.template get<T>(), void())
  1200. {
  1201. for (std::size_t i = 0; i < N; ++i)
  1202. {
  1203. arr[i] = j.at(i).template get<T>();
  1204. }
  1205. }
  1206. template<typename BasicJsonType>
  1207. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  1208. {
  1209. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  1210. }
  1211. template <typename BasicJsonType, typename T, std::size_t N>
  1212. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  1213. priority_tag<2> /*unused*/)
  1214. -> decltype(j.template get<T>(), void())
  1215. {
  1216. for (std::size_t i = 0; i < N; ++i)
  1217. {
  1218. arr[i] = j.at(i).template get<T>();
  1219. }
  1220. }
  1221. template<typename BasicJsonType, typename ConstructibleArrayType>
  1222. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  1223. -> decltype(
  1224. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  1225. j.template get<typename ConstructibleArrayType::value_type>(),
  1226. void())
  1227. {
  1228. using std::end;
  1229. ConstructibleArrayType ret;
  1230. ret.reserve(j.size());
  1231. std::transform(j.begin(), j.end(),
  1232. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  1233. {
  1234. // get<BasicJsonType>() returns *this, this won't call a from_json
  1235. // method when value_type is BasicJsonType
  1236. return i.template get<typename ConstructibleArrayType::value_type>();
  1237. });
  1238. arr = std::move(ret);
  1239. }
  1240. template <typename BasicJsonType, typename ConstructibleArrayType>
  1241. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  1242. priority_tag<0> /*unused*/)
  1243. {
  1244. using std::end;
  1245. ConstructibleArrayType ret;
  1246. std::transform(
  1247. j.begin(), j.end(), std::inserter(ret, end(ret)),
  1248. [](const BasicJsonType & i)
  1249. {
  1250. // get<BasicJsonType>() returns *this, this won't call a from_json
  1251. // method when value_type is BasicJsonType
  1252. return i.template get<typename ConstructibleArrayType::value_type>();
  1253. });
  1254. arr = std::move(ret);
  1255. }
  1256. template <typename BasicJsonType, typename ConstructibleArrayType,
  1257. enable_if_t <
  1258. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value and
  1259. not is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value and
  1260. not is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value and
  1261. not is_basic_json<ConstructibleArrayType>::value,
  1262. int > = 0 >
  1263. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  1264. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  1265. j.template get<typename ConstructibleArrayType::value_type>(),
  1266. void())
  1267. {
  1268. if (JSON_UNLIKELY(not j.is_array()))
  1269. {
  1270. JSON_THROW(type_error::create(302, "type must be array, but is " +
  1271. std::string(j.type_name())));
  1272. }
  1273. from_json_array_impl(j, arr, priority_tag<3> {});
  1274. }
  1275. template<typename BasicJsonType, typename ConstructibleObjectType,
  1276. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  1277. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  1278. {
  1279. if (JSON_UNLIKELY(not j.is_object()))
  1280. {
  1281. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  1282. }
  1283. ConstructibleObjectType ret;
  1284. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  1285. using value_type = typename ConstructibleObjectType::value_type;
  1286. std::transform(
  1287. inner_object->begin(), inner_object->end(),
  1288. std::inserter(ret, ret.begin()),
  1289. [](typename BasicJsonType::object_t::value_type const & p)
  1290. {
  1291. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  1292. });
  1293. obj = std::move(ret);
  1294. }
  1295. // overload for arithmetic types, not chosen for basic_json template arguments
  1296. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  1297. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  1298. // an arithmetic type?
  1299. template<typename BasicJsonType, typename ArithmeticType,
  1300. enable_if_t <
  1301. std::is_arithmetic<ArithmeticType>::value and
  1302. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  1303. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  1304. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  1305. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  1306. int> = 0>
  1307. void from_json(const BasicJsonType& j, ArithmeticType& val)
  1308. {
  1309. switch (static_cast<value_t>(j))
  1310. {
  1311. case value_t::number_unsigned:
  1312. {
  1313. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  1314. break;
  1315. }
  1316. case value_t::number_integer:
  1317. {
  1318. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  1319. break;
  1320. }
  1321. case value_t::number_float:
  1322. {
  1323. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  1324. break;
  1325. }
  1326. case value_t::boolean:
  1327. {
  1328. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  1329. break;
  1330. }
  1331. default:
  1332. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  1333. }
  1334. }
  1335. template<typename BasicJsonType, typename A1, typename A2>
  1336. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  1337. {
  1338. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  1339. }
  1340. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  1341. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/)
  1342. {
  1343. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  1344. }
  1345. template<typename BasicJsonType, typename... Args>
  1346. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  1347. {
  1348. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  1349. }
  1350. template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  1351. typename = enable_if_t<not std::is_constructible<
  1352. typename BasicJsonType::string_t, Key>::value>>
  1353. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  1354. {
  1355. if (JSON_UNLIKELY(not j.is_array()))
  1356. {
  1357. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1358. }
  1359. m.clear();
  1360. for (const auto& p : j)
  1361. {
  1362. if (JSON_UNLIKELY(not p.is_array()))
  1363. {
  1364. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  1365. }
  1366. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  1367. }
  1368. }
  1369. template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  1370. typename = enable_if_t<not std::is_constructible<
  1371. typename BasicJsonType::string_t, Key>::value>>
  1372. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  1373. {
  1374. if (JSON_UNLIKELY(not j.is_array()))
  1375. {
  1376. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1377. }
  1378. m.clear();
  1379. for (const auto& p : j)
  1380. {
  1381. if (JSON_UNLIKELY(not p.is_array()))
  1382. {
  1383. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  1384. }
  1385. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  1386. }
  1387. }
  1388. struct from_json_fn
  1389. {
  1390. template<typename BasicJsonType, typename T>
  1391. auto operator()(const BasicJsonType& j, T& val) const
  1392. noexcept(noexcept(from_json(j, val)))
  1393. -> decltype(from_json(j, val), void())
  1394. {
  1395. return from_json(j, val);
  1396. }
  1397. };
  1398. } // namespace detail
  1399. /// namespace to hold default `from_json` function
  1400. /// to see why this is required:
  1401. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  1402. namespace
  1403. {
  1404. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  1405. } // namespace
  1406. } // namespace nlohmann
  1407. // #include <nlohmann/detail/conversions/to_json.hpp>
  1408. #include <algorithm> // copy
  1409. #include <ciso646> // or, and, not
  1410. #include <iterator> // begin, end
  1411. #include <string> // string
  1412. #include <tuple> // tuple, get
  1413. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  1414. #include <utility> // move, forward, declval, pair
  1415. #include <valarray> // valarray
  1416. #include <vector> // vector
  1417. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  1418. #include <cstddef> // size_t
  1419. #include <iterator> // input_iterator_tag
  1420. #include <string> // string, to_string
  1421. #include <tuple> // tuple_size, get, tuple_element
  1422. // #include <nlohmann/detail/meta/type_traits.hpp>
  1423. // #include <nlohmann/detail/value_t.hpp>
  1424. namespace nlohmann
  1425. {
  1426. namespace detail
  1427. {
  1428. template <typename IteratorType> class iteration_proxy_value
  1429. {
  1430. public:
  1431. using difference_type = std::ptrdiff_t;
  1432. using value_type = iteration_proxy_value;
  1433. using pointer = value_type * ;
  1434. using reference = value_type & ;
  1435. using iterator_category = std::input_iterator_tag;
  1436. private:
  1437. /// the iterator
  1438. IteratorType anchor;
  1439. /// an index for arrays (used to create key names)
  1440. std::size_t array_index = 0;
  1441. /// last stringified array index
  1442. mutable std::size_t array_index_last = 0;
  1443. /// a string representation of the array index
  1444. mutable std::string array_index_str = "0";
  1445. /// an empty string (to return a reference for primitive values)
  1446. const std::string empty_str = "";
  1447. public:
  1448. explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {}
  1449. /// dereference operator (needed for range-based for)
  1450. iteration_proxy_value& operator*()
  1451. {
  1452. return *this;
  1453. }
  1454. /// increment operator (needed for range-based for)
  1455. iteration_proxy_value& operator++()
  1456. {
  1457. ++anchor;
  1458. ++array_index;
  1459. return *this;
  1460. }
  1461. /// equality operator (needed for InputIterator)
  1462. bool operator==(const iteration_proxy_value& o) const
  1463. {
  1464. return anchor == o.anchor;
  1465. }
  1466. /// inequality operator (needed for range-based for)
  1467. bool operator!=(const iteration_proxy_value& o) const
  1468. {
  1469. return anchor != o.anchor;
  1470. }
  1471. /// return key of the iterator
  1472. const std::string& key() const
  1473. {
  1474. assert(anchor.m_object != nullptr);
  1475. switch (anchor.m_object->type())
  1476. {
  1477. // use integer array index as key
  1478. case value_t::array:
  1479. {
  1480. if (array_index != array_index_last)
  1481. {
  1482. array_index_str = std::to_string(array_index);
  1483. array_index_last = array_index;
  1484. }
  1485. return array_index_str;
  1486. }
  1487. // use key from the object
  1488. case value_t::object:
  1489. return anchor.key();
  1490. // use an empty key for all primitive types
  1491. default:
  1492. return empty_str;
  1493. }
  1494. }
  1495. /// return value of the iterator
  1496. typename IteratorType::reference value() const
  1497. {
  1498. return anchor.value();
  1499. }
  1500. };
  1501. /// proxy class for the items() function
  1502. template<typename IteratorType> class iteration_proxy
  1503. {
  1504. private:
  1505. /// the container to iterate
  1506. typename IteratorType::reference container;
  1507. public:
  1508. /// construct iteration proxy from a container
  1509. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  1510. : container(cont) {}
  1511. /// return iterator begin (needed for range-based for)
  1512. iteration_proxy_value<IteratorType> begin() noexcept
  1513. {
  1514. return iteration_proxy_value<IteratorType>(container.begin());
  1515. }
  1516. /// return iterator end (needed for range-based for)
  1517. iteration_proxy_value<IteratorType> end() noexcept
  1518. {
  1519. return iteration_proxy_value<IteratorType>(container.end());
  1520. }
  1521. };
  1522. // Structured Bindings Support
  1523. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  1524. // And see https://github.com/nlohmann/json/pull/1391
  1525. template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  1526. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  1527. {
  1528. return i.key();
  1529. }
  1530. // Structured Bindings Support
  1531. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  1532. // And see https://github.com/nlohmann/json/pull/1391
  1533. template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  1534. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  1535. {
  1536. return i.value();
  1537. }
  1538. } // namespace detail
  1539. } // namespace nlohmann
  1540. // The Addition to the STD Namespace is required to add
  1541. // Structured Bindings Support to the iteration_proxy_value class
  1542. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  1543. // And see https://github.com/nlohmann/json/pull/1391
  1544. namespace std
  1545. {
  1546. #if defined(__clang__)
  1547. // Fix: https://github.com/nlohmann/json/issues/1401
  1548. #pragma clang diagnostic push
  1549. #pragma clang diagnostic ignored "-Wmismatched-tags"
  1550. #endif
  1551. template <typename IteratorType>
  1552. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  1553. : public std::integral_constant<std::size_t, 2> {};
  1554. template <std::size_t N, typename IteratorType>
  1555. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  1556. {
  1557. public:
  1558. using type = decltype(
  1559. get<N>(std::declval <
  1560. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  1561. };
  1562. #if defined(__clang__)
  1563. #pragma clang diagnostic pop
  1564. #endif
  1565. } // namespace std
  1566. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1567. // #include <nlohmann/detail/meta/type_traits.hpp>
  1568. // #include <nlohmann/detail/value_t.hpp>
  1569. namespace nlohmann
  1570. {
  1571. namespace detail
  1572. {
  1573. //////////////////
  1574. // constructors //
  1575. //////////////////
  1576. template<value_t> struct external_constructor;
  1577. template<>
  1578. struct external_constructor<value_t::boolean>
  1579. {
  1580. template<typename BasicJsonType>
  1581. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  1582. {
  1583. j.m_type = value_t::boolean;
  1584. j.m_value = b;
  1585. j.assert_invariant();
  1586. }
  1587. };
  1588. template<>
  1589. struct external_constructor<value_t::string>
  1590. {
  1591. template<typename BasicJsonType>
  1592. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  1593. {
  1594. j.m_type = value_t::string;
  1595. j.m_value = s;
  1596. j.assert_invariant();
  1597. }
  1598. template<typename BasicJsonType>
  1599. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  1600. {
  1601. j.m_type = value_t::string;
  1602. j.m_value = std::move(s);
  1603. j.assert_invariant();
  1604. }
  1605. template<typename BasicJsonType, typename CompatibleStringType,
  1606. enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  1607. int> = 0>
  1608. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  1609. {
  1610. j.m_type = value_t::string;
  1611. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  1612. j.assert_invariant();
  1613. }
  1614. };
  1615. template<>
  1616. struct external_constructor<value_t::number_float>
  1617. {
  1618. template<typename BasicJsonType>
  1619. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  1620. {
  1621. j.m_type = value_t::number_float;
  1622. j.m_value = val;
  1623. j.assert_invariant();
  1624. }
  1625. };
  1626. template<>
  1627. struct external_constructor<value_t::number_unsigned>
  1628. {
  1629. template<typename BasicJsonType>
  1630. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  1631. {
  1632. j.m_type = value_t::number_unsigned;
  1633. j.m_value = val;
  1634. j.assert_invariant();
  1635. }
  1636. };
  1637. template<>
  1638. struct external_constructor<value_t::number_integer>
  1639. {
  1640. template<typename BasicJsonType>
  1641. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  1642. {
  1643. j.m_type = value_t::number_integer;
  1644. j.m_value = val;
  1645. j.assert_invariant();
  1646. }
  1647. };
  1648. template<>
  1649. struct external_constructor<value_t::array>
  1650. {
  1651. template<typename BasicJsonType>
  1652. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  1653. {
  1654. j.m_type = value_t::array;
  1655. j.m_value = arr;
  1656. j.assert_invariant();
  1657. }
  1658. template<typename BasicJsonType>
  1659. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  1660. {
  1661. j.m_type = value_t::array;
  1662. j.m_value = std::move(arr);
  1663. j.assert_invariant();
  1664. }
  1665. template<typename BasicJsonType, typename CompatibleArrayType,
  1666. enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  1667. int> = 0>
  1668. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  1669. {
  1670. using std::begin;
  1671. using std::end;
  1672. j.m_type = value_t::array;
  1673. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  1674. j.assert_invariant();
  1675. }
  1676. template<typename BasicJsonType>
  1677. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  1678. {
  1679. j.m_type = value_t::array;
  1680. j.m_value = value_t::array;
  1681. j.m_value.array->reserve(arr.size());
  1682. for (const bool x : arr)
  1683. {
  1684. j.m_value.array->push_back(x);
  1685. }
  1686. j.assert_invariant();
  1687. }
  1688. template<typename BasicJsonType, typename T,
  1689. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  1690. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  1691. {
  1692. j.m_type = value_t::array;
  1693. j.m_value = value_t::array;
  1694. j.m_value.array->resize(arr.size());
  1695. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  1696. j.assert_invariant();
  1697. }
  1698. };
  1699. template<>
  1700. struct external_constructor<value_t::object>
  1701. {
  1702. template<typename BasicJsonType>
  1703. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  1704. {
  1705. j.m_type = value_t::object;
  1706. j.m_value = obj;
  1707. j.assert_invariant();
  1708. }
  1709. template<typename BasicJsonType>
  1710. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  1711. {
  1712. j.m_type = value_t::object;
  1713. j.m_value = std::move(obj);
  1714. j.assert_invariant();
  1715. }
  1716. template<typename BasicJsonType, typename CompatibleObjectType,
  1717. enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
  1718. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  1719. {
  1720. using std::begin;
  1721. using std::end;
  1722. j.m_type = value_t::object;
  1723. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  1724. j.assert_invariant();
  1725. }
  1726. };
  1727. /////////////
  1728. // to_json //
  1729. /////////////
  1730. template<typename BasicJsonType, typename T,
  1731. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  1732. void to_json(BasicJsonType& j, T b) noexcept
  1733. {
  1734. external_constructor<value_t::boolean>::construct(j, b);
  1735. }
  1736. template<typename BasicJsonType, typename CompatibleString,
  1737. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  1738. void to_json(BasicJsonType& j, const CompatibleString& s)
  1739. {
  1740. external_constructor<value_t::string>::construct(j, s);
  1741. }
  1742. template<typename BasicJsonType>
  1743. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  1744. {
  1745. external_constructor<value_t::string>::construct(j, std::move(s));
  1746. }
  1747. template<typename BasicJsonType, typename FloatType,
  1748. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  1749. void to_json(BasicJsonType& j, FloatType val) noexcept
  1750. {
  1751. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  1752. }
  1753. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  1754. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  1755. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  1756. {
  1757. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  1758. }
  1759. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  1760. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  1761. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  1762. {
  1763. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  1764. }
  1765. template<typename BasicJsonType, typename EnumType,
  1766. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  1767. void to_json(BasicJsonType& j, EnumType e) noexcept
  1768. {
  1769. using underlying_type = typename std::underlying_type<EnumType>::type;
  1770. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  1771. }
  1772. template<typename BasicJsonType>
  1773. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  1774. {
  1775. external_constructor<value_t::array>::construct(j, e);
  1776. }
  1777. template <typename BasicJsonType, typename CompatibleArrayType,
  1778. enable_if_t<is_compatible_array_type<BasicJsonType,
  1779. CompatibleArrayType>::value and
  1780. not is_compatible_object_type<
  1781. BasicJsonType, CompatibleArrayType>::value and
  1782. not is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value and
  1783. not is_basic_json<CompatibleArrayType>::value,
  1784. int> = 0>
  1785. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  1786. {
  1787. external_constructor<value_t::array>::construct(j, arr);
  1788. }
  1789. template<typename BasicJsonType, typename T,
  1790. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  1791. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  1792. {
  1793. external_constructor<value_t::array>::construct(j, std::move(arr));
  1794. }
  1795. template<typename BasicJsonType>
  1796. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  1797. {
  1798. external_constructor<value_t::array>::construct(j, std::move(arr));
  1799. }
  1800. template<typename BasicJsonType, typename CompatibleObjectType,
  1801. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value and not is_basic_json<CompatibleObjectType>::value, int> = 0>
  1802. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  1803. {
  1804. external_constructor<value_t::object>::construct(j, obj);
  1805. }
  1806. template<typename BasicJsonType>
  1807. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  1808. {
  1809. external_constructor<value_t::object>::construct(j, std::move(obj));
  1810. }
  1811. template <
  1812. typename BasicJsonType, typename T, std::size_t N,
  1813. enable_if_t<not std::is_constructible<typename BasicJsonType::string_t,
  1814. const T(&)[N]>::value,
  1815. int> = 0 >
  1816. void to_json(BasicJsonType& j, const T(&arr)[N])
  1817. {
  1818. external_constructor<value_t::array>::construct(j, arr);
  1819. }
  1820. template<typename BasicJsonType, typename... Args>
  1821. void to_json(BasicJsonType& j, const std::pair<Args...>& p)
  1822. {
  1823. j = { p.first, p.second };
  1824. }
  1825. // for https://github.com/nlohmann/json/pull/1134
  1826. template < typename BasicJsonType, typename T,
  1827. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  1828. void to_json(BasicJsonType& j, const T& b)
  1829. {
  1830. j = { {b.key(), b.value()} };
  1831. }
  1832. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  1833. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  1834. {
  1835. j = { std::get<Idx>(t)... };
  1836. }
  1837. template<typename BasicJsonType, typename... Args>
  1838. void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
  1839. {
  1840. to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  1841. }
  1842. struct to_json_fn
  1843. {
  1844. template<typename BasicJsonType, typename T>
  1845. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  1846. -> decltype(to_json(j, std::forward<T>(val)), void())
  1847. {
  1848. return to_json(j, std::forward<T>(val));
  1849. }
  1850. };
  1851. } // namespace detail
  1852. /// namespace to hold default `to_json` function
  1853. namespace
  1854. {
  1855. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  1856. } // namespace
  1857. } // namespace nlohmann
  1858. namespace nlohmann
  1859. {
  1860. template<typename, typename>
  1861. struct adl_serializer
  1862. {
  1863. /*!
  1864. @brief convert a JSON value to any value type
  1865. This function is usually called by the `get()` function of the
  1866. @ref basic_json class (either explicit or via conversion operators).
  1867. @param[in] j JSON value to read from
  1868. @param[in,out] val value to write to
  1869. */
  1870. template<typename BasicJsonType, typename ValueType>
  1871. static auto from_json(BasicJsonType&& j, ValueType& val) noexcept(
  1872. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  1873. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  1874. {
  1875. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  1876. }
  1877. /*!
  1878. @brief convert any value type to a JSON value
  1879. This function is usually called by the constructors of the @ref basic_json
  1880. class.
  1881. @param[in,out] j JSON value to write to
  1882. @param[in] val value to read from
  1883. */
  1884. template <typename BasicJsonType, typename ValueType>
  1885. static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
  1886. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  1887. -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
  1888. {
  1889. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  1890. }
  1891. };
  1892. } // namespace nlohmann
  1893. // #include <nlohmann/detail/conversions/from_json.hpp>
  1894. // #include <nlohmann/detail/conversions/to_json.hpp>
  1895. // #include <nlohmann/detail/exceptions.hpp>
  1896. // #include <nlohmann/detail/input/binary_reader.hpp>
  1897. #include <algorithm> // generate_n
  1898. #include <array> // array
  1899. #include <cassert> // assert
  1900. #include <cmath> // ldexp
  1901. #include <cstddef> // size_t
  1902. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  1903. #include <cstdio> // snprintf
  1904. #include <cstring> // memcpy
  1905. #include <iterator> // back_inserter
  1906. #include <limits> // numeric_limits
  1907. #include <string> // char_traits, string
  1908. #include <utility> // make_pair, move
  1909. // #include <nlohmann/detail/exceptions.hpp>
  1910. // #include <nlohmann/detail/input/input_adapters.hpp>
  1911. #include <array> // array
  1912. #include <cassert> // assert
  1913. #include <cstddef> // size_t
  1914. #include <cstdio> //FILE *
  1915. #include <cstring> // strlen
  1916. #include <istream> // istream
  1917. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  1918. #include <memory> // shared_ptr, make_shared, addressof
  1919. #include <numeric> // accumulate
  1920. #include <string> // string, char_traits
  1921. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  1922. #include <utility> // pair, declval
  1923. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  1924. // #include <nlohmann/detail/macro_scope.hpp>
  1925. namespace nlohmann
  1926. {
  1927. namespace detail
  1928. {
  1929. /// the supported input formats
  1930. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  1931. ////////////////////
  1932. // input adapters //
  1933. ////////////////////
  1934. /*!
  1935. @brief abstract input adapter interface
  1936. Produces a stream of std::char_traits<char>::int_type characters from a
  1937. std::istream, a buffer, or some other input type. Accepts the return of
  1938. exactly one non-EOF character for future input. The int_type characters
  1939. returned consist of all valid char values as positive values (typically
  1940. unsigned char), plus an EOF value outside that range, specified by the value
  1941. of the function std::char_traits<char>::eof(). This value is typically -1, but
  1942. could be any arbitrary value which is not a valid char value.
  1943. */
  1944. struct input_adapter_protocol
  1945. {
  1946. /// get a character [0,255] or std::char_traits<char>::eof().
  1947. virtual std::char_traits<char>::int_type get_character() = 0;
  1948. virtual ~input_adapter_protocol() = default;
  1949. };
  1950. /// a type to simplify interfaces
  1951. using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
  1952. /*!
  1953. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  1954. buffer. This adapter is a very low level adapter.
  1955. */
  1956. class file_input_adapter : public input_adapter_protocol
  1957. {
  1958. public:
  1959. explicit file_input_adapter(std::FILE* f) noexcept
  1960. : m_file(f)
  1961. {}
  1962. // make class move-only
  1963. file_input_adapter(const file_input_adapter&) = delete;
  1964. file_input_adapter(file_input_adapter&&) = default;
  1965. file_input_adapter& operator=(const file_input_adapter&) = delete;
  1966. file_input_adapter& operator=(file_input_adapter&&) = default;
  1967. ~file_input_adapter() override = default;
  1968. std::char_traits<char>::int_type get_character() noexcept override
  1969. {
  1970. return std::fgetc(m_file);
  1971. }
  1972. private:
  1973. /// the file pointer to read from
  1974. std::FILE* m_file;
  1975. };
  1976. /*!
  1977. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  1978. beginning of input. Does not support changing the underlying std::streambuf
  1979. in mid-input. Maintains underlying std::istream and std::streambuf to support
  1980. subsequent use of standard std::istream operations to process any input
  1981. characters following those used in parsing the JSON input. Clears the
  1982. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  1983. subsequent call for input from the std::istream.
  1984. */
  1985. class input_stream_adapter : public input_adapter_protocol
  1986. {
  1987. public:
  1988. ~input_stream_adapter() override
  1989. {
  1990. // clear stream flags; we use underlying streambuf I/O, do not
  1991. // maintain ifstream flags, except eof
  1992. is.clear(is.rdstate() & std::ios::eofbit);
  1993. }
  1994. explicit input_stream_adapter(std::istream& i)
  1995. : is(i), sb(*i.rdbuf())
  1996. {}
  1997. // delete because of pointer members
  1998. input_stream_adapter(const input_stream_adapter&) = delete;
  1999. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  2000. input_stream_adapter(input_stream_adapter&&) = delete;
  2001. input_stream_adapter& operator=(input_stream_adapter&&) = delete;
  2002. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  2003. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  2004. // end up as the same value, eg. 0xFFFFFFFF.
  2005. std::char_traits<char>::int_type get_character() override
  2006. {
  2007. auto res = sb.sbumpc();
  2008. // set eof manually, as we don't use the istream interface.
  2009. if (res == EOF)
  2010. {
  2011. is.clear(is.rdstate() | std::ios::eofbit);
  2012. }
  2013. return res;
  2014. }
  2015. private:
  2016. /// the associated input stream
  2017. std::istream& is;
  2018. std::streambuf& sb;
  2019. };
  2020. /// input adapter for buffer input
  2021. class input_buffer_adapter : public input_adapter_protocol
  2022. {
  2023. public:
  2024. input_buffer_adapter(const char* b, const std::size_t l) noexcept
  2025. : cursor(b), limit(b + l)
  2026. {}
  2027. // delete because of pointer members
  2028. input_buffer_adapter(const input_buffer_adapter&) = delete;
  2029. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  2030. input_buffer_adapter(input_buffer_adapter&&) = delete;
  2031. input_buffer_adapter& operator=(input_buffer_adapter&&) = delete;
  2032. ~input_buffer_adapter() override = default;
  2033. std::char_traits<char>::int_type get_character() noexcept override
  2034. {
  2035. if (JSON_LIKELY(cursor < limit))
  2036. {
  2037. return std::char_traits<char>::to_int_type(*(cursor++));
  2038. }
  2039. return std::char_traits<char>::eof();
  2040. }
  2041. private:
  2042. /// pointer to the current character
  2043. const char* cursor;
  2044. /// pointer past the last character
  2045. const char* const limit;
  2046. };
  2047. template<typename WideStringType, size_t T>
  2048. struct wide_string_input_helper
  2049. {
  2050. // UTF-32
  2051. static void fill_buffer(const WideStringType& str,
  2052. size_t& current_wchar,
  2053. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  2054. size_t& utf8_bytes_index,
  2055. size_t& utf8_bytes_filled)
  2056. {
  2057. utf8_bytes_index = 0;
  2058. if (current_wchar == str.size())
  2059. {
  2060. utf8_bytes[0] = std::char_traits<char>::eof();
  2061. utf8_bytes_filled = 1;
  2062. }
  2063. else
  2064. {
  2065. // get the current character
  2066. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  2067. // UTF-32 to UTF-8 encoding
  2068. if (wc < 0x80)
  2069. {
  2070. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  2071. utf8_bytes_filled = 1;
  2072. }
  2073. else if (wc <= 0x7FF)
  2074. {
  2075. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u) & 0x1Fu));
  2076. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  2077. utf8_bytes_filled = 2;
  2078. }
  2079. else if (wc <= 0xFFFF)
  2080. {
  2081. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u) & 0x0Fu));
  2082. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  2083. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  2084. utf8_bytes_filled = 3;
  2085. }
  2086. else if (wc <= 0x10FFFF)
  2087. {
  2088. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((wc >> 18u) & 0x07u));
  2089. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 12u) & 0x3Fu));
  2090. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  2091. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  2092. utf8_bytes_filled = 4;
  2093. }
  2094. else
  2095. {
  2096. // unknown character
  2097. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  2098. utf8_bytes_filled = 1;
  2099. }
  2100. }
  2101. }
  2102. };
  2103. template<typename WideStringType>
  2104. struct wide_string_input_helper<WideStringType, 2>
  2105. {
  2106. // UTF-16
  2107. static void fill_buffer(const WideStringType& str,
  2108. size_t& current_wchar,
  2109. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  2110. size_t& utf8_bytes_index,
  2111. size_t& utf8_bytes_filled)
  2112. {
  2113. utf8_bytes_index = 0;
  2114. if (current_wchar == str.size())
  2115. {
  2116. utf8_bytes[0] = std::char_traits<char>::eof();
  2117. utf8_bytes_filled = 1;
  2118. }
  2119. else
  2120. {
  2121. // get the current character
  2122. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  2123. // UTF-16 to UTF-8 encoding
  2124. if (wc < 0x80)
  2125. {
  2126. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  2127. utf8_bytes_filled = 1;
  2128. }
  2129. else if (wc <= 0x7FF)
  2130. {
  2131. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u)));
  2132. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  2133. utf8_bytes_filled = 2;
  2134. }
  2135. else if (0xD800 > wc or wc >= 0xE000)
  2136. {
  2137. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u)));
  2138. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  2139. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  2140. utf8_bytes_filled = 3;
  2141. }
  2142. else
  2143. {
  2144. if (current_wchar < str.size())
  2145. {
  2146. const auto wc2 = static_cast<unsigned int>(str[current_wchar++]);
  2147. const auto charcode = 0x10000u + (((wc & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  2148. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  2149. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  2150. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  2151. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  2152. utf8_bytes_filled = 4;
  2153. }
  2154. else
  2155. {
  2156. // unknown character
  2157. ++current_wchar;
  2158. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  2159. utf8_bytes_filled = 1;
  2160. }
  2161. }
  2162. }
  2163. }
  2164. };
  2165. template<typename WideStringType>
  2166. class wide_string_input_adapter : public input_adapter_protocol
  2167. {
  2168. public:
  2169. explicit wide_string_input_adapter(const WideStringType& w) noexcept
  2170. : str(w)
  2171. {}
  2172. std::char_traits<char>::int_type get_character() noexcept override
  2173. {
  2174. // check if buffer needs to be filled
  2175. if (utf8_bytes_index == utf8_bytes_filled)
  2176. {
  2177. fill_buffer<sizeof(typename WideStringType::value_type)>();
  2178. assert(utf8_bytes_filled > 0);
  2179. assert(utf8_bytes_index == 0);
  2180. }
  2181. // use buffer
  2182. assert(utf8_bytes_filled > 0);
  2183. assert(utf8_bytes_index < utf8_bytes_filled);
  2184. return utf8_bytes[utf8_bytes_index++];
  2185. }
  2186. private:
  2187. template<size_t T>
  2188. void fill_buffer()
  2189. {
  2190. wide_string_input_helper<WideStringType, T>::fill_buffer(str, current_wchar, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  2191. }
  2192. /// the wstring to process
  2193. const WideStringType& str;
  2194. /// index of the current wchar in str
  2195. std::size_t current_wchar = 0;
  2196. /// a buffer for UTF-8 bytes
  2197. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  2198. /// index to the utf8_codes array for the next valid byte
  2199. std::size_t utf8_bytes_index = 0;
  2200. /// number of valid bytes in the utf8_codes array
  2201. std::size_t utf8_bytes_filled = 0;
  2202. };
  2203. class input_adapter
  2204. {
  2205. public:
  2206. // native support
  2207. input_adapter(std::FILE* file)
  2208. : ia(std::make_shared<file_input_adapter>(file)) {}
  2209. /// input adapter for input stream
  2210. input_adapter(std::istream& i)
  2211. : ia(std::make_shared<input_stream_adapter>(i)) {}
  2212. /// input adapter for input stream
  2213. input_adapter(std::istream&& i)
  2214. : ia(std::make_shared<input_stream_adapter>(i)) {}
  2215. input_adapter(const std::wstring& ws)
  2216. : ia(std::make_shared<wide_string_input_adapter<std::wstring>>(ws)) {}
  2217. input_adapter(const std::u16string& ws)
  2218. : ia(std::make_shared<wide_string_input_adapter<std::u16string>>(ws)) {}
  2219. input_adapter(const std::u32string& ws)
  2220. : ia(std::make_shared<wide_string_input_adapter<std::u32string>>(ws)) {}
  2221. /// input adapter for buffer
  2222. template<typename CharT,
  2223. typename std::enable_if<
  2224. std::is_pointer<CharT>::value and
  2225. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  2226. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  2227. int>::type = 0>
  2228. input_adapter(CharT b, std::size_t l)
  2229. : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
  2230. // derived support
  2231. /// input adapter for string literal
  2232. template<typename CharT,
  2233. typename std::enable_if<
  2234. std::is_pointer<CharT>::value and
  2235. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  2236. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  2237. int>::type = 0>
  2238. input_adapter(CharT b)
  2239. : input_adapter(reinterpret_cast<const char*>(b),
  2240. std::strlen(reinterpret_cast<const char*>(b))) {}
  2241. /// input adapter for iterator range with contiguous storage
  2242. template<class IteratorType,
  2243. typename std::enable_if<
  2244. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  2245. int>::type = 0>
  2246. input_adapter(IteratorType first, IteratorType last)
  2247. {
  2248. #ifndef NDEBUG
  2249. // assertion to check that the iterator range is indeed contiguous,
  2250. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  2251. const auto is_contiguous = std::accumulate(
  2252. first, last, std::pair<bool, int>(true, 0),
  2253. [&first](std::pair<bool, int> res, decltype(*first) val)
  2254. {
  2255. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  2256. return res;
  2257. }).first;
  2258. assert(is_contiguous);
  2259. #endif
  2260. // assertion to check that each element is 1 byte long
  2261. static_assert(
  2262. sizeof(typename iterator_traits<IteratorType>::value_type) == 1,
  2263. "each element in the iterator range must have the size of 1 byte");
  2264. const auto len = static_cast<size_t>(std::distance(first, last));
  2265. if (JSON_LIKELY(len > 0))
  2266. {
  2267. // there is at least one element: use the address of first
  2268. ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
  2269. }
  2270. else
  2271. {
  2272. // the address of first cannot be used: use nullptr
  2273. ia = std::make_shared<input_buffer_adapter>(nullptr, len);
  2274. }
  2275. }
  2276. /// input adapter for array
  2277. template<class T, std::size_t N>
  2278. input_adapter(T (&array)[N])
  2279. : input_adapter(std::begin(array), std::end(array)) {}
  2280. /// input adapter for contiguous container
  2281. template<class ContiguousContainer, typename
  2282. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  2283. std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  2284. int>::type = 0>
  2285. input_adapter(const ContiguousContainer& c)
  2286. : input_adapter(std::begin(c), std::end(c)) {}
  2287. operator input_adapter_t()
  2288. {
  2289. return ia;
  2290. }
  2291. private:
  2292. /// the actual adapter
  2293. input_adapter_t ia = nullptr;
  2294. };
  2295. } // namespace detail
  2296. } // namespace nlohmann
  2297. // #include <nlohmann/detail/input/json_sax.hpp>
  2298. #include <cassert> // assert
  2299. #include <cstddef>
  2300. #include <string> // string
  2301. #include <utility> // move
  2302. #include <vector> // vector
  2303. // #include <nlohmann/detail/exceptions.hpp>
  2304. // #include <nlohmann/detail/macro_scope.hpp>
  2305. namespace nlohmann
  2306. {
  2307. /*!
  2308. @brief SAX interface
  2309. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  2310. Each function is called in different situations while the input is parsed. The
  2311. boolean return value informs the parser whether to continue processing the
  2312. input.
  2313. */
  2314. template<typename BasicJsonType>
  2315. struct json_sax
  2316. {
  2317. /// type for (signed) integers
  2318. using number_integer_t = typename BasicJsonType::number_integer_t;
  2319. /// type for unsigned integers
  2320. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2321. /// type for floating-point numbers
  2322. using number_float_t = typename BasicJsonType::number_float_t;
  2323. /// type for strings
  2324. using string_t = typename BasicJsonType::string_t;
  2325. /*!
  2326. @brief a null value was read
  2327. @return whether parsing should proceed
  2328. */
  2329. virtual bool null() = 0;
  2330. /*!
  2331. @brief a boolean value was read
  2332. @param[in] val boolean value
  2333. @return whether parsing should proceed
  2334. */
  2335. virtual bool boolean(bool val) = 0;
  2336. /*!
  2337. @brief an integer number was read
  2338. @param[in] val integer value
  2339. @return whether parsing should proceed
  2340. */
  2341. virtual bool number_integer(number_integer_t val) = 0;
  2342. /*!
  2343. @brief an unsigned integer number was read
  2344. @param[in] val unsigned integer value
  2345. @return whether parsing should proceed
  2346. */
  2347. virtual bool number_unsigned(number_unsigned_t val) = 0;
  2348. /*!
  2349. @brief an floating-point number was read
  2350. @param[in] val floating-point value
  2351. @param[in] s raw token value
  2352. @return whether parsing should proceed
  2353. */
  2354. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  2355. /*!
  2356. @brief a string was read
  2357. @param[in] val string value
  2358. @return whether parsing should proceed
  2359. @note It is safe to move the passed string.
  2360. */
  2361. virtual bool string(string_t& val) = 0;
  2362. /*!
  2363. @brief the beginning of an object was read
  2364. @param[in] elements number of object elements or -1 if unknown
  2365. @return whether parsing should proceed
  2366. @note binary formats may report the number of elements
  2367. */
  2368. virtual bool start_object(std::size_t elements) = 0;
  2369. /*!
  2370. @brief an object key was read
  2371. @param[in] val object key
  2372. @return whether parsing should proceed
  2373. @note It is safe to move the passed string.
  2374. */
  2375. virtual bool key(string_t& val) = 0;
  2376. /*!
  2377. @brief the end of an object was read
  2378. @return whether parsing should proceed
  2379. */
  2380. virtual bool end_object() = 0;
  2381. /*!
  2382. @brief the beginning of an array was read
  2383. @param[in] elements number of array elements or -1 if unknown
  2384. @return whether parsing should proceed
  2385. @note binary formats may report the number of elements
  2386. */
  2387. virtual bool start_array(std::size_t elements) = 0;
  2388. /*!
  2389. @brief the end of an array was read
  2390. @return whether parsing should proceed
  2391. */
  2392. virtual bool end_array() = 0;
  2393. /*!
  2394. @brief a parse error occurred
  2395. @param[in] position the position in the input where the error occurs
  2396. @param[in] last_token the last read token
  2397. @param[in] ex an exception object describing the error
  2398. @return whether parsing should proceed (must return false)
  2399. */
  2400. virtual bool parse_error(std::size_t position,
  2401. const std::string& last_token,
  2402. const detail::exception& ex) = 0;
  2403. virtual ~json_sax() = default;
  2404. };
  2405. namespace detail
  2406. {
  2407. /*!
  2408. @brief SAX implementation to create a JSON value from SAX events
  2409. This class implements the @ref json_sax interface and processes the SAX events
  2410. to create a JSON value which makes it basically a DOM parser. The structure or
  2411. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  2412. a pointer to the respective array or object for each recursion depth.
  2413. After successful parsing, the value that is passed by reference to the
  2414. constructor contains the parsed value.
  2415. @tparam BasicJsonType the JSON type
  2416. */
  2417. template<typename BasicJsonType>
  2418. class json_sax_dom_parser
  2419. {
  2420. public:
  2421. using number_integer_t = typename BasicJsonType::number_integer_t;
  2422. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2423. using number_float_t = typename BasicJsonType::number_float_t;
  2424. using string_t = typename BasicJsonType::string_t;
  2425. /*!
  2426. @param[in, out] r reference to a JSON value that is manipulated while
  2427. parsing
  2428. @param[in] allow_exceptions_ whether parse errors yield exceptions
  2429. */
  2430. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  2431. : root(r), allow_exceptions(allow_exceptions_)
  2432. {}
  2433. // make class move-only
  2434. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  2435. json_sax_dom_parser(json_sax_dom_parser&&) = default;
  2436. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  2437. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default;
  2438. ~json_sax_dom_parser() = default;
  2439. bool null()
  2440. {
  2441. handle_value(nullptr);
  2442. return true;
  2443. }
  2444. bool boolean(bool val)
  2445. {
  2446. handle_value(val);
  2447. return true;
  2448. }
  2449. bool number_integer(number_integer_t val)
  2450. {
  2451. handle_value(val);
  2452. return true;
  2453. }
  2454. bool number_unsigned(number_unsigned_t val)
  2455. {
  2456. handle_value(val);
  2457. return true;
  2458. }
  2459. bool number_float(number_float_t val, const string_t& /*unused*/)
  2460. {
  2461. handle_value(val);
  2462. return true;
  2463. }
  2464. bool string(string_t& val)
  2465. {
  2466. handle_value(val);
  2467. return true;
  2468. }
  2469. bool start_object(std::size_t len)
  2470. {
  2471. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  2472. if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  2473. {
  2474. JSON_THROW(out_of_range::create(408,
  2475. "excessive object size: " + std::to_string(len)));
  2476. }
  2477. return true;
  2478. }
  2479. bool key(string_t& val)
  2480. {
  2481. // add null at given key and store the reference for later
  2482. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  2483. return true;
  2484. }
  2485. bool end_object()
  2486. {
  2487. ref_stack.pop_back();
  2488. return true;
  2489. }
  2490. bool start_array(std::size_t len)
  2491. {
  2492. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  2493. if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  2494. {
  2495. JSON_THROW(out_of_range::create(408,
  2496. "excessive array size: " + std::to_string(len)));
  2497. }
  2498. return true;
  2499. }
  2500. bool end_array()
  2501. {
  2502. ref_stack.pop_back();
  2503. return true;
  2504. }
  2505. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  2506. const detail::exception& ex)
  2507. {
  2508. errored = true;
  2509. if (allow_exceptions)
  2510. {
  2511. // determine the proper exception type from the id
  2512. switch ((ex.id / 100) % 100)
  2513. {
  2514. case 1:
  2515. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  2516. case 4:
  2517. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  2518. // LCOV_EXCL_START
  2519. case 2:
  2520. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  2521. case 3:
  2522. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  2523. case 5:
  2524. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  2525. default:
  2526. assert(false);
  2527. // LCOV_EXCL_STOP
  2528. }
  2529. }
  2530. return false;
  2531. }
  2532. constexpr bool is_errored() const
  2533. {
  2534. return errored;
  2535. }
  2536. private:
  2537. /*!
  2538. @invariant If the ref stack is empty, then the passed value will be the new
  2539. root.
  2540. @invariant If the ref stack contains a value, then it is an array or an
  2541. object to which we can add elements
  2542. */
  2543. template<typename Value>
  2544. BasicJsonType* handle_value(Value&& v)
  2545. {
  2546. if (ref_stack.empty())
  2547. {
  2548. root = BasicJsonType(std::forward<Value>(v));
  2549. return &root;
  2550. }
  2551. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  2552. if (ref_stack.back()->is_array())
  2553. {
  2554. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  2555. return &(ref_stack.back()->m_value.array->back());
  2556. }
  2557. assert(ref_stack.back()->is_object());
  2558. assert(object_element);
  2559. *object_element = BasicJsonType(std::forward<Value>(v));
  2560. return object_element;
  2561. }
  2562. /// the parsed JSON value
  2563. BasicJsonType& root;
  2564. /// stack to model hierarchy of values
  2565. std::vector<BasicJsonType*> ref_stack {};
  2566. /// helper to hold the reference for the next object element
  2567. BasicJsonType* object_element = nullptr;
  2568. /// whether a syntax error occurred
  2569. bool errored = false;
  2570. /// whether to throw exceptions in case of errors
  2571. const bool allow_exceptions = true;
  2572. };
  2573. template<typename BasicJsonType>
  2574. class json_sax_dom_callback_parser
  2575. {
  2576. public:
  2577. using number_integer_t = typename BasicJsonType::number_integer_t;
  2578. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2579. using number_float_t = typename BasicJsonType::number_float_t;
  2580. using string_t = typename BasicJsonType::string_t;
  2581. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  2582. using parse_event_t = typename BasicJsonType::parse_event_t;
  2583. json_sax_dom_callback_parser(BasicJsonType& r,
  2584. const parser_callback_t cb,
  2585. const bool allow_exceptions_ = true)
  2586. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  2587. {
  2588. keep_stack.push_back(true);
  2589. }
  2590. // make class move-only
  2591. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  2592. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default;
  2593. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  2594. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default;
  2595. ~json_sax_dom_callback_parser() = default;
  2596. bool null()
  2597. {
  2598. handle_value(nullptr);
  2599. return true;
  2600. }
  2601. bool boolean(bool val)
  2602. {
  2603. handle_value(val);
  2604. return true;
  2605. }
  2606. bool number_integer(number_integer_t val)
  2607. {
  2608. handle_value(val);
  2609. return true;
  2610. }
  2611. bool number_unsigned(number_unsigned_t val)
  2612. {
  2613. handle_value(val);
  2614. return true;
  2615. }
  2616. bool number_float(number_float_t val, const string_t& /*unused*/)
  2617. {
  2618. handle_value(val);
  2619. return true;
  2620. }
  2621. bool string(string_t& val)
  2622. {
  2623. handle_value(val);
  2624. return true;
  2625. }
  2626. bool start_object(std::size_t len)
  2627. {
  2628. // check callback for object start
  2629. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  2630. keep_stack.push_back(keep);
  2631. auto val = handle_value(BasicJsonType::value_t::object, true);
  2632. ref_stack.push_back(val.second);
  2633. // check object limit
  2634. if (ref_stack.back() and JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  2635. {
  2636. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len)));
  2637. }
  2638. return true;
  2639. }
  2640. bool key(string_t& val)
  2641. {
  2642. BasicJsonType k = BasicJsonType(val);
  2643. // check callback for key
  2644. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  2645. key_keep_stack.push_back(keep);
  2646. // add discarded value at given key and store the reference for later
  2647. if (keep and ref_stack.back())
  2648. {
  2649. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  2650. }
  2651. return true;
  2652. }
  2653. bool end_object()
  2654. {
  2655. if (ref_stack.back() and not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  2656. {
  2657. // discard object
  2658. *ref_stack.back() = discarded;
  2659. }
  2660. assert(not ref_stack.empty());
  2661. assert(not keep_stack.empty());
  2662. ref_stack.pop_back();
  2663. keep_stack.pop_back();
  2664. if (not ref_stack.empty() and ref_stack.back() and ref_stack.back()->is_object())
  2665. {
  2666. // remove discarded value
  2667. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  2668. {
  2669. if (it->is_discarded())
  2670. {
  2671. ref_stack.back()->erase(it);
  2672. break;
  2673. }
  2674. }
  2675. }
  2676. return true;
  2677. }
  2678. bool start_array(std::size_t len)
  2679. {
  2680. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  2681. keep_stack.push_back(keep);
  2682. auto val = handle_value(BasicJsonType::value_t::array, true);
  2683. ref_stack.push_back(val.second);
  2684. // check array limit
  2685. if (ref_stack.back() and JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  2686. {
  2687. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len)));
  2688. }
  2689. return true;
  2690. }
  2691. bool end_array()
  2692. {
  2693. bool keep = true;
  2694. if (ref_stack.back())
  2695. {
  2696. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  2697. if (not keep)
  2698. {
  2699. // discard array
  2700. *ref_stack.back() = discarded;
  2701. }
  2702. }
  2703. assert(not ref_stack.empty());
  2704. assert(not keep_stack.empty());
  2705. ref_stack.pop_back();
  2706. keep_stack.pop_back();
  2707. // remove discarded value
  2708. if (not keep and not ref_stack.empty() and ref_stack.back()->is_array())
  2709. {
  2710. ref_stack.back()->m_value.array->pop_back();
  2711. }
  2712. return true;
  2713. }
  2714. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  2715. const detail::exception& ex)
  2716. {
  2717. errored = true;
  2718. if (allow_exceptions)
  2719. {
  2720. // determine the proper exception type from the id
  2721. switch ((ex.id / 100) % 100)
  2722. {
  2723. case 1:
  2724. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  2725. case 4:
  2726. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  2727. // LCOV_EXCL_START
  2728. case 2:
  2729. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  2730. case 3:
  2731. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  2732. case 5:
  2733. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  2734. default:
  2735. assert(false);
  2736. // LCOV_EXCL_STOP
  2737. }
  2738. }
  2739. return false;
  2740. }
  2741. constexpr bool is_errored() const
  2742. {
  2743. return errored;
  2744. }
  2745. private:
  2746. /*!
  2747. @param[in] v value to add to the JSON value we build during parsing
  2748. @param[in] skip_callback whether we should skip calling the callback
  2749. function; this is required after start_array() and
  2750. start_object() SAX events, because otherwise we would call the
  2751. callback function with an empty array or object, respectively.
  2752. @invariant If the ref stack is empty, then the passed value will be the new
  2753. root.
  2754. @invariant If the ref stack contains a value, then it is an array or an
  2755. object to which we can add elements
  2756. @return pair of boolean (whether value should be kept) and pointer (to the
  2757. passed value in the ref_stack hierarchy; nullptr if not kept)
  2758. */
  2759. template<typename Value>
  2760. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  2761. {
  2762. assert(not keep_stack.empty());
  2763. // do not handle this value if we know it would be added to a discarded
  2764. // container
  2765. if (not keep_stack.back())
  2766. {
  2767. return {false, nullptr};
  2768. }
  2769. // create value
  2770. auto value = BasicJsonType(std::forward<Value>(v));
  2771. // check callback
  2772. const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  2773. // do not handle this value if we just learnt it shall be discarded
  2774. if (not keep)
  2775. {
  2776. return {false, nullptr};
  2777. }
  2778. if (ref_stack.empty())
  2779. {
  2780. root = std::move(value);
  2781. return {true, &root};
  2782. }
  2783. // skip this value if we already decided to skip the parent
  2784. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  2785. if (not ref_stack.back())
  2786. {
  2787. return {false, nullptr};
  2788. }
  2789. // we now only expect arrays and objects
  2790. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  2791. // array
  2792. if (ref_stack.back()->is_array())
  2793. {
  2794. ref_stack.back()->m_value.array->push_back(std::move(value));
  2795. return {true, &(ref_stack.back()->m_value.array->back())};
  2796. }
  2797. // object
  2798. assert(ref_stack.back()->is_object());
  2799. // check if we should store an element for the current key
  2800. assert(not key_keep_stack.empty());
  2801. const bool store_element = key_keep_stack.back();
  2802. key_keep_stack.pop_back();
  2803. if (not store_element)
  2804. {
  2805. return {false, nullptr};
  2806. }
  2807. assert(object_element);
  2808. *object_element = std::move(value);
  2809. return {true, object_element};
  2810. }
  2811. /// the parsed JSON value
  2812. BasicJsonType& root;
  2813. /// stack to model hierarchy of values
  2814. std::vector<BasicJsonType*> ref_stack {};
  2815. /// stack to manage which values to keep
  2816. std::vector<bool> keep_stack {};
  2817. /// stack to manage which object keys to keep
  2818. std::vector<bool> key_keep_stack {};
  2819. /// helper to hold the reference for the next object element
  2820. BasicJsonType* object_element = nullptr;
  2821. /// whether a syntax error occurred
  2822. bool errored = false;
  2823. /// callback function
  2824. const parser_callback_t callback = nullptr;
  2825. /// whether to throw exceptions in case of errors
  2826. const bool allow_exceptions = true;
  2827. /// a discarded value for the callback
  2828. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  2829. };
  2830. template<typename BasicJsonType>
  2831. class json_sax_acceptor
  2832. {
  2833. public:
  2834. using number_integer_t = typename BasicJsonType::number_integer_t;
  2835. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2836. using number_float_t = typename BasicJsonType::number_float_t;
  2837. using string_t = typename BasicJsonType::string_t;
  2838. bool null()
  2839. {
  2840. return true;
  2841. }
  2842. bool boolean(bool /*unused*/)
  2843. {
  2844. return true;
  2845. }
  2846. bool number_integer(number_integer_t /*unused*/)
  2847. {
  2848. return true;
  2849. }
  2850. bool number_unsigned(number_unsigned_t /*unused*/)
  2851. {
  2852. return true;
  2853. }
  2854. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  2855. {
  2856. return true;
  2857. }
  2858. bool string(string_t& /*unused*/)
  2859. {
  2860. return true;
  2861. }
  2862. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  2863. {
  2864. return true;
  2865. }
  2866. bool key(string_t& /*unused*/)
  2867. {
  2868. return true;
  2869. }
  2870. bool end_object()
  2871. {
  2872. return true;
  2873. }
  2874. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  2875. {
  2876. return true;
  2877. }
  2878. bool end_array()
  2879. {
  2880. return true;
  2881. }
  2882. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  2883. {
  2884. return false;
  2885. }
  2886. };
  2887. } // namespace detail
  2888. } // namespace nlohmann
  2889. // #include <nlohmann/detail/macro_scope.hpp>
  2890. // #include <nlohmann/detail/meta/is_sax.hpp>
  2891. #include <cstdint> // size_t
  2892. #include <utility> // declval
  2893. #include <string> // string
  2894. // #include <nlohmann/detail/meta/detected.hpp>
  2895. // #include <nlohmann/detail/meta/type_traits.hpp>
  2896. namespace nlohmann
  2897. {
  2898. namespace detail
  2899. {
  2900. template <typename T>
  2901. using null_function_t = decltype(std::declval<T&>().null());
  2902. template <typename T>
  2903. using boolean_function_t =
  2904. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  2905. template <typename T, typename Integer>
  2906. using number_integer_function_t =
  2907. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  2908. template <typename T, typename Unsigned>
  2909. using number_unsigned_function_t =
  2910. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  2911. template <typename T, typename Float, typename String>
  2912. using number_float_function_t = decltype(std::declval<T&>().number_float(
  2913. std::declval<Float>(), std::declval<const String&>()));
  2914. template <typename T, typename String>
  2915. using string_function_t =
  2916. decltype(std::declval<T&>().string(std::declval<String&>()));
  2917. template <typename T>
  2918. using start_object_function_t =
  2919. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  2920. template <typename T, typename String>
  2921. using key_function_t =
  2922. decltype(std::declval<T&>().key(std::declval<String&>()));
  2923. template <typename T>
  2924. using end_object_function_t = decltype(std::declval<T&>().end_object());
  2925. template <typename T>
  2926. using start_array_function_t =
  2927. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  2928. template <typename T>
  2929. using end_array_function_t = decltype(std::declval<T&>().end_array());
  2930. template <typename T, typename Exception>
  2931. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  2932. std::declval<std::size_t>(), std::declval<const std::string&>(),
  2933. std::declval<const Exception&>()));
  2934. template <typename SAX, typename BasicJsonType>
  2935. struct is_sax
  2936. {
  2937. private:
  2938. static_assert(is_basic_json<BasicJsonType>::value,
  2939. "BasicJsonType must be of type basic_json<...>");
  2940. using number_integer_t = typename BasicJsonType::number_integer_t;
  2941. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2942. using number_float_t = typename BasicJsonType::number_float_t;
  2943. using string_t = typename BasicJsonType::string_t;
  2944. using exception_t = typename BasicJsonType::exception;
  2945. public:
  2946. static constexpr bool value =
  2947. is_detected_exact<bool, null_function_t, SAX>::value &&
  2948. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  2949. is_detected_exact<bool, number_integer_function_t, SAX,
  2950. number_integer_t>::value &&
  2951. is_detected_exact<bool, number_unsigned_function_t, SAX,
  2952. number_unsigned_t>::value &&
  2953. is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
  2954. string_t>::value &&
  2955. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  2956. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  2957. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  2958. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  2959. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  2960. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  2961. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  2962. };
  2963. template <typename SAX, typename BasicJsonType>
  2964. struct is_sax_static_asserts
  2965. {
  2966. private:
  2967. static_assert(is_basic_json<BasicJsonType>::value,
  2968. "BasicJsonType must be of type basic_json<...>");
  2969. using number_integer_t = typename BasicJsonType::number_integer_t;
  2970. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2971. using number_float_t = typename BasicJsonType::number_float_t;
  2972. using string_t = typename BasicJsonType::string_t;
  2973. using exception_t = typename BasicJsonType::exception;
  2974. public:
  2975. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  2976. "Missing/invalid function: bool null()");
  2977. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  2978. "Missing/invalid function: bool boolean(bool)");
  2979. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  2980. "Missing/invalid function: bool boolean(bool)");
  2981. static_assert(
  2982. is_detected_exact<bool, number_integer_function_t, SAX,
  2983. number_integer_t>::value,
  2984. "Missing/invalid function: bool number_integer(number_integer_t)");
  2985. static_assert(
  2986. is_detected_exact<bool, number_unsigned_function_t, SAX,
  2987. number_unsigned_t>::value,
  2988. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  2989. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  2990. number_float_t, string_t>::value,
  2991. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  2992. static_assert(
  2993. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  2994. "Missing/invalid function: bool string(string_t&)");
  2995. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  2996. "Missing/invalid function: bool start_object(std::size_t)");
  2997. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  2998. "Missing/invalid function: bool key(string_t&)");
  2999. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  3000. "Missing/invalid function: bool end_object()");
  3001. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  3002. "Missing/invalid function: bool start_array(std::size_t)");
  3003. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  3004. "Missing/invalid function: bool end_array()");
  3005. static_assert(
  3006. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  3007. "Missing/invalid function: bool parse_error(std::size_t, const "
  3008. "std::string&, const exception&)");
  3009. };
  3010. } // namespace detail
  3011. } // namespace nlohmann
  3012. // #include <nlohmann/detail/value_t.hpp>
  3013. namespace nlohmann
  3014. {
  3015. namespace detail
  3016. {
  3017. ///////////////////
  3018. // binary reader //
  3019. ///////////////////
  3020. /*!
  3021. @brief deserialization of CBOR, MessagePack, and UBJSON values
  3022. */
  3023. template<typename BasicJsonType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  3024. class binary_reader
  3025. {
  3026. using number_integer_t = typename BasicJsonType::number_integer_t;
  3027. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3028. using number_float_t = typename BasicJsonType::number_float_t;
  3029. using string_t = typename BasicJsonType::string_t;
  3030. using json_sax_t = SAX;
  3031. public:
  3032. /*!
  3033. @brief create a binary reader
  3034. @param[in] adapter input adapter to read from
  3035. */
  3036. explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
  3037. {
  3038. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  3039. assert(ia);
  3040. }
  3041. // make class move-only
  3042. binary_reader(const binary_reader&) = delete;
  3043. binary_reader(binary_reader&&) = default;
  3044. binary_reader& operator=(const binary_reader&) = delete;
  3045. binary_reader& operator=(binary_reader&&) = default;
  3046. ~binary_reader() = default;
  3047. /*!
  3048. @param[in] format the binary format to parse
  3049. @param[in] sax_ a SAX event processor
  3050. @param[in] strict whether to expect the input to be consumed completed
  3051. @return
  3052. */
  3053. bool sax_parse(const input_format_t format,
  3054. json_sax_t* sax_,
  3055. const bool strict = true)
  3056. {
  3057. sax = sax_;
  3058. bool result = false;
  3059. switch (format)
  3060. {
  3061. case input_format_t::bson:
  3062. result = parse_bson_internal();
  3063. break;
  3064. case input_format_t::cbor:
  3065. result = parse_cbor_internal();
  3066. break;
  3067. case input_format_t::msgpack:
  3068. result = parse_msgpack_internal();
  3069. break;
  3070. case input_format_t::ubjson:
  3071. result = parse_ubjson_internal();
  3072. break;
  3073. default: // LCOV_EXCL_LINE
  3074. assert(false); // LCOV_EXCL_LINE
  3075. }
  3076. // strict mode: next byte must be EOF
  3077. if (result and strict)
  3078. {
  3079. if (format == input_format_t::ubjson)
  3080. {
  3081. get_ignore_noop();
  3082. }
  3083. else
  3084. {
  3085. get();
  3086. }
  3087. if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
  3088. {
  3089. return sax->parse_error(chars_read, get_token_string(),
  3090. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
  3091. }
  3092. }
  3093. return result;
  3094. }
  3095. /*!
  3096. @brief determine system byte order
  3097. @return true if and only if system's byte order is little endian
  3098. @note from http://stackoverflow.com/a/1001328/266378
  3099. */
  3100. static constexpr bool little_endianess(int num = 1) noexcept
  3101. {
  3102. return *reinterpret_cast<char*>(&num) == 1;
  3103. }
  3104. private:
  3105. //////////
  3106. // BSON //
  3107. //////////
  3108. /*!
  3109. @brief Reads in a BSON-object and passes it to the SAX-parser.
  3110. @return whether a valid BSON-value was passed to the SAX parser
  3111. */
  3112. bool parse_bson_internal()
  3113. {
  3114. std::int32_t document_size;
  3115. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  3116. if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
  3117. {
  3118. return false;
  3119. }
  3120. if (JSON_UNLIKELY(not parse_bson_element_list(/*is_array*/false)))
  3121. {
  3122. return false;
  3123. }
  3124. return sax->end_object();
  3125. }
  3126. /*!
  3127. @brief Parses a C-style string from the BSON input.
  3128. @param[in, out] result A reference to the string variable where the read
  3129. string is to be stored.
  3130. @return `true` if the \x00-byte indicating the end of the string was
  3131. encountered before the EOF; false` indicates an unexpected EOF.
  3132. */
  3133. bool get_bson_cstr(string_t& result)
  3134. {
  3135. auto out = std::back_inserter(result);
  3136. while (true)
  3137. {
  3138. get();
  3139. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::bson, "cstring")))
  3140. {
  3141. return false;
  3142. }
  3143. if (current == 0x00)
  3144. {
  3145. return true;
  3146. }
  3147. *out++ = static_cast<char>(current);
  3148. }
  3149. return true;
  3150. }
  3151. /*!
  3152. @brief Parses a zero-terminated string of length @a len from the BSON
  3153. input.
  3154. @param[in] len The length (including the zero-byte at the end) of the
  3155. string to be read.
  3156. @param[in, out] result A reference to the string variable where the read
  3157. string is to be stored.
  3158. @tparam NumberType The type of the length @a len
  3159. @pre len >= 1
  3160. @return `true` if the string was successfully parsed
  3161. */
  3162. template<typename NumberType>
  3163. bool get_bson_string(const NumberType len, string_t& result)
  3164. {
  3165. if (JSON_UNLIKELY(len < 1))
  3166. {
  3167. auto last_token = get_token_string();
  3168. 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")));
  3169. }
  3170. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) and get() != std::char_traits<char>::eof();
  3171. }
  3172. /*!
  3173. @brief Read a BSON document element of the given @a element_type.
  3174. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  3175. @param[in] element_type_parse_position The position in the input stream,
  3176. where the `element_type` was read.
  3177. @warning Not all BSON element types are supported yet. An unsupported
  3178. @a element_type will give rise to a parse_error.114:
  3179. Unsupported BSON record type 0x...
  3180. @return whether a valid BSON-object/array was passed to the SAX parser
  3181. */
  3182. bool parse_bson_element_internal(const int element_type,
  3183. const std::size_t element_type_parse_position)
  3184. {
  3185. switch (element_type)
  3186. {
  3187. case 0x01: // double
  3188. {
  3189. double number;
  3190. return get_number<double, true>(input_format_t::bson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  3191. }
  3192. case 0x02: // string
  3193. {
  3194. std::int32_t len;
  3195. string_t value;
  3196. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_string(len, value) and sax->string(value);
  3197. }
  3198. case 0x03: // object
  3199. {
  3200. return parse_bson_internal();
  3201. }
  3202. case 0x04: // array
  3203. {
  3204. return parse_bson_array();
  3205. }
  3206. case 0x08: // boolean
  3207. {
  3208. return sax->boolean(get() != 0);
  3209. }
  3210. case 0x0A: // null
  3211. {
  3212. return sax->null();
  3213. }
  3214. case 0x10: // int32
  3215. {
  3216. std::int32_t value;
  3217. return get_number<std::int32_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  3218. }
  3219. case 0x12: // int64
  3220. {
  3221. std::int64_t value;
  3222. return get_number<std::int64_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  3223. }
  3224. default: // anything else not supported (yet)
  3225. {
  3226. std::array<char, 3> cr{{}};
  3227. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type));
  3228. 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())));
  3229. }
  3230. }
  3231. }
  3232. /*!
  3233. @brief Read a BSON element list (as specified in the BSON-spec)
  3234. The same binary layout is used for objects and arrays, hence it must be
  3235. indicated with the argument @a is_array which one is expected
  3236. (true --> array, false --> object).
  3237. @param[in] is_array Determines if the element list being read is to be
  3238. treated as an object (@a is_array == false), or as an
  3239. array (@a is_array == true).
  3240. @return whether a valid BSON-object/array was passed to the SAX parser
  3241. */
  3242. bool parse_bson_element_list(const bool is_array)
  3243. {
  3244. string_t key;
  3245. while (int element_type = get())
  3246. {
  3247. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::bson, "element list")))
  3248. {
  3249. return false;
  3250. }
  3251. const std::size_t element_type_parse_position = chars_read;
  3252. if (JSON_UNLIKELY(not get_bson_cstr(key)))
  3253. {
  3254. return false;
  3255. }
  3256. if (not is_array and not sax->key(key))
  3257. {
  3258. return false;
  3259. }
  3260. if (JSON_UNLIKELY(not parse_bson_element_internal(element_type, element_type_parse_position)))
  3261. {
  3262. return false;
  3263. }
  3264. // get_bson_cstr only appends
  3265. key.clear();
  3266. }
  3267. return true;
  3268. }
  3269. /*!
  3270. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  3271. @return whether a valid BSON-array was passed to the SAX parser
  3272. */
  3273. bool parse_bson_array()
  3274. {
  3275. std::int32_t document_size;
  3276. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  3277. if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
  3278. {
  3279. return false;
  3280. }
  3281. if (JSON_UNLIKELY(not parse_bson_element_list(/*is_array*/true)))
  3282. {
  3283. return false;
  3284. }
  3285. return sax->end_array();
  3286. }
  3287. //////////
  3288. // CBOR //
  3289. //////////
  3290. /*!
  3291. @param[in] get_char whether a new character should be retrieved from the
  3292. input (true, default) or whether the last read
  3293. character should be considered instead
  3294. @return whether a valid CBOR value was passed to the SAX parser
  3295. */
  3296. bool parse_cbor_internal(const bool get_char = true)
  3297. {
  3298. switch (get_char ? get() : current)
  3299. {
  3300. // EOF
  3301. case std::char_traits<char>::eof():
  3302. return unexpect_eof(input_format_t::cbor, "value");
  3303. // Integer 0x00..0x17 (0..23)
  3304. case 0x00:
  3305. case 0x01:
  3306. case 0x02:
  3307. case 0x03:
  3308. case 0x04:
  3309. case 0x05:
  3310. case 0x06:
  3311. case 0x07:
  3312. case 0x08:
  3313. case 0x09:
  3314. case 0x0A:
  3315. case 0x0B:
  3316. case 0x0C:
  3317. case 0x0D:
  3318. case 0x0E:
  3319. case 0x0F:
  3320. case 0x10:
  3321. case 0x11:
  3322. case 0x12:
  3323. case 0x13:
  3324. case 0x14:
  3325. case 0x15:
  3326. case 0x16:
  3327. case 0x17:
  3328. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  3329. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  3330. {
  3331. std::uint8_t number;
  3332. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  3333. }
  3334. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  3335. {
  3336. std::uint16_t number;
  3337. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  3338. }
  3339. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  3340. {
  3341. std::uint32_t number;
  3342. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  3343. }
  3344. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  3345. {
  3346. std::uint64_t number;
  3347. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  3348. }
  3349. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  3350. case 0x20:
  3351. case 0x21:
  3352. case 0x22:
  3353. case 0x23:
  3354. case 0x24:
  3355. case 0x25:
  3356. case 0x26:
  3357. case 0x27:
  3358. case 0x28:
  3359. case 0x29:
  3360. case 0x2A:
  3361. case 0x2B:
  3362. case 0x2C:
  3363. case 0x2D:
  3364. case 0x2E:
  3365. case 0x2F:
  3366. case 0x30:
  3367. case 0x31:
  3368. case 0x32:
  3369. case 0x33:
  3370. case 0x34:
  3371. case 0x35:
  3372. case 0x36:
  3373. case 0x37:
  3374. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  3375. case 0x38: // Negative integer (one-byte uint8_t follows)
  3376. {
  3377. std::uint8_t number;
  3378. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  3379. }
  3380. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  3381. {
  3382. std::uint16_t number;
  3383. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  3384. }
  3385. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  3386. {
  3387. std::uint32_t number;
  3388. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  3389. }
  3390. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  3391. {
  3392. std::uint64_t number;
  3393. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1)
  3394. - static_cast<number_integer_t>(number));
  3395. }
  3396. // UTF-8 string (0x00..0x17 bytes follow)
  3397. case 0x60:
  3398. case 0x61:
  3399. case 0x62:
  3400. case 0x63:
  3401. case 0x64:
  3402. case 0x65:
  3403. case 0x66:
  3404. case 0x67:
  3405. case 0x68:
  3406. case 0x69:
  3407. case 0x6A:
  3408. case 0x6B:
  3409. case 0x6C:
  3410. case 0x6D:
  3411. case 0x6E:
  3412. case 0x6F:
  3413. case 0x70:
  3414. case 0x71:
  3415. case 0x72:
  3416. case 0x73:
  3417. case 0x74:
  3418. case 0x75:
  3419. case 0x76:
  3420. case 0x77:
  3421. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  3422. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  3423. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  3424. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  3425. case 0x7F: // UTF-8 string (indefinite length)
  3426. {
  3427. string_t s;
  3428. return get_cbor_string(s) and sax->string(s);
  3429. }
  3430. // array (0x00..0x17 data items follow)
  3431. case 0x80:
  3432. case 0x81:
  3433. case 0x82:
  3434. case 0x83:
  3435. case 0x84:
  3436. case 0x85:
  3437. case 0x86:
  3438. case 0x87:
  3439. case 0x88:
  3440. case 0x89:
  3441. case 0x8A:
  3442. case 0x8B:
  3443. case 0x8C:
  3444. case 0x8D:
  3445. case 0x8E:
  3446. case 0x8F:
  3447. case 0x90:
  3448. case 0x91:
  3449. case 0x92:
  3450. case 0x93:
  3451. case 0x94:
  3452. case 0x95:
  3453. case 0x96:
  3454. case 0x97:
  3455. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  3456. case 0x98: // array (one-byte uint8_t for n follows)
  3457. {
  3458. std::uint8_t len;
  3459. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  3460. }
  3461. case 0x99: // array (two-byte uint16_t for n follow)
  3462. {
  3463. std::uint16_t len;
  3464. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  3465. }
  3466. case 0x9A: // array (four-byte uint32_t for n follow)
  3467. {
  3468. std::uint32_t len;
  3469. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  3470. }
  3471. case 0x9B: // array (eight-byte uint64_t for n follow)
  3472. {
  3473. std::uint64_t len;
  3474. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  3475. }
  3476. case 0x9F: // array (indefinite length)
  3477. return get_cbor_array(std::size_t(-1));
  3478. // map (0x00..0x17 pairs of data items follow)
  3479. case 0xA0:
  3480. case 0xA1:
  3481. case 0xA2:
  3482. case 0xA3:
  3483. case 0xA4:
  3484. case 0xA5:
  3485. case 0xA6:
  3486. case 0xA7:
  3487. case 0xA8:
  3488. case 0xA9:
  3489. case 0xAA:
  3490. case 0xAB:
  3491. case 0xAC:
  3492. case 0xAD:
  3493. case 0xAE:
  3494. case 0xAF:
  3495. case 0xB0:
  3496. case 0xB1:
  3497. case 0xB2:
  3498. case 0xB3:
  3499. case 0xB4:
  3500. case 0xB5:
  3501. case 0xB6:
  3502. case 0xB7:
  3503. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  3504. case 0xB8: // map (one-byte uint8_t for n follows)
  3505. {
  3506. std::uint8_t len;
  3507. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  3508. }
  3509. case 0xB9: // map (two-byte uint16_t for n follow)
  3510. {
  3511. std::uint16_t len;
  3512. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  3513. }
  3514. case 0xBA: // map (four-byte uint32_t for n follow)
  3515. {
  3516. std::uint32_t len;
  3517. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  3518. }
  3519. case 0xBB: // map (eight-byte uint64_t for n follow)
  3520. {
  3521. std::uint64_t len;
  3522. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  3523. }
  3524. case 0xBF: // map (indefinite length)
  3525. return get_cbor_object(std::size_t(-1));
  3526. case 0xF4: // false
  3527. return sax->boolean(false);
  3528. case 0xF5: // true
  3529. return sax->boolean(true);
  3530. case 0xF6: // null
  3531. return sax->null();
  3532. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  3533. {
  3534. const int byte1_raw = get();
  3535. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  3536. {
  3537. return false;
  3538. }
  3539. const int byte2_raw = get();
  3540. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  3541. {
  3542. return false;
  3543. }
  3544. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  3545. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  3546. // code from RFC 7049, Appendix D, Figure 3:
  3547. // As half-precision floating-point numbers were only added
  3548. // to IEEE 754 in 2008, today's programming platforms often
  3549. // still only have limited support for them. It is very
  3550. // easy to include at least decoding support for them even
  3551. // without such support. An example of a small decoder for
  3552. // half-precision floating-point numbers in the C language
  3553. // is shown in Fig. 3.
  3554. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  3555. const double val = [&half]
  3556. {
  3557. const int exp = (half >> 10u) & 0x1Fu;
  3558. const unsigned int mant = half & 0x3FFu;
  3559. assert(0 <= exp and exp <= 32);
  3560. assert(0 <= mant and mant <= 1024);
  3561. switch (exp)
  3562. {
  3563. case 0:
  3564. return std::ldexp(mant, -24);
  3565. case 31:
  3566. return (mant == 0)
  3567. ? std::numeric_limits<double>::infinity()
  3568. : std::numeric_limits<double>::quiet_NaN();
  3569. default:
  3570. return std::ldexp(mant + 1024, exp - 25);
  3571. }
  3572. }();
  3573. return sax->number_float((half & 0x8000u) != 0
  3574. ? static_cast<number_float_t>(-val)
  3575. : static_cast<number_float_t>(val), "");
  3576. }
  3577. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  3578. {
  3579. float number;
  3580. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  3581. }
  3582. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  3583. {
  3584. double number;
  3585. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  3586. }
  3587. default: // anything else (0xFF is handled inside the other types)
  3588. {
  3589. auto last_token = get_token_string();
  3590. 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")));
  3591. }
  3592. }
  3593. }
  3594. /*!
  3595. @brief reads a CBOR string
  3596. This function first reads starting bytes to determine the expected
  3597. string length and then copies this number of bytes into a string.
  3598. Additionally, CBOR's strings with indefinite lengths are supported.
  3599. @param[out] result created string
  3600. @return whether string creation completed
  3601. */
  3602. bool get_cbor_string(string_t& result)
  3603. {
  3604. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::cbor, "string")))
  3605. {
  3606. return false;
  3607. }
  3608. switch (current)
  3609. {
  3610. // UTF-8 string (0x00..0x17 bytes follow)
  3611. case 0x60:
  3612. case 0x61:
  3613. case 0x62:
  3614. case 0x63:
  3615. case 0x64:
  3616. case 0x65:
  3617. case 0x66:
  3618. case 0x67:
  3619. case 0x68:
  3620. case 0x69:
  3621. case 0x6A:
  3622. case 0x6B:
  3623. case 0x6C:
  3624. case 0x6D:
  3625. case 0x6E:
  3626. case 0x6F:
  3627. case 0x70:
  3628. case 0x71:
  3629. case 0x72:
  3630. case 0x73:
  3631. case 0x74:
  3632. case 0x75:
  3633. case 0x76:
  3634. case 0x77:
  3635. {
  3636. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  3637. }
  3638. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  3639. {
  3640. std::uint8_t len;
  3641. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  3642. }
  3643. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  3644. {
  3645. std::uint16_t len;
  3646. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  3647. }
  3648. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  3649. {
  3650. std::uint32_t len;
  3651. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  3652. }
  3653. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  3654. {
  3655. std::uint64_t len;
  3656. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  3657. }
  3658. case 0x7F: // UTF-8 string (indefinite length)
  3659. {
  3660. while (get() != 0xFF)
  3661. {
  3662. string_t chunk;
  3663. if (not get_cbor_string(chunk))
  3664. {
  3665. return false;
  3666. }
  3667. result.append(chunk);
  3668. }
  3669. return true;
  3670. }
  3671. default:
  3672. {
  3673. auto last_token = get_token_string();
  3674. 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")));
  3675. }
  3676. }
  3677. }
  3678. /*!
  3679. @param[in] len the length of the array or std::size_t(-1) for an
  3680. array of indefinite size
  3681. @return whether array creation completed
  3682. */
  3683. bool get_cbor_array(const std::size_t len)
  3684. {
  3685. if (JSON_UNLIKELY(not sax->start_array(len)))
  3686. {
  3687. return false;
  3688. }
  3689. if (len != std::size_t(-1))
  3690. {
  3691. for (std::size_t i = 0; i < len; ++i)
  3692. {
  3693. if (JSON_UNLIKELY(not parse_cbor_internal()))
  3694. {
  3695. return false;
  3696. }
  3697. }
  3698. }
  3699. else
  3700. {
  3701. while (get() != 0xFF)
  3702. {
  3703. if (JSON_UNLIKELY(not parse_cbor_internal(false)))
  3704. {
  3705. return false;
  3706. }
  3707. }
  3708. }
  3709. return sax->end_array();
  3710. }
  3711. /*!
  3712. @param[in] len the length of the object or std::size_t(-1) for an
  3713. object of indefinite size
  3714. @return whether object creation completed
  3715. */
  3716. bool get_cbor_object(const std::size_t len)
  3717. {
  3718. if (JSON_UNLIKELY(not sax->start_object(len)))
  3719. {
  3720. return false;
  3721. }
  3722. string_t key;
  3723. if (len != std::size_t(-1))
  3724. {
  3725. for (std::size_t i = 0; i < len; ++i)
  3726. {
  3727. get();
  3728. if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  3729. {
  3730. return false;
  3731. }
  3732. if (JSON_UNLIKELY(not parse_cbor_internal()))
  3733. {
  3734. return false;
  3735. }
  3736. key.clear();
  3737. }
  3738. }
  3739. else
  3740. {
  3741. while (get() != 0xFF)
  3742. {
  3743. if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  3744. {
  3745. return false;
  3746. }
  3747. if (JSON_UNLIKELY(not parse_cbor_internal()))
  3748. {
  3749. return false;
  3750. }
  3751. key.clear();
  3752. }
  3753. }
  3754. return sax->end_object();
  3755. }
  3756. /////////////
  3757. // MsgPack //
  3758. /////////////
  3759. /*!
  3760. @return whether a valid MessagePack value was passed to the SAX parser
  3761. */
  3762. bool parse_msgpack_internal()
  3763. {
  3764. switch (get())
  3765. {
  3766. // EOF
  3767. case std::char_traits<char>::eof():
  3768. return unexpect_eof(input_format_t::msgpack, "value");
  3769. // positive fixint
  3770. case 0x00:
  3771. case 0x01:
  3772. case 0x02:
  3773. case 0x03:
  3774. case 0x04:
  3775. case 0x05:
  3776. case 0x06:
  3777. case 0x07:
  3778. case 0x08:
  3779. case 0x09:
  3780. case 0x0A:
  3781. case 0x0B:
  3782. case 0x0C:
  3783. case 0x0D:
  3784. case 0x0E:
  3785. case 0x0F:
  3786. case 0x10:
  3787. case 0x11:
  3788. case 0x12:
  3789. case 0x13:
  3790. case 0x14:
  3791. case 0x15:
  3792. case 0x16:
  3793. case 0x17:
  3794. case 0x18:
  3795. case 0x19:
  3796. case 0x1A:
  3797. case 0x1B:
  3798. case 0x1C:
  3799. case 0x1D:
  3800. case 0x1E:
  3801. case 0x1F:
  3802. case 0x20:
  3803. case 0x21:
  3804. case 0x22:
  3805. case 0x23:
  3806. case 0x24:
  3807. case 0x25:
  3808. case 0x26:
  3809. case 0x27:
  3810. case 0x28:
  3811. case 0x29:
  3812. case 0x2A:
  3813. case 0x2B:
  3814. case 0x2C:
  3815. case 0x2D:
  3816. case 0x2E:
  3817. case 0x2F:
  3818. case 0x30:
  3819. case 0x31:
  3820. case 0x32:
  3821. case 0x33:
  3822. case 0x34:
  3823. case 0x35:
  3824. case 0x36:
  3825. case 0x37:
  3826. case 0x38:
  3827. case 0x39:
  3828. case 0x3A:
  3829. case 0x3B:
  3830. case 0x3C:
  3831. case 0x3D:
  3832. case 0x3E:
  3833. case 0x3F:
  3834. case 0x40:
  3835. case 0x41:
  3836. case 0x42:
  3837. case 0x43:
  3838. case 0x44:
  3839. case 0x45:
  3840. case 0x46:
  3841. case 0x47:
  3842. case 0x48:
  3843. case 0x49:
  3844. case 0x4A:
  3845. case 0x4B:
  3846. case 0x4C:
  3847. case 0x4D:
  3848. case 0x4E:
  3849. case 0x4F:
  3850. case 0x50:
  3851. case 0x51:
  3852. case 0x52:
  3853. case 0x53:
  3854. case 0x54:
  3855. case 0x55:
  3856. case 0x56:
  3857. case 0x57:
  3858. case 0x58:
  3859. case 0x59:
  3860. case 0x5A:
  3861. case 0x5B:
  3862. case 0x5C:
  3863. case 0x5D:
  3864. case 0x5E:
  3865. case 0x5F:
  3866. case 0x60:
  3867. case 0x61:
  3868. case 0x62:
  3869. case 0x63:
  3870. case 0x64:
  3871. case 0x65:
  3872. case 0x66:
  3873. case 0x67:
  3874. case 0x68:
  3875. case 0x69:
  3876. case 0x6A:
  3877. case 0x6B:
  3878. case 0x6C:
  3879. case 0x6D:
  3880. case 0x6E:
  3881. case 0x6F:
  3882. case 0x70:
  3883. case 0x71:
  3884. case 0x72:
  3885. case 0x73:
  3886. case 0x74:
  3887. case 0x75:
  3888. case 0x76:
  3889. case 0x77:
  3890. case 0x78:
  3891. case 0x79:
  3892. case 0x7A:
  3893. case 0x7B:
  3894. case 0x7C:
  3895. case 0x7D:
  3896. case 0x7E:
  3897. case 0x7F:
  3898. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  3899. // fixmap
  3900. case 0x80:
  3901. case 0x81:
  3902. case 0x82:
  3903. case 0x83:
  3904. case 0x84:
  3905. case 0x85:
  3906. case 0x86:
  3907. case 0x87:
  3908. case 0x88:
  3909. case 0x89:
  3910. case 0x8A:
  3911. case 0x8B:
  3912. case 0x8C:
  3913. case 0x8D:
  3914. case 0x8E:
  3915. case 0x8F:
  3916. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  3917. // fixarray
  3918. case 0x90:
  3919. case 0x91:
  3920. case 0x92:
  3921. case 0x93:
  3922. case 0x94:
  3923. case 0x95:
  3924. case 0x96:
  3925. case 0x97:
  3926. case 0x98:
  3927. case 0x99:
  3928. case 0x9A:
  3929. case 0x9B:
  3930. case 0x9C:
  3931. case 0x9D:
  3932. case 0x9E:
  3933. case 0x9F:
  3934. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  3935. // fixstr
  3936. case 0xA0:
  3937. case 0xA1:
  3938. case 0xA2:
  3939. case 0xA3:
  3940. case 0xA4:
  3941. case 0xA5:
  3942. case 0xA6:
  3943. case 0xA7:
  3944. case 0xA8:
  3945. case 0xA9:
  3946. case 0xAA:
  3947. case 0xAB:
  3948. case 0xAC:
  3949. case 0xAD:
  3950. case 0xAE:
  3951. case 0xAF:
  3952. case 0xB0:
  3953. case 0xB1:
  3954. case 0xB2:
  3955. case 0xB3:
  3956. case 0xB4:
  3957. case 0xB5:
  3958. case 0xB6:
  3959. case 0xB7:
  3960. case 0xB8:
  3961. case 0xB9:
  3962. case 0xBA:
  3963. case 0xBB:
  3964. case 0xBC:
  3965. case 0xBD:
  3966. case 0xBE:
  3967. case 0xBF:
  3968. {
  3969. string_t s;
  3970. return get_msgpack_string(s) and sax->string(s);
  3971. }
  3972. case 0xC0: // nil
  3973. return sax->null();
  3974. case 0xC2: // false
  3975. return sax->boolean(false);
  3976. case 0xC3: // true
  3977. return sax->boolean(true);
  3978. case 0xCA: // float 32
  3979. {
  3980. float number;
  3981. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  3982. }
  3983. case 0xCB: // float 64
  3984. {
  3985. double number;
  3986. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  3987. }
  3988. case 0xCC: // uint 8
  3989. {
  3990. std::uint8_t number;
  3991. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  3992. }
  3993. case 0xCD: // uint 16
  3994. {
  3995. std::uint16_t number;
  3996. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  3997. }
  3998. case 0xCE: // uint 32
  3999. {
  4000. std::uint32_t number;
  4001. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  4002. }
  4003. case 0xCF: // uint 64
  4004. {
  4005. std::uint64_t number;
  4006. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  4007. }
  4008. case 0xD0: // int 8
  4009. {
  4010. std::int8_t number;
  4011. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  4012. }
  4013. case 0xD1: // int 16
  4014. {
  4015. std::int16_t number;
  4016. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  4017. }
  4018. case 0xD2: // int 32
  4019. {
  4020. std::int32_t number;
  4021. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  4022. }
  4023. case 0xD3: // int 64
  4024. {
  4025. std::int64_t number;
  4026. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  4027. }
  4028. case 0xD9: // str 8
  4029. case 0xDA: // str 16
  4030. case 0xDB: // str 32
  4031. {
  4032. string_t s;
  4033. return get_msgpack_string(s) and sax->string(s);
  4034. }
  4035. case 0xDC: // array 16
  4036. {
  4037. std::uint16_t len;
  4038. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  4039. }
  4040. case 0xDD: // array 32
  4041. {
  4042. std::uint32_t len;
  4043. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  4044. }
  4045. case 0xDE: // map 16
  4046. {
  4047. std::uint16_t len;
  4048. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  4049. }
  4050. case 0xDF: // map 32
  4051. {
  4052. std::uint32_t len;
  4053. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  4054. }
  4055. // negative fixint
  4056. case 0xE0:
  4057. case 0xE1:
  4058. case 0xE2:
  4059. case 0xE3:
  4060. case 0xE4:
  4061. case 0xE5:
  4062. case 0xE6:
  4063. case 0xE7:
  4064. case 0xE8:
  4065. case 0xE9:
  4066. case 0xEA:
  4067. case 0xEB:
  4068. case 0xEC:
  4069. case 0xED:
  4070. case 0xEE:
  4071. case 0xEF:
  4072. case 0xF0:
  4073. case 0xF1:
  4074. case 0xF2:
  4075. case 0xF3:
  4076. case 0xF4:
  4077. case 0xF5:
  4078. case 0xF6:
  4079. case 0xF7:
  4080. case 0xF8:
  4081. case 0xF9:
  4082. case 0xFA:
  4083. case 0xFB:
  4084. case 0xFC:
  4085. case 0xFD:
  4086. case 0xFE:
  4087. case 0xFF:
  4088. return sax->number_integer(static_cast<std::int8_t>(current));
  4089. default: // anything else
  4090. {
  4091. auto last_token = get_token_string();
  4092. 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")));
  4093. }
  4094. }
  4095. }
  4096. /*!
  4097. @brief reads a MessagePack string
  4098. This function first reads starting bytes to determine the expected
  4099. string length and then copies this number of bytes into a string.
  4100. @param[out] result created string
  4101. @return whether string creation completed
  4102. */
  4103. bool get_msgpack_string(string_t& result)
  4104. {
  4105. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "string")))
  4106. {
  4107. return false;
  4108. }
  4109. switch (current)
  4110. {
  4111. // fixstr
  4112. case 0xA0:
  4113. case 0xA1:
  4114. case 0xA2:
  4115. case 0xA3:
  4116. case 0xA4:
  4117. case 0xA5:
  4118. case 0xA6:
  4119. case 0xA7:
  4120. case 0xA8:
  4121. case 0xA9:
  4122. case 0xAA:
  4123. case 0xAB:
  4124. case 0xAC:
  4125. case 0xAD:
  4126. case 0xAE:
  4127. case 0xAF:
  4128. case 0xB0:
  4129. case 0xB1:
  4130. case 0xB2:
  4131. case 0xB3:
  4132. case 0xB4:
  4133. case 0xB5:
  4134. case 0xB6:
  4135. case 0xB7:
  4136. case 0xB8:
  4137. case 0xB9:
  4138. case 0xBA:
  4139. case 0xBB:
  4140. case 0xBC:
  4141. case 0xBD:
  4142. case 0xBE:
  4143. case 0xBF:
  4144. {
  4145. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  4146. }
  4147. case 0xD9: // str 8
  4148. {
  4149. std::uint8_t len;
  4150. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  4151. }
  4152. case 0xDA: // str 16
  4153. {
  4154. std::uint16_t len;
  4155. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  4156. }
  4157. case 0xDB: // str 32
  4158. {
  4159. std::uint32_t len;
  4160. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  4161. }
  4162. default:
  4163. {
  4164. auto last_token = get_token_string();
  4165. 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")));
  4166. }
  4167. }
  4168. }
  4169. /*!
  4170. @param[in] len the length of the array
  4171. @return whether array creation completed
  4172. */
  4173. bool get_msgpack_array(const std::size_t len)
  4174. {
  4175. if (JSON_UNLIKELY(not sax->start_array(len)))
  4176. {
  4177. return false;
  4178. }
  4179. for (std::size_t i = 0; i < len; ++i)
  4180. {
  4181. if (JSON_UNLIKELY(not parse_msgpack_internal()))
  4182. {
  4183. return false;
  4184. }
  4185. }
  4186. return sax->end_array();
  4187. }
  4188. /*!
  4189. @param[in] len the length of the object
  4190. @return whether object creation completed
  4191. */
  4192. bool get_msgpack_object(const std::size_t len)
  4193. {
  4194. if (JSON_UNLIKELY(not sax->start_object(len)))
  4195. {
  4196. return false;
  4197. }
  4198. string_t key;
  4199. for (std::size_t i = 0; i < len; ++i)
  4200. {
  4201. get();
  4202. if (JSON_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
  4203. {
  4204. return false;
  4205. }
  4206. if (JSON_UNLIKELY(not parse_msgpack_internal()))
  4207. {
  4208. return false;
  4209. }
  4210. key.clear();
  4211. }
  4212. return sax->end_object();
  4213. }
  4214. ////////////
  4215. // UBJSON //
  4216. ////////////
  4217. /*!
  4218. @param[in] get_char whether a new character should be retrieved from the
  4219. input (true, default) or whether the last read
  4220. character should be considered instead
  4221. @return whether a valid UBJSON value was passed to the SAX parser
  4222. */
  4223. bool parse_ubjson_internal(const bool get_char = true)
  4224. {
  4225. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  4226. }
  4227. /*!
  4228. @brief reads a UBJSON string
  4229. This function is either called after reading the 'S' byte explicitly
  4230. indicating a string, or in case of an object key where the 'S' byte can be
  4231. left out.
  4232. @param[out] result created string
  4233. @param[in] get_char whether a new character should be retrieved from the
  4234. input (true, default) or whether the last read
  4235. character should be considered instead
  4236. @return whether string creation completed
  4237. */
  4238. bool get_ubjson_string(string_t& result, const bool get_char = true)
  4239. {
  4240. if (get_char)
  4241. {
  4242. get(); // TODO(niels): may we ignore N here?
  4243. }
  4244. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  4245. {
  4246. return false;
  4247. }
  4248. switch (current)
  4249. {
  4250. case 'U':
  4251. {
  4252. std::uint8_t len;
  4253. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  4254. }
  4255. case 'i':
  4256. {
  4257. std::int8_t len;
  4258. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  4259. }
  4260. case 'I':
  4261. {
  4262. std::int16_t len;
  4263. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  4264. }
  4265. case 'l':
  4266. {
  4267. std::int32_t len;
  4268. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  4269. }
  4270. case 'L':
  4271. {
  4272. std::int64_t len;
  4273. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  4274. }
  4275. default:
  4276. auto last_token = get_token_string();
  4277. 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")));
  4278. }
  4279. }
  4280. /*!
  4281. @param[out] result determined size
  4282. @return whether size determination completed
  4283. */
  4284. bool get_ubjson_size_value(std::size_t& result)
  4285. {
  4286. switch (get_ignore_noop())
  4287. {
  4288. case 'U':
  4289. {
  4290. std::uint8_t number;
  4291. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  4292. {
  4293. return false;
  4294. }
  4295. result = static_cast<std::size_t>(number);
  4296. return true;
  4297. }
  4298. case 'i':
  4299. {
  4300. std::int8_t number;
  4301. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  4302. {
  4303. return false;
  4304. }
  4305. result = static_cast<std::size_t>(number);
  4306. return true;
  4307. }
  4308. case 'I':
  4309. {
  4310. std::int16_t number;
  4311. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  4312. {
  4313. return false;
  4314. }
  4315. result = static_cast<std::size_t>(number);
  4316. return true;
  4317. }
  4318. case 'l':
  4319. {
  4320. std::int32_t number;
  4321. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  4322. {
  4323. return false;
  4324. }
  4325. result = static_cast<std::size_t>(number);
  4326. return true;
  4327. }
  4328. case 'L':
  4329. {
  4330. std::int64_t number;
  4331. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  4332. {
  4333. return false;
  4334. }
  4335. result = static_cast<std::size_t>(number);
  4336. return true;
  4337. }
  4338. default:
  4339. {
  4340. auto last_token = get_token_string();
  4341. 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")));
  4342. }
  4343. }
  4344. }
  4345. /*!
  4346. @brief determine the type and size for a container
  4347. In the optimized UBJSON format, a type and a size can be provided to allow
  4348. for a more compact representation.
  4349. @param[out] result pair of the size and the type
  4350. @return whether pair creation completed
  4351. */
  4352. bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
  4353. {
  4354. result.first = string_t::npos; // size
  4355. result.second = 0; // type
  4356. get_ignore_noop();
  4357. if (current == '$')
  4358. {
  4359. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  4360. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "type")))
  4361. {
  4362. return false;
  4363. }
  4364. get_ignore_noop();
  4365. if (JSON_UNLIKELY(current != '#'))
  4366. {
  4367. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  4368. {
  4369. return false;
  4370. }
  4371. auto last_token = get_token_string();
  4372. 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")));
  4373. }
  4374. return get_ubjson_size_value(result.first);
  4375. }
  4376. if (current == '#')
  4377. {
  4378. return get_ubjson_size_value(result.first);
  4379. }
  4380. return true;
  4381. }
  4382. /*!
  4383. @param prefix the previously read or set type prefix
  4384. @return whether value creation completed
  4385. */
  4386. bool get_ubjson_value(const int prefix)
  4387. {
  4388. switch (prefix)
  4389. {
  4390. case std::char_traits<char>::eof(): // EOF
  4391. return unexpect_eof(input_format_t::ubjson, "value");
  4392. case 'T': // true
  4393. return sax->boolean(true);
  4394. case 'F': // false
  4395. return sax->boolean(false);
  4396. case 'Z': // null
  4397. return sax->null();
  4398. case 'U':
  4399. {
  4400. std::uint8_t number;
  4401. return get_number(input_format_t::ubjson, number) and sax->number_unsigned(number);
  4402. }
  4403. case 'i':
  4404. {
  4405. std::int8_t number;
  4406. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  4407. }
  4408. case 'I':
  4409. {
  4410. std::int16_t number;
  4411. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  4412. }
  4413. case 'l':
  4414. {
  4415. std::int32_t number;
  4416. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  4417. }
  4418. case 'L':
  4419. {
  4420. std::int64_t number;
  4421. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  4422. }
  4423. case 'd':
  4424. {
  4425. float number;
  4426. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  4427. }
  4428. case 'D':
  4429. {
  4430. double number;
  4431. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  4432. }
  4433. case 'C': // char
  4434. {
  4435. get();
  4436. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "char")))
  4437. {
  4438. return false;
  4439. }
  4440. if (JSON_UNLIKELY(current > 127))
  4441. {
  4442. auto last_token = get_token_string();
  4443. 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")));
  4444. }
  4445. string_t s(1, static_cast<char>(current));
  4446. return sax->string(s);
  4447. }
  4448. case 'S': // string
  4449. {
  4450. string_t s;
  4451. return get_ubjson_string(s) and sax->string(s);
  4452. }
  4453. case '[': // array
  4454. return get_ubjson_array();
  4455. case '{': // object
  4456. return get_ubjson_object();
  4457. default: // anything else
  4458. {
  4459. auto last_token = get_token_string();
  4460. 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")));
  4461. }
  4462. }
  4463. }
  4464. /*!
  4465. @return whether array creation completed
  4466. */
  4467. bool get_ubjson_array()
  4468. {
  4469. std::pair<std::size_t, int> size_and_type;
  4470. if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  4471. {
  4472. return false;
  4473. }
  4474. if (size_and_type.first != string_t::npos)
  4475. {
  4476. if (JSON_UNLIKELY(not sax->start_array(size_and_type.first)))
  4477. {
  4478. return false;
  4479. }
  4480. if (size_and_type.second != 0)
  4481. {
  4482. if (size_and_type.second != 'N')
  4483. {
  4484. for (std::size_t i = 0; i < size_and_type.first; ++i)
  4485. {
  4486. if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  4487. {
  4488. return false;
  4489. }
  4490. }
  4491. }
  4492. }
  4493. else
  4494. {
  4495. for (std::size_t i = 0; i < size_and_type.first; ++i)
  4496. {
  4497. if (JSON_UNLIKELY(not parse_ubjson_internal()))
  4498. {
  4499. return false;
  4500. }
  4501. }
  4502. }
  4503. }
  4504. else
  4505. {
  4506. if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
  4507. {
  4508. return false;
  4509. }
  4510. while (current != ']')
  4511. {
  4512. if (JSON_UNLIKELY(not parse_ubjson_internal(false)))
  4513. {
  4514. return false;
  4515. }
  4516. get_ignore_noop();
  4517. }
  4518. }
  4519. return sax->end_array();
  4520. }
  4521. /*!
  4522. @return whether object creation completed
  4523. */
  4524. bool get_ubjson_object()
  4525. {
  4526. std::pair<std::size_t, int> size_and_type;
  4527. if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  4528. {
  4529. return false;
  4530. }
  4531. string_t key;
  4532. if (size_and_type.first != string_t::npos)
  4533. {
  4534. if (JSON_UNLIKELY(not sax->start_object(size_and_type.first)))
  4535. {
  4536. return false;
  4537. }
  4538. if (size_and_type.second != 0)
  4539. {
  4540. for (std::size_t i = 0; i < size_and_type.first; ++i)
  4541. {
  4542. if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  4543. {
  4544. return false;
  4545. }
  4546. if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  4547. {
  4548. return false;
  4549. }
  4550. key.clear();
  4551. }
  4552. }
  4553. else
  4554. {
  4555. for (std::size_t i = 0; i < size_and_type.first; ++i)
  4556. {
  4557. if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  4558. {
  4559. return false;
  4560. }
  4561. if (JSON_UNLIKELY(not parse_ubjson_internal()))
  4562. {
  4563. return false;
  4564. }
  4565. key.clear();
  4566. }
  4567. }
  4568. }
  4569. else
  4570. {
  4571. if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
  4572. {
  4573. return false;
  4574. }
  4575. while (current != '}')
  4576. {
  4577. if (JSON_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
  4578. {
  4579. return false;
  4580. }
  4581. if (JSON_UNLIKELY(not parse_ubjson_internal()))
  4582. {
  4583. return false;
  4584. }
  4585. get_ignore_noop();
  4586. key.clear();
  4587. }
  4588. }
  4589. return sax->end_object();
  4590. }
  4591. ///////////////////////
  4592. // Utility functions //
  4593. ///////////////////////
  4594. /*!
  4595. @brief get next character from the input
  4596. This function provides the interface to the used input adapter. It does
  4597. not throw in case the input reached EOF, but returns a -'ve valued
  4598. `std::char_traits<char>::eof()` in that case.
  4599. @return character read from the input
  4600. */
  4601. int get()
  4602. {
  4603. ++chars_read;
  4604. return current = ia->get_character();
  4605. }
  4606. /*!
  4607. @return character read from the input after ignoring all 'N' entries
  4608. */
  4609. int get_ignore_noop()
  4610. {
  4611. do
  4612. {
  4613. get();
  4614. }
  4615. while (current == 'N');
  4616. return current;
  4617. }
  4618. /*
  4619. @brief read a number from the input
  4620. @tparam NumberType the type of the number
  4621. @param[in] format the current format (for diagnostics)
  4622. @param[out] result number of type @a NumberType
  4623. @return whether conversion completed
  4624. @note This function needs to respect the system's endianess, because
  4625. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  4626. (big endian) and therefore need reordering on little endian systems.
  4627. */
  4628. template<typename NumberType, bool InputIsLittleEndian = false>
  4629. bool get_number(const input_format_t format, NumberType& result)
  4630. {
  4631. // step 1: read input into array with system's byte order
  4632. std::array<std::uint8_t, sizeof(NumberType)> vec;
  4633. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  4634. {
  4635. get();
  4636. if (JSON_UNLIKELY(not unexpect_eof(format, "number")))
  4637. {
  4638. return false;
  4639. }
  4640. // reverse byte order prior to conversion if necessary
  4641. if (is_little_endian != InputIsLittleEndian)
  4642. {
  4643. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  4644. }
  4645. else
  4646. {
  4647. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  4648. }
  4649. }
  4650. // step 2: convert array into number of type T and return
  4651. std::memcpy(&result, vec.data(), sizeof(NumberType));
  4652. return true;
  4653. }
  4654. /*!
  4655. @brief create a string by reading characters from the input
  4656. @tparam NumberType the type of the number
  4657. @param[in] format the current format (for diagnostics)
  4658. @param[in] len number of characters to read
  4659. @param[out] result string created by reading @a len bytes
  4660. @return whether string creation completed
  4661. @note We can not reserve @a len bytes for the result, because @a len
  4662. may be too large. Usually, @ref unexpect_eof() detects the end of
  4663. the input before we run out of string memory.
  4664. */
  4665. template<typename NumberType>
  4666. bool get_string(const input_format_t format,
  4667. const NumberType len,
  4668. string_t& result)
  4669. {
  4670. bool success = true;
  4671. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  4672. {
  4673. get();
  4674. if (JSON_UNLIKELY(not unexpect_eof(format, "string")))
  4675. {
  4676. success = false;
  4677. }
  4678. return static_cast<char>(current);
  4679. });
  4680. return success;
  4681. }
  4682. /*!
  4683. @param[in] format the current format (for diagnostics)
  4684. @param[in] context further context information (for diagnostics)
  4685. @return whether the last read character is not EOF
  4686. */
  4687. bool unexpect_eof(const input_format_t format, const char* context) const
  4688. {
  4689. if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
  4690. {
  4691. return sax->parse_error(chars_read, "<end of file>",
  4692. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
  4693. }
  4694. return true;
  4695. }
  4696. /*!
  4697. @return a string representation of the last read byte
  4698. */
  4699. std::string get_token_string() const
  4700. {
  4701. std::array<char, 3> cr{{}};
  4702. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current));
  4703. return std::string{cr.data()};
  4704. }
  4705. /*!
  4706. @param[in] format the current format
  4707. @param[in] detail a detailed error message
  4708. @param[in] context further contect information
  4709. @return a message string to use in the parse_error exceptions
  4710. */
  4711. std::string exception_message(const input_format_t format,
  4712. const std::string& detail,
  4713. const std::string& context) const
  4714. {
  4715. std::string error_msg = "syntax error while parsing ";
  4716. switch (format)
  4717. {
  4718. case input_format_t::cbor:
  4719. error_msg += "CBOR";
  4720. break;
  4721. case input_format_t::msgpack:
  4722. error_msg += "MessagePack";
  4723. break;
  4724. case input_format_t::ubjson:
  4725. error_msg += "UBJSON";
  4726. break;
  4727. case input_format_t::bson:
  4728. error_msg += "BSON";
  4729. break;
  4730. default: // LCOV_EXCL_LINE
  4731. assert(false); // LCOV_EXCL_LINE
  4732. }
  4733. return error_msg + " " + context + ": " + detail;
  4734. }
  4735. private:
  4736. /// input adapter
  4737. input_adapter_t ia = nullptr;
  4738. /// the current character
  4739. int current = std::char_traits<char>::eof();
  4740. /// the number of characters read
  4741. std::size_t chars_read = 0;
  4742. /// whether we can assume little endianess
  4743. const bool is_little_endian = little_endianess();
  4744. /// the SAX parser
  4745. json_sax_t* sax = nullptr;
  4746. };
  4747. } // namespace detail
  4748. } // namespace nlohmann
  4749. // #include <nlohmann/detail/input/input_adapters.hpp>
  4750. // #include <nlohmann/detail/input/lexer.hpp>
  4751. #include <array> // array
  4752. #include <clocale> // localeconv
  4753. #include <cstddef> // size_t
  4754. #include <cstdio> // snprintf
  4755. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  4756. #include <initializer_list> // initializer_list
  4757. #include <string> // char_traits, string
  4758. #include <utility> // move
  4759. #include <vector> // vector
  4760. // #include <nlohmann/detail/input/input_adapters.hpp>
  4761. // #include <nlohmann/detail/input/position_t.hpp>
  4762. // #include <nlohmann/detail/macro_scope.hpp>
  4763. namespace nlohmann
  4764. {
  4765. namespace detail
  4766. {
  4767. ///////////
  4768. // lexer //
  4769. ///////////
  4770. /*!
  4771. @brief lexical analysis
  4772. This class organizes the lexical analysis during JSON deserialization.
  4773. */
  4774. template<typename BasicJsonType>
  4775. class lexer
  4776. {
  4777. using number_integer_t = typename BasicJsonType::number_integer_t;
  4778. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4779. using number_float_t = typename BasicJsonType::number_float_t;
  4780. using string_t = typename BasicJsonType::string_t;
  4781. public:
  4782. /// token types for the parser
  4783. enum class token_type
  4784. {
  4785. uninitialized, ///< indicating the scanner is uninitialized
  4786. literal_true, ///< the `true` literal
  4787. literal_false, ///< the `false` literal
  4788. literal_null, ///< the `null` literal
  4789. value_string, ///< a string -- use get_string() for actual value
  4790. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  4791. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  4792. value_float, ///< an floating point number -- use get_number_float() for actual value
  4793. begin_array, ///< the character for array begin `[`
  4794. begin_object, ///< the character for object begin `{`
  4795. end_array, ///< the character for array end `]`
  4796. end_object, ///< the character for object end `}`
  4797. name_separator, ///< the name separator `:`
  4798. value_separator, ///< the value separator `,`
  4799. parse_error, ///< indicating a parse error
  4800. end_of_input, ///< indicating the end of the input buffer
  4801. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  4802. };
  4803. /// return name of values of type token_type (only used for errors)
  4804. static const char* token_type_name(const token_type t) noexcept
  4805. {
  4806. switch (t)
  4807. {
  4808. case token_type::uninitialized:
  4809. return "<uninitialized>";
  4810. case token_type::literal_true:
  4811. return "true literal";
  4812. case token_type::literal_false:
  4813. return "false literal";
  4814. case token_type::literal_null:
  4815. return "null literal";
  4816. case token_type::value_string:
  4817. return "string literal";
  4818. case lexer::token_type::value_unsigned:
  4819. case lexer::token_type::value_integer:
  4820. case lexer::token_type::value_float:
  4821. return "number literal";
  4822. case token_type::begin_array:
  4823. return "'['";
  4824. case token_type::begin_object:
  4825. return "'{'";
  4826. case token_type::end_array:
  4827. return "']'";
  4828. case token_type::end_object:
  4829. return "'}'";
  4830. case token_type::name_separator:
  4831. return "':'";
  4832. case token_type::value_separator:
  4833. return "','";
  4834. case token_type::parse_error:
  4835. return "<parse error>";
  4836. case token_type::end_of_input:
  4837. return "end of input";
  4838. case token_type::literal_or_value:
  4839. return "'[', '{', or a literal";
  4840. // LCOV_EXCL_START
  4841. default: // catch non-enum values
  4842. return "unknown token";
  4843. // LCOV_EXCL_STOP
  4844. }
  4845. }
  4846. explicit lexer(detail::input_adapter_t&& adapter)
  4847. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  4848. // delete because of pointer members
  4849. lexer(const lexer&) = delete;
  4850. lexer(lexer&&) = delete;
  4851. lexer& operator=(lexer&) = delete;
  4852. lexer& operator=(lexer&&) = delete;
  4853. ~lexer() = default;
  4854. private:
  4855. /////////////////////
  4856. // locales
  4857. /////////////////////
  4858. /// return the locale-dependent decimal point
  4859. static char get_decimal_point() noexcept
  4860. {
  4861. const auto loc = localeconv();
  4862. assert(loc != nullptr);
  4863. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  4864. }
  4865. /////////////////////
  4866. // scan functions
  4867. /////////////////////
  4868. /*!
  4869. @brief get codepoint from 4 hex characters following `\u`
  4870. For input "\u c1 c2 c3 c4" the codepoint is:
  4871. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  4872. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  4873. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  4874. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  4875. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  4876. between the ASCII value of the character and the desired integer value.
  4877. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  4878. non-hex character)
  4879. */
  4880. int get_codepoint()
  4881. {
  4882. // this function only makes sense after reading `\u`
  4883. assert(current == 'u');
  4884. int codepoint = 0;
  4885. const auto factors = { 12u, 8u, 4u, 0u };
  4886. for (const auto factor : factors)
  4887. {
  4888. get();
  4889. if (current >= '0' and current <= '9')
  4890. {
  4891. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  4892. }
  4893. else if (current >= 'A' and current <= 'F')
  4894. {
  4895. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  4896. }
  4897. else if (current >= 'a' and current <= 'f')
  4898. {
  4899. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  4900. }
  4901. else
  4902. {
  4903. return -1;
  4904. }
  4905. }
  4906. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  4907. return codepoint;
  4908. }
  4909. /*!
  4910. @brief check if the next byte(s) are inside a given range
  4911. Adds the current byte and, for each passed range, reads a new byte and
  4912. checks if it is inside the range. If a violation was detected, set up an
  4913. error message and return false. Otherwise, return true.
  4914. @param[in] ranges list of integers; interpreted as list of pairs of
  4915. inclusive lower and upper bound, respectively
  4916. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  4917. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  4918. @return true if and only if no range violation was detected
  4919. */
  4920. bool next_byte_in_range(std::initializer_list<int> ranges)
  4921. {
  4922. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  4923. add(current);
  4924. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  4925. {
  4926. get();
  4927. if (JSON_LIKELY(*range <= current and current <= *(++range)))
  4928. {
  4929. add(current);
  4930. }
  4931. else
  4932. {
  4933. error_message = "invalid string: ill-formed UTF-8 byte";
  4934. return false;
  4935. }
  4936. }
  4937. return true;
  4938. }
  4939. /*!
  4940. @brief scan a string literal
  4941. This function scans a string according to Sect. 7 of RFC 7159. While
  4942. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  4943. function returns successfully, token_buffer is *not* null-terminated (as it
  4944. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  4945. string.
  4946. @return token_type::value_string if string could be successfully scanned,
  4947. token_type::parse_error otherwise
  4948. @note In case of errors, variable error_message contains a textual
  4949. description.
  4950. */
  4951. token_type scan_string()
  4952. {
  4953. // reset token_buffer (ignore opening quote)
  4954. reset();
  4955. // we entered the function by reading an open quote
  4956. assert(current == '\"');
  4957. while (true)
  4958. {
  4959. // get next character
  4960. switch (get())
  4961. {
  4962. // end of file while parsing string
  4963. case std::char_traits<char>::eof():
  4964. {
  4965. error_message = "invalid string: missing closing quote";
  4966. return token_type::parse_error;
  4967. }
  4968. // closing quote
  4969. case '\"':
  4970. {
  4971. return token_type::value_string;
  4972. }
  4973. // escapes
  4974. case '\\':
  4975. {
  4976. switch (get())
  4977. {
  4978. // quotation mark
  4979. case '\"':
  4980. add('\"');
  4981. break;
  4982. // reverse solidus
  4983. case '\\':
  4984. add('\\');
  4985. break;
  4986. // solidus
  4987. case '/':
  4988. add('/');
  4989. break;
  4990. // backspace
  4991. case 'b':
  4992. add('\b');
  4993. break;
  4994. // form feed
  4995. case 'f':
  4996. add('\f');
  4997. break;
  4998. // line feed
  4999. case 'n':
  5000. add('\n');
  5001. break;
  5002. // carriage return
  5003. case 'r':
  5004. add('\r');
  5005. break;
  5006. // tab
  5007. case 't':
  5008. add('\t');
  5009. break;
  5010. // unicode escapes
  5011. case 'u':
  5012. {
  5013. const int codepoint1 = get_codepoint();
  5014. int codepoint = codepoint1; // start with codepoint1
  5015. if (JSON_UNLIKELY(codepoint1 == -1))
  5016. {
  5017. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  5018. return token_type::parse_error;
  5019. }
  5020. // check if code point is a high surrogate
  5021. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  5022. {
  5023. // expect next \uxxxx entry
  5024. if (JSON_LIKELY(get() == '\\' and get() == 'u'))
  5025. {
  5026. const int codepoint2 = get_codepoint();
  5027. if (JSON_UNLIKELY(codepoint2 == -1))
  5028. {
  5029. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  5030. return token_type::parse_error;
  5031. }
  5032. // check if codepoint2 is a low surrogate
  5033. if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  5034. {
  5035. // overwrite codepoint
  5036. codepoint = static_cast<int>(
  5037. // high surrogate occupies the most significant 22 bits
  5038. (static_cast<unsigned int>(codepoint1) << 10u)
  5039. // low surrogate occupies the least significant 15 bits
  5040. + static_cast<unsigned int>(codepoint2)
  5041. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  5042. // in the result so we have to subtract with:
  5043. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  5044. - 0x35FDC00u);
  5045. }
  5046. else
  5047. {
  5048. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  5049. return token_type::parse_error;
  5050. }
  5051. }
  5052. else
  5053. {
  5054. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  5055. return token_type::parse_error;
  5056. }
  5057. }
  5058. else
  5059. {
  5060. if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  5061. {
  5062. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  5063. return token_type::parse_error;
  5064. }
  5065. }
  5066. // result of the above calculation yields a proper codepoint
  5067. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  5068. // translate codepoint into bytes
  5069. if (codepoint < 0x80)
  5070. {
  5071. // 1-byte characters: 0xxxxxxx (ASCII)
  5072. add(codepoint);
  5073. }
  5074. else if (codepoint <= 0x7FF)
  5075. {
  5076. // 2-byte characters: 110xxxxx 10xxxxxx
  5077. add(static_cast<int>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  5078. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  5079. }
  5080. else if (codepoint <= 0xFFFF)
  5081. {
  5082. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  5083. add(static_cast<int>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  5084. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  5085. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  5086. }
  5087. else
  5088. {
  5089. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  5090. add(static_cast<int>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  5091. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  5092. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  5093. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  5094. }
  5095. break;
  5096. }
  5097. // other characters after escape
  5098. default:
  5099. error_message = "invalid string: forbidden character after backslash";
  5100. return token_type::parse_error;
  5101. }
  5102. break;
  5103. }
  5104. // invalid control characters
  5105. case 0x00:
  5106. {
  5107. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  5108. return token_type::parse_error;
  5109. }
  5110. case 0x01:
  5111. {
  5112. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  5113. return token_type::parse_error;
  5114. }
  5115. case 0x02:
  5116. {
  5117. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  5118. return token_type::parse_error;
  5119. }
  5120. case 0x03:
  5121. {
  5122. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  5123. return token_type::parse_error;
  5124. }
  5125. case 0x04:
  5126. {
  5127. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  5128. return token_type::parse_error;
  5129. }
  5130. case 0x05:
  5131. {
  5132. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  5133. return token_type::parse_error;
  5134. }
  5135. case 0x06:
  5136. {
  5137. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  5138. return token_type::parse_error;
  5139. }
  5140. case 0x07:
  5141. {
  5142. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  5143. return token_type::parse_error;
  5144. }
  5145. case 0x08:
  5146. {
  5147. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  5148. return token_type::parse_error;
  5149. }
  5150. case 0x09:
  5151. {
  5152. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  5153. return token_type::parse_error;
  5154. }
  5155. case 0x0A:
  5156. {
  5157. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  5158. return token_type::parse_error;
  5159. }
  5160. case 0x0B:
  5161. {
  5162. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  5163. return token_type::parse_error;
  5164. }
  5165. case 0x0C:
  5166. {
  5167. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  5168. return token_type::parse_error;
  5169. }
  5170. case 0x0D:
  5171. {
  5172. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  5173. return token_type::parse_error;
  5174. }
  5175. case 0x0E:
  5176. {
  5177. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  5178. return token_type::parse_error;
  5179. }
  5180. case 0x0F:
  5181. {
  5182. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  5183. return token_type::parse_error;
  5184. }
  5185. case 0x10:
  5186. {
  5187. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  5188. return token_type::parse_error;
  5189. }
  5190. case 0x11:
  5191. {
  5192. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  5193. return token_type::parse_error;
  5194. }
  5195. case 0x12:
  5196. {
  5197. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  5198. return token_type::parse_error;
  5199. }
  5200. case 0x13:
  5201. {
  5202. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  5203. return token_type::parse_error;
  5204. }
  5205. case 0x14:
  5206. {
  5207. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  5208. return token_type::parse_error;
  5209. }
  5210. case 0x15:
  5211. {
  5212. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  5213. return token_type::parse_error;
  5214. }
  5215. case 0x16:
  5216. {
  5217. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  5218. return token_type::parse_error;
  5219. }
  5220. case 0x17:
  5221. {
  5222. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  5223. return token_type::parse_error;
  5224. }
  5225. case 0x18:
  5226. {
  5227. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  5228. return token_type::parse_error;
  5229. }
  5230. case 0x19:
  5231. {
  5232. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  5233. return token_type::parse_error;
  5234. }
  5235. case 0x1A:
  5236. {
  5237. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  5238. return token_type::parse_error;
  5239. }
  5240. case 0x1B:
  5241. {
  5242. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  5243. return token_type::parse_error;
  5244. }
  5245. case 0x1C:
  5246. {
  5247. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  5248. return token_type::parse_error;
  5249. }
  5250. case 0x1D:
  5251. {
  5252. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  5253. return token_type::parse_error;
  5254. }
  5255. case 0x1E:
  5256. {
  5257. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  5258. return token_type::parse_error;
  5259. }
  5260. case 0x1F:
  5261. {
  5262. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  5263. return token_type::parse_error;
  5264. }
  5265. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  5266. case 0x20:
  5267. case 0x21:
  5268. case 0x23:
  5269. case 0x24:
  5270. case 0x25:
  5271. case 0x26:
  5272. case 0x27:
  5273. case 0x28:
  5274. case 0x29:
  5275. case 0x2A:
  5276. case 0x2B:
  5277. case 0x2C:
  5278. case 0x2D:
  5279. case 0x2E:
  5280. case 0x2F:
  5281. case 0x30:
  5282. case 0x31:
  5283. case 0x32:
  5284. case 0x33:
  5285. case 0x34:
  5286. case 0x35:
  5287. case 0x36:
  5288. case 0x37:
  5289. case 0x38:
  5290. case 0x39:
  5291. case 0x3A:
  5292. case 0x3B:
  5293. case 0x3C:
  5294. case 0x3D:
  5295. case 0x3E:
  5296. case 0x3F:
  5297. case 0x40:
  5298. case 0x41:
  5299. case 0x42:
  5300. case 0x43:
  5301. case 0x44:
  5302. case 0x45:
  5303. case 0x46:
  5304. case 0x47:
  5305. case 0x48:
  5306. case 0x49:
  5307. case 0x4A:
  5308. case 0x4B:
  5309. case 0x4C:
  5310. case 0x4D:
  5311. case 0x4E:
  5312. case 0x4F:
  5313. case 0x50:
  5314. case 0x51:
  5315. case 0x52:
  5316. case 0x53:
  5317. case 0x54:
  5318. case 0x55:
  5319. case 0x56:
  5320. case 0x57:
  5321. case 0x58:
  5322. case 0x59:
  5323. case 0x5A:
  5324. case 0x5B:
  5325. case 0x5D:
  5326. case 0x5E:
  5327. case 0x5F:
  5328. case 0x60:
  5329. case 0x61:
  5330. case 0x62:
  5331. case 0x63:
  5332. case 0x64:
  5333. case 0x65:
  5334. case 0x66:
  5335. case 0x67:
  5336. case 0x68:
  5337. case 0x69:
  5338. case 0x6A:
  5339. case 0x6B:
  5340. case 0x6C:
  5341. case 0x6D:
  5342. case 0x6E:
  5343. case 0x6F:
  5344. case 0x70:
  5345. case 0x71:
  5346. case 0x72:
  5347. case 0x73:
  5348. case 0x74:
  5349. case 0x75:
  5350. case 0x76:
  5351. case 0x77:
  5352. case 0x78:
  5353. case 0x79:
  5354. case 0x7A:
  5355. case 0x7B:
  5356. case 0x7C:
  5357. case 0x7D:
  5358. case 0x7E:
  5359. case 0x7F:
  5360. {
  5361. add(current);
  5362. break;
  5363. }
  5364. // U+0080..U+07FF: bytes C2..DF 80..BF
  5365. case 0xC2:
  5366. case 0xC3:
  5367. case 0xC4:
  5368. case 0xC5:
  5369. case 0xC6:
  5370. case 0xC7:
  5371. case 0xC8:
  5372. case 0xC9:
  5373. case 0xCA:
  5374. case 0xCB:
  5375. case 0xCC:
  5376. case 0xCD:
  5377. case 0xCE:
  5378. case 0xCF:
  5379. case 0xD0:
  5380. case 0xD1:
  5381. case 0xD2:
  5382. case 0xD3:
  5383. case 0xD4:
  5384. case 0xD5:
  5385. case 0xD6:
  5386. case 0xD7:
  5387. case 0xD8:
  5388. case 0xD9:
  5389. case 0xDA:
  5390. case 0xDB:
  5391. case 0xDC:
  5392. case 0xDD:
  5393. case 0xDE:
  5394. case 0xDF:
  5395. {
  5396. if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  5397. {
  5398. return token_type::parse_error;
  5399. }
  5400. break;
  5401. }
  5402. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  5403. case 0xE0:
  5404. {
  5405. if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  5406. {
  5407. return token_type::parse_error;
  5408. }
  5409. break;
  5410. }
  5411. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  5412. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  5413. case 0xE1:
  5414. case 0xE2:
  5415. case 0xE3:
  5416. case 0xE4:
  5417. case 0xE5:
  5418. case 0xE6:
  5419. case 0xE7:
  5420. case 0xE8:
  5421. case 0xE9:
  5422. case 0xEA:
  5423. case 0xEB:
  5424. case 0xEC:
  5425. case 0xEE:
  5426. case 0xEF:
  5427. {
  5428. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  5429. {
  5430. return token_type::parse_error;
  5431. }
  5432. break;
  5433. }
  5434. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  5435. case 0xED:
  5436. {
  5437. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  5438. {
  5439. return token_type::parse_error;
  5440. }
  5441. break;
  5442. }
  5443. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  5444. case 0xF0:
  5445. {
  5446. if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  5447. {
  5448. return token_type::parse_error;
  5449. }
  5450. break;
  5451. }
  5452. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  5453. case 0xF1:
  5454. case 0xF2:
  5455. case 0xF3:
  5456. {
  5457. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  5458. {
  5459. return token_type::parse_error;
  5460. }
  5461. break;
  5462. }
  5463. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  5464. case 0xF4:
  5465. {
  5466. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  5467. {
  5468. return token_type::parse_error;
  5469. }
  5470. break;
  5471. }
  5472. // remaining bytes (80..C1 and F5..FF) are ill-formed
  5473. default:
  5474. {
  5475. error_message = "invalid string: ill-formed UTF-8 byte";
  5476. return token_type::parse_error;
  5477. }
  5478. }
  5479. }
  5480. }
  5481. static void strtof(float& f, const char* str, char** endptr) noexcept
  5482. {
  5483. f = std::strtof(str, endptr);
  5484. }
  5485. static void strtof(double& f, const char* str, char** endptr) noexcept
  5486. {
  5487. f = std::strtod(str, endptr);
  5488. }
  5489. static void strtof(long double& f, const char* str, char** endptr) noexcept
  5490. {
  5491. f = std::strtold(str, endptr);
  5492. }
  5493. /*!
  5494. @brief scan a number literal
  5495. This function scans a string according to Sect. 6 of RFC 7159.
  5496. The function is realized with a deterministic finite state machine derived
  5497. from the grammar described in RFC 7159. Starting in state "init", the
  5498. input is read and used to determined the next state. Only state "done"
  5499. accepts the number. State "error" is a trap state to model errors. In the
  5500. table below, "anything" means any character but the ones listed before.
  5501. state | 0 | 1-9 | e E | + | - | . | anything
  5502. ---------|----------|----------|----------|---------|---------|----------|-----------
  5503. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  5504. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  5505. zero | done | done | exponent | done | done | decimal1 | done
  5506. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  5507. decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
  5508. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  5509. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  5510. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  5511. any2 | any2 | any2 | done | done | done | done | done
  5512. The state machine is realized with one label per state (prefixed with
  5513. "scan_number_") and `goto` statements between them. The state machine
  5514. contains cycles, but any cycle can be left when EOF is read. Therefore,
  5515. the function is guaranteed to terminate.
  5516. During scanning, the read bytes are stored in token_buffer. This string is
  5517. then converted to a signed integer, an unsigned integer, or a
  5518. floating-point number.
  5519. @return token_type::value_unsigned, token_type::value_integer, or
  5520. token_type::value_float if number could be successfully scanned,
  5521. token_type::parse_error otherwise
  5522. @note The scanner is independent of the current locale. Internally, the
  5523. locale's decimal point is used instead of `.` to work with the
  5524. locale-dependent converters.
  5525. */
  5526. token_type scan_number() // lgtm [cpp/use-of-goto]
  5527. {
  5528. // reset token_buffer to store the number's bytes
  5529. reset();
  5530. // the type of the parsed number; initially set to unsigned; will be
  5531. // changed if minus sign, decimal point or exponent is read
  5532. token_type number_type = token_type::value_unsigned;
  5533. // state (init): we just found out we need to scan a number
  5534. switch (current)
  5535. {
  5536. case '-':
  5537. {
  5538. add(current);
  5539. goto scan_number_minus;
  5540. }
  5541. case '0':
  5542. {
  5543. add(current);
  5544. goto scan_number_zero;
  5545. }
  5546. case '1':
  5547. case '2':
  5548. case '3':
  5549. case '4':
  5550. case '5':
  5551. case '6':
  5552. case '7':
  5553. case '8':
  5554. case '9':
  5555. {
  5556. add(current);
  5557. goto scan_number_any1;
  5558. }
  5559. // all other characters are rejected outside scan_number()
  5560. default: // LCOV_EXCL_LINE
  5561. assert(false); // LCOV_EXCL_LINE
  5562. }
  5563. scan_number_minus:
  5564. // state: we just parsed a leading minus sign
  5565. number_type = token_type::value_integer;
  5566. switch (get())
  5567. {
  5568. case '0':
  5569. {
  5570. add(current);
  5571. goto scan_number_zero;
  5572. }
  5573. case '1':
  5574. case '2':
  5575. case '3':
  5576. case '4':
  5577. case '5':
  5578. case '6':
  5579. case '7':
  5580. case '8':
  5581. case '9':
  5582. {
  5583. add(current);
  5584. goto scan_number_any1;
  5585. }
  5586. default:
  5587. {
  5588. error_message = "invalid number; expected digit after '-'";
  5589. return token_type::parse_error;
  5590. }
  5591. }
  5592. scan_number_zero:
  5593. // state: we just parse a zero (maybe with a leading minus sign)
  5594. switch (get())
  5595. {
  5596. case '.':
  5597. {
  5598. add(decimal_point_char);
  5599. goto scan_number_decimal1;
  5600. }
  5601. case 'e':
  5602. case 'E':
  5603. {
  5604. add(current);
  5605. goto scan_number_exponent;
  5606. }
  5607. default:
  5608. goto scan_number_done;
  5609. }
  5610. scan_number_any1:
  5611. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  5612. switch (get())
  5613. {
  5614. case '0':
  5615. case '1':
  5616. case '2':
  5617. case '3':
  5618. case '4':
  5619. case '5':
  5620. case '6':
  5621. case '7':
  5622. case '8':
  5623. case '9':
  5624. {
  5625. add(current);
  5626. goto scan_number_any1;
  5627. }
  5628. case '.':
  5629. {
  5630. add(decimal_point_char);
  5631. goto scan_number_decimal1;
  5632. }
  5633. case 'e':
  5634. case 'E':
  5635. {
  5636. add(current);
  5637. goto scan_number_exponent;
  5638. }
  5639. default:
  5640. goto scan_number_done;
  5641. }
  5642. scan_number_decimal1:
  5643. // state: we just parsed a decimal point
  5644. number_type = token_type::value_float;
  5645. switch (get())
  5646. {
  5647. case '0':
  5648. case '1':
  5649. case '2':
  5650. case '3':
  5651. case '4':
  5652. case '5':
  5653. case '6':
  5654. case '7':
  5655. case '8':
  5656. case '9':
  5657. {
  5658. add(current);
  5659. goto scan_number_decimal2;
  5660. }
  5661. default:
  5662. {
  5663. error_message = "invalid number; expected digit after '.'";
  5664. return token_type::parse_error;
  5665. }
  5666. }
  5667. scan_number_decimal2:
  5668. // we just parsed at least one number after a decimal point
  5669. switch (get())
  5670. {
  5671. case '0':
  5672. case '1':
  5673. case '2':
  5674. case '3':
  5675. case '4':
  5676. case '5':
  5677. case '6':
  5678. case '7':
  5679. case '8':
  5680. case '9':
  5681. {
  5682. add(current);
  5683. goto scan_number_decimal2;
  5684. }
  5685. case 'e':
  5686. case 'E':
  5687. {
  5688. add(current);
  5689. goto scan_number_exponent;
  5690. }
  5691. default:
  5692. goto scan_number_done;
  5693. }
  5694. scan_number_exponent:
  5695. // we just parsed an exponent
  5696. number_type = token_type::value_float;
  5697. switch (get())
  5698. {
  5699. case '+':
  5700. case '-':
  5701. {
  5702. add(current);
  5703. goto scan_number_sign;
  5704. }
  5705. case '0':
  5706. case '1':
  5707. case '2':
  5708. case '3':
  5709. case '4':
  5710. case '5':
  5711. case '6':
  5712. case '7':
  5713. case '8':
  5714. case '9':
  5715. {
  5716. add(current);
  5717. goto scan_number_any2;
  5718. }
  5719. default:
  5720. {
  5721. error_message =
  5722. "invalid number; expected '+', '-', or digit after exponent";
  5723. return token_type::parse_error;
  5724. }
  5725. }
  5726. scan_number_sign:
  5727. // we just parsed an exponent sign
  5728. switch (get())
  5729. {
  5730. case '0':
  5731. case '1':
  5732. case '2':
  5733. case '3':
  5734. case '4':
  5735. case '5':
  5736. case '6':
  5737. case '7':
  5738. case '8':
  5739. case '9':
  5740. {
  5741. add(current);
  5742. goto scan_number_any2;
  5743. }
  5744. default:
  5745. {
  5746. error_message = "invalid number; expected digit after exponent sign";
  5747. return token_type::parse_error;
  5748. }
  5749. }
  5750. scan_number_any2:
  5751. // we just parsed a number after the exponent or exponent sign
  5752. switch (get())
  5753. {
  5754. case '0':
  5755. case '1':
  5756. case '2':
  5757. case '3':
  5758. case '4':
  5759. case '5':
  5760. case '6':
  5761. case '7':
  5762. case '8':
  5763. case '9':
  5764. {
  5765. add(current);
  5766. goto scan_number_any2;
  5767. }
  5768. default:
  5769. goto scan_number_done;
  5770. }
  5771. scan_number_done:
  5772. // unget the character after the number (we only read it to know that
  5773. // we are done scanning a number)
  5774. unget();
  5775. char* endptr = nullptr;
  5776. errno = 0;
  5777. // try to parse integers first and fall back to floats
  5778. if (number_type == token_type::value_unsigned)
  5779. {
  5780. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  5781. // we checked the number format before
  5782. assert(endptr == token_buffer.data() + token_buffer.size());
  5783. if (errno == 0)
  5784. {
  5785. value_unsigned = static_cast<number_unsigned_t>(x);
  5786. if (value_unsigned == x)
  5787. {
  5788. return token_type::value_unsigned;
  5789. }
  5790. }
  5791. }
  5792. else if (number_type == token_type::value_integer)
  5793. {
  5794. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  5795. // we checked the number format before
  5796. assert(endptr == token_buffer.data() + token_buffer.size());
  5797. if (errno == 0)
  5798. {
  5799. value_integer = static_cast<number_integer_t>(x);
  5800. if (value_integer == x)
  5801. {
  5802. return token_type::value_integer;
  5803. }
  5804. }
  5805. }
  5806. // this code is reached if we parse a floating-point number or if an
  5807. // integer conversion above failed
  5808. strtof(value_float, token_buffer.data(), &endptr);
  5809. // we checked the number format before
  5810. assert(endptr == token_buffer.data() + token_buffer.size());
  5811. return token_type::value_float;
  5812. }
  5813. /*!
  5814. @param[in] literal_text the literal text to expect
  5815. @param[in] length the length of the passed literal text
  5816. @param[in] return_type the token type to return on success
  5817. */
  5818. token_type scan_literal(const char* literal_text, const std::size_t length,
  5819. token_type return_type)
  5820. {
  5821. assert(current == literal_text[0]);
  5822. for (std::size_t i = 1; i < length; ++i)
  5823. {
  5824. if (JSON_UNLIKELY(get() != literal_text[i]))
  5825. {
  5826. error_message = "invalid literal";
  5827. return token_type::parse_error;
  5828. }
  5829. }
  5830. return return_type;
  5831. }
  5832. /////////////////////
  5833. // input management
  5834. /////////////////////
  5835. /// reset token_buffer; current character is beginning of token
  5836. void reset() noexcept
  5837. {
  5838. token_buffer.clear();
  5839. token_string.clear();
  5840. token_string.push_back(std::char_traits<char>::to_char_type(current));
  5841. }
  5842. /*
  5843. @brief get next character from the input
  5844. This function provides the interface to the used input adapter. It does
  5845. not throw in case the input reached EOF, but returns a
  5846. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  5847. for use in error messages.
  5848. @return character read from the input
  5849. */
  5850. std::char_traits<char>::int_type get()
  5851. {
  5852. ++position.chars_read_total;
  5853. ++position.chars_read_current_line;
  5854. if (next_unget)
  5855. {
  5856. // just reset the next_unget variable and work with current
  5857. next_unget = false;
  5858. }
  5859. else
  5860. {
  5861. current = ia->get_character();
  5862. }
  5863. if (JSON_LIKELY(current != std::char_traits<char>::eof()))
  5864. {
  5865. token_string.push_back(std::char_traits<char>::to_char_type(current));
  5866. }
  5867. if (current == '\n')
  5868. {
  5869. ++position.lines_read;
  5870. position.chars_read_current_line = 0;
  5871. }
  5872. return current;
  5873. }
  5874. /*!
  5875. @brief unget current character (read it again on next get)
  5876. We implement unget by setting variable next_unget to true. The input is not
  5877. changed - we just simulate ungetting by modifying chars_read_total,
  5878. chars_read_current_line, and token_string. The next call to get() will
  5879. behave as if the unget character is read again.
  5880. */
  5881. void unget()
  5882. {
  5883. next_unget = true;
  5884. --position.chars_read_total;
  5885. // in case we "unget" a newline, we have to also decrement the lines_read
  5886. if (position.chars_read_current_line == 0)
  5887. {
  5888. if (position.lines_read > 0)
  5889. {
  5890. --position.lines_read;
  5891. }
  5892. }
  5893. else
  5894. {
  5895. --position.chars_read_current_line;
  5896. }
  5897. if (JSON_LIKELY(current != std::char_traits<char>::eof()))
  5898. {
  5899. assert(not token_string.empty());
  5900. token_string.pop_back();
  5901. }
  5902. }
  5903. /// add a character to token_buffer
  5904. void add(int c)
  5905. {
  5906. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  5907. }
  5908. public:
  5909. /////////////////////
  5910. // value getters
  5911. /////////////////////
  5912. /// return integer value
  5913. constexpr number_integer_t get_number_integer() const noexcept
  5914. {
  5915. return value_integer;
  5916. }
  5917. /// return unsigned integer value
  5918. constexpr number_unsigned_t get_number_unsigned() const noexcept
  5919. {
  5920. return value_unsigned;
  5921. }
  5922. /// return floating-point value
  5923. constexpr number_float_t get_number_float() const noexcept
  5924. {
  5925. return value_float;
  5926. }
  5927. /// return current string value (implicitly resets the token; useful only once)
  5928. string_t& get_string()
  5929. {
  5930. return token_buffer;
  5931. }
  5932. /////////////////////
  5933. // diagnostics
  5934. /////////////////////
  5935. /// return position of last read token
  5936. constexpr position_t get_position() const noexcept
  5937. {
  5938. return position;
  5939. }
  5940. /// return the last read token (for errors only). Will never contain EOF
  5941. /// (an arbitrary value that is not a valid char value, often -1), because
  5942. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  5943. std::string get_token_string() const
  5944. {
  5945. // escape control characters
  5946. std::string result;
  5947. for (const auto c : token_string)
  5948. {
  5949. if ('\x00' <= c and c <= '\x1F')
  5950. {
  5951. // escape control characters
  5952. std::array<char, 9> cs{{}};
  5953. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
  5954. result += cs.data();
  5955. }
  5956. else
  5957. {
  5958. // add character as is
  5959. result.push_back(c);
  5960. }
  5961. }
  5962. return result;
  5963. }
  5964. /// return syntax error message
  5965. constexpr const char* get_error_message() const noexcept
  5966. {
  5967. return error_message;
  5968. }
  5969. /////////////////////
  5970. // actual scanner
  5971. /////////////////////
  5972. /*!
  5973. @brief skip the UTF-8 byte order mark
  5974. @return true iff there is no BOM or the correct BOM has been skipped
  5975. */
  5976. bool skip_bom()
  5977. {
  5978. if (get() == 0xEF)
  5979. {
  5980. // check if we completely parse the BOM
  5981. return get() == 0xBB and get() == 0xBF;
  5982. }
  5983. // the first character is not the beginning of the BOM; unget it to
  5984. // process is later
  5985. unget();
  5986. return true;
  5987. }
  5988. token_type scan()
  5989. {
  5990. // initially, skip the BOM
  5991. if (position.chars_read_total == 0 and not skip_bom())
  5992. {
  5993. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  5994. return token_type::parse_error;
  5995. }
  5996. // read next character and ignore whitespace
  5997. do
  5998. {
  5999. get();
  6000. }
  6001. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  6002. switch (current)
  6003. {
  6004. // structural characters
  6005. case '[':
  6006. return token_type::begin_array;
  6007. case ']':
  6008. return token_type::end_array;
  6009. case '{':
  6010. return token_type::begin_object;
  6011. case '}':
  6012. return token_type::end_object;
  6013. case ':':
  6014. return token_type::name_separator;
  6015. case ',':
  6016. return token_type::value_separator;
  6017. // literals
  6018. case 't':
  6019. return scan_literal("true", 4, token_type::literal_true);
  6020. case 'f':
  6021. return scan_literal("false", 5, token_type::literal_false);
  6022. case 'n':
  6023. return scan_literal("null", 4, token_type::literal_null);
  6024. // string
  6025. case '\"':
  6026. return scan_string();
  6027. // number
  6028. case '-':
  6029. case '0':
  6030. case '1':
  6031. case '2':
  6032. case '3':
  6033. case '4':
  6034. case '5':
  6035. case '6':
  6036. case '7':
  6037. case '8':
  6038. case '9':
  6039. return scan_number();
  6040. // end of input (the null byte is needed when parsing from
  6041. // string literals)
  6042. case '\0':
  6043. case std::char_traits<char>::eof():
  6044. return token_type::end_of_input;
  6045. // error
  6046. default:
  6047. error_message = "invalid literal";
  6048. return token_type::parse_error;
  6049. }
  6050. }
  6051. private:
  6052. /// input adapter
  6053. detail::input_adapter_t ia = nullptr;
  6054. /// the current character
  6055. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  6056. /// whether the next get() call should just return current
  6057. bool next_unget = false;
  6058. /// the start position of the current token
  6059. position_t position {};
  6060. /// raw input token string (for error messages)
  6061. std::vector<char> token_string {};
  6062. /// buffer for variable-length tokens (numbers, strings)
  6063. string_t token_buffer {};
  6064. /// a description of occurred lexer errors
  6065. const char* error_message = "";
  6066. // number values
  6067. number_integer_t value_integer = 0;
  6068. number_unsigned_t value_unsigned = 0;
  6069. number_float_t value_float = 0;
  6070. /// the decimal point
  6071. const char decimal_point_char = '.';
  6072. };
  6073. } // namespace detail
  6074. } // namespace nlohmann
  6075. // #include <nlohmann/detail/input/parser.hpp>
  6076. #include <cassert> // assert
  6077. #include <cmath> // isfinite
  6078. #include <cstdint> // uint8_t
  6079. #include <functional> // function
  6080. #include <string> // string
  6081. #include <utility> // move
  6082. #include <vector> // vector
  6083. // #include <nlohmann/detail/exceptions.hpp>
  6084. // #include <nlohmann/detail/input/input_adapters.hpp>
  6085. // #include <nlohmann/detail/input/json_sax.hpp>
  6086. // #include <nlohmann/detail/input/lexer.hpp>
  6087. // #include <nlohmann/detail/macro_scope.hpp>
  6088. // #include <nlohmann/detail/meta/is_sax.hpp>
  6089. // #include <nlohmann/detail/value_t.hpp>
  6090. namespace nlohmann
  6091. {
  6092. namespace detail
  6093. {
  6094. ////////////
  6095. // parser //
  6096. ////////////
  6097. /*!
  6098. @brief syntax analysis
  6099. This class implements a recursive decent parser.
  6100. */
  6101. template<typename BasicJsonType>
  6102. class parser
  6103. {
  6104. using number_integer_t = typename BasicJsonType::number_integer_t;
  6105. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  6106. using number_float_t = typename BasicJsonType::number_float_t;
  6107. using string_t = typename BasicJsonType::string_t;
  6108. using lexer_t = lexer<BasicJsonType>;
  6109. using token_type = typename lexer_t::token_type;
  6110. public:
  6111. enum class parse_event_t : uint8_t
  6112. {
  6113. /// the parser read `{` and started to process a JSON object
  6114. object_start,
  6115. /// the parser read `}` and finished processing a JSON object
  6116. object_end,
  6117. /// the parser read `[` and started to process a JSON array
  6118. array_start,
  6119. /// the parser read `]` and finished processing a JSON array
  6120. array_end,
  6121. /// the parser read a key of a value in an object
  6122. key,
  6123. /// the parser finished reading a JSON value
  6124. value
  6125. };
  6126. using parser_callback_t =
  6127. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  6128. /// a parser reading from an input adapter
  6129. explicit parser(detail::input_adapter_t&& adapter,
  6130. const parser_callback_t cb = nullptr,
  6131. const bool allow_exceptions_ = true)
  6132. : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
  6133. {
  6134. // read first token
  6135. get_token();
  6136. }
  6137. /*!
  6138. @brief public parser interface
  6139. @param[in] strict whether to expect the last token to be EOF
  6140. @param[in,out] result parsed JSON value
  6141. @throw parse_error.101 in case of an unexpected token
  6142. @throw parse_error.102 if to_unicode fails or surrogate error
  6143. @throw parse_error.103 if to_unicode fails
  6144. */
  6145. void parse(const bool strict, BasicJsonType& result)
  6146. {
  6147. if (callback)
  6148. {
  6149. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  6150. sax_parse_internal(&sdp);
  6151. result.assert_invariant();
  6152. // in strict mode, input must be completely read
  6153. if (strict and (get_token() != token_type::end_of_input))
  6154. {
  6155. sdp.parse_error(m_lexer.get_position(),
  6156. m_lexer.get_token_string(),
  6157. parse_error::create(101, m_lexer.get_position(),
  6158. exception_message(token_type::end_of_input, "value")));
  6159. }
  6160. // in case of an error, return discarded value
  6161. if (sdp.is_errored())
  6162. {
  6163. result = value_t::discarded;
  6164. return;
  6165. }
  6166. // set top-level value to null if it was discarded by the callback
  6167. // function
  6168. if (result.is_discarded())
  6169. {
  6170. result = nullptr;
  6171. }
  6172. }
  6173. else
  6174. {
  6175. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  6176. sax_parse_internal(&sdp);
  6177. result.assert_invariant();
  6178. // in strict mode, input must be completely read
  6179. if (strict and (get_token() != token_type::end_of_input))
  6180. {
  6181. sdp.parse_error(m_lexer.get_position(),
  6182. m_lexer.get_token_string(),
  6183. parse_error::create(101, m_lexer.get_position(),
  6184. exception_message(token_type::end_of_input, "value")));
  6185. }
  6186. // in case of an error, return discarded value
  6187. if (sdp.is_errored())
  6188. {
  6189. result = value_t::discarded;
  6190. return;
  6191. }
  6192. }
  6193. }
  6194. /*!
  6195. @brief public accept interface
  6196. @param[in] strict whether to expect the last token to be EOF
  6197. @return whether the input is a proper JSON text
  6198. */
  6199. bool accept(const bool strict = true)
  6200. {
  6201. json_sax_acceptor<BasicJsonType> sax_acceptor;
  6202. return sax_parse(&sax_acceptor, strict);
  6203. }
  6204. template <typename SAX>
  6205. bool sax_parse(SAX* sax, const bool strict = true)
  6206. {
  6207. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  6208. const bool result = sax_parse_internal(sax);
  6209. // strict mode: next byte must be EOF
  6210. if (result and strict and (get_token() != token_type::end_of_input))
  6211. {
  6212. return sax->parse_error(m_lexer.get_position(),
  6213. m_lexer.get_token_string(),
  6214. parse_error::create(101, m_lexer.get_position(),
  6215. exception_message(token_type::end_of_input, "value")));
  6216. }
  6217. return result;
  6218. }
  6219. private:
  6220. template <typename SAX>
  6221. bool sax_parse_internal(SAX* sax)
  6222. {
  6223. // stack to remember the hierarchy of structured values we are parsing
  6224. // true = array; false = object
  6225. std::vector<bool> states;
  6226. // value to avoid a goto (see comment where set to true)
  6227. bool skip_to_state_evaluation = false;
  6228. while (true)
  6229. {
  6230. if (not skip_to_state_evaluation)
  6231. {
  6232. // invariant: get_token() was called before each iteration
  6233. switch (last_token)
  6234. {
  6235. case token_type::begin_object:
  6236. {
  6237. if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
  6238. {
  6239. return false;
  6240. }
  6241. // closing } -> we are done
  6242. if (get_token() == token_type::end_object)
  6243. {
  6244. if (JSON_UNLIKELY(not sax->end_object()))
  6245. {
  6246. return false;
  6247. }
  6248. break;
  6249. }
  6250. // parse key
  6251. if (JSON_UNLIKELY(last_token != token_type::value_string))
  6252. {
  6253. return sax->parse_error(m_lexer.get_position(),
  6254. m_lexer.get_token_string(),
  6255. parse_error::create(101, m_lexer.get_position(),
  6256. exception_message(token_type::value_string, "object key")));
  6257. }
  6258. if (JSON_UNLIKELY(not sax->key(m_lexer.get_string())))
  6259. {
  6260. return false;
  6261. }
  6262. // parse separator (:)
  6263. if (JSON_UNLIKELY(get_token() != token_type::name_separator))
  6264. {
  6265. return sax->parse_error(m_lexer.get_position(),
  6266. m_lexer.get_token_string(),
  6267. parse_error::create(101, m_lexer.get_position(),
  6268. exception_message(token_type::name_separator, "object separator")));
  6269. }
  6270. // remember we are now inside an object
  6271. states.push_back(false);
  6272. // parse values
  6273. get_token();
  6274. continue;
  6275. }
  6276. case token_type::begin_array:
  6277. {
  6278. if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
  6279. {
  6280. return false;
  6281. }
  6282. // closing ] -> we are done
  6283. if (get_token() == token_type::end_array)
  6284. {
  6285. if (JSON_UNLIKELY(not sax->end_array()))
  6286. {
  6287. return false;
  6288. }
  6289. break;
  6290. }
  6291. // remember we are now inside an array
  6292. states.push_back(true);
  6293. // parse values (no need to call get_token)
  6294. continue;
  6295. }
  6296. case token_type::value_float:
  6297. {
  6298. const auto res = m_lexer.get_number_float();
  6299. if (JSON_UNLIKELY(not std::isfinite(res)))
  6300. {
  6301. return sax->parse_error(m_lexer.get_position(),
  6302. m_lexer.get_token_string(),
  6303. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  6304. }
  6305. if (JSON_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
  6306. {
  6307. return false;
  6308. }
  6309. break;
  6310. }
  6311. case token_type::literal_false:
  6312. {
  6313. if (JSON_UNLIKELY(not sax->boolean(false)))
  6314. {
  6315. return false;
  6316. }
  6317. break;
  6318. }
  6319. case token_type::literal_null:
  6320. {
  6321. if (JSON_UNLIKELY(not sax->null()))
  6322. {
  6323. return false;
  6324. }
  6325. break;
  6326. }
  6327. case token_type::literal_true:
  6328. {
  6329. if (JSON_UNLIKELY(not sax->boolean(true)))
  6330. {
  6331. return false;
  6332. }
  6333. break;
  6334. }
  6335. case token_type::value_integer:
  6336. {
  6337. if (JSON_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
  6338. {
  6339. return false;
  6340. }
  6341. break;
  6342. }
  6343. case token_type::value_string:
  6344. {
  6345. if (JSON_UNLIKELY(not sax->string(m_lexer.get_string())))
  6346. {
  6347. return false;
  6348. }
  6349. break;
  6350. }
  6351. case token_type::value_unsigned:
  6352. {
  6353. if (JSON_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
  6354. {
  6355. return false;
  6356. }
  6357. break;
  6358. }
  6359. case token_type::parse_error:
  6360. {
  6361. // using "uninitialized" to avoid "expected" message
  6362. return sax->parse_error(m_lexer.get_position(),
  6363. m_lexer.get_token_string(),
  6364. parse_error::create(101, m_lexer.get_position(),
  6365. exception_message(token_type::uninitialized, "value")));
  6366. }
  6367. default: // the last token was unexpected
  6368. {
  6369. return sax->parse_error(m_lexer.get_position(),
  6370. m_lexer.get_token_string(),
  6371. parse_error::create(101, m_lexer.get_position(),
  6372. exception_message(token_type::literal_or_value, "value")));
  6373. }
  6374. }
  6375. }
  6376. else
  6377. {
  6378. skip_to_state_evaluation = false;
  6379. }
  6380. // we reached this line after we successfully parsed a value
  6381. if (states.empty())
  6382. {
  6383. // empty stack: we reached the end of the hierarchy: done
  6384. return true;
  6385. }
  6386. if (states.back()) // array
  6387. {
  6388. // comma -> next value
  6389. if (get_token() == token_type::value_separator)
  6390. {
  6391. // parse a new value
  6392. get_token();
  6393. continue;
  6394. }
  6395. // closing ]
  6396. if (JSON_LIKELY(last_token == token_type::end_array))
  6397. {
  6398. if (JSON_UNLIKELY(not sax->end_array()))
  6399. {
  6400. return false;
  6401. }
  6402. // We are done with this array. Before we can parse a
  6403. // new value, we need to evaluate the new state first.
  6404. // By setting skip_to_state_evaluation to false, we
  6405. // are effectively jumping to the beginning of this if.
  6406. assert(not states.empty());
  6407. states.pop_back();
  6408. skip_to_state_evaluation = true;
  6409. continue;
  6410. }
  6411. return sax->parse_error(m_lexer.get_position(),
  6412. m_lexer.get_token_string(),
  6413. parse_error::create(101, m_lexer.get_position(),
  6414. exception_message(token_type::end_array, "array")));
  6415. }
  6416. else // object
  6417. {
  6418. // comma -> next value
  6419. if (get_token() == token_type::value_separator)
  6420. {
  6421. // parse key
  6422. if (JSON_UNLIKELY(get_token() != token_type::value_string))
  6423. {
  6424. return sax->parse_error(m_lexer.get_position(),
  6425. m_lexer.get_token_string(),
  6426. parse_error::create(101, m_lexer.get_position(),
  6427. exception_message(token_type::value_string, "object key")));
  6428. }
  6429. if (JSON_UNLIKELY(not sax->key(m_lexer.get_string())))
  6430. {
  6431. return false;
  6432. }
  6433. // parse separator (:)
  6434. if (JSON_UNLIKELY(get_token() != token_type::name_separator))
  6435. {
  6436. return sax->parse_error(m_lexer.get_position(),
  6437. m_lexer.get_token_string(),
  6438. parse_error::create(101, m_lexer.get_position(),
  6439. exception_message(token_type::name_separator, "object separator")));
  6440. }
  6441. // parse values
  6442. get_token();
  6443. continue;
  6444. }
  6445. // closing }
  6446. if (JSON_LIKELY(last_token == token_type::end_object))
  6447. {
  6448. if (JSON_UNLIKELY(not sax->end_object()))
  6449. {
  6450. return false;
  6451. }
  6452. // We are done with this object. Before we can parse a
  6453. // new value, we need to evaluate the new state first.
  6454. // By setting skip_to_state_evaluation to false, we
  6455. // are effectively jumping to the beginning of this if.
  6456. assert(not states.empty());
  6457. states.pop_back();
  6458. skip_to_state_evaluation = true;
  6459. continue;
  6460. }
  6461. return sax->parse_error(m_lexer.get_position(),
  6462. m_lexer.get_token_string(),
  6463. parse_error::create(101, m_lexer.get_position(),
  6464. exception_message(token_type::end_object, "object")));
  6465. }
  6466. }
  6467. }
  6468. /// get next token from lexer
  6469. token_type get_token()
  6470. {
  6471. return last_token = m_lexer.scan();
  6472. }
  6473. std::string exception_message(const token_type expected, const std::string& context)
  6474. {
  6475. std::string error_msg = "syntax error ";
  6476. if (not context.empty())
  6477. {
  6478. error_msg += "while parsing " + context + " ";
  6479. }
  6480. error_msg += "- ";
  6481. if (last_token == token_type::parse_error)
  6482. {
  6483. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  6484. m_lexer.get_token_string() + "'";
  6485. }
  6486. else
  6487. {
  6488. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  6489. }
  6490. if (expected != token_type::uninitialized)
  6491. {
  6492. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  6493. }
  6494. return error_msg;
  6495. }
  6496. private:
  6497. /// callback function
  6498. const parser_callback_t callback = nullptr;
  6499. /// the type of the last read token
  6500. token_type last_token = token_type::uninitialized;
  6501. /// the lexer
  6502. lexer_t m_lexer;
  6503. /// whether to throw exceptions in case of errors
  6504. const bool allow_exceptions = true;
  6505. };
  6506. } // namespace detail
  6507. } // namespace nlohmann
  6508. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  6509. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  6510. #include <cstddef> // ptrdiff_t
  6511. #include <limits> // numeric_limits
  6512. namespace nlohmann
  6513. {
  6514. namespace detail
  6515. {
  6516. /*
  6517. @brief an iterator for primitive JSON types
  6518. This class models an iterator for primitive JSON types (boolean, number,
  6519. string). It's only purpose is to allow the iterator/const_iterator classes
  6520. to "iterate" over primitive values. Internally, the iterator is modeled by
  6521. a `difference_type` variable. Value begin_value (`0`) models the begin,
  6522. end_value (`1`) models past the end.
  6523. */
  6524. class primitive_iterator_t
  6525. {
  6526. private:
  6527. using difference_type = std::ptrdiff_t;
  6528. static constexpr difference_type begin_value = 0;
  6529. static constexpr difference_type end_value = begin_value + 1;
  6530. /// iterator as signed integer type
  6531. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  6532. public:
  6533. constexpr difference_type get_value() const noexcept
  6534. {
  6535. return m_it;
  6536. }
  6537. /// set iterator to a defined beginning
  6538. void set_begin() noexcept
  6539. {
  6540. m_it = begin_value;
  6541. }
  6542. /// set iterator to a defined past the end
  6543. void set_end() noexcept
  6544. {
  6545. m_it = end_value;
  6546. }
  6547. /// return whether the iterator can be dereferenced
  6548. constexpr bool is_begin() const noexcept
  6549. {
  6550. return m_it == begin_value;
  6551. }
  6552. /// return whether the iterator is at end
  6553. constexpr bool is_end() const noexcept
  6554. {
  6555. return m_it == end_value;
  6556. }
  6557. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6558. {
  6559. return lhs.m_it == rhs.m_it;
  6560. }
  6561. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6562. {
  6563. return lhs.m_it < rhs.m_it;
  6564. }
  6565. primitive_iterator_t operator+(difference_type n) noexcept
  6566. {
  6567. auto result = *this;
  6568. result += n;
  6569. return result;
  6570. }
  6571. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6572. {
  6573. return lhs.m_it - rhs.m_it;
  6574. }
  6575. primitive_iterator_t& operator++() noexcept
  6576. {
  6577. ++m_it;
  6578. return *this;
  6579. }
  6580. primitive_iterator_t const operator++(int) noexcept
  6581. {
  6582. auto result = *this;
  6583. ++m_it;
  6584. return result;
  6585. }
  6586. primitive_iterator_t& operator--() noexcept
  6587. {
  6588. --m_it;
  6589. return *this;
  6590. }
  6591. primitive_iterator_t const operator--(int) noexcept
  6592. {
  6593. auto result = *this;
  6594. --m_it;
  6595. return result;
  6596. }
  6597. primitive_iterator_t& operator+=(difference_type n) noexcept
  6598. {
  6599. m_it += n;
  6600. return *this;
  6601. }
  6602. primitive_iterator_t& operator-=(difference_type n) noexcept
  6603. {
  6604. m_it -= n;
  6605. return *this;
  6606. }
  6607. };
  6608. } // namespace detail
  6609. } // namespace nlohmann
  6610. namespace nlohmann
  6611. {
  6612. namespace detail
  6613. {
  6614. /*!
  6615. @brief an iterator value
  6616. @note This structure could easily be a union, but MSVC currently does not allow
  6617. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  6618. */
  6619. template<typename BasicJsonType> struct internal_iterator
  6620. {
  6621. /// iterator for JSON objects
  6622. typename BasicJsonType::object_t::iterator object_iterator {};
  6623. /// iterator for JSON arrays
  6624. typename BasicJsonType::array_t::iterator array_iterator {};
  6625. /// generic iterator for all other types
  6626. primitive_iterator_t primitive_iterator {};
  6627. };
  6628. } // namespace detail
  6629. } // namespace nlohmann
  6630. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  6631. #include <ciso646> // not
  6632. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  6633. #include <type_traits> // conditional, is_const, remove_const
  6634. // #include <nlohmann/detail/exceptions.hpp>
  6635. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  6636. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  6637. // #include <nlohmann/detail/macro_scope.hpp>
  6638. // #include <nlohmann/detail/meta/cpp_future.hpp>
  6639. // #include <nlohmann/detail/meta/type_traits.hpp>
  6640. // #include <nlohmann/detail/value_t.hpp>
  6641. namespace nlohmann
  6642. {
  6643. namespace detail
  6644. {
  6645. // forward declare, to be able to friend it later on
  6646. template<typename IteratorType> class iteration_proxy;
  6647. template<typename IteratorType> class iteration_proxy_value;
  6648. /*!
  6649. @brief a template for a bidirectional iterator for the @ref basic_json class
  6650. This class implements a both iterators (iterator and const_iterator) for the
  6651. @ref basic_json class.
  6652. @note An iterator is called *initialized* when a pointer to a JSON value has
  6653. been set (e.g., by a constructor or a copy assignment). If the iterator is
  6654. default-constructed, it is *uninitialized* and most methods are undefined.
  6655. **The library uses assertions to detect calls on uninitialized iterators.**
  6656. @requirement The class satisfies the following concept requirements:
  6657. -
  6658. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  6659. The iterator that can be moved can be moved in both directions (i.e.
  6660. incremented and decremented).
  6661. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  6662. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  6663. */
  6664. template<typename BasicJsonType>
  6665. class iter_impl
  6666. {
  6667. /// allow basic_json to access private members
  6668. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  6669. friend BasicJsonType;
  6670. friend iteration_proxy<iter_impl>;
  6671. friend iteration_proxy_value<iter_impl>;
  6672. using object_t = typename BasicJsonType::object_t;
  6673. using array_t = typename BasicJsonType::array_t;
  6674. // make sure BasicJsonType is basic_json or const basic_json
  6675. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  6676. "iter_impl only accepts (const) basic_json");
  6677. public:
  6678. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  6679. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  6680. /// A user-defined iterator should provide publicly accessible typedefs named
  6681. /// iterator_category, value_type, difference_type, pointer, and reference.
  6682. /// Note that value_type is required to be non-const, even for constant iterators.
  6683. using iterator_category = std::bidirectional_iterator_tag;
  6684. /// the type of the values when the iterator is dereferenced
  6685. using value_type = typename BasicJsonType::value_type;
  6686. /// a type to represent differences between iterators
  6687. using difference_type = typename BasicJsonType::difference_type;
  6688. /// defines a pointer to the type iterated over (value_type)
  6689. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  6690. typename BasicJsonType::const_pointer,
  6691. typename BasicJsonType::pointer>::type;
  6692. /// defines a reference to the type iterated over (value_type)
  6693. using reference =
  6694. typename std::conditional<std::is_const<BasicJsonType>::value,
  6695. typename BasicJsonType::const_reference,
  6696. typename BasicJsonType::reference>::type;
  6697. /// default constructor
  6698. iter_impl() = default;
  6699. /*!
  6700. @brief constructor for a given JSON instance
  6701. @param[in] object pointer to a JSON object for this iterator
  6702. @pre object != nullptr
  6703. @post The iterator is initialized; i.e. `m_object != nullptr`.
  6704. */
  6705. explicit iter_impl(pointer object) noexcept : m_object(object)
  6706. {
  6707. assert(m_object != nullptr);
  6708. switch (m_object->m_type)
  6709. {
  6710. case value_t::object:
  6711. {
  6712. m_it.object_iterator = typename object_t::iterator();
  6713. break;
  6714. }
  6715. case value_t::array:
  6716. {
  6717. m_it.array_iterator = typename array_t::iterator();
  6718. break;
  6719. }
  6720. default:
  6721. {
  6722. m_it.primitive_iterator = primitive_iterator_t();
  6723. break;
  6724. }
  6725. }
  6726. }
  6727. /*!
  6728. @note The conventional copy constructor and copy assignment are implicitly
  6729. defined. Combined with the following converting constructor and
  6730. assignment, they support: (1) copy from iterator to iterator, (2)
  6731. copy from const iterator to const iterator, and (3) conversion from
  6732. iterator to const iterator. However conversion from const iterator
  6733. to iterator is not defined.
  6734. */
  6735. /*!
  6736. @brief converting constructor
  6737. @param[in] other non-const iterator to copy from
  6738. @note It is not checked whether @a other is initialized.
  6739. */
  6740. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  6741. : m_object(other.m_object), m_it(other.m_it) {}
  6742. /*!
  6743. @brief converting assignment
  6744. @param[in,out] other non-const iterator to copy from
  6745. @return const/non-const iterator
  6746. @note It is not checked whether @a other is initialized.
  6747. */
  6748. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  6749. {
  6750. m_object = other.m_object;
  6751. m_it = other.m_it;
  6752. return *this;
  6753. }
  6754. private:
  6755. /*!
  6756. @brief set the iterator to the first value
  6757. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6758. */
  6759. void set_begin() noexcept
  6760. {
  6761. assert(m_object != nullptr);
  6762. switch (m_object->m_type)
  6763. {
  6764. case value_t::object:
  6765. {
  6766. m_it.object_iterator = m_object->m_value.object->begin();
  6767. break;
  6768. }
  6769. case value_t::array:
  6770. {
  6771. m_it.array_iterator = m_object->m_value.array->begin();
  6772. break;
  6773. }
  6774. case value_t::null:
  6775. {
  6776. // set to end so begin()==end() is true: null is empty
  6777. m_it.primitive_iterator.set_end();
  6778. break;
  6779. }
  6780. default:
  6781. {
  6782. m_it.primitive_iterator.set_begin();
  6783. break;
  6784. }
  6785. }
  6786. }
  6787. /*!
  6788. @brief set the iterator past the last value
  6789. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6790. */
  6791. void set_end() noexcept
  6792. {
  6793. assert(m_object != nullptr);
  6794. switch (m_object->m_type)
  6795. {
  6796. case value_t::object:
  6797. {
  6798. m_it.object_iterator = m_object->m_value.object->end();
  6799. break;
  6800. }
  6801. case value_t::array:
  6802. {
  6803. m_it.array_iterator = m_object->m_value.array->end();
  6804. break;
  6805. }
  6806. default:
  6807. {
  6808. m_it.primitive_iterator.set_end();
  6809. break;
  6810. }
  6811. }
  6812. }
  6813. public:
  6814. /*!
  6815. @brief return a reference to the value pointed to by the iterator
  6816. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6817. */
  6818. reference operator*() const
  6819. {
  6820. assert(m_object != nullptr);
  6821. switch (m_object->m_type)
  6822. {
  6823. case value_t::object:
  6824. {
  6825. assert(m_it.object_iterator != m_object->m_value.object->end());
  6826. return m_it.object_iterator->second;
  6827. }
  6828. case value_t::array:
  6829. {
  6830. assert(m_it.array_iterator != m_object->m_value.array->end());
  6831. return *m_it.array_iterator;
  6832. }
  6833. case value_t::null:
  6834. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  6835. default:
  6836. {
  6837. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  6838. {
  6839. return *m_object;
  6840. }
  6841. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  6842. }
  6843. }
  6844. }
  6845. /*!
  6846. @brief dereference the iterator
  6847. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6848. */
  6849. pointer operator->() const
  6850. {
  6851. assert(m_object != nullptr);
  6852. switch (m_object->m_type)
  6853. {
  6854. case value_t::object:
  6855. {
  6856. assert(m_it.object_iterator != m_object->m_value.object->end());
  6857. return &(m_it.object_iterator->second);
  6858. }
  6859. case value_t::array:
  6860. {
  6861. assert(m_it.array_iterator != m_object->m_value.array->end());
  6862. return &*m_it.array_iterator;
  6863. }
  6864. default:
  6865. {
  6866. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  6867. {
  6868. return m_object;
  6869. }
  6870. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  6871. }
  6872. }
  6873. }
  6874. /*!
  6875. @brief post-increment (it++)
  6876. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6877. */
  6878. iter_impl const operator++(int)
  6879. {
  6880. auto result = *this;
  6881. ++(*this);
  6882. return result;
  6883. }
  6884. /*!
  6885. @brief pre-increment (++it)
  6886. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6887. */
  6888. iter_impl& operator++()
  6889. {
  6890. assert(m_object != nullptr);
  6891. switch (m_object->m_type)
  6892. {
  6893. case value_t::object:
  6894. {
  6895. std::advance(m_it.object_iterator, 1);
  6896. break;
  6897. }
  6898. case value_t::array:
  6899. {
  6900. std::advance(m_it.array_iterator, 1);
  6901. break;
  6902. }
  6903. default:
  6904. {
  6905. ++m_it.primitive_iterator;
  6906. break;
  6907. }
  6908. }
  6909. return *this;
  6910. }
  6911. /*!
  6912. @brief post-decrement (it--)
  6913. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6914. */
  6915. iter_impl const operator--(int)
  6916. {
  6917. auto result = *this;
  6918. --(*this);
  6919. return result;
  6920. }
  6921. /*!
  6922. @brief pre-decrement (--it)
  6923. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6924. */
  6925. iter_impl& operator--()
  6926. {
  6927. assert(m_object != nullptr);
  6928. switch (m_object->m_type)
  6929. {
  6930. case value_t::object:
  6931. {
  6932. std::advance(m_it.object_iterator, -1);
  6933. break;
  6934. }
  6935. case value_t::array:
  6936. {
  6937. std::advance(m_it.array_iterator, -1);
  6938. break;
  6939. }
  6940. default:
  6941. {
  6942. --m_it.primitive_iterator;
  6943. break;
  6944. }
  6945. }
  6946. return *this;
  6947. }
  6948. /*!
  6949. @brief comparison: equal
  6950. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6951. */
  6952. bool operator==(const iter_impl& other) const
  6953. {
  6954. // if objects are not the same, the comparison is undefined
  6955. if (JSON_UNLIKELY(m_object != other.m_object))
  6956. {
  6957. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  6958. }
  6959. assert(m_object != nullptr);
  6960. switch (m_object->m_type)
  6961. {
  6962. case value_t::object:
  6963. return (m_it.object_iterator == other.m_it.object_iterator);
  6964. case value_t::array:
  6965. return (m_it.array_iterator == other.m_it.array_iterator);
  6966. default:
  6967. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  6968. }
  6969. }
  6970. /*!
  6971. @brief comparison: not equal
  6972. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6973. */
  6974. bool operator!=(const iter_impl& other) const
  6975. {
  6976. return not operator==(other);
  6977. }
  6978. /*!
  6979. @brief comparison: smaller
  6980. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6981. */
  6982. bool operator<(const iter_impl& other) const
  6983. {
  6984. // if objects are not the same, the comparison is undefined
  6985. if (JSON_UNLIKELY(m_object != other.m_object))
  6986. {
  6987. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  6988. }
  6989. assert(m_object != nullptr);
  6990. switch (m_object->m_type)
  6991. {
  6992. case value_t::object:
  6993. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  6994. case value_t::array:
  6995. return (m_it.array_iterator < other.m_it.array_iterator);
  6996. default:
  6997. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  6998. }
  6999. }
  7000. /*!
  7001. @brief comparison: less than or equal
  7002. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7003. */
  7004. bool operator<=(const iter_impl& other) const
  7005. {
  7006. return not other.operator < (*this);
  7007. }
  7008. /*!
  7009. @brief comparison: greater than
  7010. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7011. */
  7012. bool operator>(const iter_impl& other) const
  7013. {
  7014. return not operator<=(other);
  7015. }
  7016. /*!
  7017. @brief comparison: greater than or equal
  7018. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7019. */
  7020. bool operator>=(const iter_impl& other) const
  7021. {
  7022. return not operator<(other);
  7023. }
  7024. /*!
  7025. @brief add to iterator
  7026. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7027. */
  7028. iter_impl& operator+=(difference_type i)
  7029. {
  7030. assert(m_object != nullptr);
  7031. switch (m_object->m_type)
  7032. {
  7033. case value_t::object:
  7034. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  7035. case value_t::array:
  7036. {
  7037. std::advance(m_it.array_iterator, i);
  7038. break;
  7039. }
  7040. default:
  7041. {
  7042. m_it.primitive_iterator += i;
  7043. break;
  7044. }
  7045. }
  7046. return *this;
  7047. }
  7048. /*!
  7049. @brief subtract from iterator
  7050. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7051. */
  7052. iter_impl& operator-=(difference_type i)
  7053. {
  7054. return operator+=(-i);
  7055. }
  7056. /*!
  7057. @brief add to iterator
  7058. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7059. */
  7060. iter_impl operator+(difference_type i) const
  7061. {
  7062. auto result = *this;
  7063. result += i;
  7064. return result;
  7065. }
  7066. /*!
  7067. @brief addition of distance and iterator
  7068. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7069. */
  7070. friend iter_impl operator+(difference_type i, const iter_impl& it)
  7071. {
  7072. auto result = it;
  7073. result += i;
  7074. return result;
  7075. }
  7076. /*!
  7077. @brief subtract from iterator
  7078. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7079. */
  7080. iter_impl operator-(difference_type i) const
  7081. {
  7082. auto result = *this;
  7083. result -= i;
  7084. return result;
  7085. }
  7086. /*!
  7087. @brief return difference
  7088. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7089. */
  7090. difference_type operator-(const iter_impl& other) const
  7091. {
  7092. assert(m_object != nullptr);
  7093. switch (m_object->m_type)
  7094. {
  7095. case value_t::object:
  7096. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  7097. case value_t::array:
  7098. return m_it.array_iterator - other.m_it.array_iterator;
  7099. default:
  7100. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  7101. }
  7102. }
  7103. /*!
  7104. @brief access to successor
  7105. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7106. */
  7107. reference operator[](difference_type n) const
  7108. {
  7109. assert(m_object != nullptr);
  7110. switch (m_object->m_type)
  7111. {
  7112. case value_t::object:
  7113. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  7114. case value_t::array:
  7115. return *std::next(m_it.array_iterator, n);
  7116. case value_t::null:
  7117. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  7118. default:
  7119. {
  7120. if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
  7121. {
  7122. return *m_object;
  7123. }
  7124. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  7125. }
  7126. }
  7127. }
  7128. /*!
  7129. @brief return the key of an object iterator
  7130. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7131. */
  7132. const typename object_t::key_type& key() const
  7133. {
  7134. assert(m_object != nullptr);
  7135. if (JSON_LIKELY(m_object->is_object()))
  7136. {
  7137. return m_it.object_iterator->first;
  7138. }
  7139. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  7140. }
  7141. /*!
  7142. @brief return the value of an iterator
  7143. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7144. */
  7145. reference value() const
  7146. {
  7147. return operator*();
  7148. }
  7149. private:
  7150. /// associated JSON instance
  7151. pointer m_object = nullptr;
  7152. /// the actual iterator of the associated instance
  7153. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  7154. };
  7155. } // namespace detail
  7156. } // namespace nlohmann
  7157. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  7158. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  7159. #include <cstddef> // ptrdiff_t
  7160. #include <iterator> // reverse_iterator
  7161. #include <utility> // declval
  7162. namespace nlohmann
  7163. {
  7164. namespace detail
  7165. {
  7166. //////////////////////
  7167. // reverse_iterator //
  7168. //////////////////////
  7169. /*!
  7170. @brief a template for a reverse iterator class
  7171. @tparam Base the base iterator type to reverse. Valid types are @ref
  7172. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  7173. create @ref const_reverse_iterator).
  7174. @requirement The class satisfies the following concept requirements:
  7175. -
  7176. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  7177. The iterator that can be moved can be moved in both directions (i.e.
  7178. incremented and decremented).
  7179. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  7180. It is possible to write to the pointed-to element (only if @a Base is
  7181. @ref iterator).
  7182. @since version 1.0.0
  7183. */
  7184. template<typename Base>
  7185. class json_reverse_iterator : public std::reverse_iterator<Base>
  7186. {
  7187. public:
  7188. using difference_type = std::ptrdiff_t;
  7189. /// shortcut to the reverse iterator adapter
  7190. using base_iterator = std::reverse_iterator<Base>;
  7191. /// the reference type for the pointed-to element
  7192. using reference = typename Base::reference;
  7193. /// create reverse iterator from iterator
  7194. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  7195. : base_iterator(it) {}
  7196. /// create reverse iterator from base class
  7197. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  7198. /// post-increment (it++)
  7199. json_reverse_iterator const operator++(int)
  7200. {
  7201. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  7202. }
  7203. /// pre-increment (++it)
  7204. json_reverse_iterator& operator++()
  7205. {
  7206. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  7207. }
  7208. /// post-decrement (it--)
  7209. json_reverse_iterator const operator--(int)
  7210. {
  7211. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  7212. }
  7213. /// pre-decrement (--it)
  7214. json_reverse_iterator& operator--()
  7215. {
  7216. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  7217. }
  7218. /// add to iterator
  7219. json_reverse_iterator& operator+=(difference_type i)
  7220. {
  7221. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  7222. }
  7223. /// add to iterator
  7224. json_reverse_iterator operator+(difference_type i) const
  7225. {
  7226. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  7227. }
  7228. /// subtract from iterator
  7229. json_reverse_iterator operator-(difference_type i) const
  7230. {
  7231. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  7232. }
  7233. /// return difference
  7234. difference_type operator-(const json_reverse_iterator& other) const
  7235. {
  7236. return base_iterator(*this) - base_iterator(other);
  7237. }
  7238. /// access to successor
  7239. reference operator[](difference_type n) const
  7240. {
  7241. return *(this->operator+(n));
  7242. }
  7243. /// return the key of an object iterator
  7244. auto key() const -> decltype(std::declval<Base>().key())
  7245. {
  7246. auto it = --this->base();
  7247. return it.key();
  7248. }
  7249. /// return the value of an iterator
  7250. reference value() const
  7251. {
  7252. auto it = --this->base();
  7253. return it.operator * ();
  7254. }
  7255. };
  7256. } // namespace detail
  7257. } // namespace nlohmann
  7258. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  7259. // #include <nlohmann/detail/json_pointer.hpp>
  7260. #include <algorithm> // all_of
  7261. #include <cassert> // assert
  7262. #include <numeric> // accumulate
  7263. #include <string> // string
  7264. #include <utility> // move
  7265. #include <vector> // vector
  7266. // #include <nlohmann/detail/exceptions.hpp>
  7267. // #include <nlohmann/detail/macro_scope.hpp>
  7268. // #include <nlohmann/detail/value_t.hpp>
  7269. namespace nlohmann
  7270. {
  7271. template<typename BasicJsonType>
  7272. class json_pointer
  7273. {
  7274. // allow basic_json to access private members
  7275. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  7276. friend class basic_json;
  7277. public:
  7278. /*!
  7279. @brief create JSON pointer
  7280. Create a JSON pointer according to the syntax described in
  7281. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  7282. @param[in] s string representing the JSON pointer; if omitted, the empty
  7283. string is assumed which references the whole JSON value
  7284. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  7285. not begin with a slash (`/`); see example below
  7286. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  7287. not followed by `0` (representing `~`) or `1` (representing `/`); see
  7288. example below
  7289. @liveexample{The example shows the construction several valid JSON pointers
  7290. as well as the exceptional behavior.,json_pointer}
  7291. @since version 2.0.0
  7292. */
  7293. explicit json_pointer(const std::string& s = "")
  7294. : reference_tokens(split(s))
  7295. {}
  7296. /*!
  7297. @brief return a string representation of the JSON pointer
  7298. @invariant For each JSON pointer `ptr`, it holds:
  7299. @code {.cpp}
  7300. ptr == json_pointer(ptr.to_string());
  7301. @endcode
  7302. @return a string representation of the JSON pointer
  7303. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  7304. @since version 2.0.0
  7305. */
  7306. std::string to_string() const
  7307. {
  7308. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  7309. std::string{},
  7310. [](const std::string & a, const std::string & b)
  7311. {
  7312. return a + "/" + escape(b);
  7313. });
  7314. }
  7315. /// @copydoc to_string()
  7316. operator std::string() const
  7317. {
  7318. return to_string();
  7319. }
  7320. /*!
  7321. @brief append another JSON pointer at the end of this JSON pointer
  7322. @param[in] ptr JSON pointer to append
  7323. @return JSON pointer with @a ptr appended
  7324. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  7325. @complexity Linear in the length of @a ptr.
  7326. @sa @ref operator/=(std::string) to append a reference token
  7327. @sa @ref operator/=(std::size_t) to append an array index
  7328. @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  7329. @since version 3.6.0
  7330. */
  7331. json_pointer& operator/=(const json_pointer& ptr)
  7332. {
  7333. reference_tokens.insert(reference_tokens.end(),
  7334. ptr.reference_tokens.begin(),
  7335. ptr.reference_tokens.end());
  7336. return *this;
  7337. }
  7338. /*!
  7339. @brief append an unescaped reference token at the end of this JSON pointer
  7340. @param[in] token reference token to append
  7341. @return JSON pointer with @a token appended without escaping @a token
  7342. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  7343. @complexity Amortized constant.
  7344. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  7345. @sa @ref operator/=(std::size_t) to append an array index
  7346. @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator
  7347. @since version 3.6.0
  7348. */
  7349. json_pointer& operator/=(std::string token)
  7350. {
  7351. push_back(std::move(token));
  7352. return *this;
  7353. }
  7354. /*!
  7355. @brief append an array index at the end of this JSON pointer
  7356. @param[in] array_index array index ot append
  7357. @return JSON pointer with @a array_index appended
  7358. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  7359. @complexity Amortized constant.
  7360. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  7361. @sa @ref operator/=(std::string) to append a reference token
  7362. @sa @ref operator/(const json_pointer&, std::string) for a binary operator
  7363. @since version 3.6.0
  7364. */
  7365. json_pointer& operator/=(std::size_t array_index)
  7366. {
  7367. return *this /= std::to_string(array_index);
  7368. }
  7369. /*!
  7370. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  7371. @param[in] lhs JSON pointer
  7372. @param[in] rhs JSON pointer
  7373. @return a new JSON pointer with @a rhs appended to @a lhs
  7374. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  7375. @complexity Linear in the length of @a lhs and @a rhs.
  7376. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  7377. @since version 3.6.0
  7378. */
  7379. friend json_pointer operator/(const json_pointer& lhs,
  7380. const json_pointer& rhs)
  7381. {
  7382. return json_pointer(lhs) /= rhs;
  7383. }
  7384. /*!
  7385. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  7386. @param[in] ptr JSON pointer
  7387. @param[in] token reference token
  7388. @return a new JSON pointer with unescaped @a token appended to @a ptr
  7389. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  7390. @complexity Linear in the length of @a ptr.
  7391. @sa @ref operator/=(std::string) to append a reference token
  7392. @since version 3.6.0
  7393. */
  7394. friend json_pointer operator/(const json_pointer& ptr, std::string token)
  7395. {
  7396. return json_pointer(ptr) /= std::move(token);
  7397. }
  7398. /*!
  7399. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  7400. @param[in] ptr JSON pointer
  7401. @param[in] array_index array index
  7402. @return a new JSON pointer with @a array_index appended to @a ptr
  7403. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  7404. @complexity Linear in the length of @a ptr.
  7405. @sa @ref operator/=(std::size_t) to append an array index
  7406. @since version 3.6.0
  7407. */
  7408. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_index)
  7409. {
  7410. return json_pointer(ptr) /= array_index;
  7411. }
  7412. /*!
  7413. @brief returns the parent of this JSON pointer
  7414. @return parent of this JSON pointer; in case this JSON pointer is the root,
  7415. the root itself is returned
  7416. @complexity Linear in the length of the JSON pointer.
  7417. @liveexample{The example shows the result of `parent_pointer` for different
  7418. JSON Pointers.,json_pointer__parent_pointer}
  7419. @since version 3.6.0
  7420. */
  7421. json_pointer parent_pointer() const
  7422. {
  7423. if (empty())
  7424. {
  7425. return *this;
  7426. }
  7427. json_pointer res = *this;
  7428. res.pop_back();
  7429. return res;
  7430. }
  7431. /*!
  7432. @brief remove last reference token
  7433. @pre not `empty()`
  7434. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  7435. @complexity Constant.
  7436. @throw out_of_range.405 if JSON pointer has no parent
  7437. @since version 3.6.0
  7438. */
  7439. void pop_back()
  7440. {
  7441. if (JSON_UNLIKELY(empty()))
  7442. {
  7443. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  7444. }
  7445. reference_tokens.pop_back();
  7446. }
  7447. /*!
  7448. @brief return last reference token
  7449. @pre not `empty()`
  7450. @return last reference token
  7451. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  7452. @complexity Constant.
  7453. @throw out_of_range.405 if JSON pointer has no parent
  7454. @since version 3.6.0
  7455. */
  7456. const std::string& back()
  7457. {
  7458. if (JSON_UNLIKELY(empty()))
  7459. {
  7460. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  7461. }
  7462. return reference_tokens.back();
  7463. }
  7464. /*!
  7465. @brief append an unescaped token at the end of the reference pointer
  7466. @param[in] token token to add
  7467. @complexity Amortized constant.
  7468. @liveexample{The example shows the result of `push_back` for different
  7469. JSON Pointers.,json_pointer__push_back}
  7470. @since version 3.6.0
  7471. */
  7472. void push_back(const std::string& token)
  7473. {
  7474. reference_tokens.push_back(token);
  7475. }
  7476. /// @copydoc push_back(const std::string&)
  7477. void push_back(std::string&& token)
  7478. {
  7479. reference_tokens.push_back(std::move(token));
  7480. }
  7481. /*!
  7482. @brief return whether pointer points to the root document
  7483. @return true iff the JSON pointer points to the root document
  7484. @complexity Constant.
  7485. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  7486. @liveexample{The example shows the result of `empty` for different JSON
  7487. Pointers.,json_pointer__empty}
  7488. @since version 3.6.0
  7489. */
  7490. bool empty() const noexcept
  7491. {
  7492. return reference_tokens.empty();
  7493. }
  7494. private:
  7495. /*!
  7496. @param[in] s reference token to be converted into an array index
  7497. @return integer representation of @a s
  7498. @throw out_of_range.404 if string @a s could not be converted to an integer
  7499. */
  7500. static int array_index(const std::string& s)
  7501. {
  7502. std::size_t processed_chars = 0;
  7503. const int res = std::stoi(s, &processed_chars);
  7504. // check if the string was completely read
  7505. if (JSON_UNLIKELY(processed_chars != s.size()))
  7506. {
  7507. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  7508. }
  7509. return res;
  7510. }
  7511. json_pointer top() const
  7512. {
  7513. if (JSON_UNLIKELY(empty()))
  7514. {
  7515. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  7516. }
  7517. json_pointer result = *this;
  7518. result.reference_tokens = {reference_tokens[0]};
  7519. return result;
  7520. }
  7521. /*!
  7522. @brief create and return a reference to the pointed to value
  7523. @complexity Linear in the number of reference tokens.
  7524. @throw parse_error.109 if array index is not a number
  7525. @throw type_error.313 if value cannot be unflattened
  7526. */
  7527. BasicJsonType& get_and_create(BasicJsonType& j) const
  7528. {
  7529. using size_type = typename BasicJsonType::size_type;
  7530. auto result = &j;
  7531. // in case no reference tokens exist, return a reference to the JSON value
  7532. // j which will be overwritten by a primitive value
  7533. for (const auto& reference_token : reference_tokens)
  7534. {
  7535. switch (result->m_type)
  7536. {
  7537. case detail::value_t::null:
  7538. {
  7539. if (reference_token == "0")
  7540. {
  7541. // start a new array if reference token is 0
  7542. result = &result->operator[](0);
  7543. }
  7544. else
  7545. {
  7546. // start a new object otherwise
  7547. result = &result->operator[](reference_token);
  7548. }
  7549. break;
  7550. }
  7551. case detail::value_t::object:
  7552. {
  7553. // create an entry in the object
  7554. result = &result->operator[](reference_token);
  7555. break;
  7556. }
  7557. case detail::value_t::array:
  7558. {
  7559. // create an entry in the array
  7560. JSON_TRY
  7561. {
  7562. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  7563. }
  7564. JSON_CATCH(std::invalid_argument&)
  7565. {
  7566. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  7567. }
  7568. break;
  7569. }
  7570. /*
  7571. The following code is only reached if there exists a reference
  7572. token _and_ the current value is primitive. In this case, we have
  7573. an error situation, because primitive values may only occur as
  7574. single value; that is, with an empty list of reference tokens.
  7575. */
  7576. default:
  7577. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  7578. }
  7579. }
  7580. return *result;
  7581. }
  7582. /*!
  7583. @brief return a reference to the pointed to value
  7584. @note This version does not throw if a value is not present, but tries to
  7585. create nested values instead. For instance, calling this function
  7586. with pointer `"/this/that"` on a null value is equivalent to calling
  7587. `operator[]("this").operator[]("that")` on that value, effectively
  7588. changing the null value to an object.
  7589. @param[in] ptr a JSON value
  7590. @return reference to the JSON value pointed to by the JSON pointer
  7591. @complexity Linear in the length of the JSON pointer.
  7592. @throw parse_error.106 if an array index begins with '0'
  7593. @throw parse_error.109 if an array index was not a number
  7594. @throw out_of_range.404 if the JSON pointer can not be resolved
  7595. */
  7596. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  7597. {
  7598. using size_type = typename BasicJsonType::size_type;
  7599. for (const auto& reference_token : reference_tokens)
  7600. {
  7601. // convert null values to arrays or objects before continuing
  7602. if (ptr->m_type == detail::value_t::null)
  7603. {
  7604. // check if reference token is a number
  7605. const bool nums =
  7606. std::all_of(reference_token.begin(), reference_token.end(),
  7607. [](const char x)
  7608. {
  7609. return x >= '0' and x <= '9';
  7610. });
  7611. // change value to array for numbers or "-" or to object otherwise
  7612. *ptr = (nums or reference_token == "-")
  7613. ? detail::value_t::array
  7614. : detail::value_t::object;
  7615. }
  7616. switch (ptr->m_type)
  7617. {
  7618. case detail::value_t::object:
  7619. {
  7620. // use unchecked object access
  7621. ptr = &ptr->operator[](reference_token);
  7622. break;
  7623. }
  7624. case detail::value_t::array:
  7625. {
  7626. // error condition (cf. RFC 6901, Sect. 4)
  7627. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  7628. {
  7629. JSON_THROW(detail::parse_error::create(106, 0,
  7630. "array index '" + reference_token +
  7631. "' must not begin with '0'"));
  7632. }
  7633. if (reference_token == "-")
  7634. {
  7635. // explicitly treat "-" as index beyond the end
  7636. ptr = &ptr->operator[](ptr->m_value.array->size());
  7637. }
  7638. else
  7639. {
  7640. // convert array index to number; unchecked access
  7641. JSON_TRY
  7642. {
  7643. ptr = &ptr->operator[](
  7644. static_cast<size_type>(array_index(reference_token)));
  7645. }
  7646. JSON_CATCH(std::invalid_argument&)
  7647. {
  7648. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  7649. }
  7650. }
  7651. break;
  7652. }
  7653. default:
  7654. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  7655. }
  7656. }
  7657. return *ptr;
  7658. }
  7659. /*!
  7660. @throw parse_error.106 if an array index begins with '0'
  7661. @throw parse_error.109 if an array index was not a number
  7662. @throw out_of_range.402 if the array index '-' is used
  7663. @throw out_of_range.404 if the JSON pointer can not be resolved
  7664. */
  7665. BasicJsonType& get_checked(BasicJsonType* ptr) const
  7666. {
  7667. using size_type = typename BasicJsonType::size_type;
  7668. for (const auto& reference_token : reference_tokens)
  7669. {
  7670. switch (ptr->m_type)
  7671. {
  7672. case detail::value_t::object:
  7673. {
  7674. // note: at performs range check
  7675. ptr = &ptr->at(reference_token);
  7676. break;
  7677. }
  7678. case detail::value_t::array:
  7679. {
  7680. if (JSON_UNLIKELY(reference_token == "-"))
  7681. {
  7682. // "-" always fails the range check
  7683. JSON_THROW(detail::out_of_range::create(402,
  7684. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  7685. ") is out of range"));
  7686. }
  7687. // error condition (cf. RFC 6901, Sect. 4)
  7688. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  7689. {
  7690. JSON_THROW(detail::parse_error::create(106, 0,
  7691. "array index '" + reference_token +
  7692. "' must not begin with '0'"));
  7693. }
  7694. // note: at performs range check
  7695. JSON_TRY
  7696. {
  7697. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  7698. }
  7699. JSON_CATCH(std::invalid_argument&)
  7700. {
  7701. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  7702. }
  7703. break;
  7704. }
  7705. default:
  7706. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  7707. }
  7708. }
  7709. return *ptr;
  7710. }
  7711. /*!
  7712. @brief return a const reference to the pointed to value
  7713. @param[in] ptr a JSON value
  7714. @return const reference to the JSON value pointed to by the JSON
  7715. pointer
  7716. @throw parse_error.106 if an array index begins with '0'
  7717. @throw parse_error.109 if an array index was not a number
  7718. @throw out_of_range.402 if the array index '-' is used
  7719. @throw out_of_range.404 if the JSON pointer can not be resolved
  7720. */
  7721. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  7722. {
  7723. using size_type = typename BasicJsonType::size_type;
  7724. for (const auto& reference_token : reference_tokens)
  7725. {
  7726. switch (ptr->m_type)
  7727. {
  7728. case detail::value_t::object:
  7729. {
  7730. // use unchecked object access
  7731. ptr = &ptr->operator[](reference_token);
  7732. break;
  7733. }
  7734. case detail::value_t::array:
  7735. {
  7736. if (JSON_UNLIKELY(reference_token == "-"))
  7737. {
  7738. // "-" cannot be used for const access
  7739. JSON_THROW(detail::out_of_range::create(402,
  7740. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  7741. ") is out of range"));
  7742. }
  7743. // error condition (cf. RFC 6901, Sect. 4)
  7744. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  7745. {
  7746. JSON_THROW(detail::parse_error::create(106, 0,
  7747. "array index '" + reference_token +
  7748. "' must not begin with '0'"));
  7749. }
  7750. // use unchecked array access
  7751. JSON_TRY
  7752. {
  7753. ptr = &ptr->operator[](
  7754. static_cast<size_type>(array_index(reference_token)));
  7755. }
  7756. JSON_CATCH(std::invalid_argument&)
  7757. {
  7758. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  7759. }
  7760. break;
  7761. }
  7762. default:
  7763. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  7764. }
  7765. }
  7766. return *ptr;
  7767. }
  7768. /*!
  7769. @throw parse_error.106 if an array index begins with '0'
  7770. @throw parse_error.109 if an array index was not a number
  7771. @throw out_of_range.402 if the array index '-' is used
  7772. @throw out_of_range.404 if the JSON pointer can not be resolved
  7773. */
  7774. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  7775. {
  7776. using size_type = typename BasicJsonType::size_type;
  7777. for (const auto& reference_token : reference_tokens)
  7778. {
  7779. switch (ptr->m_type)
  7780. {
  7781. case detail::value_t::object:
  7782. {
  7783. // note: at performs range check
  7784. ptr = &ptr->at(reference_token);
  7785. break;
  7786. }
  7787. case detail::value_t::array:
  7788. {
  7789. if (JSON_UNLIKELY(reference_token == "-"))
  7790. {
  7791. // "-" always fails the range check
  7792. JSON_THROW(detail::out_of_range::create(402,
  7793. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  7794. ") is out of range"));
  7795. }
  7796. // error condition (cf. RFC 6901, Sect. 4)
  7797. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  7798. {
  7799. JSON_THROW(detail::parse_error::create(106, 0,
  7800. "array index '" + reference_token +
  7801. "' must not begin with '0'"));
  7802. }
  7803. // note: at performs range check
  7804. JSON_TRY
  7805. {
  7806. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  7807. }
  7808. JSON_CATCH(std::invalid_argument&)
  7809. {
  7810. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  7811. }
  7812. break;
  7813. }
  7814. default:
  7815. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  7816. }
  7817. }
  7818. return *ptr;
  7819. }
  7820. /*!
  7821. @brief split the string input to reference tokens
  7822. @note This function is only called by the json_pointer constructor.
  7823. All exceptions below are documented there.
  7824. @throw parse_error.107 if the pointer is not empty or begins with '/'
  7825. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  7826. */
  7827. static std::vector<std::string> split(const std::string& reference_string)
  7828. {
  7829. std::vector<std::string> result;
  7830. // special case: empty reference string -> no reference tokens
  7831. if (reference_string.empty())
  7832. {
  7833. return result;
  7834. }
  7835. // check if nonempty reference string begins with slash
  7836. if (JSON_UNLIKELY(reference_string[0] != '/'))
  7837. {
  7838. JSON_THROW(detail::parse_error::create(107, 1,
  7839. "JSON pointer must be empty or begin with '/' - was: '" +
  7840. reference_string + "'"));
  7841. }
  7842. // extract the reference tokens:
  7843. // - slash: position of the last read slash (or end of string)
  7844. // - start: position after the previous slash
  7845. for (
  7846. // search for the first slash after the first character
  7847. std::size_t slash = reference_string.find_first_of('/', 1),
  7848. // set the beginning of the first reference token
  7849. start = 1;
  7850. // we can stop if start == 0 (if slash == std::string::npos)
  7851. start != 0;
  7852. // set the beginning of the next reference token
  7853. // (will eventually be 0 if slash == std::string::npos)
  7854. start = (slash == std::string::npos) ? 0 : slash + 1,
  7855. // find next slash
  7856. slash = reference_string.find_first_of('/', start))
  7857. {
  7858. // use the text between the beginning of the reference token
  7859. // (start) and the last slash (slash).
  7860. auto reference_token = reference_string.substr(start, slash - start);
  7861. // check reference tokens are properly escaped
  7862. for (std::size_t pos = reference_token.find_first_of('~');
  7863. pos != std::string::npos;
  7864. pos = reference_token.find_first_of('~', pos + 1))
  7865. {
  7866. assert(reference_token[pos] == '~');
  7867. // ~ must be followed by 0 or 1
  7868. if (JSON_UNLIKELY(pos == reference_token.size() - 1 or
  7869. (reference_token[pos + 1] != '0' and
  7870. reference_token[pos + 1] != '1')))
  7871. {
  7872. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  7873. }
  7874. }
  7875. // finally, store the reference token
  7876. unescape(reference_token);
  7877. result.push_back(reference_token);
  7878. }
  7879. return result;
  7880. }
  7881. /*!
  7882. @brief replace all occurrences of a substring by another string
  7883. @param[in,out] s the string to manipulate; changed so that all
  7884. occurrences of @a f are replaced with @a t
  7885. @param[in] f the substring to replace with @a t
  7886. @param[in] t the string to replace @a f
  7887. @pre The search string @a f must not be empty. **This precondition is
  7888. enforced with an assertion.**
  7889. @since version 2.0.0
  7890. */
  7891. static void replace_substring(std::string& s, const std::string& f,
  7892. const std::string& t)
  7893. {
  7894. assert(not f.empty());
  7895. for (auto pos = s.find(f); // find first occurrence of f
  7896. pos != std::string::npos; // make sure f was found
  7897. s.replace(pos, f.size(), t), // replace with t, and
  7898. pos = s.find(f, pos + t.size())) // find next occurrence of f
  7899. {}
  7900. }
  7901. /// escape "~" to "~0" and "/" to "~1"
  7902. static std::string escape(std::string s)
  7903. {
  7904. replace_substring(s, "~", "~0");
  7905. replace_substring(s, "/", "~1");
  7906. return s;
  7907. }
  7908. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  7909. static void unescape(std::string& s)
  7910. {
  7911. replace_substring(s, "~1", "/");
  7912. replace_substring(s, "~0", "~");
  7913. }
  7914. /*!
  7915. @param[in] reference_string the reference string to the current value
  7916. @param[in] value the value to consider
  7917. @param[in,out] result the result object to insert values to
  7918. @note Empty objects or arrays are flattened to `null`.
  7919. */
  7920. static void flatten(const std::string& reference_string,
  7921. const BasicJsonType& value,
  7922. BasicJsonType& result)
  7923. {
  7924. switch (value.m_type)
  7925. {
  7926. case detail::value_t::array:
  7927. {
  7928. if (value.m_value.array->empty())
  7929. {
  7930. // flatten empty array as null
  7931. result[reference_string] = nullptr;
  7932. }
  7933. else
  7934. {
  7935. // iterate array and use index as reference string
  7936. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  7937. {
  7938. flatten(reference_string + "/" + std::to_string(i),
  7939. value.m_value.array->operator[](i), result);
  7940. }
  7941. }
  7942. break;
  7943. }
  7944. case detail::value_t::object:
  7945. {
  7946. if (value.m_value.object->empty())
  7947. {
  7948. // flatten empty object as null
  7949. result[reference_string] = nullptr;
  7950. }
  7951. else
  7952. {
  7953. // iterate object and use keys as reference string
  7954. for (const auto& element : *value.m_value.object)
  7955. {
  7956. flatten(reference_string + "/" + escape(element.first), element.second, result);
  7957. }
  7958. }
  7959. break;
  7960. }
  7961. default:
  7962. {
  7963. // add primitive value with its reference string
  7964. result[reference_string] = value;
  7965. break;
  7966. }
  7967. }
  7968. }
  7969. /*!
  7970. @param[in] value flattened JSON
  7971. @return unflattened JSON
  7972. @throw parse_error.109 if array index is not a number
  7973. @throw type_error.314 if value is not an object
  7974. @throw type_error.315 if object values are not primitive
  7975. @throw type_error.313 if value cannot be unflattened
  7976. */
  7977. static BasicJsonType
  7978. unflatten(const BasicJsonType& value)
  7979. {
  7980. if (JSON_UNLIKELY(not value.is_object()))
  7981. {
  7982. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  7983. }
  7984. BasicJsonType result;
  7985. // iterate the JSON object values
  7986. for (const auto& element : *value.m_value.object)
  7987. {
  7988. if (JSON_UNLIKELY(not element.second.is_primitive()))
  7989. {
  7990. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  7991. }
  7992. // assign value to reference pointed to by JSON pointer; Note that if
  7993. // the JSON pointer is "" (i.e., points to the whole value), function
  7994. // get_and_create returns a reference to result itself. An assignment
  7995. // will then create a primitive value.
  7996. json_pointer(element.first).get_and_create(result) = element.second;
  7997. }
  7998. return result;
  7999. }
  8000. /*!
  8001. @brief compares two JSON pointers for equality
  8002. @param[in] lhs JSON pointer to compare
  8003. @param[in] rhs JSON pointer to compare
  8004. @return whether @a lhs is equal to @a rhs
  8005. @complexity Linear in the length of the JSON pointer
  8006. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  8007. */
  8008. friend bool operator==(json_pointer const& lhs,
  8009. json_pointer const& rhs) noexcept
  8010. {
  8011. return lhs.reference_tokens == rhs.reference_tokens;
  8012. }
  8013. /*!
  8014. @brief compares two JSON pointers for inequality
  8015. @param[in] lhs JSON pointer to compare
  8016. @param[in] rhs JSON pointer to compare
  8017. @return whether @a lhs is not equal @a rhs
  8018. @complexity Linear in the length of the JSON pointer
  8019. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  8020. */
  8021. friend bool operator!=(json_pointer const& lhs,
  8022. json_pointer const& rhs) noexcept
  8023. {
  8024. return not (lhs == rhs);
  8025. }
  8026. /// the reference tokens
  8027. std::vector<std::string> reference_tokens;
  8028. };
  8029. } // namespace nlohmann
  8030. // #include <nlohmann/detail/json_ref.hpp>
  8031. #include <initializer_list>
  8032. #include <utility>
  8033. // #include <nlohmann/detail/meta/type_traits.hpp>
  8034. namespace nlohmann
  8035. {
  8036. namespace detail
  8037. {
  8038. template<typename BasicJsonType>
  8039. class json_ref
  8040. {
  8041. public:
  8042. using value_type = BasicJsonType;
  8043. json_ref(value_type&& value)
  8044. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  8045. {}
  8046. json_ref(const value_type& value)
  8047. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  8048. {}
  8049. json_ref(std::initializer_list<json_ref> init)
  8050. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  8051. {}
  8052. template <
  8053. class... Args,
  8054. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  8055. json_ref(Args && ... args)
  8056. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value),
  8057. is_rvalue(true) {}
  8058. // class should be movable only
  8059. json_ref(json_ref&&) = default;
  8060. json_ref(const json_ref&) = delete;
  8061. json_ref& operator=(const json_ref&) = delete;
  8062. json_ref& operator=(json_ref&&) = delete;
  8063. ~json_ref() = default;
  8064. value_type moved_or_copied() const
  8065. {
  8066. if (is_rvalue)
  8067. {
  8068. return std::move(*value_ref);
  8069. }
  8070. return *value_ref;
  8071. }
  8072. value_type const& operator*() const
  8073. {
  8074. return *static_cast<value_type const*>(value_ref);
  8075. }
  8076. value_type const* operator->() const
  8077. {
  8078. return static_cast<value_type const*>(value_ref);
  8079. }
  8080. private:
  8081. mutable value_type owned_value = nullptr;
  8082. value_type* value_ref = nullptr;
  8083. const bool is_rvalue;
  8084. };
  8085. } // namespace detail
  8086. } // namespace nlohmann
  8087. // #include <nlohmann/detail/macro_scope.hpp>
  8088. // #include <nlohmann/detail/meta/cpp_future.hpp>
  8089. // #include <nlohmann/detail/meta/type_traits.hpp>
  8090. // #include <nlohmann/detail/output/binary_writer.hpp>
  8091. #include <algorithm> // reverse
  8092. #include <array> // array
  8093. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  8094. #include <cstring> // memcpy
  8095. #include <limits> // numeric_limits
  8096. #include <string> // string
  8097. // #include <nlohmann/detail/input/binary_reader.hpp>
  8098. // #include <nlohmann/detail/output/output_adapters.hpp>
  8099. #include <algorithm> // copy
  8100. #include <cstddef> // size_t
  8101. #include <ios> // streamsize
  8102. #include <iterator> // back_inserter
  8103. #include <memory> // shared_ptr, make_shared
  8104. #include <ostream> // basic_ostream
  8105. #include <string> // basic_string
  8106. #include <vector> // vector
  8107. namespace nlohmann
  8108. {
  8109. namespace detail
  8110. {
  8111. /// abstract output adapter interface
  8112. template<typename CharType> struct output_adapter_protocol
  8113. {
  8114. virtual void write_character(CharType c) = 0;
  8115. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  8116. virtual ~output_adapter_protocol() = default;
  8117. };
  8118. /// a type to simplify interfaces
  8119. template<typename CharType>
  8120. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  8121. /// output adapter for byte vectors
  8122. template<typename CharType>
  8123. class output_vector_adapter : public output_adapter_protocol<CharType>
  8124. {
  8125. public:
  8126. explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
  8127. : v(vec)
  8128. {}
  8129. void write_character(CharType c) override
  8130. {
  8131. v.push_back(c);
  8132. }
  8133. void write_characters(const CharType* s, std::size_t length) override
  8134. {
  8135. std::copy(s, s + length, std::back_inserter(v));
  8136. }
  8137. private:
  8138. std::vector<CharType>& v;
  8139. };
  8140. /// output adapter for output streams
  8141. template<typename CharType>
  8142. class output_stream_adapter : public output_adapter_protocol<CharType>
  8143. {
  8144. public:
  8145. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  8146. : stream(s)
  8147. {}
  8148. void write_character(CharType c) override
  8149. {
  8150. stream.put(c);
  8151. }
  8152. void write_characters(const CharType* s, std::size_t length) override
  8153. {
  8154. stream.write(s, static_cast<std::streamsize>(length));
  8155. }
  8156. private:
  8157. std::basic_ostream<CharType>& stream;
  8158. };
  8159. /// output adapter for basic_string
  8160. template<typename CharType, typename StringType = std::basic_string<CharType>>
  8161. class output_string_adapter : public output_adapter_protocol<CharType>
  8162. {
  8163. public:
  8164. explicit output_string_adapter(StringType& s) noexcept
  8165. : str(s)
  8166. {}
  8167. void write_character(CharType c) override
  8168. {
  8169. str.push_back(c);
  8170. }
  8171. void write_characters(const CharType* s, std::size_t length) override
  8172. {
  8173. str.append(s, length);
  8174. }
  8175. private:
  8176. StringType& str;
  8177. };
  8178. template<typename CharType, typename StringType = std::basic_string<CharType>>
  8179. class output_adapter
  8180. {
  8181. public:
  8182. output_adapter(std::vector<CharType>& vec)
  8183. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  8184. output_adapter(std::basic_ostream<CharType>& s)
  8185. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  8186. output_adapter(StringType& s)
  8187. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  8188. operator output_adapter_t<CharType>()
  8189. {
  8190. return oa;
  8191. }
  8192. private:
  8193. output_adapter_t<CharType> oa = nullptr;
  8194. };
  8195. } // namespace detail
  8196. } // namespace nlohmann
  8197. namespace nlohmann
  8198. {
  8199. namespace detail
  8200. {
  8201. ///////////////////
  8202. // binary writer //
  8203. ///////////////////
  8204. /*!
  8205. @brief serialization to CBOR and MessagePack values
  8206. */
  8207. template<typename BasicJsonType, typename CharType>
  8208. class binary_writer
  8209. {
  8210. using string_t = typename BasicJsonType::string_t;
  8211. public:
  8212. /*!
  8213. @brief create a binary writer
  8214. @param[in] adapter output adapter to write to
  8215. */
  8216. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  8217. {
  8218. assert(oa);
  8219. }
  8220. /*!
  8221. @param[in] j JSON value to serialize
  8222. @pre j.type() == value_t::object
  8223. */
  8224. void write_bson(const BasicJsonType& j)
  8225. {
  8226. switch (j.type())
  8227. {
  8228. case value_t::object:
  8229. {
  8230. write_bson_object(*j.m_value.object);
  8231. break;
  8232. }
  8233. default:
  8234. {
  8235. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
  8236. }
  8237. }
  8238. }
  8239. /*!
  8240. @param[in] j JSON value to serialize
  8241. */
  8242. void write_cbor(const BasicJsonType& j)
  8243. {
  8244. switch (j.type())
  8245. {
  8246. case value_t::null:
  8247. {
  8248. oa->write_character(to_char_type(0xF6));
  8249. break;
  8250. }
  8251. case value_t::boolean:
  8252. {
  8253. oa->write_character(j.m_value.boolean
  8254. ? to_char_type(0xF5)
  8255. : to_char_type(0xF4));
  8256. break;
  8257. }
  8258. case value_t::number_integer:
  8259. {
  8260. if (j.m_value.number_integer >= 0)
  8261. {
  8262. // CBOR does not differentiate between positive signed
  8263. // integers and unsigned integers. Therefore, we used the
  8264. // code from the value_t::number_unsigned case here.
  8265. if (j.m_value.number_integer <= 0x17)
  8266. {
  8267. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  8268. }
  8269. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  8270. {
  8271. oa->write_character(to_char_type(0x18));
  8272. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  8273. }
  8274. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  8275. {
  8276. oa->write_character(to_char_type(0x19));
  8277. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  8278. }
  8279. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  8280. {
  8281. oa->write_character(to_char_type(0x1A));
  8282. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  8283. }
  8284. else
  8285. {
  8286. oa->write_character(to_char_type(0x1B));
  8287. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  8288. }
  8289. }
  8290. else
  8291. {
  8292. // The conversions below encode the sign in the first
  8293. // byte, and the value is converted to a positive number.
  8294. const auto positive_number = -1 - j.m_value.number_integer;
  8295. if (j.m_value.number_integer >= -24)
  8296. {
  8297. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  8298. }
  8299. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  8300. {
  8301. oa->write_character(to_char_type(0x38));
  8302. write_number(static_cast<std::uint8_t>(positive_number));
  8303. }
  8304. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  8305. {
  8306. oa->write_character(to_char_type(0x39));
  8307. write_number(static_cast<std::uint16_t>(positive_number));
  8308. }
  8309. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  8310. {
  8311. oa->write_character(to_char_type(0x3A));
  8312. write_number(static_cast<std::uint32_t>(positive_number));
  8313. }
  8314. else
  8315. {
  8316. oa->write_character(to_char_type(0x3B));
  8317. write_number(static_cast<std::uint64_t>(positive_number));
  8318. }
  8319. }
  8320. break;
  8321. }
  8322. case value_t::number_unsigned:
  8323. {
  8324. if (j.m_value.number_unsigned <= 0x17)
  8325. {
  8326. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  8327. }
  8328. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  8329. {
  8330. oa->write_character(to_char_type(0x18));
  8331. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  8332. }
  8333. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  8334. {
  8335. oa->write_character(to_char_type(0x19));
  8336. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  8337. }
  8338. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  8339. {
  8340. oa->write_character(to_char_type(0x1A));
  8341. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  8342. }
  8343. else
  8344. {
  8345. oa->write_character(to_char_type(0x1B));
  8346. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  8347. }
  8348. break;
  8349. }
  8350. case value_t::number_float:
  8351. {
  8352. oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
  8353. write_number(j.m_value.number_float);
  8354. break;
  8355. }
  8356. case value_t::string:
  8357. {
  8358. // step 1: write control byte and the string length
  8359. const auto N = j.m_value.string->size();
  8360. if (N <= 0x17)
  8361. {
  8362. write_number(static_cast<std::uint8_t>(0x60 + N));
  8363. }
  8364. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  8365. {
  8366. oa->write_character(to_char_type(0x78));
  8367. write_number(static_cast<std::uint8_t>(N));
  8368. }
  8369. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  8370. {
  8371. oa->write_character(to_char_type(0x79));
  8372. write_number(static_cast<std::uint16_t>(N));
  8373. }
  8374. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  8375. {
  8376. oa->write_character(to_char_type(0x7A));
  8377. write_number(static_cast<std::uint32_t>(N));
  8378. }
  8379. // LCOV_EXCL_START
  8380. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  8381. {
  8382. oa->write_character(to_char_type(0x7B));
  8383. write_number(static_cast<std::uint64_t>(N));
  8384. }
  8385. // LCOV_EXCL_STOP
  8386. // step 2: write the string
  8387. oa->write_characters(
  8388. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  8389. j.m_value.string->size());
  8390. break;
  8391. }
  8392. case value_t::array:
  8393. {
  8394. // step 1: write control byte and the array size
  8395. const auto N = j.m_value.array->size();
  8396. if (N <= 0x17)
  8397. {
  8398. write_number(static_cast<std::uint8_t>(0x80 + N));
  8399. }
  8400. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  8401. {
  8402. oa->write_character(to_char_type(0x98));
  8403. write_number(static_cast<std::uint8_t>(N));
  8404. }
  8405. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  8406. {
  8407. oa->write_character(to_char_type(0x99));
  8408. write_number(static_cast<std::uint16_t>(N));
  8409. }
  8410. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  8411. {
  8412. oa->write_character(to_char_type(0x9A));
  8413. write_number(static_cast<std::uint32_t>(N));
  8414. }
  8415. // LCOV_EXCL_START
  8416. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  8417. {
  8418. oa->write_character(to_char_type(0x9B));
  8419. write_number(static_cast<std::uint64_t>(N));
  8420. }
  8421. // LCOV_EXCL_STOP
  8422. // step 2: write each element
  8423. for (const auto& el : *j.m_value.array)
  8424. {
  8425. write_cbor(el);
  8426. }
  8427. break;
  8428. }
  8429. case value_t::object:
  8430. {
  8431. // step 1: write control byte and the object size
  8432. const auto N = j.m_value.object->size();
  8433. if (N <= 0x17)
  8434. {
  8435. write_number(static_cast<std::uint8_t>(0xA0 + N));
  8436. }
  8437. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  8438. {
  8439. oa->write_character(to_char_type(0xB8));
  8440. write_number(static_cast<std::uint8_t>(N));
  8441. }
  8442. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  8443. {
  8444. oa->write_character(to_char_type(0xB9));
  8445. write_number(static_cast<std::uint16_t>(N));
  8446. }
  8447. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  8448. {
  8449. oa->write_character(to_char_type(0xBA));
  8450. write_number(static_cast<std::uint32_t>(N));
  8451. }
  8452. // LCOV_EXCL_START
  8453. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  8454. {
  8455. oa->write_character(to_char_type(0xBB));
  8456. write_number(static_cast<std::uint64_t>(N));
  8457. }
  8458. // LCOV_EXCL_STOP
  8459. // step 2: write each element
  8460. for (const auto& el : *j.m_value.object)
  8461. {
  8462. write_cbor(el.first);
  8463. write_cbor(el.second);
  8464. }
  8465. break;
  8466. }
  8467. default:
  8468. break;
  8469. }
  8470. }
  8471. /*!
  8472. @param[in] j JSON value to serialize
  8473. */
  8474. void write_msgpack(const BasicJsonType& j)
  8475. {
  8476. switch (j.type())
  8477. {
  8478. case value_t::null: // nil
  8479. {
  8480. oa->write_character(to_char_type(0xC0));
  8481. break;
  8482. }
  8483. case value_t::boolean: // true and false
  8484. {
  8485. oa->write_character(j.m_value.boolean
  8486. ? to_char_type(0xC3)
  8487. : to_char_type(0xC2));
  8488. break;
  8489. }
  8490. case value_t::number_integer:
  8491. {
  8492. if (j.m_value.number_integer >= 0)
  8493. {
  8494. // MessagePack does not differentiate between positive
  8495. // signed integers and unsigned integers. Therefore, we used
  8496. // the code from the value_t::number_unsigned case here.
  8497. if (j.m_value.number_unsigned < 128)
  8498. {
  8499. // positive fixnum
  8500. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  8501. }
  8502. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  8503. {
  8504. // uint 8
  8505. oa->write_character(to_char_type(0xCC));
  8506. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  8507. }
  8508. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  8509. {
  8510. // uint 16
  8511. oa->write_character(to_char_type(0xCD));
  8512. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  8513. }
  8514. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  8515. {
  8516. // uint 32
  8517. oa->write_character(to_char_type(0xCE));
  8518. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  8519. }
  8520. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  8521. {
  8522. // uint 64
  8523. oa->write_character(to_char_type(0xCF));
  8524. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  8525. }
  8526. }
  8527. else
  8528. {
  8529. if (j.m_value.number_integer >= -32)
  8530. {
  8531. // negative fixnum
  8532. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  8533. }
  8534. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() and
  8535. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  8536. {
  8537. // int 8
  8538. oa->write_character(to_char_type(0xD0));
  8539. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  8540. }
  8541. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() and
  8542. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  8543. {
  8544. // int 16
  8545. oa->write_character(to_char_type(0xD1));
  8546. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  8547. }
  8548. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() and
  8549. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  8550. {
  8551. // int 32
  8552. oa->write_character(to_char_type(0xD2));
  8553. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  8554. }
  8555. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() and
  8556. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  8557. {
  8558. // int 64
  8559. oa->write_character(to_char_type(0xD3));
  8560. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  8561. }
  8562. }
  8563. break;
  8564. }
  8565. case value_t::number_unsigned:
  8566. {
  8567. if (j.m_value.number_unsigned < 128)
  8568. {
  8569. // positive fixnum
  8570. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  8571. }
  8572. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  8573. {
  8574. // uint 8
  8575. oa->write_character(to_char_type(0xCC));
  8576. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  8577. }
  8578. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  8579. {
  8580. // uint 16
  8581. oa->write_character(to_char_type(0xCD));
  8582. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  8583. }
  8584. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  8585. {
  8586. // uint 32
  8587. oa->write_character(to_char_type(0xCE));
  8588. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  8589. }
  8590. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  8591. {
  8592. // uint 64
  8593. oa->write_character(to_char_type(0xCF));
  8594. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  8595. }
  8596. break;
  8597. }
  8598. case value_t::number_float:
  8599. {
  8600. oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
  8601. write_number(j.m_value.number_float);
  8602. break;
  8603. }
  8604. case value_t::string:
  8605. {
  8606. // step 1: write control byte and the string length
  8607. const auto N = j.m_value.string->size();
  8608. if (N <= 31)
  8609. {
  8610. // fixstr
  8611. write_number(static_cast<std::uint8_t>(0xA0 | N));
  8612. }
  8613. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  8614. {
  8615. // str 8
  8616. oa->write_character(to_char_type(0xD9));
  8617. write_number(static_cast<std::uint8_t>(N));
  8618. }
  8619. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  8620. {
  8621. // str 16
  8622. oa->write_character(to_char_type(0xDA));
  8623. write_number(static_cast<std::uint16_t>(N));
  8624. }
  8625. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  8626. {
  8627. // str 32
  8628. oa->write_character(to_char_type(0xDB));
  8629. write_number(static_cast<std::uint32_t>(N));
  8630. }
  8631. // step 2: write the string
  8632. oa->write_characters(
  8633. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  8634. j.m_value.string->size());
  8635. break;
  8636. }
  8637. case value_t::array:
  8638. {
  8639. // step 1: write control byte and the array size
  8640. const auto N = j.m_value.array->size();
  8641. if (N <= 15)
  8642. {
  8643. // fixarray
  8644. write_number(static_cast<std::uint8_t>(0x90 | N));
  8645. }
  8646. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  8647. {
  8648. // array 16
  8649. oa->write_character(to_char_type(0xDC));
  8650. write_number(static_cast<std::uint16_t>(N));
  8651. }
  8652. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  8653. {
  8654. // array 32
  8655. oa->write_character(to_char_type(0xDD));
  8656. write_number(static_cast<std::uint32_t>(N));
  8657. }
  8658. // step 2: write each element
  8659. for (const auto& el : *j.m_value.array)
  8660. {
  8661. write_msgpack(el);
  8662. }
  8663. break;
  8664. }
  8665. case value_t::object:
  8666. {
  8667. // step 1: write control byte and the object size
  8668. const auto N = j.m_value.object->size();
  8669. if (N <= 15)
  8670. {
  8671. // fixmap
  8672. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  8673. }
  8674. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  8675. {
  8676. // map 16
  8677. oa->write_character(to_char_type(0xDE));
  8678. write_number(static_cast<std::uint16_t>(N));
  8679. }
  8680. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  8681. {
  8682. // map 32
  8683. oa->write_character(to_char_type(0xDF));
  8684. write_number(static_cast<std::uint32_t>(N));
  8685. }
  8686. // step 2: write each element
  8687. for (const auto& el : *j.m_value.object)
  8688. {
  8689. write_msgpack(el.first);
  8690. write_msgpack(el.second);
  8691. }
  8692. break;
  8693. }
  8694. default:
  8695. break;
  8696. }
  8697. }
  8698. /*!
  8699. @param[in] j JSON value to serialize
  8700. @param[in] use_count whether to use '#' prefixes (optimized format)
  8701. @param[in] use_type whether to use '$' prefixes (optimized format)
  8702. @param[in] add_prefix whether prefixes need to be used for this value
  8703. */
  8704. void write_ubjson(const BasicJsonType& j, const bool use_count,
  8705. const bool use_type, const bool add_prefix = true)
  8706. {
  8707. switch (j.type())
  8708. {
  8709. case value_t::null:
  8710. {
  8711. if (add_prefix)
  8712. {
  8713. oa->write_character(to_char_type('Z'));
  8714. }
  8715. break;
  8716. }
  8717. case value_t::boolean:
  8718. {
  8719. if (add_prefix)
  8720. {
  8721. oa->write_character(j.m_value.boolean
  8722. ? to_char_type('T')
  8723. : to_char_type('F'));
  8724. }
  8725. break;
  8726. }
  8727. case value_t::number_integer:
  8728. {
  8729. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  8730. break;
  8731. }
  8732. case value_t::number_unsigned:
  8733. {
  8734. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  8735. break;
  8736. }
  8737. case value_t::number_float:
  8738. {
  8739. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  8740. break;
  8741. }
  8742. case value_t::string:
  8743. {
  8744. if (add_prefix)
  8745. {
  8746. oa->write_character(to_char_type('S'));
  8747. }
  8748. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  8749. oa->write_characters(
  8750. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  8751. j.m_value.string->size());
  8752. break;
  8753. }
  8754. case value_t::array:
  8755. {
  8756. if (add_prefix)
  8757. {
  8758. oa->write_character(to_char_type('['));
  8759. }
  8760. bool prefix_required = true;
  8761. if (use_type and not j.m_value.array->empty())
  8762. {
  8763. assert(use_count);
  8764. const CharType first_prefix = ubjson_prefix(j.front());
  8765. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  8766. [this, first_prefix](const BasicJsonType & v)
  8767. {
  8768. return ubjson_prefix(v) == first_prefix;
  8769. });
  8770. if (same_prefix)
  8771. {
  8772. prefix_required = false;
  8773. oa->write_character(to_char_type('$'));
  8774. oa->write_character(first_prefix);
  8775. }
  8776. }
  8777. if (use_count)
  8778. {
  8779. oa->write_character(to_char_type('#'));
  8780. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  8781. }
  8782. for (const auto& el : *j.m_value.array)
  8783. {
  8784. write_ubjson(el, use_count, use_type, prefix_required);
  8785. }
  8786. if (not use_count)
  8787. {
  8788. oa->write_character(to_char_type(']'));
  8789. }
  8790. break;
  8791. }
  8792. case value_t::object:
  8793. {
  8794. if (add_prefix)
  8795. {
  8796. oa->write_character(to_char_type('{'));
  8797. }
  8798. bool prefix_required = true;
  8799. if (use_type and not j.m_value.object->empty())
  8800. {
  8801. assert(use_count);
  8802. const CharType first_prefix = ubjson_prefix(j.front());
  8803. const bool same_prefix = std::all_of(j.begin(), j.end(),
  8804. [this, first_prefix](const BasicJsonType & v)
  8805. {
  8806. return ubjson_prefix(v) == first_prefix;
  8807. });
  8808. if (same_prefix)
  8809. {
  8810. prefix_required = false;
  8811. oa->write_character(to_char_type('$'));
  8812. oa->write_character(first_prefix);
  8813. }
  8814. }
  8815. if (use_count)
  8816. {
  8817. oa->write_character(to_char_type('#'));
  8818. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  8819. }
  8820. for (const auto& el : *j.m_value.object)
  8821. {
  8822. write_number_with_ubjson_prefix(el.first.size(), true);
  8823. oa->write_characters(
  8824. reinterpret_cast<const CharType*>(el.first.c_str()),
  8825. el.first.size());
  8826. write_ubjson(el.second, use_count, use_type, prefix_required);
  8827. }
  8828. if (not use_count)
  8829. {
  8830. oa->write_character(to_char_type('}'));
  8831. }
  8832. break;
  8833. }
  8834. default:
  8835. break;
  8836. }
  8837. }
  8838. private:
  8839. //////////
  8840. // BSON //
  8841. //////////
  8842. /*!
  8843. @return The size of a BSON document entry header, including the id marker
  8844. and the entry name size (and its null-terminator).
  8845. */
  8846. static std::size_t calc_bson_entry_header_size(const string_t& name)
  8847. {
  8848. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  8849. if (JSON_UNLIKELY(it != BasicJsonType::string_t::npos))
  8850. {
  8851. JSON_THROW(out_of_range::create(409,
  8852. "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
  8853. }
  8854. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  8855. }
  8856. /*!
  8857. @brief Writes the given @a element_type and @a name to the output adapter
  8858. */
  8859. void write_bson_entry_header(const string_t& name,
  8860. const std::uint8_t element_type)
  8861. {
  8862. oa->write_character(to_char_type(element_type)); // boolean
  8863. oa->write_characters(
  8864. reinterpret_cast<const CharType*>(name.c_str()),
  8865. name.size() + 1u);
  8866. }
  8867. /*!
  8868. @brief Writes a BSON element with key @a name and boolean value @a value
  8869. */
  8870. void write_bson_boolean(const string_t& name,
  8871. const bool value)
  8872. {
  8873. write_bson_entry_header(name, 0x08);
  8874. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  8875. }
  8876. /*!
  8877. @brief Writes a BSON element with key @a name and double value @a value
  8878. */
  8879. void write_bson_double(const string_t& name,
  8880. const double value)
  8881. {
  8882. write_bson_entry_header(name, 0x01);
  8883. write_number<double, true>(value);
  8884. }
  8885. /*!
  8886. @return The size of the BSON-encoded string in @a value
  8887. */
  8888. static std::size_t calc_bson_string_size(const string_t& value)
  8889. {
  8890. return sizeof(std::int32_t) + value.size() + 1ul;
  8891. }
  8892. /*!
  8893. @brief Writes a BSON element with key @a name and string value @a value
  8894. */
  8895. void write_bson_string(const string_t& name,
  8896. const string_t& value)
  8897. {
  8898. write_bson_entry_header(name, 0x02);
  8899. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  8900. oa->write_characters(
  8901. reinterpret_cast<const CharType*>(value.c_str()),
  8902. value.size() + 1);
  8903. }
  8904. /*!
  8905. @brief Writes a BSON element with key @a name and null value
  8906. */
  8907. void write_bson_null(const string_t& name)
  8908. {
  8909. write_bson_entry_header(name, 0x0A);
  8910. }
  8911. /*!
  8912. @return The size of the BSON-encoded integer @a value
  8913. */
  8914. static std::size_t calc_bson_integer_size(const std::int64_t value)
  8915. {
  8916. return (std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)()
  8917. ? sizeof(std::int32_t)
  8918. : sizeof(std::int64_t);
  8919. }
  8920. /*!
  8921. @brief Writes a BSON element with key @a name and integer @a value
  8922. */
  8923. void write_bson_integer(const string_t& name,
  8924. const std::int64_t value)
  8925. {
  8926. if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)())
  8927. {
  8928. write_bson_entry_header(name, 0x10); // int32
  8929. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  8930. }
  8931. else
  8932. {
  8933. write_bson_entry_header(name, 0x12); // int64
  8934. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  8935. }
  8936. }
  8937. /*!
  8938. @return The size of the BSON-encoded unsigned integer in @a j
  8939. */
  8940. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  8941. {
  8942. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  8943. ? sizeof(std::int32_t)
  8944. : sizeof(std::int64_t);
  8945. }
  8946. /*!
  8947. @brief Writes a BSON element with key @a name and unsigned @a value
  8948. */
  8949. void write_bson_unsigned(const string_t& name,
  8950. const std::uint64_t value)
  8951. {
  8952. if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  8953. {
  8954. write_bson_entry_header(name, 0x10 /* int32 */);
  8955. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  8956. }
  8957. else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  8958. {
  8959. write_bson_entry_header(name, 0x12 /* int64 */);
  8960. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  8961. }
  8962. else
  8963. {
  8964. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
  8965. }
  8966. }
  8967. /*!
  8968. @brief Writes a BSON element with key @a name and object @a value
  8969. */
  8970. void write_bson_object_entry(const string_t& name,
  8971. const typename BasicJsonType::object_t& value)
  8972. {
  8973. write_bson_entry_header(name, 0x03); // object
  8974. write_bson_object(value);
  8975. }
  8976. /*!
  8977. @return The size of the BSON-encoded array @a value
  8978. */
  8979. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  8980. {
  8981. std::size_t embedded_document_size = 0ul;
  8982. std::size_t array_index = 0ul;
  8983. for (const auto& el : value)
  8984. {
  8985. embedded_document_size += calc_bson_element_size(std::to_string(array_index++), el);
  8986. }
  8987. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  8988. }
  8989. /*!
  8990. @brief Writes a BSON element with key @a name and array @a value
  8991. */
  8992. void write_bson_array(const string_t& name,
  8993. const typename BasicJsonType::array_t& value)
  8994. {
  8995. write_bson_entry_header(name, 0x04); // array
  8996. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  8997. std::size_t array_index = 0ul;
  8998. for (const auto& el : value)
  8999. {
  9000. write_bson_element(std::to_string(array_index++), el);
  9001. }
  9002. oa->write_character(to_char_type(0x00));
  9003. }
  9004. /*!
  9005. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  9006. @return The calculated size for the BSON document entry for @a j with the given @a name.
  9007. */
  9008. static std::size_t calc_bson_element_size(const string_t& name,
  9009. const BasicJsonType& j)
  9010. {
  9011. const auto header_size = calc_bson_entry_header_size(name);
  9012. switch (j.type())
  9013. {
  9014. case value_t::object:
  9015. return header_size + calc_bson_object_size(*j.m_value.object);
  9016. case value_t::array:
  9017. return header_size + calc_bson_array_size(*j.m_value.array);
  9018. case value_t::boolean:
  9019. return header_size + 1ul;
  9020. case value_t::number_float:
  9021. return header_size + 8ul;
  9022. case value_t::number_integer:
  9023. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  9024. case value_t::number_unsigned:
  9025. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  9026. case value_t::string:
  9027. return header_size + calc_bson_string_size(*j.m_value.string);
  9028. case value_t::null:
  9029. return header_size + 0ul;
  9030. // LCOV_EXCL_START
  9031. default:
  9032. assert(false);
  9033. return 0ul;
  9034. // LCOV_EXCL_STOP
  9035. }
  9036. }
  9037. /*!
  9038. @brief Serializes the JSON value @a j to BSON and associates it with the
  9039. key @a name.
  9040. @param name The name to associate with the JSON entity @a j within the
  9041. current BSON document
  9042. @return The size of the BSON entry
  9043. */
  9044. void write_bson_element(const string_t& name,
  9045. const BasicJsonType& j)
  9046. {
  9047. switch (j.type())
  9048. {
  9049. case value_t::object:
  9050. return write_bson_object_entry(name, *j.m_value.object);
  9051. case value_t::array:
  9052. return write_bson_array(name, *j.m_value.array);
  9053. case value_t::boolean:
  9054. return write_bson_boolean(name, j.m_value.boolean);
  9055. case value_t::number_float:
  9056. return write_bson_double(name, j.m_value.number_float);
  9057. case value_t::number_integer:
  9058. return write_bson_integer(name, j.m_value.number_integer);
  9059. case value_t::number_unsigned:
  9060. return write_bson_unsigned(name, j.m_value.number_unsigned);
  9061. case value_t::string:
  9062. return write_bson_string(name, *j.m_value.string);
  9063. case value_t::null:
  9064. return write_bson_null(name);
  9065. // LCOV_EXCL_START
  9066. default:
  9067. assert(false);
  9068. return;
  9069. // LCOV_EXCL_STOP
  9070. }
  9071. }
  9072. /*!
  9073. @brief Calculates the size of the BSON serialization of the given
  9074. JSON-object @a j.
  9075. @param[in] j JSON value to serialize
  9076. @pre j.type() == value_t::object
  9077. */
  9078. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  9079. {
  9080. std::size_t document_size = std::accumulate(value.begin(), value.end(), 0ul,
  9081. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  9082. {
  9083. return result += calc_bson_element_size(el.first, el.second);
  9084. });
  9085. return sizeof(std::int32_t) + document_size + 1ul;
  9086. }
  9087. /*!
  9088. @param[in] j JSON value to serialize
  9089. @pre j.type() == value_t::object
  9090. */
  9091. void write_bson_object(const typename BasicJsonType::object_t& value)
  9092. {
  9093. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  9094. for (const auto& el : value)
  9095. {
  9096. write_bson_element(el.first, el.second);
  9097. }
  9098. oa->write_character(to_char_type(0x00));
  9099. }
  9100. //////////
  9101. // CBOR //
  9102. //////////
  9103. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  9104. {
  9105. return to_char_type(0xFA); // Single-Precision Float
  9106. }
  9107. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  9108. {
  9109. return to_char_type(0xFB); // Double-Precision Float
  9110. }
  9111. /////////////
  9112. // MsgPack //
  9113. /////////////
  9114. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  9115. {
  9116. return to_char_type(0xCA); // float 32
  9117. }
  9118. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  9119. {
  9120. return to_char_type(0xCB); // float 64
  9121. }
  9122. ////////////
  9123. // UBJSON //
  9124. ////////////
  9125. // UBJSON: write number (floating point)
  9126. template<typename NumberType, typename std::enable_if<
  9127. std::is_floating_point<NumberType>::value, int>::type = 0>
  9128. void write_number_with_ubjson_prefix(const NumberType n,
  9129. const bool add_prefix)
  9130. {
  9131. if (add_prefix)
  9132. {
  9133. oa->write_character(get_ubjson_float_prefix(n));
  9134. }
  9135. write_number(n);
  9136. }
  9137. // UBJSON: write number (unsigned integer)
  9138. template<typename NumberType, typename std::enable_if<
  9139. std::is_unsigned<NumberType>::value, int>::type = 0>
  9140. void write_number_with_ubjson_prefix(const NumberType n,
  9141. const bool add_prefix)
  9142. {
  9143. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  9144. {
  9145. if (add_prefix)
  9146. {
  9147. oa->write_character(to_char_type('i')); // int8
  9148. }
  9149. write_number(static_cast<std::uint8_t>(n));
  9150. }
  9151. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  9152. {
  9153. if (add_prefix)
  9154. {
  9155. oa->write_character(to_char_type('U')); // uint8
  9156. }
  9157. write_number(static_cast<std::uint8_t>(n));
  9158. }
  9159. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  9160. {
  9161. if (add_prefix)
  9162. {
  9163. oa->write_character(to_char_type('I')); // int16
  9164. }
  9165. write_number(static_cast<std::int16_t>(n));
  9166. }
  9167. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  9168. {
  9169. if (add_prefix)
  9170. {
  9171. oa->write_character(to_char_type('l')); // int32
  9172. }
  9173. write_number(static_cast<std::int32_t>(n));
  9174. }
  9175. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  9176. {
  9177. if (add_prefix)
  9178. {
  9179. oa->write_character(to_char_type('L')); // int64
  9180. }
  9181. write_number(static_cast<std::int64_t>(n));
  9182. }
  9183. else
  9184. {
  9185. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  9186. }
  9187. }
  9188. // UBJSON: write number (signed integer)
  9189. template<typename NumberType, typename std::enable_if<
  9190. std::is_signed<NumberType>::value and
  9191. not std::is_floating_point<NumberType>::value, int>::type = 0>
  9192. void write_number_with_ubjson_prefix(const NumberType n,
  9193. const bool add_prefix)
  9194. {
  9195. if ((std::numeric_limits<std::int8_t>::min)() <= n and n <= (std::numeric_limits<std::int8_t>::max)())
  9196. {
  9197. if (add_prefix)
  9198. {
  9199. oa->write_character(to_char_type('i')); // int8
  9200. }
  9201. write_number(static_cast<std::int8_t>(n));
  9202. }
  9203. 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)()))
  9204. {
  9205. if (add_prefix)
  9206. {
  9207. oa->write_character(to_char_type('U')); // uint8
  9208. }
  9209. write_number(static_cast<std::uint8_t>(n));
  9210. }
  9211. else if ((std::numeric_limits<std::int16_t>::min)() <= n and n <= (std::numeric_limits<std::int16_t>::max)())
  9212. {
  9213. if (add_prefix)
  9214. {
  9215. oa->write_character(to_char_type('I')); // int16
  9216. }
  9217. write_number(static_cast<std::int16_t>(n));
  9218. }
  9219. else if ((std::numeric_limits<std::int32_t>::min)() <= n and n <= (std::numeric_limits<std::int32_t>::max)())
  9220. {
  9221. if (add_prefix)
  9222. {
  9223. oa->write_character(to_char_type('l')); // int32
  9224. }
  9225. write_number(static_cast<std::int32_t>(n));
  9226. }
  9227. else if ((std::numeric_limits<std::int64_t>::min)() <= n and n <= (std::numeric_limits<std::int64_t>::max)())
  9228. {
  9229. if (add_prefix)
  9230. {
  9231. oa->write_character(to_char_type('L')); // int64
  9232. }
  9233. write_number(static_cast<std::int64_t>(n));
  9234. }
  9235. // LCOV_EXCL_START
  9236. else
  9237. {
  9238. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  9239. }
  9240. // LCOV_EXCL_STOP
  9241. }
  9242. /*!
  9243. @brief determine the type prefix of container values
  9244. @note This function does not need to be 100% accurate when it comes to
  9245. integer limits. In case a number exceeds the limits of int64_t,
  9246. this will be detected by a later call to function
  9247. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  9248. value that does not fit the previous limits.
  9249. */
  9250. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  9251. {
  9252. switch (j.type())
  9253. {
  9254. case value_t::null:
  9255. return 'Z';
  9256. case value_t::boolean:
  9257. return j.m_value.boolean ? 'T' : 'F';
  9258. case value_t::number_integer:
  9259. {
  9260. 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)())
  9261. {
  9262. return 'i';
  9263. }
  9264. 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)())
  9265. {
  9266. return 'U';
  9267. }
  9268. 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)())
  9269. {
  9270. return 'I';
  9271. }
  9272. 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)())
  9273. {
  9274. return 'l';
  9275. }
  9276. // no check and assume int64_t (see note above)
  9277. return 'L';
  9278. }
  9279. case value_t::number_unsigned:
  9280. {
  9281. if (j.m_value.number_unsigned <= (std::numeric_limits<std::int8_t>::max)())
  9282. {
  9283. return 'i';
  9284. }
  9285. if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  9286. {
  9287. return 'U';
  9288. }
  9289. if (j.m_value.number_unsigned <= (std::numeric_limits<std::int16_t>::max)())
  9290. {
  9291. return 'I';
  9292. }
  9293. if (j.m_value.number_unsigned <= (std::numeric_limits<std::int32_t>::max)())
  9294. {
  9295. return 'l';
  9296. }
  9297. // no check and assume int64_t (see note above)
  9298. return 'L';
  9299. }
  9300. case value_t::number_float:
  9301. return get_ubjson_float_prefix(j.m_value.number_float);
  9302. case value_t::string:
  9303. return 'S';
  9304. case value_t::array:
  9305. return '[';
  9306. case value_t::object:
  9307. return '{';
  9308. default: // discarded values
  9309. return 'N';
  9310. }
  9311. }
  9312. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  9313. {
  9314. return 'd'; // float 32
  9315. }
  9316. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  9317. {
  9318. return 'D'; // float 64
  9319. }
  9320. ///////////////////////
  9321. // Utility functions //
  9322. ///////////////////////
  9323. /*
  9324. @brief write a number to output input
  9325. @param[in] n number of type @a NumberType
  9326. @tparam NumberType the type of the number
  9327. @tparam OutputIsLittleEndian Set to true if output data is
  9328. required to be little endian
  9329. @note This function needs to respect the system's endianess, because bytes
  9330. in CBOR, MessagePack, and UBJSON are stored in network order (big
  9331. endian) and therefore need reordering on little endian systems.
  9332. */
  9333. template<typename NumberType, bool OutputIsLittleEndian = false>
  9334. void write_number(const NumberType n)
  9335. {
  9336. // step 1: write number to array of length NumberType
  9337. std::array<CharType, sizeof(NumberType)> vec;
  9338. std::memcpy(vec.data(), &n, sizeof(NumberType));
  9339. // step 2: write array to output (with possible reordering)
  9340. if (is_little_endian != OutputIsLittleEndian)
  9341. {
  9342. // reverse byte order prior to conversion if necessary
  9343. std::reverse(vec.begin(), vec.end());
  9344. }
  9345. oa->write_characters(vec.data(), sizeof(NumberType));
  9346. }
  9347. public:
  9348. // The following to_char_type functions are implement the conversion
  9349. // between uint8_t and CharType. In case CharType is not unsigned,
  9350. // such a conversion is required to allow values greater than 128.
  9351. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  9352. template < typename C = CharType,
  9353. enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value > * = nullptr >
  9354. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  9355. {
  9356. return *reinterpret_cast<char*>(&x);
  9357. }
  9358. template < typename C = CharType,
  9359. enable_if_t < std::is_signed<C>::value and std::is_unsigned<char>::value > * = nullptr >
  9360. static CharType to_char_type(std::uint8_t x) noexcept
  9361. {
  9362. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  9363. static_assert(std::is_pod<CharType>::value, "CharType must be POD");
  9364. CharType result;
  9365. std::memcpy(&result, &x, sizeof(x));
  9366. return result;
  9367. }
  9368. template<typename C = CharType,
  9369. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  9370. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  9371. {
  9372. return x;
  9373. }
  9374. template < typename InputCharType, typename C = CharType,
  9375. enable_if_t <
  9376. std::is_signed<C>::value and
  9377. std::is_signed<char>::value and
  9378. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  9379. > * = nullptr >
  9380. static constexpr CharType to_char_type(InputCharType x) noexcept
  9381. {
  9382. return x;
  9383. }
  9384. private:
  9385. /// whether we can assume little endianess
  9386. const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
  9387. /// the output
  9388. output_adapter_t<CharType> oa = nullptr;
  9389. };
  9390. } // namespace detail
  9391. } // namespace nlohmann
  9392. // #include <nlohmann/detail/output/output_adapters.hpp>
  9393. // #include <nlohmann/detail/output/serializer.hpp>
  9394. #include <algorithm> // reverse, remove, fill, find, none_of
  9395. #include <array> // array
  9396. #include <cassert> // assert
  9397. #include <ciso646> // and, or
  9398. #include <clocale> // localeconv, lconv
  9399. #include <cmath> // labs, isfinite, isnan, signbit
  9400. #include <cstddef> // size_t, ptrdiff_t
  9401. #include <cstdint> // uint8_t
  9402. #include <cstdio> // snprintf
  9403. #include <limits> // numeric_limits
  9404. #include <string> // string
  9405. #include <type_traits> // is_same
  9406. #include <utility> // move
  9407. // #include <nlohmann/detail/conversions/to_chars.hpp>
  9408. #include <array> // array
  9409. #include <cassert> // assert
  9410. #include <ciso646> // or, and, not
  9411. #include <cmath> // signbit, isfinite
  9412. #include <cstdint> // intN_t, uintN_t
  9413. #include <cstring> // memcpy, memmove
  9414. #include <limits> // numeric_limits
  9415. #include <type_traits> // conditional
  9416. namespace nlohmann
  9417. {
  9418. namespace detail
  9419. {
  9420. /*!
  9421. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  9422. conversion.
  9423. This implementation is a slightly modified version of the reference
  9424. implementation which may be obtained from
  9425. http://florian.loitsch.com/publications (bench.tar.gz).
  9426. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  9427. For a detailed description of the algorithm see:
  9428. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  9429. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  9430. Language Design and Implementation, PLDI 2010
  9431. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  9432. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  9433. Design and Implementation, PLDI 1996
  9434. */
  9435. namespace dtoa_impl
  9436. {
  9437. template <typename Target, typename Source>
  9438. Target reinterpret_bits(const Source source)
  9439. {
  9440. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  9441. Target target;
  9442. std::memcpy(&target, &source, sizeof(Source));
  9443. return target;
  9444. }
  9445. struct diyfp // f * 2^e
  9446. {
  9447. static constexpr int kPrecision = 64; // = q
  9448. std::uint64_t f = 0;
  9449. int e = 0;
  9450. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  9451. /*!
  9452. @brief returns x - y
  9453. @pre x.e == y.e and x.f >= y.f
  9454. */
  9455. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  9456. {
  9457. assert(x.e == y.e);
  9458. assert(x.f >= y.f);
  9459. return {x.f - y.f, x.e};
  9460. }
  9461. /*!
  9462. @brief returns x * y
  9463. @note The result is rounded. (Only the upper q bits are returned.)
  9464. */
  9465. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  9466. {
  9467. static_assert(kPrecision == 64, "internal error");
  9468. // Computes:
  9469. // f = round((x.f * y.f) / 2^q)
  9470. // e = x.e + y.e + q
  9471. // Emulate the 64-bit * 64-bit multiplication:
  9472. //
  9473. // p = u * v
  9474. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  9475. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  9476. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  9477. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  9478. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  9479. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  9480. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  9481. //
  9482. // (Since Q might be larger than 2^32 - 1)
  9483. //
  9484. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  9485. //
  9486. // (Q_hi + H does not overflow a 64-bit int)
  9487. //
  9488. // = p_lo + 2^64 p_hi
  9489. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  9490. const std::uint64_t u_hi = x.f >> 32u;
  9491. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  9492. const std::uint64_t v_hi = y.f >> 32u;
  9493. const std::uint64_t p0 = u_lo * v_lo;
  9494. const std::uint64_t p1 = u_lo * v_hi;
  9495. const std::uint64_t p2 = u_hi * v_lo;
  9496. const std::uint64_t p3 = u_hi * v_hi;
  9497. const std::uint64_t p0_hi = p0 >> 32u;
  9498. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  9499. const std::uint64_t p1_hi = p1 >> 32u;
  9500. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  9501. const std::uint64_t p2_hi = p2 >> 32u;
  9502. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  9503. // The full product might now be computed as
  9504. //
  9505. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  9506. // p_lo = p0_lo + (Q << 32)
  9507. //
  9508. // But in this particular case here, the full p_lo is not required.
  9509. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  9510. // Q_hi + 1 does not overflow).
  9511. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  9512. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  9513. return {h, x.e + y.e + 64};
  9514. }
  9515. /*!
  9516. @brief normalize x such that the significand is >= 2^(q-1)
  9517. @pre x.f != 0
  9518. */
  9519. static diyfp normalize(diyfp x) noexcept
  9520. {
  9521. assert(x.f != 0);
  9522. while ((x.f >> 63u) == 0)
  9523. {
  9524. x.f <<= 1u;
  9525. x.e--;
  9526. }
  9527. return x;
  9528. }
  9529. /*!
  9530. @brief normalize x such that the result has the exponent E
  9531. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  9532. */
  9533. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  9534. {
  9535. const int delta = x.e - target_exponent;
  9536. assert(delta >= 0);
  9537. assert(((x.f << delta) >> delta) == x.f);
  9538. return {x.f << delta, target_exponent};
  9539. }
  9540. };
  9541. struct boundaries
  9542. {
  9543. diyfp w;
  9544. diyfp minus;
  9545. diyfp plus;
  9546. };
  9547. /*!
  9548. Compute the (normalized) diyfp representing the input number 'value' and its
  9549. boundaries.
  9550. @pre value must be finite and positive
  9551. */
  9552. template <typename FloatType>
  9553. boundaries compute_boundaries(FloatType value)
  9554. {
  9555. assert(std::isfinite(value));
  9556. assert(value > 0);
  9557. // Convert the IEEE representation into a diyfp.
  9558. //
  9559. // If v is denormal:
  9560. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  9561. // If v is normalized:
  9562. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  9563. static_assert(std::numeric_limits<FloatType>::is_iec559,
  9564. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  9565. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  9566. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  9567. constexpr int kMinExp = 1 - kBias;
  9568. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  9569. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  9570. const std::uint64_t bits = reinterpret_bits<bits_type>(value);
  9571. const std::uint64_t E = bits >> (kPrecision - 1);
  9572. const std::uint64_t F = bits & (kHiddenBit - 1);
  9573. const bool is_denormal = E == 0;
  9574. const diyfp v = is_denormal
  9575. ? diyfp(F, kMinExp)
  9576. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  9577. // Compute the boundaries m- and m+ of the floating-point value
  9578. // v = f * 2^e.
  9579. //
  9580. // Determine v- and v+, the floating-point predecessor and successor if v,
  9581. // respectively.
  9582. //
  9583. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  9584. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  9585. //
  9586. // v+ = v + 2^e
  9587. //
  9588. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  9589. // between m- and m+ round to v, regardless of how the input rounding
  9590. // algorithm breaks ties.
  9591. //
  9592. // ---+-------------+-------------+-------------+-------------+--- (A)
  9593. // v- m- v m+ v+
  9594. //
  9595. // -----------------+------+------+-------------+-------------+--- (B)
  9596. // v- m- v m+ v+
  9597. const bool lower_boundary_is_closer = F == 0 and E > 1;
  9598. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  9599. const diyfp m_minus = lower_boundary_is_closer
  9600. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  9601. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  9602. // Determine the normalized w+ = m+.
  9603. const diyfp w_plus = diyfp::normalize(m_plus);
  9604. // Determine w- = m- such that e_(w-) = e_(w+).
  9605. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  9606. return {diyfp::normalize(v), w_minus, w_plus};
  9607. }
  9608. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  9609. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  9610. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  9611. //
  9612. // alpha <= e = e_c + e_w + q <= gamma
  9613. //
  9614. // or
  9615. //
  9616. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  9617. // <= f_c * f_w * 2^gamma
  9618. //
  9619. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  9620. //
  9621. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  9622. //
  9623. // or
  9624. //
  9625. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  9626. //
  9627. // The choice of (alpha,gamma) determines the size of the table and the form of
  9628. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  9629. // in practice:
  9630. //
  9631. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  9632. // processed independently: An integral part p1, and a fractional part p2:
  9633. //
  9634. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  9635. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  9636. // = p1 + p2 * 2^e
  9637. //
  9638. // The conversion of p1 into decimal form requires a series of divisions and
  9639. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  9640. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  9641. // achieved by choosing
  9642. //
  9643. // -e >= 32 or e <= -32 := gamma
  9644. //
  9645. // In order to convert the fractional part
  9646. //
  9647. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  9648. //
  9649. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  9650. // d[-i] are extracted in order:
  9651. //
  9652. // (10 * p2) div 2^-e = d[-1]
  9653. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  9654. //
  9655. // The multiplication by 10 must not overflow. It is sufficient to choose
  9656. //
  9657. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  9658. //
  9659. // Since p2 = f mod 2^-e < 2^-e,
  9660. //
  9661. // -e <= 60 or e >= -60 := alpha
  9662. constexpr int kAlpha = -60;
  9663. constexpr int kGamma = -32;
  9664. struct cached_power // c = f * 2^e ~= 10^k
  9665. {
  9666. std::uint64_t f;
  9667. int e;
  9668. int k;
  9669. };
  9670. /*!
  9671. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  9672. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  9673. satisfies (Definition 3.2 from [1])
  9674. alpha <= e_c + e + q <= gamma.
  9675. */
  9676. inline cached_power get_cached_power_for_binary_exponent(int e)
  9677. {
  9678. // Now
  9679. //
  9680. // alpha <= e_c + e + q <= gamma (1)
  9681. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  9682. //
  9683. // and since the c's are normalized, 2^(q-1) <= f_c,
  9684. //
  9685. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  9686. // ==> 2^(alpha - e - 1) <= c
  9687. //
  9688. // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as
  9689. //
  9690. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  9691. // = ceil( (alpha - e - 1) * log_10(2) )
  9692. //
  9693. // From the paper:
  9694. // "In theory the result of the procedure could be wrong since c is rounded,
  9695. // and the computation itself is approximated [...]. In practice, however,
  9696. // this simple function is sufficient."
  9697. //
  9698. // For IEEE double precision floating-point numbers converted into
  9699. // normalized diyfp's w = f * 2^e, with q = 64,
  9700. //
  9701. // e >= -1022 (min IEEE exponent)
  9702. // -52 (p - 1)
  9703. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  9704. // -11 (normalize the diyfp)
  9705. // = -1137
  9706. //
  9707. // and
  9708. //
  9709. // e <= +1023 (max IEEE exponent)
  9710. // -52 (p - 1)
  9711. // -11 (normalize the diyfp)
  9712. // = 960
  9713. //
  9714. // This binary exponent range [-1137,960] results in a decimal exponent
  9715. // range [-307,324]. One does not need to store a cached power for each
  9716. // k in this range. For each such k it suffices to find a cached power
  9717. // such that the exponent of the product lies in [alpha,gamma].
  9718. // This implies that the difference of the decimal exponents of adjacent
  9719. // table entries must be less than or equal to
  9720. //
  9721. // floor( (gamma - alpha) * log_10(2) ) = 8.
  9722. //
  9723. // (A smaller distance gamma-alpha would require a larger table.)
  9724. // NB:
  9725. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  9726. constexpr int kCachedPowersMinDecExp = -300;
  9727. constexpr int kCachedPowersDecStep = 8;
  9728. static constexpr std::array<cached_power, 79> kCachedPowers =
  9729. {
  9730. {
  9731. { 0xAB70FE17C79AC6CA, -1060, -300 },
  9732. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  9733. { 0xBE5691EF416BD60C, -1007, -284 },
  9734. { 0x8DD01FAD907FFC3C, -980, -276 },
  9735. { 0xD3515C2831559A83, -954, -268 },
  9736. { 0x9D71AC8FADA6C9B5, -927, -260 },
  9737. { 0xEA9C227723EE8BCB, -901, -252 },
  9738. { 0xAECC49914078536D, -874, -244 },
  9739. { 0x823C12795DB6CE57, -847, -236 },
  9740. { 0xC21094364DFB5637, -821, -228 },
  9741. { 0x9096EA6F3848984F, -794, -220 },
  9742. { 0xD77485CB25823AC7, -768, -212 },
  9743. { 0xA086CFCD97BF97F4, -741, -204 },
  9744. { 0xEF340A98172AACE5, -715, -196 },
  9745. { 0xB23867FB2A35B28E, -688, -188 },
  9746. { 0x84C8D4DFD2C63F3B, -661, -180 },
  9747. { 0xC5DD44271AD3CDBA, -635, -172 },
  9748. { 0x936B9FCEBB25C996, -608, -164 },
  9749. { 0xDBAC6C247D62A584, -582, -156 },
  9750. { 0xA3AB66580D5FDAF6, -555, -148 },
  9751. { 0xF3E2F893DEC3F126, -529, -140 },
  9752. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  9753. { 0x87625F056C7C4A8B, -475, -124 },
  9754. { 0xC9BCFF6034C13053, -449, -116 },
  9755. { 0x964E858C91BA2655, -422, -108 },
  9756. { 0xDFF9772470297EBD, -396, -100 },
  9757. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  9758. { 0xF8A95FCF88747D94, -343, -84 },
  9759. { 0xB94470938FA89BCF, -316, -76 },
  9760. { 0x8A08F0F8BF0F156B, -289, -68 },
  9761. { 0xCDB02555653131B6, -263, -60 },
  9762. { 0x993FE2C6D07B7FAC, -236, -52 },
  9763. { 0xE45C10C42A2B3B06, -210, -44 },
  9764. { 0xAA242499697392D3, -183, -36 },
  9765. { 0xFD87B5F28300CA0E, -157, -28 },
  9766. { 0xBCE5086492111AEB, -130, -20 },
  9767. { 0x8CBCCC096F5088CC, -103, -12 },
  9768. { 0xD1B71758E219652C, -77, -4 },
  9769. { 0x9C40000000000000, -50, 4 },
  9770. { 0xE8D4A51000000000, -24, 12 },
  9771. { 0xAD78EBC5AC620000, 3, 20 },
  9772. { 0x813F3978F8940984, 30, 28 },
  9773. { 0xC097CE7BC90715B3, 56, 36 },
  9774. { 0x8F7E32CE7BEA5C70, 83, 44 },
  9775. { 0xD5D238A4ABE98068, 109, 52 },
  9776. { 0x9F4F2726179A2245, 136, 60 },
  9777. { 0xED63A231D4C4FB27, 162, 68 },
  9778. { 0xB0DE65388CC8ADA8, 189, 76 },
  9779. { 0x83C7088E1AAB65DB, 216, 84 },
  9780. { 0xC45D1DF942711D9A, 242, 92 },
  9781. { 0x924D692CA61BE758, 269, 100 },
  9782. { 0xDA01EE641A708DEA, 295, 108 },
  9783. { 0xA26DA3999AEF774A, 322, 116 },
  9784. { 0xF209787BB47D6B85, 348, 124 },
  9785. { 0xB454E4A179DD1877, 375, 132 },
  9786. { 0x865B86925B9BC5C2, 402, 140 },
  9787. { 0xC83553C5C8965D3D, 428, 148 },
  9788. { 0x952AB45CFA97A0B3, 455, 156 },
  9789. { 0xDE469FBD99A05FE3, 481, 164 },
  9790. { 0xA59BC234DB398C25, 508, 172 },
  9791. { 0xF6C69A72A3989F5C, 534, 180 },
  9792. { 0xB7DCBF5354E9BECE, 561, 188 },
  9793. { 0x88FCF317F22241E2, 588, 196 },
  9794. { 0xCC20CE9BD35C78A5, 614, 204 },
  9795. { 0x98165AF37B2153DF, 641, 212 },
  9796. { 0xE2A0B5DC971F303A, 667, 220 },
  9797. { 0xA8D9D1535CE3B396, 694, 228 },
  9798. { 0xFB9B7CD9A4A7443C, 720, 236 },
  9799. { 0xBB764C4CA7A44410, 747, 244 },
  9800. { 0x8BAB8EEFB6409C1A, 774, 252 },
  9801. { 0xD01FEF10A657842C, 800, 260 },
  9802. { 0x9B10A4E5E9913129, 827, 268 },
  9803. { 0xE7109BFBA19C0C9D, 853, 276 },
  9804. { 0xAC2820D9623BF429, 880, 284 },
  9805. { 0x80444B5E7AA7CF85, 907, 292 },
  9806. { 0xBF21E44003ACDD2D, 933, 300 },
  9807. { 0x8E679C2F5E44FF8F, 960, 308 },
  9808. { 0xD433179D9C8CB841, 986, 316 },
  9809. { 0x9E19DB92B4E31BA9, 1013, 324 },
  9810. }
  9811. };
  9812. // This computation gives exactly the same results for k as
  9813. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  9814. // for |e| <= 1500, but doesn't require floating-point operations.
  9815. // NB: log_10(2) ~= 78913 / 2^18
  9816. assert(e >= -1500);
  9817. assert(e <= 1500);
  9818. const int f = kAlpha - e - 1;
  9819. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  9820. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  9821. assert(index >= 0);
  9822. assert(static_cast<std::size_t>(index) < kCachedPowers.size());
  9823. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  9824. assert(kAlpha <= cached.e + e + 64);
  9825. assert(kGamma >= cached.e + e + 64);
  9826. return cached;
  9827. }
  9828. /*!
  9829. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  9830. For n == 0, returns 1 and sets pow10 := 1.
  9831. */
  9832. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  9833. {
  9834. // LCOV_EXCL_START
  9835. if (n >= 1000000000)
  9836. {
  9837. pow10 = 1000000000;
  9838. return 10;
  9839. }
  9840. // LCOV_EXCL_STOP
  9841. else if (n >= 100000000)
  9842. {
  9843. pow10 = 100000000;
  9844. return 9;
  9845. }
  9846. else if (n >= 10000000)
  9847. {
  9848. pow10 = 10000000;
  9849. return 8;
  9850. }
  9851. else if (n >= 1000000)
  9852. {
  9853. pow10 = 1000000;
  9854. return 7;
  9855. }
  9856. else if (n >= 100000)
  9857. {
  9858. pow10 = 100000;
  9859. return 6;
  9860. }
  9861. else if (n >= 10000)
  9862. {
  9863. pow10 = 10000;
  9864. return 5;
  9865. }
  9866. else if (n >= 1000)
  9867. {
  9868. pow10 = 1000;
  9869. return 4;
  9870. }
  9871. else if (n >= 100)
  9872. {
  9873. pow10 = 100;
  9874. return 3;
  9875. }
  9876. else if (n >= 10)
  9877. {
  9878. pow10 = 10;
  9879. return 2;
  9880. }
  9881. else
  9882. {
  9883. pow10 = 1;
  9884. return 1;
  9885. }
  9886. }
  9887. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  9888. std::uint64_t rest, std::uint64_t ten_k)
  9889. {
  9890. assert(len >= 1);
  9891. assert(dist <= delta);
  9892. assert(rest <= delta);
  9893. assert(ten_k > 0);
  9894. // <--------------------------- delta ---->
  9895. // <---- dist --------->
  9896. // --------------[------------------+-------------------]--------------
  9897. // M- w M+
  9898. //
  9899. // ten_k
  9900. // <------>
  9901. // <---- rest ---->
  9902. // --------------[------------------+----+--------------]--------------
  9903. // w V
  9904. // = buf * 10^k
  9905. //
  9906. // ten_k represents a unit-in-the-last-place in the decimal representation
  9907. // stored in buf.
  9908. // Decrement buf by ten_k while this takes buf closer to w.
  9909. // The tests are written in this order to avoid overflow in unsigned
  9910. // integer arithmetic.
  9911. while (rest < dist
  9912. and delta - rest >= ten_k
  9913. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  9914. {
  9915. assert(buf[len - 1] != '0');
  9916. buf[len - 1]--;
  9917. rest += ten_k;
  9918. }
  9919. }
  9920. /*!
  9921. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  9922. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  9923. */
  9924. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  9925. diyfp M_minus, diyfp w, diyfp M_plus)
  9926. {
  9927. static_assert(kAlpha >= -60, "internal error");
  9928. static_assert(kGamma <= -32, "internal error");
  9929. // Generates the digits (and the exponent) of a decimal floating-point
  9930. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  9931. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  9932. //
  9933. // <--------------------------- delta ---->
  9934. // <---- dist --------->
  9935. // --------------[------------------+-------------------]--------------
  9936. // M- w M+
  9937. //
  9938. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  9939. // V is in [M-,M+].
  9940. assert(M_plus.e >= kAlpha);
  9941. assert(M_plus.e <= kGamma);
  9942. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  9943. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  9944. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  9945. //
  9946. // M+ = f * 2^e
  9947. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  9948. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  9949. // = p1 + p2 * 2^e
  9950. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  9951. 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.)
  9952. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  9953. // 1)
  9954. //
  9955. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  9956. assert(p1 > 0);
  9957. std::uint32_t pow10;
  9958. const int k = find_largest_pow10(p1, pow10);
  9959. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  9960. //
  9961. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  9962. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  9963. //
  9964. // M+ = p1 + p2 * 2^e
  9965. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  9966. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  9967. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  9968. //
  9969. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  9970. //
  9971. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  9972. //
  9973. // but stop as soon as
  9974. //
  9975. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  9976. int n = k;
  9977. while (n > 0)
  9978. {
  9979. // Invariants:
  9980. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  9981. // pow10 = 10^(n-1) <= p1 < 10^n
  9982. //
  9983. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  9984. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  9985. //
  9986. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  9987. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  9988. //
  9989. assert(d <= 9);
  9990. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  9991. //
  9992. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  9993. //
  9994. p1 = r;
  9995. n--;
  9996. //
  9997. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  9998. // pow10 = 10^n
  9999. //
  10000. // Now check if enough digits have been generated.
  10001. // Compute
  10002. //
  10003. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  10004. //
  10005. // Note:
  10006. // Since rest and delta share the same exponent e, it suffices to
  10007. // compare the significands.
  10008. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  10009. if (rest <= delta)
  10010. {
  10011. // V = buffer * 10^n, with M- <= V <= M+.
  10012. decimal_exponent += n;
  10013. // We may now just stop. But instead look if the buffer could be
  10014. // decremented to bring V closer to w.
  10015. //
  10016. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  10017. // The rounding procedure works with diyfp's with an implicit
  10018. // exponent of e.
  10019. //
  10020. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  10021. //
  10022. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  10023. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  10024. return;
  10025. }
  10026. pow10 /= 10;
  10027. //
  10028. // pow10 = 10^(n-1) <= p1 < 10^n
  10029. // Invariants restored.
  10030. }
  10031. // 2)
  10032. //
  10033. // The digits of the integral part have been generated:
  10034. //
  10035. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  10036. // = buffer + p2 * 2^e
  10037. //
  10038. // Now generate the digits of the fractional part p2 * 2^e.
  10039. //
  10040. // Note:
  10041. // No decimal point is generated: the exponent is adjusted instead.
  10042. //
  10043. // p2 actually represents the fraction
  10044. //
  10045. // p2 * 2^e
  10046. // = p2 / 2^-e
  10047. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  10048. //
  10049. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  10050. //
  10051. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  10052. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  10053. //
  10054. // using
  10055. //
  10056. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  10057. // = ( d) * 2^-e + ( r)
  10058. //
  10059. // or
  10060. // 10^m * p2 * 2^e = d + r * 2^e
  10061. //
  10062. // i.e.
  10063. //
  10064. // M+ = buffer + p2 * 2^e
  10065. // = buffer + 10^-m * (d + r * 2^e)
  10066. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  10067. //
  10068. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  10069. assert(p2 > delta);
  10070. int m = 0;
  10071. for (;;)
  10072. {
  10073. // Invariant:
  10074. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  10075. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  10076. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  10077. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  10078. //
  10079. assert(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  10080. p2 *= 10;
  10081. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  10082. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  10083. //
  10084. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  10085. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  10086. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  10087. //
  10088. assert(d <= 9);
  10089. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  10090. //
  10091. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  10092. //
  10093. p2 = r;
  10094. m++;
  10095. //
  10096. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  10097. // Invariant restored.
  10098. // Check if enough digits have been generated.
  10099. //
  10100. // 10^-m * p2 * 2^e <= delta * 2^e
  10101. // p2 * 2^e <= 10^m * delta * 2^e
  10102. // p2 <= 10^m * delta
  10103. delta *= 10;
  10104. dist *= 10;
  10105. if (p2 <= delta)
  10106. {
  10107. break;
  10108. }
  10109. }
  10110. // V = buffer * 10^-m, with M- <= V <= M+.
  10111. decimal_exponent -= m;
  10112. // 1 ulp in the decimal representation is now 10^-m.
  10113. // Since delta and dist are now scaled by 10^m, we need to do the
  10114. // same with ulp in order to keep the units in sync.
  10115. //
  10116. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  10117. //
  10118. const std::uint64_t ten_m = one.f;
  10119. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  10120. // By construction this algorithm generates the shortest possible decimal
  10121. // number (Loitsch, Theorem 6.2) which rounds back to w.
  10122. // For an input number of precision p, at least
  10123. //
  10124. // N = 1 + ceil(p * log_10(2))
  10125. //
  10126. // decimal digits are sufficient to identify all binary floating-point
  10127. // numbers (Matula, "In-and-Out conversions").
  10128. // This implies that the algorithm does not produce more than N decimal
  10129. // digits.
  10130. //
  10131. // N = 17 for p = 53 (IEEE double precision)
  10132. // N = 9 for p = 24 (IEEE single precision)
  10133. }
  10134. /*!
  10135. v = buf * 10^decimal_exponent
  10136. len is the length of the buffer (number of decimal digits)
  10137. The buffer must be large enough, i.e. >= max_digits10.
  10138. */
  10139. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  10140. diyfp m_minus, diyfp v, diyfp m_plus)
  10141. {
  10142. assert(m_plus.e == m_minus.e);
  10143. assert(m_plus.e == v.e);
  10144. // --------(-----------------------+-----------------------)-------- (A)
  10145. // m- v m+
  10146. //
  10147. // --------------------(-----------+-----------------------)-------- (B)
  10148. // m- v m+
  10149. //
  10150. // First scale v (and m- and m+) such that the exponent is in the range
  10151. // [alpha, gamma].
  10152. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  10153. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  10154. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  10155. const diyfp w = diyfp::mul(v, c_minus_k);
  10156. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  10157. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  10158. // ----(---+---)---------------(---+---)---------------(---+---)----
  10159. // w- w w+
  10160. // = c*m- = c*v = c*m+
  10161. //
  10162. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  10163. // w+ are now off by a small amount.
  10164. // In fact:
  10165. //
  10166. // w - v * 10^k < 1 ulp
  10167. //
  10168. // To account for this inaccuracy, add resp. subtract 1 ulp.
  10169. //
  10170. // --------+---[---------------(---+---)---------------]---+--------
  10171. // w- M- w M+ w+
  10172. //
  10173. // Now any number in [M-, M+] (bounds included) will round to w when input,
  10174. // regardless of how the input rounding algorithm breaks ties.
  10175. //
  10176. // And digit_gen generates the shortest possible such number in [M-, M+].
  10177. // Note that this does not mean that Grisu2 always generates the shortest
  10178. // possible number in the interval (m-, m+).
  10179. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  10180. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  10181. decimal_exponent = -cached.k; // = -(-k) = k
  10182. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  10183. }
  10184. /*!
  10185. v = buf * 10^decimal_exponent
  10186. len is the length of the buffer (number of decimal digits)
  10187. The buffer must be large enough, i.e. >= max_digits10.
  10188. */
  10189. template <typename FloatType>
  10190. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  10191. {
  10192. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  10193. "internal error: not enough precision");
  10194. assert(std::isfinite(value));
  10195. assert(value > 0);
  10196. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  10197. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  10198. // decimal representations are not exactly "short".
  10199. //
  10200. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  10201. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  10202. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  10203. // does.
  10204. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  10205. // representation using the corresponding std::from_chars function recovers value exactly". That
  10206. // indicates that single precision floating-point numbers should be recovered using
  10207. // 'std::strtof'.
  10208. //
  10209. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  10210. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  10211. // value is off by 1 ulp.
  10212. #if 0
  10213. const boundaries w = compute_boundaries(static_cast<double>(value));
  10214. #else
  10215. const boundaries w = compute_boundaries(value);
  10216. #endif
  10217. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  10218. }
  10219. /*!
  10220. @brief appends a decimal representation of e to buf
  10221. @return a pointer to the element following the exponent.
  10222. @pre -1000 < e < 1000
  10223. */
  10224. inline char* append_exponent(char* buf, int e)
  10225. {
  10226. assert(e > -1000);
  10227. assert(e < 1000);
  10228. if (e < 0)
  10229. {
  10230. e = -e;
  10231. *buf++ = '-';
  10232. }
  10233. else
  10234. {
  10235. *buf++ = '+';
  10236. }
  10237. auto k = static_cast<std::uint32_t>(e);
  10238. if (k < 10)
  10239. {
  10240. // Always print at least two digits in the exponent.
  10241. // This is for compatibility with printf("%g").
  10242. *buf++ = '0';
  10243. *buf++ = static_cast<char>('0' + k);
  10244. }
  10245. else if (k < 100)
  10246. {
  10247. *buf++ = static_cast<char>('0' + k / 10);
  10248. k %= 10;
  10249. *buf++ = static_cast<char>('0' + k);
  10250. }
  10251. else
  10252. {
  10253. *buf++ = static_cast<char>('0' + k / 100);
  10254. k %= 100;
  10255. *buf++ = static_cast<char>('0' + k / 10);
  10256. k %= 10;
  10257. *buf++ = static_cast<char>('0' + k);
  10258. }
  10259. return buf;
  10260. }
  10261. /*!
  10262. @brief prettify v = buf * 10^decimal_exponent
  10263. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  10264. notation. Otherwise it will be printed in exponential notation.
  10265. @pre min_exp < 0
  10266. @pre max_exp > 0
  10267. */
  10268. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  10269. int min_exp, int max_exp)
  10270. {
  10271. assert(min_exp < 0);
  10272. assert(max_exp > 0);
  10273. const int k = len;
  10274. const int n = len + decimal_exponent;
  10275. // v = buf * 10^(n-k)
  10276. // k is the length of the buffer (number of decimal digits)
  10277. // n is the position of the decimal point relative to the start of the buffer.
  10278. if (k <= n and n <= max_exp)
  10279. {
  10280. // digits[000]
  10281. // len <= max_exp + 2
  10282. std::memset(buf + k, '0', static_cast<size_t>(n - k));
  10283. // Make it look like a floating-point number (#362, #378)
  10284. buf[n + 0] = '.';
  10285. buf[n + 1] = '0';
  10286. return buf + (n + 2);
  10287. }
  10288. if (0 < n and n <= max_exp)
  10289. {
  10290. // dig.its
  10291. // len <= max_digits10 + 1
  10292. assert(k > n);
  10293. std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
  10294. buf[n] = '.';
  10295. return buf + (k + 1);
  10296. }
  10297. if (min_exp < n and n <= 0)
  10298. {
  10299. // 0.[000]digits
  10300. // len <= 2 + (-min_exp - 1) + max_digits10
  10301. std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
  10302. buf[0] = '0';
  10303. buf[1] = '.';
  10304. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  10305. return buf + (2 + (-n) + k);
  10306. }
  10307. if (k == 1)
  10308. {
  10309. // dE+123
  10310. // len <= 1 + 5
  10311. buf += 1;
  10312. }
  10313. else
  10314. {
  10315. // d.igitsE+123
  10316. // len <= max_digits10 + 1 + 5
  10317. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
  10318. buf[1] = '.';
  10319. buf += 1 + k;
  10320. }
  10321. *buf++ = 'e';
  10322. return append_exponent(buf, n - 1);
  10323. }
  10324. } // namespace dtoa_impl
  10325. /*!
  10326. @brief generates a decimal representation of the floating-point number value in [first, last).
  10327. The format of the resulting decimal representation is similar to printf's %g
  10328. format. Returns an iterator pointing past-the-end of the decimal representation.
  10329. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  10330. @note The buffer must be large enough.
  10331. @note The result is NOT null-terminated.
  10332. */
  10333. template <typename FloatType>
  10334. char* to_chars(char* first, const char* last, FloatType value)
  10335. {
  10336. static_cast<void>(last); // maybe unused - fix warning
  10337. assert(std::isfinite(value));
  10338. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  10339. if (std::signbit(value))
  10340. {
  10341. value = -value;
  10342. *first++ = '-';
  10343. }
  10344. if (value == 0) // +-0
  10345. {
  10346. *first++ = '0';
  10347. // Make it look like a floating-point number (#362, #378)
  10348. *first++ = '.';
  10349. *first++ = '0';
  10350. return first;
  10351. }
  10352. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  10353. // Compute v = buffer * 10^decimal_exponent.
  10354. // The decimal digits are stored in the buffer, which needs to be interpreted
  10355. // as an unsigned decimal integer.
  10356. // len is the length of the buffer, i.e. the number of decimal digits.
  10357. int len = 0;
  10358. int decimal_exponent = 0;
  10359. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  10360. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  10361. // Format the buffer like printf("%.*g", prec, value)
  10362. constexpr int kMinExp = -4;
  10363. // Use digits10 here to increase compatibility with version 2.
  10364. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  10365. assert(last - first >= kMaxExp + 2);
  10366. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  10367. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  10368. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  10369. }
  10370. } // namespace detail
  10371. } // namespace nlohmann
  10372. // #include <nlohmann/detail/exceptions.hpp>
  10373. // #include <nlohmann/detail/macro_scope.hpp>
  10374. // #include <nlohmann/detail/meta/cpp_future.hpp>
  10375. // #include <nlohmann/detail/output/binary_writer.hpp>
  10376. // #include <nlohmann/detail/output/output_adapters.hpp>
  10377. // #include <nlohmann/detail/value_t.hpp>
  10378. namespace nlohmann
  10379. {
  10380. namespace detail
  10381. {
  10382. ///////////////////
  10383. // serialization //
  10384. ///////////////////
  10385. /// how to treat decoding errors
  10386. enum class error_handler_t
  10387. {
  10388. strict, ///< throw a type_error exception in case of invalid UTF-8
  10389. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  10390. ignore ///< ignore invalid UTF-8 sequences
  10391. };
  10392. template<typename BasicJsonType>
  10393. class serializer
  10394. {
  10395. using string_t = typename BasicJsonType::string_t;
  10396. using number_float_t = typename BasicJsonType::number_float_t;
  10397. using number_integer_t = typename BasicJsonType::number_integer_t;
  10398. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  10399. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  10400. static constexpr std::uint8_t UTF8_REJECT = 1;
  10401. public:
  10402. /*!
  10403. @param[in] s output stream to serialize to
  10404. @param[in] ichar indentation character to use
  10405. @param[in] error_handler_ how to react on decoding errors
  10406. */
  10407. serializer(output_adapter_t<char> s, const char ichar,
  10408. error_handler_t error_handler_ = error_handler_t::strict)
  10409. : o(std::move(s))
  10410. , loc(std::localeconv())
  10411. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep))
  10412. , decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point))
  10413. , indent_char(ichar)
  10414. , indent_string(512, indent_char)
  10415. , error_handler(error_handler_)
  10416. {}
  10417. // delete because of pointer members
  10418. serializer(const serializer&) = delete;
  10419. serializer& operator=(const serializer&) = delete;
  10420. serializer(serializer&&) = delete;
  10421. serializer& operator=(serializer&&) = delete;
  10422. ~serializer() = default;
  10423. /*!
  10424. @brief internal implementation of the serialization function
  10425. This function is called by the public member function dump and organizes
  10426. the serialization internally. The indentation level is propagated as
  10427. additional parameter. In case of arrays and objects, the function is
  10428. called recursively.
  10429. - strings and object keys are escaped using `escape_string()`
  10430. - integer numbers are converted implicitly via `operator<<`
  10431. - floating-point numbers are converted to a string using `"%g"` format
  10432. @param[in] val value to serialize
  10433. @param[in] pretty_print whether the output shall be pretty-printed
  10434. @param[in] indent_step the indent level
  10435. @param[in] current_indent the current indent level (only used internally)
  10436. */
  10437. void dump(const BasicJsonType& val, const bool pretty_print,
  10438. const bool ensure_ascii,
  10439. const unsigned int indent_step,
  10440. const unsigned int current_indent = 0)
  10441. {
  10442. switch (val.m_type)
  10443. {
  10444. case value_t::object:
  10445. {
  10446. if (val.m_value.object->empty())
  10447. {
  10448. o->write_characters("{}", 2);
  10449. return;
  10450. }
  10451. if (pretty_print)
  10452. {
  10453. o->write_characters("{\n", 2);
  10454. // variable to hold indentation for recursive calls
  10455. const auto new_indent = current_indent + indent_step;
  10456. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  10457. {
  10458. indent_string.resize(indent_string.size() * 2, ' ');
  10459. }
  10460. // first n-1 elements
  10461. auto i = val.m_value.object->cbegin();
  10462. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  10463. {
  10464. o->write_characters(indent_string.c_str(), new_indent);
  10465. o->write_character('\"');
  10466. dump_escaped(i->first, ensure_ascii);
  10467. o->write_characters("\": ", 3);
  10468. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  10469. o->write_characters(",\n", 2);
  10470. }
  10471. // last element
  10472. assert(i != val.m_value.object->cend());
  10473. assert(std::next(i) == val.m_value.object->cend());
  10474. o->write_characters(indent_string.c_str(), new_indent);
  10475. o->write_character('\"');
  10476. dump_escaped(i->first, ensure_ascii);
  10477. o->write_characters("\": ", 3);
  10478. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  10479. o->write_character('\n');
  10480. o->write_characters(indent_string.c_str(), current_indent);
  10481. o->write_character('}');
  10482. }
  10483. else
  10484. {
  10485. o->write_character('{');
  10486. // first n-1 elements
  10487. auto i = val.m_value.object->cbegin();
  10488. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  10489. {
  10490. o->write_character('\"');
  10491. dump_escaped(i->first, ensure_ascii);
  10492. o->write_characters("\":", 2);
  10493. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  10494. o->write_character(',');
  10495. }
  10496. // last element
  10497. assert(i != val.m_value.object->cend());
  10498. assert(std::next(i) == val.m_value.object->cend());
  10499. o->write_character('\"');
  10500. dump_escaped(i->first, ensure_ascii);
  10501. o->write_characters("\":", 2);
  10502. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  10503. o->write_character('}');
  10504. }
  10505. return;
  10506. }
  10507. case value_t::array:
  10508. {
  10509. if (val.m_value.array->empty())
  10510. {
  10511. o->write_characters("[]", 2);
  10512. return;
  10513. }
  10514. if (pretty_print)
  10515. {
  10516. o->write_characters("[\n", 2);
  10517. // variable to hold indentation for recursive calls
  10518. const auto new_indent = current_indent + indent_step;
  10519. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  10520. {
  10521. indent_string.resize(indent_string.size() * 2, ' ');
  10522. }
  10523. // first n-1 elements
  10524. for (auto i = val.m_value.array->cbegin();
  10525. i != val.m_value.array->cend() - 1; ++i)
  10526. {
  10527. o->write_characters(indent_string.c_str(), new_indent);
  10528. dump(*i, true, ensure_ascii, indent_step, new_indent);
  10529. o->write_characters(",\n", 2);
  10530. }
  10531. // last element
  10532. assert(not val.m_value.array->empty());
  10533. o->write_characters(indent_string.c_str(), new_indent);
  10534. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  10535. o->write_character('\n');
  10536. o->write_characters(indent_string.c_str(), current_indent);
  10537. o->write_character(']');
  10538. }
  10539. else
  10540. {
  10541. o->write_character('[');
  10542. // first n-1 elements
  10543. for (auto i = val.m_value.array->cbegin();
  10544. i != val.m_value.array->cend() - 1; ++i)
  10545. {
  10546. dump(*i, false, ensure_ascii, indent_step, current_indent);
  10547. o->write_character(',');
  10548. }
  10549. // last element
  10550. assert(not val.m_value.array->empty());
  10551. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  10552. o->write_character(']');
  10553. }
  10554. return;
  10555. }
  10556. case value_t::string:
  10557. {
  10558. o->write_character('\"');
  10559. dump_escaped(*val.m_value.string, ensure_ascii);
  10560. o->write_character('\"');
  10561. return;
  10562. }
  10563. case value_t::boolean:
  10564. {
  10565. if (val.m_value.boolean)
  10566. {
  10567. o->write_characters("true", 4);
  10568. }
  10569. else
  10570. {
  10571. o->write_characters("false", 5);
  10572. }
  10573. return;
  10574. }
  10575. case value_t::number_integer:
  10576. {
  10577. dump_integer(val.m_value.number_integer);
  10578. return;
  10579. }
  10580. case value_t::number_unsigned:
  10581. {
  10582. dump_integer(val.m_value.number_unsigned);
  10583. return;
  10584. }
  10585. case value_t::number_float:
  10586. {
  10587. dump_float(val.m_value.number_float);
  10588. return;
  10589. }
  10590. case value_t::discarded:
  10591. {
  10592. o->write_characters("<discarded>", 11);
  10593. return;
  10594. }
  10595. case value_t::null:
  10596. {
  10597. o->write_characters("null", 4);
  10598. return;
  10599. }
  10600. default: // LCOV_EXCL_LINE
  10601. assert(false); // LCOV_EXCL_LINE
  10602. }
  10603. }
  10604. private:
  10605. /*!
  10606. @brief dump escaped string
  10607. Escape a string by replacing certain special characters by a sequence of an
  10608. escape character (backslash) and another character and other control
  10609. characters by a sequence of "\u" followed by a four-digit hex
  10610. representation. The escaped string is written to output stream @a o.
  10611. @param[in] s the string to escape
  10612. @param[in] ensure_ascii whether to escape non-ASCII characters with
  10613. \uXXXX sequences
  10614. @complexity Linear in the length of string @a s.
  10615. */
  10616. void dump_escaped(const string_t& s, const bool ensure_ascii)
  10617. {
  10618. std::uint32_t codepoint;
  10619. std::uint8_t state = UTF8_ACCEPT;
  10620. std::size_t bytes = 0; // number of bytes written to string_buffer
  10621. // number of bytes written at the point of the last valid byte
  10622. std::size_t bytes_after_last_accept = 0;
  10623. std::size_t undumped_chars = 0;
  10624. for (std::size_t i = 0; i < s.size(); ++i)
  10625. {
  10626. const auto byte = static_cast<uint8_t>(s[i]);
  10627. switch (decode(state, codepoint, byte))
  10628. {
  10629. case UTF8_ACCEPT: // decode found a new code point
  10630. {
  10631. switch (codepoint)
  10632. {
  10633. case 0x08: // backspace
  10634. {
  10635. string_buffer[bytes++] = '\\';
  10636. string_buffer[bytes++] = 'b';
  10637. break;
  10638. }
  10639. case 0x09: // horizontal tab
  10640. {
  10641. string_buffer[bytes++] = '\\';
  10642. string_buffer[bytes++] = 't';
  10643. break;
  10644. }
  10645. case 0x0A: // newline
  10646. {
  10647. string_buffer[bytes++] = '\\';
  10648. string_buffer[bytes++] = 'n';
  10649. break;
  10650. }
  10651. case 0x0C: // formfeed
  10652. {
  10653. string_buffer[bytes++] = '\\';
  10654. string_buffer[bytes++] = 'f';
  10655. break;
  10656. }
  10657. case 0x0D: // carriage return
  10658. {
  10659. string_buffer[bytes++] = '\\';
  10660. string_buffer[bytes++] = 'r';
  10661. break;
  10662. }
  10663. case 0x22: // quotation mark
  10664. {
  10665. string_buffer[bytes++] = '\\';
  10666. string_buffer[bytes++] = '\"';
  10667. break;
  10668. }
  10669. case 0x5C: // reverse solidus
  10670. {
  10671. string_buffer[bytes++] = '\\';
  10672. string_buffer[bytes++] = '\\';
  10673. break;
  10674. }
  10675. default:
  10676. {
  10677. // escape control characters (0x00..0x1F) or, if
  10678. // ensure_ascii parameter is used, non-ASCII characters
  10679. if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
  10680. {
  10681. if (codepoint <= 0xFFFF)
  10682. {
  10683. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  10684. static_cast<std::uint16_t>(codepoint));
  10685. bytes += 6;
  10686. }
  10687. else
  10688. {
  10689. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  10690. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  10691. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  10692. bytes += 12;
  10693. }
  10694. }
  10695. else
  10696. {
  10697. // copy byte to buffer (all previous bytes
  10698. // been copied have in default case above)
  10699. string_buffer[bytes++] = s[i];
  10700. }
  10701. break;
  10702. }
  10703. }
  10704. // write buffer and reset index; there must be 13 bytes
  10705. // left, as this is the maximal number of bytes to be
  10706. // written ("\uxxxx\uxxxx\0") for one code point
  10707. if (string_buffer.size() - bytes < 13)
  10708. {
  10709. o->write_characters(string_buffer.data(), bytes);
  10710. bytes = 0;
  10711. }
  10712. // remember the byte position of this accept
  10713. bytes_after_last_accept = bytes;
  10714. undumped_chars = 0;
  10715. break;
  10716. }
  10717. case UTF8_REJECT: // decode found invalid UTF-8 byte
  10718. {
  10719. switch (error_handler)
  10720. {
  10721. case error_handler_t::strict:
  10722. {
  10723. std::string sn(3, '\0');
  10724. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  10725. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  10726. }
  10727. case error_handler_t::ignore:
  10728. case error_handler_t::replace:
  10729. {
  10730. // in case we saw this character the first time, we
  10731. // would like to read it again, because the byte
  10732. // may be OK for itself, but just not OK for the
  10733. // previous sequence
  10734. if (undumped_chars > 0)
  10735. {
  10736. --i;
  10737. }
  10738. // reset length buffer to the last accepted index;
  10739. // thus removing/ignoring the invalid characters
  10740. bytes = bytes_after_last_accept;
  10741. if (error_handler == error_handler_t::replace)
  10742. {
  10743. // add a replacement character
  10744. if (ensure_ascii)
  10745. {
  10746. string_buffer[bytes++] = '\\';
  10747. string_buffer[bytes++] = 'u';
  10748. string_buffer[bytes++] = 'f';
  10749. string_buffer[bytes++] = 'f';
  10750. string_buffer[bytes++] = 'f';
  10751. string_buffer[bytes++] = 'd';
  10752. }
  10753. else
  10754. {
  10755. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  10756. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  10757. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  10758. }
  10759. // write buffer and reset index; there must be 13 bytes
  10760. // left, as this is the maximal number of bytes to be
  10761. // written ("\uxxxx\uxxxx\0") for one code point
  10762. if (string_buffer.size() - bytes < 13)
  10763. {
  10764. o->write_characters(string_buffer.data(), bytes);
  10765. bytes = 0;
  10766. }
  10767. bytes_after_last_accept = bytes;
  10768. }
  10769. undumped_chars = 0;
  10770. // continue processing the string
  10771. state = UTF8_ACCEPT;
  10772. break;
  10773. }
  10774. default: // LCOV_EXCL_LINE
  10775. assert(false); // LCOV_EXCL_LINE
  10776. }
  10777. break;
  10778. }
  10779. default: // decode found yet incomplete multi-byte code point
  10780. {
  10781. if (not ensure_ascii)
  10782. {
  10783. // code point will not be escaped - copy byte to buffer
  10784. string_buffer[bytes++] = s[i];
  10785. }
  10786. ++undumped_chars;
  10787. break;
  10788. }
  10789. }
  10790. }
  10791. // we finished processing the string
  10792. if (JSON_LIKELY(state == UTF8_ACCEPT))
  10793. {
  10794. // write buffer
  10795. if (bytes > 0)
  10796. {
  10797. o->write_characters(string_buffer.data(), bytes);
  10798. }
  10799. }
  10800. else
  10801. {
  10802. // we finish reading, but do not accept: string was incomplete
  10803. switch (error_handler)
  10804. {
  10805. case error_handler_t::strict:
  10806. {
  10807. std::string sn(3, '\0');
  10808. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  10809. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  10810. }
  10811. case error_handler_t::ignore:
  10812. {
  10813. // write all accepted bytes
  10814. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  10815. break;
  10816. }
  10817. case error_handler_t::replace:
  10818. {
  10819. // write all accepted bytes
  10820. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  10821. // add a replacement character
  10822. if (ensure_ascii)
  10823. {
  10824. o->write_characters("\\ufffd", 6);
  10825. }
  10826. else
  10827. {
  10828. o->write_characters("\xEF\xBF\xBD", 3);
  10829. }
  10830. break;
  10831. }
  10832. default: // LCOV_EXCL_LINE
  10833. assert(false); // LCOV_EXCL_LINE
  10834. }
  10835. }
  10836. }
  10837. /*!
  10838. @brief count digits
  10839. Count the number of decimal (base 10) digits for an input unsigned integer.
  10840. @param[in] x unsigned integer number to count its digits
  10841. @return number of decimal digits
  10842. */
  10843. inline unsigned int count_digits(number_unsigned_t x) noexcept
  10844. {
  10845. unsigned int n_digits = 1;
  10846. for (;;)
  10847. {
  10848. if (x < 10)
  10849. {
  10850. return n_digits;
  10851. }
  10852. if (x < 100)
  10853. {
  10854. return n_digits + 1;
  10855. }
  10856. if (x < 1000)
  10857. {
  10858. return n_digits + 2;
  10859. }
  10860. if (x < 10000)
  10861. {
  10862. return n_digits + 3;
  10863. }
  10864. x = x / 10000u;
  10865. n_digits += 4;
  10866. }
  10867. }
  10868. /*!
  10869. @brief dump an integer
  10870. Dump a given integer to output stream @a o. Works internally with
  10871. @a number_buffer.
  10872. @param[in] x integer number (signed or unsigned) to dump
  10873. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  10874. */
  10875. template<typename NumberType, detail::enable_if_t<
  10876. std::is_same<NumberType, number_unsigned_t>::value or
  10877. std::is_same<NumberType, number_integer_t>::value,
  10878. int> = 0>
  10879. void dump_integer(NumberType x)
  10880. {
  10881. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  10882. {
  10883. {
  10884. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  10885. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  10886. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  10887. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  10888. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  10889. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  10890. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  10891. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  10892. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  10893. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  10894. }
  10895. };
  10896. // special case for "0"
  10897. if (x == 0)
  10898. {
  10899. o->write_character('0');
  10900. return;
  10901. }
  10902. // use a pointer to fill the buffer
  10903. auto buffer_ptr = number_buffer.begin();
  10904. const bool is_negative = std::is_same<NumberType, number_integer_t>::value and not(x >= 0); // see issue #755
  10905. number_unsigned_t abs_value;
  10906. unsigned int n_chars;
  10907. if (is_negative)
  10908. {
  10909. *buffer_ptr = '-';
  10910. abs_value = static_cast<number_unsigned_t>(std::abs(static_cast<std::intmax_t>(x)));
  10911. // account one more byte for the minus sign
  10912. n_chars = 1 + count_digits(abs_value);
  10913. }
  10914. else
  10915. {
  10916. abs_value = static_cast<number_unsigned_t>(x);
  10917. n_chars = count_digits(abs_value);
  10918. }
  10919. // spare 1 byte for '\0'
  10920. assert(n_chars < number_buffer.size() - 1);
  10921. // jump to the end to generate the string from backward
  10922. // so we later avoid reversing the result
  10923. buffer_ptr += n_chars;
  10924. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  10925. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  10926. while (abs_value >= 100)
  10927. {
  10928. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  10929. abs_value /= 100;
  10930. *(--buffer_ptr) = digits_to_99[digits_index][1];
  10931. *(--buffer_ptr) = digits_to_99[digits_index][0];
  10932. }
  10933. if (abs_value >= 10)
  10934. {
  10935. const auto digits_index = static_cast<unsigned>(abs_value);
  10936. *(--buffer_ptr) = digits_to_99[digits_index][1];
  10937. *(--buffer_ptr) = digits_to_99[digits_index][0];
  10938. }
  10939. else
  10940. {
  10941. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  10942. }
  10943. o->write_characters(number_buffer.data(), n_chars);
  10944. }
  10945. /*!
  10946. @brief dump a floating-point number
  10947. Dump a given floating-point number to output stream @a o. Works internally
  10948. with @a number_buffer.
  10949. @param[in] x floating-point number to dump
  10950. */
  10951. void dump_float(number_float_t x)
  10952. {
  10953. // NaN / inf
  10954. if (not std::isfinite(x))
  10955. {
  10956. o->write_characters("null", 4);
  10957. return;
  10958. }
  10959. // If number_float_t is an IEEE-754 single or double precision number,
  10960. // use the Grisu2 algorithm to produce short numbers which are
  10961. // guaranteed to round-trip, using strtof and strtod, resp.
  10962. //
  10963. // NB: The test below works if <long double> == <double>.
  10964. static constexpr bool is_ieee_single_or_double
  10965. = (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
  10966. (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);
  10967. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  10968. }
  10969. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  10970. {
  10971. char* begin = number_buffer.data();
  10972. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  10973. o->write_characters(begin, static_cast<size_t>(end - begin));
  10974. }
  10975. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  10976. {
  10977. // get number of digits for a float -> text -> float round-trip
  10978. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  10979. // the actual conversion
  10980. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  10981. // negative value indicates an error
  10982. assert(len > 0);
  10983. // check if buffer was large enough
  10984. assert(static_cast<std::size_t>(len) < number_buffer.size());
  10985. // erase thousands separator
  10986. if (thousands_sep != '\0')
  10987. {
  10988. const auto end = std::remove(number_buffer.begin(),
  10989. number_buffer.begin() + len, thousands_sep);
  10990. std::fill(end, number_buffer.end(), '\0');
  10991. assert((end - number_buffer.begin()) <= len);
  10992. len = (end - number_buffer.begin());
  10993. }
  10994. // convert decimal point to '.'
  10995. if (decimal_point != '\0' and decimal_point != '.')
  10996. {
  10997. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  10998. if (dec_pos != number_buffer.end())
  10999. {
  11000. *dec_pos = '.';
  11001. }
  11002. }
  11003. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  11004. // determine if need to append ".0"
  11005. const bool value_is_int_like =
  11006. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  11007. [](char c)
  11008. {
  11009. return c == '.' or c == 'e';
  11010. });
  11011. if (value_is_int_like)
  11012. {
  11013. o->write_characters(".0", 2);
  11014. }
  11015. }
  11016. /*!
  11017. @brief check whether a string is UTF-8 encoded
  11018. The function checks each byte of a string whether it is UTF-8 encoded. The
  11019. result of the check is stored in the @a state parameter. The function must
  11020. be called initially with state 0 (accept). State 1 means the string must
  11021. be rejected, because the current byte is not allowed. If the string is
  11022. completely processed, but the state is non-zero, the string ended
  11023. prematurely; that is, the last byte indicated more bytes should have
  11024. followed.
  11025. @param[in,out] state the state of the decoding
  11026. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  11027. @param[in] byte next byte to decode
  11028. @return new state
  11029. @note The function has been edited: a std::array is used.
  11030. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  11031. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  11032. */
  11033. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  11034. {
  11035. static const std::array<std::uint8_t, 400> utf8d =
  11036. {
  11037. {
  11038. 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
  11039. 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
  11040. 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
  11041. 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
  11042. 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
  11043. 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
  11044. 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
  11045. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  11046. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  11047. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  11048. 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
  11049. 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
  11050. 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
  11051. 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
  11052. }
  11053. };
  11054. const std::uint8_t type = utf8d[byte];
  11055. codep = (state != UTF8_ACCEPT)
  11056. ? (byte & 0x3fu) | (codep << 6u)
  11057. : (0xFFu >> type) & (byte);
  11058. state = utf8d[256u + state * 16u + type];
  11059. return state;
  11060. }
  11061. private:
  11062. /// the output of the serializer
  11063. output_adapter_t<char> o = nullptr;
  11064. /// a (hopefully) large enough character buffer
  11065. std::array<char, 64> number_buffer{{}};
  11066. /// the locale
  11067. const std::lconv* loc = nullptr;
  11068. /// the locale's thousand separator character
  11069. const char thousands_sep = '\0';
  11070. /// the locale's decimal point character
  11071. const char decimal_point = '\0';
  11072. /// string buffer
  11073. std::array<char, 512> string_buffer{{}};
  11074. /// the indentation character
  11075. const char indent_char;
  11076. /// the indentation string
  11077. string_t indent_string;
  11078. /// error_handler how to react on decoding errors
  11079. const error_handler_t error_handler;
  11080. };
  11081. } // namespace detail
  11082. } // namespace nlohmann
  11083. // #include <nlohmann/detail/value_t.hpp>
  11084. // #include <nlohmann/json_fwd.hpp>
  11085. /*!
  11086. @brief namespace for Niels Lohmann
  11087. @see https://github.com/nlohmann
  11088. @since version 1.0.0
  11089. */
  11090. namespace nlohmann
  11091. {
  11092. /*!
  11093. @brief a class to store JSON values
  11094. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  11095. in @ref object_t)
  11096. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  11097. in @ref array_t)
  11098. @tparam StringType type for JSON strings and object keys (`std::string` by
  11099. default; will be used in @ref string_t)
  11100. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  11101. in @ref boolean_t)
  11102. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  11103. default; will be used in @ref number_integer_t)
  11104. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  11105. `uint64_t` by default; will be used in @ref number_unsigned_t)
  11106. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  11107. default; will be used in @ref number_float_t)
  11108. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  11109. default)
  11110. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  11111. and `from_json()` (@ref adl_serializer by default)
  11112. @requirement The class satisfies the following concept requirements:
  11113. - Basic
  11114. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  11115. JSON values can be default constructed. The result will be a JSON null
  11116. value.
  11117. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  11118. A JSON value can be constructed from an rvalue argument.
  11119. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  11120. A JSON value can be copy-constructed from an lvalue expression.
  11121. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  11122. A JSON value van be assigned from an rvalue argument.
  11123. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  11124. A JSON value can be copy-assigned from an lvalue expression.
  11125. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  11126. JSON values can be destructed.
  11127. - Layout
  11128. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  11129. JSON values have
  11130. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  11131. All non-static data members are private and standard layout types, the
  11132. class has no virtual functions or (virtual) base classes.
  11133. - Library-wide
  11134. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  11135. JSON values can be compared with `==`, see @ref
  11136. operator==(const_reference,const_reference).
  11137. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  11138. JSON values can be compared with `<`, see @ref
  11139. operator<(const_reference,const_reference).
  11140. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  11141. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  11142. other compatible types, using unqualified function call @ref swap().
  11143. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  11144. JSON values can be compared against `std::nullptr_t` objects which are used
  11145. to model the `null` value.
  11146. - Container
  11147. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  11148. JSON values can be used like STL containers and provide iterator access.
  11149. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  11150. JSON values can be used like STL containers and provide reverse iterator
  11151. access.
  11152. @invariant The member variables @a m_value and @a m_type have the following
  11153. relationship:
  11154. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  11155. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  11156. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  11157. The invariants are checked by member function assert_invariant().
  11158. @internal
  11159. @note ObjectType trick from http://stackoverflow.com/a/9860911
  11160. @endinternal
  11161. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  11162. Format](http://rfc7159.net/rfc7159)
  11163. @since version 1.0.0
  11164. @nosubgrouping
  11165. */
  11166. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  11167. class basic_json
  11168. {
  11169. private:
  11170. template<detail::value_t> friend struct detail::external_constructor;
  11171. friend ::nlohmann::json_pointer<basic_json>;
  11172. friend ::nlohmann::detail::parser<basic_json>;
  11173. friend ::nlohmann::detail::serializer<basic_json>;
  11174. template<typename BasicJsonType>
  11175. friend class ::nlohmann::detail::iter_impl;
  11176. template<typename BasicJsonType, typename CharType>
  11177. friend class ::nlohmann::detail::binary_writer;
  11178. template<typename BasicJsonType, typename SAX>
  11179. friend class ::nlohmann::detail::binary_reader;
  11180. template<typename BasicJsonType>
  11181. friend class ::nlohmann::detail::json_sax_dom_parser;
  11182. template<typename BasicJsonType>
  11183. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  11184. /// workaround type for MSVC
  11185. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  11186. // convenience aliases for types residing in namespace detail;
  11187. using lexer = ::nlohmann::detail::lexer<basic_json>;
  11188. using parser = ::nlohmann::detail::parser<basic_json>;
  11189. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  11190. template<typename BasicJsonType>
  11191. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  11192. template<typename BasicJsonType>
  11193. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  11194. template<typename Iterator>
  11195. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  11196. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  11197. template<typename CharType>
  11198. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  11199. using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
  11200. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  11201. using serializer = ::nlohmann::detail::serializer<basic_json>;
  11202. public:
  11203. using value_t = detail::value_t;
  11204. /// JSON Pointer, see @ref nlohmann::json_pointer
  11205. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  11206. template<typename T, typename SFINAE>
  11207. using json_serializer = JSONSerializer<T, SFINAE>;
  11208. /// how to treat decoding errors
  11209. using error_handler_t = detail::error_handler_t;
  11210. /// helper type for initializer lists of basic_json values
  11211. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  11212. using input_format_t = detail::input_format_t;
  11213. /// SAX interface type, see @ref nlohmann::json_sax
  11214. using json_sax_t = json_sax<basic_json>;
  11215. ////////////////
  11216. // exceptions //
  11217. ////////////////
  11218. /// @name exceptions
  11219. /// Classes to implement user-defined exceptions.
  11220. /// @{
  11221. /// @copydoc detail::exception
  11222. using exception = detail::exception;
  11223. /// @copydoc detail::parse_error
  11224. using parse_error = detail::parse_error;
  11225. /// @copydoc detail::invalid_iterator
  11226. using invalid_iterator = detail::invalid_iterator;
  11227. /// @copydoc detail::type_error
  11228. using type_error = detail::type_error;
  11229. /// @copydoc detail::out_of_range
  11230. using out_of_range = detail::out_of_range;
  11231. /// @copydoc detail::other_error
  11232. using other_error = detail::other_error;
  11233. /// @}
  11234. /////////////////////
  11235. // container types //
  11236. /////////////////////
  11237. /// @name container types
  11238. /// The canonic container types to use @ref basic_json like any other STL
  11239. /// container.
  11240. /// @{
  11241. /// the type of elements in a basic_json container
  11242. using value_type = basic_json;
  11243. /// the type of an element reference
  11244. using reference = value_type&;
  11245. /// the type of an element const reference
  11246. using const_reference = const value_type&;
  11247. /// a type to represent differences between iterators
  11248. using difference_type = std::ptrdiff_t;
  11249. /// a type to represent container sizes
  11250. using size_type = std::size_t;
  11251. /// the allocator type
  11252. using allocator_type = AllocatorType<basic_json>;
  11253. /// the type of an element pointer
  11254. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  11255. /// the type of an element const pointer
  11256. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  11257. /// an iterator for a basic_json container
  11258. using iterator = iter_impl<basic_json>;
  11259. /// a const iterator for a basic_json container
  11260. using const_iterator = iter_impl<const basic_json>;
  11261. /// a reverse iterator for a basic_json container
  11262. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  11263. /// a const reverse iterator for a basic_json container
  11264. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  11265. /// @}
  11266. /*!
  11267. @brief returns the allocator associated with the container
  11268. */
  11269. static allocator_type get_allocator()
  11270. {
  11271. return allocator_type();
  11272. }
  11273. /*!
  11274. @brief returns version information on the library
  11275. This function returns a JSON object with information about the library,
  11276. including the version number and information on the platform and compiler.
  11277. @return JSON object holding version information
  11278. key | description
  11279. ----------- | ---------------
  11280. `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).
  11281. `copyright` | The copyright line for the library as string.
  11282. `name` | The name of the library as string.
  11283. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  11284. `url` | The URL of the project as string.
  11285. `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).
  11286. @liveexample{The following code shows an example output of the `meta()`
  11287. function.,meta}
  11288. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11289. changes to any JSON value.
  11290. @complexity Constant.
  11291. @since 2.1.0
  11292. */
  11293. JSON_NODISCARD
  11294. static basic_json meta()
  11295. {
  11296. basic_json result;
  11297. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  11298. result["name"] = "JSON for Modern C++";
  11299. result["url"] = "https://github.com/nlohmann/json";
  11300. result["version"]["string"] =
  11301. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  11302. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  11303. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  11304. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  11305. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  11306. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  11307. #ifdef _WIN32
  11308. result["platform"] = "win32";
  11309. #elif defined __linux__
  11310. result["platform"] = "linux";
  11311. #elif defined __APPLE__
  11312. result["platform"] = "apple";
  11313. #elif defined __unix__
  11314. result["platform"] = "unix";
  11315. #else
  11316. result["platform"] = "unknown";
  11317. #endif
  11318. #if defined(__ICC) || defined(__INTEL_COMPILER)
  11319. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  11320. #elif defined(__clang__)
  11321. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  11322. #elif defined(__GNUC__) || defined(__GNUG__)
  11323. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  11324. #elif defined(__HP_cc) || defined(__HP_aCC)
  11325. result["compiler"] = "hp"
  11326. #elif defined(__IBMCPP__)
  11327. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  11328. #elif defined(_MSC_VER)
  11329. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  11330. #elif defined(__PGI)
  11331. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  11332. #elif defined(__SUNPRO_CC)
  11333. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  11334. #else
  11335. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  11336. #endif
  11337. #ifdef __cplusplus
  11338. result["compiler"]["c++"] = std::to_string(__cplusplus);
  11339. #else
  11340. result["compiler"]["c++"] = "unknown";
  11341. #endif
  11342. return result;
  11343. }
  11344. ///////////////////////////
  11345. // JSON value data types //
  11346. ///////////////////////////
  11347. /// @name JSON value data types
  11348. /// The data types to store a JSON value. These types are derived from
  11349. /// the template arguments passed to class @ref basic_json.
  11350. /// @{
  11351. #if defined(JSON_HAS_CPP_14)
  11352. // Use transparent comparator if possible, combined with perfect forwarding
  11353. // on find() and count() calls prevents unnecessary string construction.
  11354. using object_comparator_t = std::less<>;
  11355. #else
  11356. using object_comparator_t = std::less<StringType>;
  11357. #endif
  11358. /*!
  11359. @brief a type for an object
  11360. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  11361. > An object is an unordered collection of zero or more name/value pairs,
  11362. > where a name is a string and a value is a string, number, boolean, null,
  11363. > object, or array.
  11364. To store objects in C++, a type is defined by the template parameters
  11365. described below.
  11366. @tparam ObjectType the container to store objects (e.g., `std::map` or
  11367. `std::unordered_map`)
  11368. @tparam StringType the type of the keys or names (e.g., `std::string`).
  11369. The comparison function `std::less<StringType>` is used to order elements
  11370. inside the container.
  11371. @tparam AllocatorType the allocator to use for objects (e.g.,
  11372. `std::allocator`)
  11373. #### Default type
  11374. With the default values for @a ObjectType (`std::map`), @a StringType
  11375. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  11376. value for @a object_t is:
  11377. @code {.cpp}
  11378. std::map<
  11379. std::string, // key_type
  11380. basic_json, // value_type
  11381. std::less<std::string>, // key_compare
  11382. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  11383. >
  11384. @endcode
  11385. #### Behavior
  11386. The choice of @a object_t influences the behavior of the JSON class. With
  11387. the default type, objects have the following behavior:
  11388. - When all names are unique, objects will be interoperable in the sense
  11389. that all software implementations receiving that object will agree on
  11390. the name-value mappings.
  11391. - When the names within an object are not unique, it is unspecified which
  11392. one of the values for a given key will be chosen. For instance,
  11393. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  11394. `{"key": 2}`.
  11395. - Internally, name/value pairs are stored in lexicographical order of the
  11396. names. Objects will also be serialized (see @ref dump) in this order.
  11397. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  11398. and serialized as `{"a": 2, "b": 1}`.
  11399. - When comparing objects, the order of the name/value pairs is irrelevant.
  11400. This makes objects interoperable in the sense that they will not be
  11401. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  11402. `{"a": 2, "b": 1}` will be treated as equal.
  11403. #### Limits
  11404. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  11405. > An implementation may set limits on the maximum depth of nesting.
  11406. In this class, the object's limit of nesting is not explicitly constrained.
  11407. However, a maximum depth of nesting may be introduced by the compiler or
  11408. runtime environment. A theoretical limit can be queried by calling the
  11409. @ref max_size function of a JSON object.
  11410. #### Storage
  11411. Objects are stored as pointers in a @ref basic_json type. That is, for any
  11412. access to object values, a pointer of type `object_t*` must be
  11413. dereferenced.
  11414. @sa @ref array_t -- type for an array value
  11415. @since version 1.0.0
  11416. @note The order name/value pairs are added to the object is *not*
  11417. preserved by the library. Therefore, iterating an object may return
  11418. name/value pairs in a different order than they were originally stored. In
  11419. fact, keys will be traversed in alphabetical order as `std::map` with
  11420. `std::less` is used by default. Please note this behavior conforms to [RFC
  11421. 7159](http://rfc7159.net/rfc7159), because any order implements the
  11422. specified "unordered" nature of JSON objects.
  11423. */
  11424. using object_t = ObjectType<StringType,
  11425. basic_json,
  11426. object_comparator_t,
  11427. AllocatorType<std::pair<const StringType,
  11428. basic_json>>>;
  11429. /*!
  11430. @brief a type for an array
  11431. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  11432. > An array is an ordered sequence of zero or more values.
  11433. To store objects in C++, a type is defined by the template parameters
  11434. explained below.
  11435. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  11436. `std::list`)
  11437. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  11438. #### Default type
  11439. With the default values for @a ArrayType (`std::vector`) and @a
  11440. AllocatorType (`std::allocator`), the default value for @a array_t is:
  11441. @code {.cpp}
  11442. std::vector<
  11443. basic_json, // value_type
  11444. std::allocator<basic_json> // allocator_type
  11445. >
  11446. @endcode
  11447. #### Limits
  11448. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  11449. > An implementation may set limits on the maximum depth of nesting.
  11450. In this class, the array's limit of nesting is not explicitly constrained.
  11451. However, a maximum depth of nesting may be introduced by the compiler or
  11452. runtime environment. A theoretical limit can be queried by calling the
  11453. @ref max_size function of a JSON array.
  11454. #### Storage
  11455. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  11456. access to array values, a pointer of type `array_t*` must be dereferenced.
  11457. @sa @ref object_t -- type for an object value
  11458. @since version 1.0.0
  11459. */
  11460. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  11461. /*!
  11462. @brief a type for a string
  11463. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  11464. > A string is a sequence of zero or more Unicode characters.
  11465. To store objects in C++, a type is defined by the template parameter
  11466. described below. Unicode values are split by the JSON class into
  11467. byte-sized characters during deserialization.
  11468. @tparam StringType the container to store strings (e.g., `std::string`).
  11469. Note this container is used for keys/names in objects, see @ref object_t.
  11470. #### Default type
  11471. With the default values for @a StringType (`std::string`), the default
  11472. value for @a string_t is:
  11473. @code {.cpp}
  11474. std::string
  11475. @endcode
  11476. #### Encoding
  11477. Strings are stored in UTF-8 encoding. Therefore, functions like
  11478. `std::string::size()` or `std::string::length()` return the number of
  11479. bytes in the string rather than the number of characters or glyphs.
  11480. #### String comparison
  11481. [RFC 7159](http://rfc7159.net/rfc7159) states:
  11482. > Software implementations are typically required to test names of object
  11483. > members for equality. Implementations that transform the textual
  11484. > representation into sequences of Unicode code units and then perform the
  11485. > comparison numerically, code unit by code unit, are interoperable in the
  11486. > sense that implementations will agree in all cases on equality or
  11487. > inequality of two strings. For example, implementations that compare
  11488. > strings with escaped characters unconverted may incorrectly find that
  11489. > `"a\\b"` and `"a\u005Cb"` are not equal.
  11490. This implementation is interoperable as it does compare strings code unit
  11491. by code unit.
  11492. #### Storage
  11493. String values are stored as pointers in a @ref basic_json type. That is,
  11494. for any access to string values, a pointer of type `string_t*` must be
  11495. dereferenced.
  11496. @since version 1.0.0
  11497. */
  11498. using string_t = StringType;
  11499. /*!
  11500. @brief a type for a boolean
  11501. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  11502. type which differentiates the two literals `true` and `false`.
  11503. To store objects in C++, a type is defined by the template parameter @a
  11504. BooleanType which chooses the type to use.
  11505. #### Default type
  11506. With the default values for @a BooleanType (`bool`), the default value for
  11507. @a boolean_t is:
  11508. @code {.cpp}
  11509. bool
  11510. @endcode
  11511. #### Storage
  11512. Boolean values are stored directly inside a @ref basic_json type.
  11513. @since version 1.0.0
  11514. */
  11515. using boolean_t = BooleanType;
  11516. /*!
  11517. @brief a type for a number (integer)
  11518. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  11519. > The representation of numbers is similar to that used in most
  11520. > programming languages. A number is represented in base 10 using decimal
  11521. > digits. It contains an integer component that may be prefixed with an
  11522. > optional minus sign, which may be followed by a fraction part and/or an
  11523. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  11524. > cannot be represented in the grammar below (such as Infinity and NaN)
  11525. > are not permitted.
  11526. This description includes both integer and floating-point numbers.
  11527. However, C++ allows more precise storage if it is known whether the number
  11528. is a signed integer, an unsigned integer or a floating-point number.
  11529. Therefore, three different types, @ref number_integer_t, @ref
  11530. number_unsigned_t and @ref number_float_t are used.
  11531. To store integer numbers in C++, a type is defined by the template
  11532. parameter @a NumberIntegerType which chooses the type to use.
  11533. #### Default type
  11534. With the default values for @a NumberIntegerType (`int64_t`), the default
  11535. value for @a number_integer_t is:
  11536. @code {.cpp}
  11537. int64_t
  11538. @endcode
  11539. #### Default behavior
  11540. - The restrictions about leading zeros is not enforced in C++. Instead,
  11541. leading zeros in integer literals lead to an interpretation as octal
  11542. number. Internally, the value will be stored as decimal number. For
  11543. instance, the C++ integer literal `010` will be serialized to `8`.
  11544. During deserialization, leading zeros yield an error.
  11545. - Not-a-number (NaN) values will be serialized to `null`.
  11546. #### Limits
  11547. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  11548. > An implementation may set limits on the range and precision of numbers.
  11549. When the default type is used, the maximal integer number that can be
  11550. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  11551. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  11552. that are out of range will yield over/underflow when used in a
  11553. constructor. During deserialization, too large or small integer numbers
  11554. will be automatically be stored as @ref number_unsigned_t or @ref
  11555. number_float_t.
  11556. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  11557. > Note that when such software is used, numbers that are integers and are
  11558. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  11559. > that implementations will agree exactly on their numeric values.
  11560. As this range is a subrange of the exactly supported range [INT64_MIN,
  11561. INT64_MAX], this class's integer type is interoperable.
  11562. #### Storage
  11563. Integer number values are stored directly inside a @ref basic_json type.
  11564. @sa @ref number_float_t -- type for number values (floating-point)
  11565. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  11566. @since version 1.0.0
  11567. */
  11568. using number_integer_t = NumberIntegerType;
  11569. /*!
  11570. @brief a type for a number (unsigned)
  11571. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  11572. > The representation of numbers is similar to that used in most
  11573. > programming languages. A number is represented in base 10 using decimal
  11574. > digits. It contains an integer component that may be prefixed with an
  11575. > optional minus sign, which may be followed by a fraction part and/or an
  11576. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  11577. > cannot be represented in the grammar below (such as Infinity and NaN)
  11578. > are not permitted.
  11579. This description includes both integer and floating-point numbers.
  11580. However, C++ allows more precise storage if it is known whether the number
  11581. is a signed integer, an unsigned integer or a floating-point number.
  11582. Therefore, three different types, @ref number_integer_t, @ref
  11583. number_unsigned_t and @ref number_float_t are used.
  11584. To store unsigned integer numbers in C++, a type is defined by the
  11585. template parameter @a NumberUnsignedType which chooses the type to use.
  11586. #### Default type
  11587. With the default values for @a NumberUnsignedType (`uint64_t`), the
  11588. default value for @a number_unsigned_t is:
  11589. @code {.cpp}
  11590. uint64_t
  11591. @endcode
  11592. #### Default behavior
  11593. - The restrictions about leading zeros is not enforced in C++. Instead,
  11594. leading zeros in integer literals lead to an interpretation as octal
  11595. number. Internally, the value will be stored as decimal number. For
  11596. instance, the C++ integer literal `010` will be serialized to `8`.
  11597. During deserialization, leading zeros yield an error.
  11598. - Not-a-number (NaN) values will be serialized to `null`.
  11599. #### Limits
  11600. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  11601. > An implementation may set limits on the range and precision of numbers.
  11602. When the default type is used, the maximal integer number that can be
  11603. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  11604. number that can be stored is `0`. Integer numbers that are out of range
  11605. will yield over/underflow when used in a constructor. During
  11606. deserialization, too large or small integer numbers will be automatically
  11607. be stored as @ref number_integer_t or @ref number_float_t.
  11608. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  11609. > Note that when such software is used, numbers that are integers and are
  11610. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  11611. > that implementations will agree exactly on their numeric values.
  11612. As this range is a subrange (when considered in conjunction with the
  11613. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  11614. this class's integer type is interoperable.
  11615. #### Storage
  11616. Integer number values are stored directly inside a @ref basic_json type.
  11617. @sa @ref number_float_t -- type for number values (floating-point)
  11618. @sa @ref number_integer_t -- type for number values (integer)
  11619. @since version 2.0.0
  11620. */
  11621. using number_unsigned_t = NumberUnsignedType;
  11622. /*!
  11623. @brief a type for a number (floating-point)
  11624. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  11625. > The representation of numbers is similar to that used in most
  11626. > programming languages. A number is represented in base 10 using decimal
  11627. > digits. It contains an integer component that may be prefixed with an
  11628. > optional minus sign, which may be followed by a fraction part and/or an
  11629. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  11630. > cannot be represented in the grammar below (such as Infinity and NaN)
  11631. > are not permitted.
  11632. This description includes both integer and floating-point numbers.
  11633. However, C++ allows more precise storage if it is known whether the number
  11634. is a signed integer, an unsigned integer or a floating-point number.
  11635. Therefore, three different types, @ref number_integer_t, @ref
  11636. number_unsigned_t and @ref number_float_t are used.
  11637. To store floating-point numbers in C++, a type is defined by the template
  11638. parameter @a NumberFloatType which chooses the type to use.
  11639. #### Default type
  11640. With the default values for @a NumberFloatType (`double`), the default
  11641. value for @a number_float_t is:
  11642. @code {.cpp}
  11643. double
  11644. @endcode
  11645. #### Default behavior
  11646. - The restrictions about leading zeros is not enforced in C++. Instead,
  11647. leading zeros in floating-point literals will be ignored. Internally,
  11648. the value will be stored as decimal number. For instance, the C++
  11649. floating-point literal `01.2` will be serialized to `1.2`. During
  11650. deserialization, leading zeros yield an error.
  11651. - Not-a-number (NaN) values will be serialized to `null`.
  11652. #### Limits
  11653. [RFC 7159](http://rfc7159.net/rfc7159) states:
  11654. > This specification allows implementations to set limits on the range and
  11655. > precision of numbers accepted. Since software that implements IEEE
  11656. > 754-2008 binary64 (double precision) numbers is generally available and
  11657. > widely used, good interoperability can be achieved by implementations
  11658. > that expect no more precision or range than these provide, in the sense
  11659. > that implementations will approximate JSON numbers within the expected
  11660. > precision.
  11661. This implementation does exactly follow this approach, as it uses double
  11662. precision floating-point numbers. Note values smaller than
  11663. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  11664. will be stored as NaN internally and be serialized to `null`.
  11665. #### Storage
  11666. Floating-point number values are stored directly inside a @ref basic_json
  11667. type.
  11668. @sa @ref number_integer_t -- type for number values (integer)
  11669. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  11670. @since version 1.0.0
  11671. */
  11672. using number_float_t = NumberFloatType;
  11673. /// @}
  11674. private:
  11675. /// helper for exception-safe object creation
  11676. template<typename T, typename... Args>
  11677. static T* create(Args&& ... args)
  11678. {
  11679. AllocatorType<T> alloc;
  11680. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  11681. auto deleter = [&](T * object)
  11682. {
  11683. AllocatorTraits::deallocate(alloc, object, 1);
  11684. };
  11685. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  11686. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  11687. assert(object != nullptr);
  11688. return object.release();
  11689. }
  11690. ////////////////////////
  11691. // JSON value storage //
  11692. ////////////////////////
  11693. /*!
  11694. @brief a JSON value
  11695. The actual storage for a JSON value of the @ref basic_json class. This
  11696. union combines the different storage types for the JSON value types
  11697. defined in @ref value_t.
  11698. JSON type | value_t type | used type
  11699. --------- | --------------- | ------------------------
  11700. object | object | pointer to @ref object_t
  11701. array | array | pointer to @ref array_t
  11702. string | string | pointer to @ref string_t
  11703. boolean | boolean | @ref boolean_t
  11704. number | number_integer | @ref number_integer_t
  11705. number | number_unsigned | @ref number_unsigned_t
  11706. number | number_float | @ref number_float_t
  11707. null | null | *no value is stored*
  11708. @note Variable-length types (objects, arrays, and strings) are stored as
  11709. pointers. The size of the union should not exceed 64 bits if the default
  11710. value types are used.
  11711. @since version 1.0.0
  11712. */
  11713. union json_value
  11714. {
  11715. /// object (stored with pointer to save storage)
  11716. object_t* object;
  11717. /// array (stored with pointer to save storage)
  11718. array_t* array;
  11719. /// string (stored with pointer to save storage)
  11720. string_t* string;
  11721. /// boolean
  11722. boolean_t boolean;
  11723. /// number (integer)
  11724. number_integer_t number_integer;
  11725. /// number (unsigned integer)
  11726. number_unsigned_t number_unsigned;
  11727. /// number (floating-point)
  11728. number_float_t number_float;
  11729. /// default constructor (for null values)
  11730. json_value() = default;
  11731. /// constructor for booleans
  11732. json_value(boolean_t v) noexcept : boolean(v) {}
  11733. /// constructor for numbers (integer)
  11734. json_value(number_integer_t v) noexcept : number_integer(v) {}
  11735. /// constructor for numbers (unsigned)
  11736. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  11737. /// constructor for numbers (floating-point)
  11738. json_value(number_float_t v) noexcept : number_float(v) {}
  11739. /// constructor for empty values of a given type
  11740. json_value(value_t t)
  11741. {
  11742. switch (t)
  11743. {
  11744. case value_t::object:
  11745. {
  11746. object = create<object_t>();
  11747. break;
  11748. }
  11749. case value_t::array:
  11750. {
  11751. array = create<array_t>();
  11752. break;
  11753. }
  11754. case value_t::string:
  11755. {
  11756. string = create<string_t>("");
  11757. break;
  11758. }
  11759. case value_t::boolean:
  11760. {
  11761. boolean = boolean_t(false);
  11762. break;
  11763. }
  11764. case value_t::number_integer:
  11765. {
  11766. number_integer = number_integer_t(0);
  11767. break;
  11768. }
  11769. case value_t::number_unsigned:
  11770. {
  11771. number_unsigned = number_unsigned_t(0);
  11772. break;
  11773. }
  11774. case value_t::number_float:
  11775. {
  11776. number_float = number_float_t(0.0);
  11777. break;
  11778. }
  11779. case value_t::null:
  11780. {
  11781. object = nullptr; // silence warning, see #821
  11782. break;
  11783. }
  11784. default:
  11785. {
  11786. object = nullptr; // silence warning, see #821
  11787. if (JSON_UNLIKELY(t == value_t::null))
  11788. {
  11789. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.6.1")); // LCOV_EXCL_LINE
  11790. }
  11791. break;
  11792. }
  11793. }
  11794. }
  11795. /// constructor for strings
  11796. json_value(const string_t& value)
  11797. {
  11798. string = create<string_t>(value);
  11799. }
  11800. /// constructor for rvalue strings
  11801. json_value(string_t&& value)
  11802. {
  11803. string = create<string_t>(std::move(value));
  11804. }
  11805. /// constructor for objects
  11806. json_value(const object_t& value)
  11807. {
  11808. object = create<object_t>(value);
  11809. }
  11810. /// constructor for rvalue objects
  11811. json_value(object_t&& value)
  11812. {
  11813. object = create<object_t>(std::move(value));
  11814. }
  11815. /// constructor for arrays
  11816. json_value(const array_t& value)
  11817. {
  11818. array = create<array_t>(value);
  11819. }
  11820. /// constructor for rvalue arrays
  11821. json_value(array_t&& value)
  11822. {
  11823. array = create<array_t>(std::move(value));
  11824. }
  11825. void destroy(value_t t) noexcept
  11826. {
  11827. switch (t)
  11828. {
  11829. case value_t::object:
  11830. {
  11831. AllocatorType<object_t> alloc;
  11832. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  11833. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  11834. break;
  11835. }
  11836. case value_t::array:
  11837. {
  11838. AllocatorType<array_t> alloc;
  11839. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  11840. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  11841. break;
  11842. }
  11843. case value_t::string:
  11844. {
  11845. AllocatorType<string_t> alloc;
  11846. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  11847. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  11848. break;
  11849. }
  11850. default:
  11851. {
  11852. break;
  11853. }
  11854. }
  11855. }
  11856. };
  11857. /*!
  11858. @brief checks the class invariants
  11859. This function asserts the class invariants. It needs to be called at the
  11860. end of every constructor to make sure that created objects respect the
  11861. invariant. Furthermore, it has to be called each time the type of a JSON
  11862. value is changed, because the invariant expresses a relationship between
  11863. @a m_type and @a m_value.
  11864. */
  11865. void assert_invariant() const noexcept
  11866. {
  11867. assert(m_type != value_t::object or m_value.object != nullptr);
  11868. assert(m_type != value_t::array or m_value.array != nullptr);
  11869. assert(m_type != value_t::string or m_value.string != nullptr);
  11870. }
  11871. public:
  11872. //////////////////////////
  11873. // JSON parser callback //
  11874. //////////////////////////
  11875. /*!
  11876. @brief parser event types
  11877. The parser callback distinguishes the following events:
  11878. - `object_start`: the parser read `{` and started to process a JSON object
  11879. - `key`: the parser read a key of a value in an object
  11880. - `object_end`: the parser read `}` and finished processing a JSON object
  11881. - `array_start`: the parser read `[` and started to process a JSON array
  11882. - `array_end`: the parser read `]` and finished processing a JSON array
  11883. - `value`: the parser finished reading a JSON value
  11884. @image html callback_events.png "Example when certain parse events are triggered"
  11885. @sa @ref parser_callback_t for more information and examples
  11886. */
  11887. using parse_event_t = typename parser::parse_event_t;
  11888. /*!
  11889. @brief per-element parser callback type
  11890. With a parser callback function, the result of parsing a JSON text can be
  11891. influenced. When passed to @ref parse, it is called on certain events
  11892. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  11893. depth @a depth and context JSON value @a parsed. The return value of the
  11894. callback function is a boolean indicating whether the element that emitted
  11895. the callback shall be kept or not.
  11896. We distinguish six scenarios (determined by the event type) in which the
  11897. callback function can be called. The following table describes the values
  11898. of the parameters @a depth, @a event, and @a parsed.
  11899. parameter @a event | description | parameter @a depth | parameter @a parsed
  11900. ------------------ | ----------- | ------------------ | -------------------
  11901. 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
  11902. 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
  11903. 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
  11904. 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
  11905. 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
  11906. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  11907. @image html callback_events.png "Example when certain parse events are triggered"
  11908. Discarding a value (i.e., returning `false`) has different effects
  11909. depending on the context in which function was called:
  11910. - Discarded values in structured types are skipped. That is, the parser
  11911. will behave as if the discarded value was never read.
  11912. - In case a value outside a structured type is skipped, it is replaced
  11913. with `null`. This case happens if the top-level element is skipped.
  11914. @param[in] depth the depth of the recursion during parsing
  11915. @param[in] event an event of type parse_event_t indicating the context in
  11916. the callback function has been called
  11917. @param[in,out] parsed the current intermediate parse result; note that
  11918. writing to this value has no effect for parse_event_t::key events
  11919. @return Whether the JSON value which called the function during parsing
  11920. should be kept (`true`) or not (`false`). In the latter case, it is either
  11921. skipped completely or replaced by an empty discarded object.
  11922. @sa @ref parse for examples
  11923. @since version 1.0.0
  11924. */
  11925. using parser_callback_t = typename parser::parser_callback_t;
  11926. //////////////////
  11927. // constructors //
  11928. //////////////////
  11929. /// @name constructors and destructors
  11930. /// Constructors of class @ref basic_json, copy/move constructor, copy
  11931. /// assignment, static functions creating objects, and the destructor.
  11932. /// @{
  11933. /*!
  11934. @brief create an empty value with a given type
  11935. Create an empty JSON value with a given type. The value will be default
  11936. initialized with an empty value which depends on the type:
  11937. Value type | initial value
  11938. ----------- | -------------
  11939. null | `null`
  11940. boolean | `false`
  11941. string | `""`
  11942. number | `0`
  11943. object | `{}`
  11944. array | `[]`
  11945. @param[in] v the type of the value to create
  11946. @complexity Constant.
  11947. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11948. changes to any JSON value.
  11949. @liveexample{The following code shows the constructor for different @ref
  11950. value_t values,basic_json__value_t}
  11951. @sa @ref clear() -- restores the postcondition of this constructor
  11952. @since version 1.0.0
  11953. */
  11954. basic_json(const value_t v)
  11955. : m_type(v), m_value(v)
  11956. {
  11957. assert_invariant();
  11958. }
  11959. /*!
  11960. @brief create a null object
  11961. Create a `null` JSON value. It either takes a null pointer as parameter
  11962. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  11963. The passed null pointer itself is not read -- it is only used to choose
  11964. the right constructor.
  11965. @complexity Constant.
  11966. @exceptionsafety No-throw guarantee: this constructor never throws
  11967. exceptions.
  11968. @liveexample{The following code shows the constructor with and without a
  11969. null pointer parameter.,basic_json__nullptr_t}
  11970. @since version 1.0.0
  11971. */
  11972. basic_json(std::nullptr_t = nullptr) noexcept
  11973. : basic_json(value_t::null)
  11974. {
  11975. assert_invariant();
  11976. }
  11977. /*!
  11978. @brief create a JSON value
  11979. This is a "catch all" constructor for all compatible JSON types; that is,
  11980. types for which a `to_json()` method exists. The constructor forwards the
  11981. parameter @a val to that method (to `json_serializer<U>::to_json` method
  11982. with `U = uncvref_t<CompatibleType>`, to be exact).
  11983. Template type @a CompatibleType includes, but is not limited to, the
  11984. following types:
  11985. - **arrays**: @ref array_t and all kinds of compatible containers such as
  11986. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  11987. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  11988. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  11989. which a @ref basic_json value can be constructed.
  11990. - **objects**: @ref object_t and all kinds of compatible associative
  11991. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  11992. and `std::unordered_multimap` with a `key_type` compatible to
  11993. @ref string_t and a `value_type` from which a @ref basic_json value can
  11994. be constructed.
  11995. - **strings**: @ref string_t, string literals, and all compatible string
  11996. containers can be used.
  11997. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  11998. @ref number_float_t, and all convertible number types such as `int`,
  11999. `size_t`, `int64_t`, `float` or `double` can be used.
  12000. - **boolean**: @ref boolean_t / `bool` can be used.
  12001. See the examples below.
  12002. @tparam CompatibleType a type such that:
  12003. - @a CompatibleType is not derived from `std::istream`,
  12004. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  12005. constructors),
  12006. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  12007. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  12008. @ref json_pointer, @ref iterator, etc ...)
  12009. - @ref @ref json_serializer<U> has a
  12010. `to_json(basic_json_t&, CompatibleType&&)` method
  12011. @tparam U = `uncvref_t<CompatibleType>`
  12012. @param[in] val the value to be forwarded to the respective constructor
  12013. @complexity Usually linear in the size of the passed @a val, also
  12014. depending on the implementation of the called `to_json()`
  12015. method.
  12016. @exceptionsafety Depends on the called constructor. For types directly
  12017. supported by the library (i.e., all types for which no `to_json()` function
  12018. was provided), strong guarantee holds: if an exception is thrown, there are
  12019. no changes to any JSON value.
  12020. @liveexample{The following code shows the constructor with several
  12021. compatible types.,basic_json__CompatibleType}
  12022. @since version 2.1.0
  12023. */
  12024. template <typename CompatibleType,
  12025. typename U = detail::uncvref_t<CompatibleType>,
  12026. detail::enable_if_t<
  12027. not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  12028. basic_json(CompatibleType && val) noexcept(noexcept(
  12029. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  12030. std::forward<CompatibleType>(val))))
  12031. {
  12032. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  12033. assert_invariant();
  12034. }
  12035. /*!
  12036. @brief create a JSON value from an existing one
  12037. This is a constructor for existing @ref basic_json types.
  12038. It does not hijack copy/move constructors, since the parameter has different
  12039. template arguments than the current ones.
  12040. The constructor tries to convert the internal @ref m_value of the parameter.
  12041. @tparam BasicJsonType a type such that:
  12042. - @a BasicJsonType is a @ref basic_json type.
  12043. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  12044. @param[in] val the @ref basic_json value to be converted.
  12045. @complexity Usually linear in the size of the passed @a val, also
  12046. depending on the implementation of the called `to_json()`
  12047. method.
  12048. @exceptionsafety Depends on the called constructor. For types directly
  12049. supported by the library (i.e., all types for which no `to_json()` function
  12050. was provided), strong guarantee holds: if an exception is thrown, there are
  12051. no changes to any JSON value.
  12052. @since version 3.2.0
  12053. */
  12054. template <typename BasicJsonType,
  12055. detail::enable_if_t<
  12056. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  12057. basic_json(const BasicJsonType& val)
  12058. {
  12059. using other_boolean_t = typename BasicJsonType::boolean_t;
  12060. using other_number_float_t = typename BasicJsonType::number_float_t;
  12061. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  12062. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  12063. using other_string_t = typename BasicJsonType::string_t;
  12064. using other_object_t = typename BasicJsonType::object_t;
  12065. using other_array_t = typename BasicJsonType::array_t;
  12066. switch (val.type())
  12067. {
  12068. case value_t::boolean:
  12069. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  12070. break;
  12071. case value_t::number_float:
  12072. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  12073. break;
  12074. case value_t::number_integer:
  12075. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  12076. break;
  12077. case value_t::number_unsigned:
  12078. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  12079. break;
  12080. case value_t::string:
  12081. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  12082. break;
  12083. case value_t::object:
  12084. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  12085. break;
  12086. case value_t::array:
  12087. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  12088. break;
  12089. case value_t::null:
  12090. *this = nullptr;
  12091. break;
  12092. case value_t::discarded:
  12093. m_type = value_t::discarded;
  12094. break;
  12095. default: // LCOV_EXCL_LINE
  12096. assert(false); // LCOV_EXCL_LINE
  12097. }
  12098. assert_invariant();
  12099. }
  12100. /*!
  12101. @brief create a container (array or object) from an initializer list
  12102. Creates a JSON value of type array or object from the passed initializer
  12103. list @a init. In case @a type_deduction is `true` (default), the type of
  12104. the JSON value to be created is deducted from the initializer list @a init
  12105. according to the following rules:
  12106. 1. If the list is empty, an empty JSON object value `{}` is created.
  12107. 2. If the list consists of pairs whose first element is a string, a JSON
  12108. object value is created where the first elements of the pairs are
  12109. treated as keys and the second elements are as values.
  12110. 3. In all other cases, an array is created.
  12111. The rules aim to create the best fit between a C++ initializer list and
  12112. JSON values. The rationale is as follows:
  12113. 1. The empty initializer list is written as `{}` which is exactly an empty
  12114. JSON object.
  12115. 2. C++ has no way of describing mapped types other than to list a list of
  12116. pairs. As JSON requires that keys must be of type string, rule 2 is the
  12117. weakest constraint one can pose on initializer lists to interpret them
  12118. as an object.
  12119. 3. In all other cases, the initializer list could not be interpreted as
  12120. JSON object type, so interpreting it as JSON array type is safe.
  12121. With the rules described above, the following JSON values cannot be
  12122. expressed by an initializer list:
  12123. - the empty array (`[]`): use @ref array(initializer_list_t)
  12124. with an empty initializer list in this case
  12125. - arrays whose elements satisfy rule 2: use @ref
  12126. array(initializer_list_t) with the same initializer list
  12127. in this case
  12128. @note When used without parentheses around an empty initializer list, @ref
  12129. basic_json() is called instead of this function, yielding the JSON null
  12130. value.
  12131. @param[in] init initializer list with JSON values
  12132. @param[in] type_deduction internal parameter; when set to `true`, the type
  12133. of the JSON value is deducted from the initializer list @a init; when set
  12134. to `false`, the type provided via @a manual_type is forced. This mode is
  12135. used by the functions @ref array(initializer_list_t) and
  12136. @ref object(initializer_list_t).
  12137. @param[in] manual_type internal parameter; when @a type_deduction is set
  12138. to `false`, the created JSON value will use the provided type (only @ref
  12139. value_t::array and @ref value_t::object are valid); when @a type_deduction
  12140. is set to `true`, this parameter has no effect
  12141. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  12142. `value_t::object`, but @a init contains an element which is not a pair
  12143. whose first element is a string. In this case, the constructor could not
  12144. create an object. If @a type_deduction would have be `true`, an array
  12145. would have been created. See @ref object(initializer_list_t)
  12146. for an example.
  12147. @complexity Linear in the size of the initializer list @a init.
  12148. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12149. changes to any JSON value.
  12150. @liveexample{The example below shows how JSON values are created from
  12151. initializer lists.,basic_json__list_init_t}
  12152. @sa @ref array(initializer_list_t) -- create a JSON array
  12153. value from an initializer list
  12154. @sa @ref object(initializer_list_t) -- create a JSON object
  12155. value from an initializer list
  12156. @since version 1.0.0
  12157. */
  12158. basic_json(initializer_list_t init,
  12159. bool type_deduction = true,
  12160. value_t manual_type = value_t::array)
  12161. {
  12162. // check if each element is an array with two elements whose first
  12163. // element is a string
  12164. bool is_an_object = std::all_of(init.begin(), init.end(),
  12165. [](const detail::json_ref<basic_json>& element_ref)
  12166. {
  12167. return element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string();
  12168. });
  12169. // adjust type if type deduction is not wanted
  12170. if (not type_deduction)
  12171. {
  12172. // if array is wanted, do not create an object though possible
  12173. if (manual_type == value_t::array)
  12174. {
  12175. is_an_object = false;
  12176. }
  12177. // if object is wanted but impossible, throw an exception
  12178. if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object))
  12179. {
  12180. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  12181. }
  12182. }
  12183. if (is_an_object)
  12184. {
  12185. // the initializer list is a list of pairs -> create object
  12186. m_type = value_t::object;
  12187. m_value = value_t::object;
  12188. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  12189. {
  12190. auto element = element_ref.moved_or_copied();
  12191. m_value.object->emplace(
  12192. std::move(*((*element.m_value.array)[0].m_value.string)),
  12193. std::move((*element.m_value.array)[1]));
  12194. });
  12195. }
  12196. else
  12197. {
  12198. // the initializer list describes an array -> create array
  12199. m_type = value_t::array;
  12200. m_value.array = create<array_t>(init.begin(), init.end());
  12201. }
  12202. assert_invariant();
  12203. }
  12204. /*!
  12205. @brief explicitly create an array from an initializer list
  12206. Creates a JSON array value from a given initializer list. That is, given a
  12207. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  12208. initializer list is empty, the empty array `[]` is created.
  12209. @note This function is only needed to express two edge cases that cannot
  12210. be realized with the initializer list constructor (@ref
  12211. basic_json(initializer_list_t, bool, value_t)). These cases
  12212. are:
  12213. 1. creating an array whose elements are all pairs whose first element is a
  12214. string -- in this case, the initializer list constructor would create an
  12215. object, taking the first elements as keys
  12216. 2. creating an empty array -- passing the empty initializer list to the
  12217. initializer list constructor yields an empty object
  12218. @param[in] init initializer list with JSON values to create an array from
  12219. (optional)
  12220. @return JSON array value
  12221. @complexity Linear in the size of @a init.
  12222. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12223. changes to any JSON value.
  12224. @liveexample{The following code shows an example for the `array`
  12225. function.,array}
  12226. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  12227. create a JSON value from an initializer list
  12228. @sa @ref object(initializer_list_t) -- create a JSON object
  12229. value from an initializer list
  12230. @since version 1.0.0
  12231. */
  12232. JSON_NODISCARD
  12233. static basic_json array(initializer_list_t init = {})
  12234. {
  12235. return basic_json(init, false, value_t::array);
  12236. }
  12237. /*!
  12238. @brief explicitly create an object from an initializer list
  12239. Creates a JSON object value from a given initializer list. The initializer
  12240. lists elements must be pairs, and their first elements must be strings. If
  12241. the initializer list is empty, the empty object `{}` is created.
  12242. @note This function is only added for symmetry reasons. In contrast to the
  12243. related function @ref array(initializer_list_t), there are
  12244. no cases which can only be expressed by this function. That is, any
  12245. initializer list @a init can also be passed to the initializer list
  12246. constructor @ref basic_json(initializer_list_t, bool, value_t).
  12247. @param[in] init initializer list to create an object from (optional)
  12248. @return JSON object value
  12249. @throw type_error.301 if @a init is not a list of pairs whose first
  12250. elements are strings. In this case, no object can be created. When such a
  12251. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  12252. an array would have been created from the passed initializer list @a init.
  12253. See example below.
  12254. @complexity Linear in the size of @a init.
  12255. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12256. changes to any JSON value.
  12257. @liveexample{The following code shows an example for the `object`
  12258. function.,object}
  12259. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  12260. create a JSON value from an initializer list
  12261. @sa @ref array(initializer_list_t) -- create a JSON array
  12262. value from an initializer list
  12263. @since version 1.0.0
  12264. */
  12265. JSON_NODISCARD
  12266. static basic_json object(initializer_list_t init = {})
  12267. {
  12268. return basic_json(init, false, value_t::object);
  12269. }
  12270. /*!
  12271. @brief construct an array with count copies of given value
  12272. Constructs a JSON array value by creating @a cnt copies of a passed value.
  12273. In case @a cnt is `0`, an empty array is created.
  12274. @param[in] cnt the number of JSON copies of @a val to create
  12275. @param[in] val the JSON value to copy
  12276. @post `std::distance(begin(),end()) == cnt` holds.
  12277. @complexity Linear in @a cnt.
  12278. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12279. changes to any JSON value.
  12280. @liveexample{The following code shows examples for the @ref
  12281. basic_json(size_type\, const basic_json&)
  12282. constructor.,basic_json__size_type_basic_json}
  12283. @since version 1.0.0
  12284. */
  12285. basic_json(size_type cnt, const basic_json& val)
  12286. : m_type(value_t::array)
  12287. {
  12288. m_value.array = create<array_t>(cnt, val);
  12289. assert_invariant();
  12290. }
  12291. /*!
  12292. @brief construct a JSON container given an iterator range
  12293. Constructs the JSON value with the contents of the range `[first, last)`.
  12294. The semantics depends on the different types a JSON value can have:
  12295. - In case of a null type, invalid_iterator.206 is thrown.
  12296. - In case of other primitive types (number, boolean, or string), @a first
  12297. must be `begin()` and @a last must be `end()`. In this case, the value is
  12298. copied. Otherwise, invalid_iterator.204 is thrown.
  12299. - In case of structured types (array, object), the constructor behaves as
  12300. similar versions for `std::vector` or `std::map`; that is, a JSON array
  12301. or object is constructed from the values in the range.
  12302. @tparam InputIT an input iterator type (@ref iterator or @ref
  12303. const_iterator)
  12304. @param[in] first begin of the range to copy from (included)
  12305. @param[in] last end of the range to copy from (excluded)
  12306. @pre Iterators @a first and @a last must be initialized. **This
  12307. precondition is enforced with an assertion (see warning).** If
  12308. assertions are switched off, a violation of this precondition yields
  12309. undefined behavior.
  12310. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  12311. checked efficiently. Only certain edge cases are detected; see the
  12312. description of the exceptions below. A violation of this precondition
  12313. yields undefined behavior.
  12314. @warning A precondition is enforced with a runtime assertion that will
  12315. result in calling `std::abort` if this precondition is not met.
  12316. Assertions can be disabled by defining `NDEBUG` at compile time.
  12317. See https://en.cppreference.com/w/cpp/error/assert for more
  12318. information.
  12319. @throw invalid_iterator.201 if iterators @a first and @a last are not
  12320. compatible (i.e., do not belong to the same JSON value). In this case,
  12321. the range `[first, last)` is undefined.
  12322. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  12323. primitive type (number, boolean, or string), but @a first does not point
  12324. to the first element any more. In this case, the range `[first, last)` is
  12325. undefined. See example code below.
  12326. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  12327. null value. In this case, the range `[first, last)` is undefined.
  12328. @complexity Linear in distance between @a first and @a last.
  12329. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12330. changes to any JSON value.
  12331. @liveexample{The example below shows several ways to create JSON values by
  12332. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  12333. @since version 1.0.0
  12334. */
  12335. template<class InputIT, typename std::enable_if<
  12336. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  12337. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  12338. basic_json(InputIT first, InputIT last)
  12339. {
  12340. assert(first.m_object != nullptr);
  12341. assert(last.m_object != nullptr);
  12342. // make sure iterator fits the current value
  12343. if (JSON_UNLIKELY(first.m_object != last.m_object))
  12344. {
  12345. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  12346. }
  12347. // copy type from first iterator
  12348. m_type = first.m_object->m_type;
  12349. // check if iterator range is complete for primitive values
  12350. switch (m_type)
  12351. {
  12352. case value_t::boolean:
  12353. case value_t::number_float:
  12354. case value_t::number_integer:
  12355. case value_t::number_unsigned:
  12356. case value_t::string:
  12357. {
  12358. if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  12359. or not last.m_it.primitive_iterator.is_end()))
  12360. {
  12361. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  12362. }
  12363. break;
  12364. }
  12365. default:
  12366. break;
  12367. }
  12368. switch (m_type)
  12369. {
  12370. case value_t::number_integer:
  12371. {
  12372. m_value.number_integer = first.m_object->m_value.number_integer;
  12373. break;
  12374. }
  12375. case value_t::number_unsigned:
  12376. {
  12377. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  12378. break;
  12379. }
  12380. case value_t::number_float:
  12381. {
  12382. m_value.number_float = first.m_object->m_value.number_float;
  12383. break;
  12384. }
  12385. case value_t::boolean:
  12386. {
  12387. m_value.boolean = first.m_object->m_value.boolean;
  12388. break;
  12389. }
  12390. case value_t::string:
  12391. {
  12392. m_value = *first.m_object->m_value.string;
  12393. break;
  12394. }
  12395. case value_t::object:
  12396. {
  12397. m_value.object = create<object_t>(first.m_it.object_iterator,
  12398. last.m_it.object_iterator);
  12399. break;
  12400. }
  12401. case value_t::array:
  12402. {
  12403. m_value.array = create<array_t>(first.m_it.array_iterator,
  12404. last.m_it.array_iterator);
  12405. break;
  12406. }
  12407. default:
  12408. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  12409. std::string(first.m_object->type_name())));
  12410. }
  12411. assert_invariant();
  12412. }
  12413. ///////////////////////////////////////
  12414. // other constructors and destructor //
  12415. ///////////////////////////////////////
  12416. /// @private
  12417. basic_json(const detail::json_ref<basic_json>& ref)
  12418. : basic_json(ref.moved_or_copied())
  12419. {}
  12420. /*!
  12421. @brief copy constructor
  12422. Creates a copy of a given JSON value.
  12423. @param[in] other the JSON value to copy
  12424. @post `*this == other`
  12425. @complexity Linear in the size of @a other.
  12426. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12427. changes to any JSON value.
  12428. @requirement This function helps `basic_json` satisfying the
  12429. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12430. requirements:
  12431. - The complexity is linear.
  12432. - As postcondition, it holds: `other == basic_json(other)`.
  12433. @liveexample{The following code shows an example for the copy
  12434. constructor.,basic_json__basic_json}
  12435. @since version 1.0.0
  12436. */
  12437. basic_json(const basic_json& other)
  12438. : m_type(other.m_type)
  12439. {
  12440. // check of passed value is valid
  12441. other.assert_invariant();
  12442. switch (m_type)
  12443. {
  12444. case value_t::object:
  12445. {
  12446. m_value = *other.m_value.object;
  12447. break;
  12448. }
  12449. case value_t::array:
  12450. {
  12451. m_value = *other.m_value.array;
  12452. break;
  12453. }
  12454. case value_t::string:
  12455. {
  12456. m_value = *other.m_value.string;
  12457. break;
  12458. }
  12459. case value_t::boolean:
  12460. {
  12461. m_value = other.m_value.boolean;
  12462. break;
  12463. }
  12464. case value_t::number_integer:
  12465. {
  12466. m_value = other.m_value.number_integer;
  12467. break;
  12468. }
  12469. case value_t::number_unsigned:
  12470. {
  12471. m_value = other.m_value.number_unsigned;
  12472. break;
  12473. }
  12474. case value_t::number_float:
  12475. {
  12476. m_value = other.m_value.number_float;
  12477. break;
  12478. }
  12479. default:
  12480. break;
  12481. }
  12482. assert_invariant();
  12483. }
  12484. /*!
  12485. @brief move constructor
  12486. Move constructor. Constructs a JSON value with the contents of the given
  12487. value @a other using move semantics. It "steals" the resources from @a
  12488. other and leaves it as JSON null value.
  12489. @param[in,out] other value to move to this object
  12490. @post `*this` has the same value as @a other before the call.
  12491. @post @a other is a JSON null value.
  12492. @complexity Constant.
  12493. @exceptionsafety No-throw guarantee: this constructor never throws
  12494. exceptions.
  12495. @requirement This function helps `basic_json` satisfying the
  12496. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  12497. requirements.
  12498. @liveexample{The code below shows the move constructor explicitly called
  12499. via std::move.,basic_json__moveconstructor}
  12500. @since version 1.0.0
  12501. */
  12502. basic_json(basic_json&& other) noexcept
  12503. : m_type(std::move(other.m_type)),
  12504. m_value(std::move(other.m_value))
  12505. {
  12506. // check that passed value is valid
  12507. other.assert_invariant();
  12508. // invalidate payload
  12509. other.m_type = value_t::null;
  12510. other.m_value = {};
  12511. assert_invariant();
  12512. }
  12513. /*!
  12514. @brief copy assignment
  12515. Copy assignment operator. Copies a JSON value via the "copy and swap"
  12516. strategy: It is expressed in terms of the copy constructor, destructor,
  12517. and the `swap()` member function.
  12518. @param[in] other value to copy from
  12519. @complexity Linear.
  12520. @requirement This function helps `basic_json` satisfying the
  12521. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12522. requirements:
  12523. - The complexity is linear.
  12524. @liveexample{The code below shows and example for the copy assignment. It
  12525. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  12526. copy of `a` (which is the null value after the swap) is
  12527. destroyed.,basic_json__copyassignment}
  12528. @since version 1.0.0
  12529. */
  12530. basic_json& operator=(basic_json other) noexcept (
  12531. std::is_nothrow_move_constructible<value_t>::value and
  12532. std::is_nothrow_move_assignable<value_t>::value and
  12533. std::is_nothrow_move_constructible<json_value>::value and
  12534. std::is_nothrow_move_assignable<json_value>::value
  12535. )
  12536. {
  12537. // check that passed value is valid
  12538. other.assert_invariant();
  12539. using std::swap;
  12540. swap(m_type, other.m_type);
  12541. swap(m_value, other.m_value);
  12542. assert_invariant();
  12543. return *this;
  12544. }
  12545. /*!
  12546. @brief destructor
  12547. Destroys the JSON value and frees all allocated memory.
  12548. @complexity Linear.
  12549. @requirement This function helps `basic_json` satisfying the
  12550. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12551. requirements:
  12552. - The complexity is linear.
  12553. - All stored elements are destroyed and all memory is freed.
  12554. @since version 1.0.0
  12555. */
  12556. ~basic_json() noexcept
  12557. {
  12558. assert_invariant();
  12559. m_value.destroy(m_type);
  12560. }
  12561. /// @}
  12562. public:
  12563. ///////////////////////
  12564. // object inspection //
  12565. ///////////////////////
  12566. /// @name object inspection
  12567. /// Functions to inspect the type of a JSON value.
  12568. /// @{
  12569. /*!
  12570. @brief serialization
  12571. Serialization function for JSON values. The function tries to mimic
  12572. Python's `json.dumps()` function, and currently supports its @a indent
  12573. and @a ensure_ascii parameters.
  12574. @param[in] indent If indent is nonnegative, then array elements and object
  12575. members will be pretty-printed with that indent level. An indent level of
  12576. `0` will only insert newlines. `-1` (the default) selects the most compact
  12577. representation.
  12578. @param[in] indent_char The character to use for indentation if @a indent is
  12579. greater than `0`. The default is ` ` (space).
  12580. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  12581. in the output are escaped with `\uXXXX` sequences, and the result consists
  12582. of ASCII characters only.
  12583. @param[in] error_handler how to react on decoding errors; there are three
  12584. possible values: `strict` (throws and exception in case a decoding error
  12585. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  12586. and `ignore` (ignore invalid UTF-8 sequences during serialization).
  12587. @return string containing the serialization of the JSON value
  12588. @throw type_error.316 if a string stored inside the JSON value is not
  12589. UTF-8 encoded
  12590. @complexity Linear.
  12591. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12592. changes in the JSON value.
  12593. @liveexample{The following example shows the effect of different @a indent\,
  12594. @a indent_char\, and @a ensure_ascii parameters to the result of the
  12595. serialization.,dump}
  12596. @see https://docs.python.org/2/library/json.html#json.dump
  12597. @since version 1.0.0; indentation character @a indent_char, option
  12598. @a ensure_ascii and exceptions added in version 3.0.0; error
  12599. handlers added in version 3.4.0.
  12600. */
  12601. string_t dump(const int indent = -1,
  12602. const char indent_char = ' ',
  12603. const bool ensure_ascii = false,
  12604. const error_handler_t error_handler = error_handler_t::strict) const
  12605. {
  12606. string_t result;
  12607. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  12608. if (indent >= 0)
  12609. {
  12610. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  12611. }
  12612. else
  12613. {
  12614. s.dump(*this, false, ensure_ascii, 0);
  12615. }
  12616. return result;
  12617. }
  12618. /*!
  12619. @brief return the type of the JSON value (explicit)
  12620. Return the type of the JSON value as a value from the @ref value_t
  12621. enumeration.
  12622. @return the type of the JSON value
  12623. Value type | return value
  12624. ------------------------- | -------------------------
  12625. null | value_t::null
  12626. boolean | value_t::boolean
  12627. string | value_t::string
  12628. number (integer) | value_t::number_integer
  12629. number (unsigned integer) | value_t::number_unsigned
  12630. number (floating-point) | value_t::number_float
  12631. object | value_t::object
  12632. array | value_t::array
  12633. discarded | value_t::discarded
  12634. @complexity Constant.
  12635. @exceptionsafety No-throw guarantee: this member function never throws
  12636. exceptions.
  12637. @liveexample{The following code exemplifies `type()` for all JSON
  12638. types.,type}
  12639. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  12640. @sa @ref type_name() -- return the type as string
  12641. @since version 1.0.0
  12642. */
  12643. constexpr value_t type() const noexcept
  12644. {
  12645. return m_type;
  12646. }
  12647. /*!
  12648. @brief return whether type is primitive
  12649. This function returns true if and only if the JSON type is primitive
  12650. (string, number, boolean, or null).
  12651. @return `true` if type is primitive (string, number, boolean, or null),
  12652. `false` otherwise.
  12653. @complexity Constant.
  12654. @exceptionsafety No-throw guarantee: this member function never throws
  12655. exceptions.
  12656. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  12657. types.,is_primitive}
  12658. @sa @ref is_structured() -- returns whether JSON value is structured
  12659. @sa @ref is_null() -- returns whether JSON value is `null`
  12660. @sa @ref is_string() -- returns whether JSON value is a string
  12661. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  12662. @sa @ref is_number() -- returns whether JSON value is a number
  12663. @since version 1.0.0
  12664. */
  12665. constexpr bool is_primitive() const noexcept
  12666. {
  12667. return is_null() or is_string() or is_boolean() or is_number();
  12668. }
  12669. /*!
  12670. @brief return whether type is structured
  12671. This function returns true if and only if the JSON type is structured
  12672. (array or object).
  12673. @return `true` if type is structured (array or object), `false` otherwise.
  12674. @complexity Constant.
  12675. @exceptionsafety No-throw guarantee: this member function never throws
  12676. exceptions.
  12677. @liveexample{The following code exemplifies `is_structured()` for all JSON
  12678. types.,is_structured}
  12679. @sa @ref is_primitive() -- returns whether value is primitive
  12680. @sa @ref is_array() -- returns whether value is an array
  12681. @sa @ref is_object() -- returns whether value is an object
  12682. @since version 1.0.0
  12683. */
  12684. constexpr bool is_structured() const noexcept
  12685. {
  12686. return is_array() or is_object();
  12687. }
  12688. /*!
  12689. @brief return whether value is null
  12690. This function returns true if and only if the JSON value is null.
  12691. @return `true` if type is null, `false` otherwise.
  12692. @complexity Constant.
  12693. @exceptionsafety No-throw guarantee: this member function never throws
  12694. exceptions.
  12695. @liveexample{The following code exemplifies `is_null()` for all JSON
  12696. types.,is_null}
  12697. @since version 1.0.0
  12698. */
  12699. constexpr bool is_null() const noexcept
  12700. {
  12701. return m_type == value_t::null;
  12702. }
  12703. /*!
  12704. @brief return whether value is a boolean
  12705. This function returns true if and only if the JSON value is a boolean.
  12706. @return `true` if type is boolean, `false` otherwise.
  12707. @complexity Constant.
  12708. @exceptionsafety No-throw guarantee: this member function never throws
  12709. exceptions.
  12710. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  12711. types.,is_boolean}
  12712. @since version 1.0.0
  12713. */
  12714. constexpr bool is_boolean() const noexcept
  12715. {
  12716. return m_type == value_t::boolean;
  12717. }
  12718. /*!
  12719. @brief return whether value is a number
  12720. This function returns true if and only if the JSON value is a number. This
  12721. includes both integer (signed and unsigned) and floating-point values.
  12722. @return `true` if type is number (regardless whether integer, unsigned
  12723. integer or floating-type), `false` otherwise.
  12724. @complexity Constant.
  12725. @exceptionsafety No-throw guarantee: this member function never throws
  12726. exceptions.
  12727. @liveexample{The following code exemplifies `is_number()` for all JSON
  12728. types.,is_number}
  12729. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  12730. integer number
  12731. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  12732. number
  12733. @sa @ref is_number_float() -- check if value is a floating-point number
  12734. @since version 1.0.0
  12735. */
  12736. constexpr bool is_number() const noexcept
  12737. {
  12738. return is_number_integer() or is_number_float();
  12739. }
  12740. /*!
  12741. @brief return whether value is an integer number
  12742. This function returns true if and only if the JSON value is a signed or
  12743. unsigned integer number. This excludes floating-point values.
  12744. @return `true` if type is an integer or unsigned integer number, `false`
  12745. otherwise.
  12746. @complexity Constant.
  12747. @exceptionsafety No-throw guarantee: this member function never throws
  12748. exceptions.
  12749. @liveexample{The following code exemplifies `is_number_integer()` for all
  12750. JSON types.,is_number_integer}
  12751. @sa @ref is_number() -- check if value is a number
  12752. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  12753. number
  12754. @sa @ref is_number_float() -- check if value is a floating-point number
  12755. @since version 1.0.0
  12756. */
  12757. constexpr bool is_number_integer() const noexcept
  12758. {
  12759. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  12760. }
  12761. /*!
  12762. @brief return whether value is an unsigned integer number
  12763. This function returns true if and only if the JSON value is an unsigned
  12764. integer number. This excludes floating-point and signed integer values.
  12765. @return `true` if type is an unsigned integer number, `false` otherwise.
  12766. @complexity Constant.
  12767. @exceptionsafety No-throw guarantee: this member function never throws
  12768. exceptions.
  12769. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  12770. JSON types.,is_number_unsigned}
  12771. @sa @ref is_number() -- check if value is a number
  12772. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  12773. integer number
  12774. @sa @ref is_number_float() -- check if value is a floating-point number
  12775. @since version 2.0.0
  12776. */
  12777. constexpr bool is_number_unsigned() const noexcept
  12778. {
  12779. return m_type == value_t::number_unsigned;
  12780. }
  12781. /*!
  12782. @brief return whether value is a floating-point number
  12783. This function returns true if and only if the JSON value is a
  12784. floating-point number. This excludes signed and unsigned integer values.
  12785. @return `true` if type is a floating-point number, `false` otherwise.
  12786. @complexity Constant.
  12787. @exceptionsafety No-throw guarantee: this member function never throws
  12788. exceptions.
  12789. @liveexample{The following code exemplifies `is_number_float()` for all
  12790. JSON types.,is_number_float}
  12791. @sa @ref is_number() -- check if value is number
  12792. @sa @ref is_number_integer() -- check if value is an integer number
  12793. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  12794. number
  12795. @since version 1.0.0
  12796. */
  12797. constexpr bool is_number_float() const noexcept
  12798. {
  12799. return m_type == value_t::number_float;
  12800. }
  12801. /*!
  12802. @brief return whether value is an object
  12803. This function returns true if and only if the JSON value is an object.
  12804. @return `true` if type is object, `false` otherwise.
  12805. @complexity Constant.
  12806. @exceptionsafety No-throw guarantee: this member function never throws
  12807. exceptions.
  12808. @liveexample{The following code exemplifies `is_object()` for all JSON
  12809. types.,is_object}
  12810. @since version 1.0.0
  12811. */
  12812. constexpr bool is_object() const noexcept
  12813. {
  12814. return m_type == value_t::object;
  12815. }
  12816. /*!
  12817. @brief return whether value is an array
  12818. This function returns true if and only if the JSON value is an array.
  12819. @return `true` if type is array, `false` otherwise.
  12820. @complexity Constant.
  12821. @exceptionsafety No-throw guarantee: this member function never throws
  12822. exceptions.
  12823. @liveexample{The following code exemplifies `is_array()` for all JSON
  12824. types.,is_array}
  12825. @since version 1.0.0
  12826. */
  12827. constexpr bool is_array() const noexcept
  12828. {
  12829. return m_type == value_t::array;
  12830. }
  12831. /*!
  12832. @brief return whether value is a string
  12833. This function returns true if and only if the JSON value is a string.
  12834. @return `true` if type is string, `false` otherwise.
  12835. @complexity Constant.
  12836. @exceptionsafety No-throw guarantee: this member function never throws
  12837. exceptions.
  12838. @liveexample{The following code exemplifies `is_string()` for all JSON
  12839. types.,is_string}
  12840. @since version 1.0.0
  12841. */
  12842. constexpr bool is_string() const noexcept
  12843. {
  12844. return m_type == value_t::string;
  12845. }
  12846. /*!
  12847. @brief return whether value is discarded
  12848. This function returns true if and only if the JSON value was discarded
  12849. during parsing with a callback function (see @ref parser_callback_t).
  12850. @note This function will always be `false` for JSON values after parsing.
  12851. That is, discarded values can only occur during parsing, but will be
  12852. removed when inside a structured value or replaced by null in other cases.
  12853. @return `true` if type is discarded, `false` otherwise.
  12854. @complexity Constant.
  12855. @exceptionsafety No-throw guarantee: this member function never throws
  12856. exceptions.
  12857. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  12858. types.,is_discarded}
  12859. @since version 1.0.0
  12860. */
  12861. constexpr bool is_discarded() const noexcept
  12862. {
  12863. return m_type == value_t::discarded;
  12864. }
  12865. /*!
  12866. @brief return the type of the JSON value (implicit)
  12867. Implicitly return the type of the JSON value as a value from the @ref
  12868. value_t enumeration.
  12869. @return the type of the JSON value
  12870. @complexity Constant.
  12871. @exceptionsafety No-throw guarantee: this member function never throws
  12872. exceptions.
  12873. @liveexample{The following code exemplifies the @ref value_t operator for
  12874. all JSON types.,operator__value_t}
  12875. @sa @ref type() -- return the type of the JSON value (explicit)
  12876. @sa @ref type_name() -- return the type as string
  12877. @since version 1.0.0
  12878. */
  12879. constexpr operator value_t() const noexcept
  12880. {
  12881. return m_type;
  12882. }
  12883. /// @}
  12884. private:
  12885. //////////////////
  12886. // value access //
  12887. //////////////////
  12888. /// get a boolean (explicit)
  12889. boolean_t get_impl(boolean_t* /*unused*/) const
  12890. {
  12891. if (JSON_LIKELY(is_boolean()))
  12892. {
  12893. return m_value.boolean;
  12894. }
  12895. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  12896. }
  12897. /// get a pointer to the value (object)
  12898. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  12899. {
  12900. return is_object() ? m_value.object : nullptr;
  12901. }
  12902. /// get a pointer to the value (object)
  12903. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  12904. {
  12905. return is_object() ? m_value.object : nullptr;
  12906. }
  12907. /// get a pointer to the value (array)
  12908. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  12909. {
  12910. return is_array() ? m_value.array : nullptr;
  12911. }
  12912. /// get a pointer to the value (array)
  12913. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  12914. {
  12915. return is_array() ? m_value.array : nullptr;
  12916. }
  12917. /// get a pointer to the value (string)
  12918. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  12919. {
  12920. return is_string() ? m_value.string : nullptr;
  12921. }
  12922. /// get a pointer to the value (string)
  12923. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  12924. {
  12925. return is_string() ? m_value.string : nullptr;
  12926. }
  12927. /// get a pointer to the value (boolean)
  12928. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  12929. {
  12930. return is_boolean() ? &m_value.boolean : nullptr;
  12931. }
  12932. /// get a pointer to the value (boolean)
  12933. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  12934. {
  12935. return is_boolean() ? &m_value.boolean : nullptr;
  12936. }
  12937. /// get a pointer to the value (integer number)
  12938. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  12939. {
  12940. return is_number_integer() ? &m_value.number_integer : nullptr;
  12941. }
  12942. /// get a pointer to the value (integer number)
  12943. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  12944. {
  12945. return is_number_integer() ? &m_value.number_integer : nullptr;
  12946. }
  12947. /// get a pointer to the value (unsigned number)
  12948. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  12949. {
  12950. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  12951. }
  12952. /// get a pointer to the value (unsigned number)
  12953. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  12954. {
  12955. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  12956. }
  12957. /// get a pointer to the value (floating-point number)
  12958. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  12959. {
  12960. return is_number_float() ? &m_value.number_float : nullptr;
  12961. }
  12962. /// get a pointer to the value (floating-point number)
  12963. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  12964. {
  12965. return is_number_float() ? &m_value.number_float : nullptr;
  12966. }
  12967. /*!
  12968. @brief helper function to implement get_ref()
  12969. This function helps to implement get_ref() without code duplication for
  12970. const and non-const overloads
  12971. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  12972. @throw type_error.303 if ReferenceType does not match underlying value
  12973. type of the current JSON
  12974. */
  12975. template<typename ReferenceType, typename ThisType>
  12976. static ReferenceType get_ref_impl(ThisType& obj)
  12977. {
  12978. // delegate the call to get_ptr<>()
  12979. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  12980. if (JSON_LIKELY(ptr != nullptr))
  12981. {
  12982. return *ptr;
  12983. }
  12984. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  12985. }
  12986. public:
  12987. /// @name value access
  12988. /// Direct access to the stored value of a JSON value.
  12989. /// @{
  12990. /*!
  12991. @brief get special-case overload
  12992. This overloads avoids a lot of template boilerplate, it can be seen as the
  12993. identity method
  12994. @tparam BasicJsonType == @ref basic_json
  12995. @return a copy of *this
  12996. @complexity Constant.
  12997. @since version 2.1.0
  12998. */
  12999. template<typename BasicJsonType, detail::enable_if_t<
  13000. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  13001. int> = 0>
  13002. basic_json get() const
  13003. {
  13004. return *this;
  13005. }
  13006. /*!
  13007. @brief get special-case overload
  13008. This overloads converts the current @ref basic_json in a different
  13009. @ref basic_json type
  13010. @tparam BasicJsonType == @ref basic_json
  13011. @return a copy of *this, converted into @tparam BasicJsonType
  13012. @complexity Depending on the implementation of the called `from_json()`
  13013. method.
  13014. @since version 3.2.0
  13015. */
  13016. template<typename BasicJsonType, detail::enable_if_t<
  13017. not std::is_same<BasicJsonType, basic_json>::value and
  13018. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  13019. BasicJsonType get() const
  13020. {
  13021. return *this;
  13022. }
  13023. /*!
  13024. @brief get a value (explicit)
  13025. Explicit type conversion between the JSON value and a compatible value
  13026. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  13027. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  13028. The value is converted by calling the @ref json_serializer<ValueType>
  13029. `from_json()` method.
  13030. The function is equivalent to executing
  13031. @code {.cpp}
  13032. ValueType ret;
  13033. JSONSerializer<ValueType>::from_json(*this, ret);
  13034. return ret;
  13035. @endcode
  13036. This overloads is chosen if:
  13037. - @a ValueType is not @ref basic_json,
  13038. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  13039. `void from_json(const basic_json&, ValueType&)`, and
  13040. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  13041. the form `ValueType from_json(const basic_json&)`
  13042. @tparam ValueTypeCV the provided value type
  13043. @tparam ValueType the returned value type
  13044. @return copy of the JSON value, converted to @a ValueType
  13045. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  13046. @liveexample{The example below shows several conversions from JSON values
  13047. to other types. There a few things to note: (1) Floating-point numbers can
  13048. be converted to integers\, (2) A JSON array can be converted to a standard
  13049. `std::vector<short>`\, (3) A JSON object can be converted to C++
  13050. associative containers such as `std::unordered_map<std::string\,
  13051. json>`.,get__ValueType_const}
  13052. @since version 2.1.0
  13053. */
  13054. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  13055. detail::enable_if_t <
  13056. not detail::is_basic_json<ValueType>::value and
  13057. detail::has_from_json<basic_json_t, ValueType>::value and
  13058. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  13059. int> = 0>
  13060. ValueType get() const noexcept(noexcept(
  13061. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  13062. {
  13063. // we cannot static_assert on ValueTypeCV being non-const, because
  13064. // there is support for get<const basic_json_t>(), which is why we
  13065. // still need the uncvref
  13066. static_assert(not std::is_reference<ValueTypeCV>::value,
  13067. "get() cannot be used with reference types, you might want to use get_ref()");
  13068. static_assert(std::is_default_constructible<ValueType>::value,
  13069. "types must be DefaultConstructible when used with get()");
  13070. ValueType ret;
  13071. JSONSerializer<ValueType>::from_json(*this, ret);
  13072. return ret;
  13073. }
  13074. /*!
  13075. @brief get a value (explicit); special case
  13076. Explicit type conversion between the JSON value and a compatible value
  13077. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  13078. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  13079. The value is converted by calling the @ref json_serializer<ValueType>
  13080. `from_json()` method.
  13081. The function is equivalent to executing
  13082. @code {.cpp}
  13083. return JSONSerializer<ValueTypeCV>::from_json(*this);
  13084. @endcode
  13085. This overloads is chosen if:
  13086. - @a ValueType is not @ref basic_json and
  13087. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  13088. `ValueType from_json(const basic_json&)`
  13089. @note If @ref json_serializer<ValueType> has both overloads of
  13090. `from_json()`, this one is chosen.
  13091. @tparam ValueTypeCV the provided value type
  13092. @tparam ValueType the returned value type
  13093. @return copy of the JSON value, converted to @a ValueType
  13094. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  13095. @since version 2.1.0
  13096. */
  13097. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  13098. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  13099. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  13100. int> = 0>
  13101. ValueType get() const noexcept(noexcept(
  13102. JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
  13103. {
  13104. static_assert(not std::is_reference<ValueTypeCV>::value,
  13105. "get() cannot be used with reference types, you might want to use get_ref()");
  13106. return JSONSerializer<ValueTypeCV>::from_json(*this);
  13107. }
  13108. /*!
  13109. @brief get a value (explicit)
  13110. Explicit type conversion between the JSON value and a compatible value.
  13111. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  13112. `from_json()` method.
  13113. The function is equivalent to executing
  13114. @code {.cpp}
  13115. ValueType v;
  13116. JSONSerializer<ValueType>::from_json(*this, v);
  13117. @endcode
  13118. This overloads is chosen if:
  13119. - @a ValueType is not @ref basic_json,
  13120. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  13121. `void from_json(const basic_json&, ValueType&)`, and
  13122. @tparam ValueType the input parameter type.
  13123. @return the input parameter, allowing chaining calls.
  13124. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  13125. @liveexample{The example below shows several conversions from JSON values
  13126. to other types. There a few things to note: (1) Floating-point numbers can
  13127. be converted to integers\, (2) A JSON array can be converted to a standard
  13128. `std::vector<short>`\, (3) A JSON object can be converted to C++
  13129. associative containers such as `std::unordered_map<std::string\,
  13130. json>`.,get_to}
  13131. @since version 3.3.0
  13132. */
  13133. template<typename ValueType,
  13134. detail::enable_if_t <
  13135. not detail::is_basic_json<ValueType>::value and
  13136. detail::has_from_json<basic_json_t, ValueType>::value,
  13137. int> = 0>
  13138. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  13139. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  13140. {
  13141. JSONSerializer<ValueType>::from_json(*this, v);
  13142. return v;
  13143. }
  13144. template <
  13145. typename T, std::size_t N,
  13146. typename Array = T (&)[N],
  13147. detail::enable_if_t <
  13148. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  13149. Array get_to(T (&v)[N]) const
  13150. noexcept(noexcept(JSONSerializer<Array>::from_json(
  13151. std::declval<const basic_json_t&>(), v)))
  13152. {
  13153. JSONSerializer<Array>::from_json(*this, v);
  13154. return v;
  13155. }
  13156. /*!
  13157. @brief get a pointer value (implicit)
  13158. Implicit pointer access to the internally stored JSON value. No copies are
  13159. made.
  13160. @warning Writing data to the pointee of the result yields an undefined
  13161. state.
  13162. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  13163. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  13164. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  13165. assertion.
  13166. @return pointer to the internally stored JSON value if the requested
  13167. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  13168. @complexity Constant.
  13169. @liveexample{The example below shows how pointers to internal values of a
  13170. JSON value can be requested. Note that no type conversions are made and a
  13171. `nullptr` is returned if the value and the requested pointer type does not
  13172. match.,get_ptr}
  13173. @since version 1.0.0
  13174. */
  13175. template<typename PointerType, typename std::enable_if<
  13176. std::is_pointer<PointerType>::value, int>::type = 0>
  13177. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  13178. {
  13179. // delegate the call to get_impl_ptr<>()
  13180. return get_impl_ptr(static_cast<PointerType>(nullptr));
  13181. }
  13182. /*!
  13183. @brief get a pointer value (implicit)
  13184. @copydoc get_ptr()
  13185. */
  13186. template<typename PointerType, typename std::enable_if<
  13187. std::is_pointer<PointerType>::value and
  13188. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  13189. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  13190. {
  13191. // delegate the call to get_impl_ptr<>() const
  13192. return get_impl_ptr(static_cast<PointerType>(nullptr));
  13193. }
  13194. /*!
  13195. @brief get a pointer value (explicit)
  13196. Explicit pointer access to the internally stored JSON value. No copies are
  13197. made.
  13198. @warning The pointer becomes invalid if the underlying JSON object
  13199. changes.
  13200. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  13201. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  13202. @ref number_unsigned_t, or @ref number_float_t.
  13203. @return pointer to the internally stored JSON value if the requested
  13204. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  13205. @complexity Constant.
  13206. @liveexample{The example below shows how pointers to internal values of a
  13207. JSON value can be requested. Note that no type conversions are made and a
  13208. `nullptr` is returned if the value and the requested pointer type does not
  13209. match.,get__PointerType}
  13210. @sa @ref get_ptr() for explicit pointer-member access
  13211. @since version 1.0.0
  13212. */
  13213. template<typename PointerType, typename std::enable_if<
  13214. std::is_pointer<PointerType>::value, int>::type = 0>
  13215. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  13216. {
  13217. // delegate the call to get_ptr
  13218. return get_ptr<PointerType>();
  13219. }
  13220. /*!
  13221. @brief get a pointer value (explicit)
  13222. @copydoc get()
  13223. */
  13224. template<typename PointerType, typename std::enable_if<
  13225. std::is_pointer<PointerType>::value, int>::type = 0>
  13226. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  13227. {
  13228. // delegate the call to get_ptr
  13229. return get_ptr<PointerType>();
  13230. }
  13231. /*!
  13232. @brief get a reference value (implicit)
  13233. Implicit reference access to the internally stored JSON value. No copies
  13234. are made.
  13235. @warning Writing data to the referee of the result yields an undefined
  13236. state.
  13237. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  13238. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  13239. @ref number_float_t. Enforced by static assertion.
  13240. @return reference to the internally stored JSON value if the requested
  13241. reference type @a ReferenceType fits to the JSON value; throws
  13242. type_error.303 otherwise
  13243. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  13244. with the stored JSON value; see example below
  13245. @complexity Constant.
  13246. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  13247. @since version 1.1.0
  13248. */
  13249. template<typename ReferenceType, typename std::enable_if<
  13250. std::is_reference<ReferenceType>::value, int>::type = 0>
  13251. ReferenceType get_ref()
  13252. {
  13253. // delegate call to get_ref_impl
  13254. return get_ref_impl<ReferenceType>(*this);
  13255. }
  13256. /*!
  13257. @brief get a reference value (implicit)
  13258. @copydoc get_ref()
  13259. */
  13260. template<typename ReferenceType, typename std::enable_if<
  13261. std::is_reference<ReferenceType>::value and
  13262. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  13263. ReferenceType get_ref() const
  13264. {
  13265. // delegate call to get_ref_impl
  13266. return get_ref_impl<ReferenceType>(*this);
  13267. }
  13268. /*!
  13269. @brief get a value (implicit)
  13270. Implicit type conversion between the JSON value and a compatible value.
  13271. The call is realized by calling @ref get() const.
  13272. @tparam ValueType non-pointer type compatible to the JSON value, for
  13273. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  13274. `std::vector` types for JSON arrays. The character type of @ref string_t
  13275. as well as an initializer list of this type is excluded to avoid
  13276. ambiguities as these types implicitly convert to `std::string`.
  13277. @return copy of the JSON value, converted to type @a ValueType
  13278. @throw type_error.302 in case passed type @a ValueType is incompatible
  13279. to the JSON value type (e.g., the JSON value is of type boolean, but a
  13280. string is requested); see example below
  13281. @complexity Linear in the size of the JSON value.
  13282. @liveexample{The example below shows several conversions from JSON values
  13283. to other types. There a few things to note: (1) Floating-point numbers can
  13284. be converted to integers\, (2) A JSON array can be converted to a standard
  13285. `std::vector<short>`\, (3) A JSON object can be converted to C++
  13286. associative containers such as `std::unordered_map<std::string\,
  13287. json>`.,operator__ValueType}
  13288. @since version 1.0.0
  13289. */
  13290. template < typename ValueType, typename std::enable_if <
  13291. not std::is_pointer<ValueType>::value and
  13292. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  13293. not std::is_same<ValueType, typename string_t::value_type>::value and
  13294. not detail::is_basic_json<ValueType>::value
  13295. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  13296. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  13297. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) and _MSC_VER <= 1914))
  13298. and not std::is_same<ValueType, typename std::string_view>::value
  13299. #endif
  13300. #endif
  13301. and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  13302. , int >::type = 0 >
  13303. operator ValueType() const
  13304. {
  13305. // delegate the call to get<>() const
  13306. return get<ValueType>();
  13307. }
  13308. /// @}
  13309. ////////////////////
  13310. // element access //
  13311. ////////////////////
  13312. /// @name element access
  13313. /// Access to the JSON value.
  13314. /// @{
  13315. /*!
  13316. @brief access specified array element with bounds checking
  13317. Returns a reference to the element at specified location @a idx, with
  13318. bounds checking.
  13319. @param[in] idx index of the element to access
  13320. @return reference to the element at index @a idx
  13321. @throw type_error.304 if the JSON value is not an array; in this case,
  13322. calling `at` with an index makes no sense. See example below.
  13323. @throw out_of_range.401 if the index @a idx is out of range of the array;
  13324. that is, `idx >= size()`. See example below.
  13325. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13326. changes in the JSON value.
  13327. @complexity Constant.
  13328. @since version 1.0.0
  13329. @liveexample{The example below shows how array elements can be read and
  13330. written using `at()`. It also demonstrates the different exceptions that
  13331. can be thrown.,at__size_type}
  13332. */
  13333. reference at(size_type idx)
  13334. {
  13335. // at only works for arrays
  13336. if (JSON_LIKELY(is_array()))
  13337. {
  13338. JSON_TRY
  13339. {
  13340. return m_value.array->at(idx);
  13341. }
  13342. JSON_CATCH (std::out_of_range&)
  13343. {
  13344. // create better exception explanation
  13345. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  13346. }
  13347. }
  13348. else
  13349. {
  13350. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  13351. }
  13352. }
  13353. /*!
  13354. @brief access specified array element with bounds checking
  13355. Returns a const reference to the element at specified location @a idx,
  13356. with bounds checking.
  13357. @param[in] idx index of the element to access
  13358. @return const reference to the element at index @a idx
  13359. @throw type_error.304 if the JSON value is not an array; in this case,
  13360. calling `at` with an index makes no sense. See example below.
  13361. @throw out_of_range.401 if the index @a idx is out of range of the array;
  13362. that is, `idx >= size()`. See example below.
  13363. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13364. changes in the JSON value.
  13365. @complexity Constant.
  13366. @since version 1.0.0
  13367. @liveexample{The example below shows how array elements can be read using
  13368. `at()`. It also demonstrates the different exceptions that can be thrown.,
  13369. at__size_type_const}
  13370. */
  13371. const_reference at(size_type idx) const
  13372. {
  13373. // at only works for arrays
  13374. if (JSON_LIKELY(is_array()))
  13375. {
  13376. JSON_TRY
  13377. {
  13378. return m_value.array->at(idx);
  13379. }
  13380. JSON_CATCH (std::out_of_range&)
  13381. {
  13382. // create better exception explanation
  13383. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  13384. }
  13385. }
  13386. else
  13387. {
  13388. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  13389. }
  13390. }
  13391. /*!
  13392. @brief access specified object element with bounds checking
  13393. Returns a reference to the element at with specified key @a key, with
  13394. bounds checking.
  13395. @param[in] key key of the element to access
  13396. @return reference to the element at key @a key
  13397. @throw type_error.304 if the JSON value is not an object; in this case,
  13398. calling `at` with a key makes no sense. See example below.
  13399. @throw out_of_range.403 if the key @a key is is not stored in the object;
  13400. that is, `find(key) == end()`. See example below.
  13401. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13402. changes in the JSON value.
  13403. @complexity Logarithmic in the size of the container.
  13404. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  13405. access by reference
  13406. @sa @ref value() for access by value with a default value
  13407. @since version 1.0.0
  13408. @liveexample{The example below shows how object elements can be read and
  13409. written using `at()`. It also demonstrates the different exceptions that
  13410. can be thrown.,at__object_t_key_type}
  13411. */
  13412. reference at(const typename object_t::key_type& key)
  13413. {
  13414. // at only works for objects
  13415. if (JSON_LIKELY(is_object()))
  13416. {
  13417. JSON_TRY
  13418. {
  13419. return m_value.object->at(key);
  13420. }
  13421. JSON_CATCH (std::out_of_range&)
  13422. {
  13423. // create better exception explanation
  13424. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  13425. }
  13426. }
  13427. else
  13428. {
  13429. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  13430. }
  13431. }
  13432. /*!
  13433. @brief access specified object element with bounds checking
  13434. Returns a const reference to the element at with specified key @a key,
  13435. with bounds checking.
  13436. @param[in] key key of the element to access
  13437. @return const reference to the element at key @a key
  13438. @throw type_error.304 if the JSON value is not an object; in this case,
  13439. calling `at` with a key makes no sense. See example below.
  13440. @throw out_of_range.403 if the key @a key is is not stored in the object;
  13441. that is, `find(key) == end()`. See example below.
  13442. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13443. changes in the JSON value.
  13444. @complexity Logarithmic in the size of the container.
  13445. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  13446. access by reference
  13447. @sa @ref value() for access by value with a default value
  13448. @since version 1.0.0
  13449. @liveexample{The example below shows how object elements can be read using
  13450. `at()`. It also demonstrates the different exceptions that can be thrown.,
  13451. at__object_t_key_type_const}
  13452. */
  13453. const_reference at(const typename object_t::key_type& key) const
  13454. {
  13455. // at only works for objects
  13456. if (JSON_LIKELY(is_object()))
  13457. {
  13458. JSON_TRY
  13459. {
  13460. return m_value.object->at(key);
  13461. }
  13462. JSON_CATCH (std::out_of_range&)
  13463. {
  13464. // create better exception explanation
  13465. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  13466. }
  13467. }
  13468. else
  13469. {
  13470. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  13471. }
  13472. }
  13473. /*!
  13474. @brief access specified array element
  13475. Returns a reference to the element at specified location @a idx.
  13476. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  13477. then the array is silently filled up with `null` values to make `idx` a
  13478. valid reference to the last stored element.
  13479. @param[in] idx index of the element to access
  13480. @return reference to the element at index @a idx
  13481. @throw type_error.305 if the JSON value is not an array or null; in that
  13482. cases, using the [] operator with an index makes no sense.
  13483. @complexity Constant if @a idx is in the range of the array. Otherwise
  13484. linear in `idx - size()`.
  13485. @liveexample{The example below shows how array elements can be read and
  13486. written using `[]` operator. Note the addition of `null`
  13487. values.,operatorarray__size_type}
  13488. @since version 1.0.0
  13489. */
  13490. reference operator[](size_type idx)
  13491. {
  13492. // implicitly convert null value to an empty array
  13493. if (is_null())
  13494. {
  13495. m_type = value_t::array;
  13496. m_value.array = create<array_t>();
  13497. assert_invariant();
  13498. }
  13499. // operator[] only works for arrays
  13500. if (JSON_LIKELY(is_array()))
  13501. {
  13502. // fill up array with null values if given idx is outside range
  13503. if (idx >= m_value.array->size())
  13504. {
  13505. m_value.array->insert(m_value.array->end(),
  13506. idx - m_value.array->size() + 1,
  13507. basic_json());
  13508. }
  13509. return m_value.array->operator[](idx);
  13510. }
  13511. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  13512. }
  13513. /*!
  13514. @brief access specified array element
  13515. Returns a const reference to the element at specified location @a idx.
  13516. @param[in] idx index of the element to access
  13517. @return const reference to the element at index @a idx
  13518. @throw type_error.305 if the JSON value is not an array; in that case,
  13519. using the [] operator with an index makes no sense.
  13520. @complexity Constant.
  13521. @liveexample{The example below shows how array elements can be read using
  13522. the `[]` operator.,operatorarray__size_type_const}
  13523. @since version 1.0.0
  13524. */
  13525. const_reference operator[](size_type idx) const
  13526. {
  13527. // const operator[] only works for arrays
  13528. if (JSON_LIKELY(is_array()))
  13529. {
  13530. return m_value.array->operator[](idx);
  13531. }
  13532. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  13533. }
  13534. /*!
  13535. @brief access specified object element
  13536. Returns a reference to the element at with specified key @a key.
  13537. @note If @a key is not found in the object, then it is silently added to
  13538. the object and filled with a `null` value to make `key` a valid reference.
  13539. In case the value was `null` before, it is converted to an object.
  13540. @param[in] key key of the element to access
  13541. @return reference to the element at key @a key
  13542. @throw type_error.305 if the JSON value is not an object or null; in that
  13543. cases, using the [] operator with a key makes no sense.
  13544. @complexity Logarithmic in the size of the container.
  13545. @liveexample{The example below shows how object elements can be read and
  13546. written using the `[]` operator.,operatorarray__key_type}
  13547. @sa @ref at(const typename object_t::key_type&) for access by reference
  13548. with range checking
  13549. @sa @ref value() for access by value with a default value
  13550. @since version 1.0.0
  13551. */
  13552. reference operator[](const typename object_t::key_type& key)
  13553. {
  13554. // implicitly convert null value to an empty object
  13555. if (is_null())
  13556. {
  13557. m_type = value_t::object;
  13558. m_value.object = create<object_t>();
  13559. assert_invariant();
  13560. }
  13561. // operator[] only works for objects
  13562. if (JSON_LIKELY(is_object()))
  13563. {
  13564. return m_value.object->operator[](key);
  13565. }
  13566. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  13567. }
  13568. /*!
  13569. @brief read-only access specified object element
  13570. Returns a const reference to the element at with specified key @a key. No
  13571. bounds checking is performed.
  13572. @warning If the element with key @a key does not exist, the behavior is
  13573. undefined.
  13574. @param[in] key key of the element to access
  13575. @return const reference to the element at key @a key
  13576. @pre The element with key @a key must exist. **This precondition is
  13577. enforced with an assertion.**
  13578. @throw type_error.305 if the JSON value is not an object; in that case,
  13579. using the [] operator with a key makes no sense.
  13580. @complexity Logarithmic in the size of the container.
  13581. @liveexample{The example below shows how object elements can be read using
  13582. the `[]` operator.,operatorarray__key_type_const}
  13583. @sa @ref at(const typename object_t::key_type&) for access by reference
  13584. with range checking
  13585. @sa @ref value() for access by value with a default value
  13586. @since version 1.0.0
  13587. */
  13588. const_reference operator[](const typename object_t::key_type& key) const
  13589. {
  13590. // const operator[] only works for objects
  13591. if (JSON_LIKELY(is_object()))
  13592. {
  13593. assert(m_value.object->find(key) != m_value.object->end());
  13594. return m_value.object->find(key)->second;
  13595. }
  13596. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  13597. }
  13598. /*!
  13599. @brief access specified object element
  13600. Returns a reference to the element at with specified key @a key.
  13601. @note If @a key is not found in the object, then it is silently added to
  13602. the object and filled with a `null` value to make `key` a valid reference.
  13603. In case the value was `null` before, it is converted to an object.
  13604. @param[in] key key of the element to access
  13605. @return reference to the element at key @a key
  13606. @throw type_error.305 if the JSON value is not an object or null; in that
  13607. cases, using the [] operator with a key makes no sense.
  13608. @complexity Logarithmic in the size of the container.
  13609. @liveexample{The example below shows how object elements can be read and
  13610. written using the `[]` operator.,operatorarray__key_type}
  13611. @sa @ref at(const typename object_t::key_type&) for access by reference
  13612. with range checking
  13613. @sa @ref value() for access by value with a default value
  13614. @since version 1.1.0
  13615. */
  13616. template<typename T>
  13617. reference operator[](T* key)
  13618. {
  13619. // implicitly convert null to object
  13620. if (is_null())
  13621. {
  13622. m_type = value_t::object;
  13623. m_value = value_t::object;
  13624. assert_invariant();
  13625. }
  13626. // at only works for objects
  13627. if (JSON_LIKELY(is_object()))
  13628. {
  13629. return m_value.object->operator[](key);
  13630. }
  13631. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  13632. }
  13633. /*!
  13634. @brief read-only access specified object element
  13635. Returns a const reference to the element at with specified key @a key. No
  13636. bounds checking is performed.
  13637. @warning If the element with key @a key does not exist, the behavior is
  13638. undefined.
  13639. @param[in] key key of the element to access
  13640. @return const reference to the element at key @a key
  13641. @pre The element with key @a key must exist. **This precondition is
  13642. enforced with an assertion.**
  13643. @throw type_error.305 if the JSON value is not an object; in that case,
  13644. using the [] operator with a key makes no sense.
  13645. @complexity Logarithmic in the size of the container.
  13646. @liveexample{The example below shows how object elements can be read using
  13647. the `[]` operator.,operatorarray__key_type_const}
  13648. @sa @ref at(const typename object_t::key_type&) for access by reference
  13649. with range checking
  13650. @sa @ref value() for access by value with a default value
  13651. @since version 1.1.0
  13652. */
  13653. template<typename T>
  13654. const_reference operator[](T* key) const
  13655. {
  13656. // at only works for objects
  13657. if (JSON_LIKELY(is_object()))
  13658. {
  13659. assert(m_value.object->find(key) != m_value.object->end());
  13660. return m_value.object->find(key)->second;
  13661. }
  13662. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  13663. }
  13664. /*!
  13665. @brief access specified object element with default value
  13666. Returns either a copy of an object's element at the specified key @a key
  13667. or a given default value if no element with key @a key exists.
  13668. The function is basically equivalent to executing
  13669. @code {.cpp}
  13670. try {
  13671. return at(key);
  13672. } catch(out_of_range) {
  13673. return default_value;
  13674. }
  13675. @endcode
  13676. @note Unlike @ref at(const typename object_t::key_type&), this function
  13677. does not throw if the given key @a key was not found.
  13678. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  13679. function does not implicitly add an element to the position defined by @a
  13680. key. This function is furthermore also applicable to const objects.
  13681. @param[in] key key of the element to access
  13682. @param[in] default_value the value to return if @a key is not found
  13683. @tparam ValueType type compatible to JSON values, for instance `int` for
  13684. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  13685. JSON arrays. Note the type of the expected value at @a key and the default
  13686. value @a default_value must be compatible.
  13687. @return copy of the element at key @a key or @a default_value if @a key
  13688. is not found
  13689. @throw type_error.302 if @a default_value does not match the type of the
  13690. value at @a key
  13691. @throw type_error.306 if the JSON value is not an object; in that case,
  13692. using `value()` with a key makes no sense.
  13693. @complexity Logarithmic in the size of the container.
  13694. @liveexample{The example below shows how object elements can be queried
  13695. with a default value.,basic_json__value}
  13696. @sa @ref at(const typename object_t::key_type&) for access by reference
  13697. with range checking
  13698. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  13699. access by reference
  13700. @since version 1.0.0
  13701. */
  13702. template<class ValueType, typename std::enable_if<
  13703. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  13704. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  13705. {
  13706. // at only works for objects
  13707. if (JSON_LIKELY(is_object()))
  13708. {
  13709. // if key is found, return value and given default value otherwise
  13710. const auto it = find(key);
  13711. if (it != end())
  13712. {
  13713. return *it;
  13714. }
  13715. return default_value;
  13716. }
  13717. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  13718. }
  13719. /*!
  13720. @brief overload for a default value of type const char*
  13721. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  13722. */
  13723. string_t value(const typename object_t::key_type& key, const char* default_value) const
  13724. {
  13725. return value(key, string_t(default_value));
  13726. }
  13727. /*!
  13728. @brief access specified object element via JSON Pointer with default value
  13729. Returns either a copy of an object's element at the specified key @a key
  13730. or a given default value if no element with key @a key exists.
  13731. The function is basically equivalent to executing
  13732. @code {.cpp}
  13733. try {
  13734. return at(ptr);
  13735. } catch(out_of_range) {
  13736. return default_value;
  13737. }
  13738. @endcode
  13739. @note Unlike @ref at(const json_pointer&), this function does not throw
  13740. if the given key @a key was not found.
  13741. @param[in] ptr a JSON pointer to the element to access
  13742. @param[in] default_value the value to return if @a ptr found no value
  13743. @tparam ValueType type compatible to JSON values, for instance `int` for
  13744. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  13745. JSON arrays. Note the type of the expected value at @a key and the default
  13746. value @a default_value must be compatible.
  13747. @return copy of the element at key @a key or @a default_value if @a key
  13748. is not found
  13749. @throw type_error.302 if @a default_value does not match the type of the
  13750. value at @a ptr
  13751. @throw type_error.306 if the JSON value is not an object; in that case,
  13752. using `value()` with a key makes no sense.
  13753. @complexity Logarithmic in the size of the container.
  13754. @liveexample{The example below shows how object elements can be queried
  13755. with a default value.,basic_json__value_ptr}
  13756. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  13757. @since version 2.0.2
  13758. */
  13759. template<class ValueType, typename std::enable_if<
  13760. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  13761. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  13762. {
  13763. // at only works for objects
  13764. if (JSON_LIKELY(is_object()))
  13765. {
  13766. // if pointer resolves a value, return it or use default value
  13767. JSON_TRY
  13768. {
  13769. return ptr.get_checked(this);
  13770. }
  13771. JSON_INTERNAL_CATCH (out_of_range&)
  13772. {
  13773. return default_value;
  13774. }
  13775. }
  13776. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  13777. }
  13778. /*!
  13779. @brief overload for a default value of type const char*
  13780. @copydoc basic_json::value(const json_pointer&, ValueType) const
  13781. */
  13782. string_t value(const json_pointer& ptr, const char* default_value) const
  13783. {
  13784. return value(ptr, string_t(default_value));
  13785. }
  13786. /*!
  13787. @brief access the first element
  13788. Returns a reference to the first element in the container. For a JSON
  13789. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  13790. @return In case of a structured type (array or object), a reference to the
  13791. first element is returned. In case of number, string, or boolean values, a
  13792. reference to the value is returned.
  13793. @complexity Constant.
  13794. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  13795. or an empty array or object (undefined behavior, **guarded by
  13796. assertions**).
  13797. @post The JSON value remains unchanged.
  13798. @throw invalid_iterator.214 when called on `null` value
  13799. @liveexample{The following code shows an example for `front()`.,front}
  13800. @sa @ref back() -- access the last element
  13801. @since version 1.0.0
  13802. */
  13803. reference front()
  13804. {
  13805. return *begin();
  13806. }
  13807. /*!
  13808. @copydoc basic_json::front()
  13809. */
  13810. const_reference front() const
  13811. {
  13812. return *cbegin();
  13813. }
  13814. /*!
  13815. @brief access the last element
  13816. Returns a reference to the last element in the container. For a JSON
  13817. container `c`, the expression `c.back()` is equivalent to
  13818. @code {.cpp}
  13819. auto tmp = c.end();
  13820. --tmp;
  13821. return *tmp;
  13822. @endcode
  13823. @return In case of a structured type (array or object), a reference to the
  13824. last element is returned. In case of number, string, or boolean values, a
  13825. reference to the value is returned.
  13826. @complexity Constant.
  13827. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  13828. or an empty array or object (undefined behavior, **guarded by
  13829. assertions**).
  13830. @post The JSON value remains unchanged.
  13831. @throw invalid_iterator.214 when called on a `null` value. See example
  13832. below.
  13833. @liveexample{The following code shows an example for `back()`.,back}
  13834. @sa @ref front() -- access the first element
  13835. @since version 1.0.0
  13836. */
  13837. reference back()
  13838. {
  13839. auto tmp = end();
  13840. --tmp;
  13841. return *tmp;
  13842. }
  13843. /*!
  13844. @copydoc basic_json::back()
  13845. */
  13846. const_reference back() const
  13847. {
  13848. auto tmp = cend();
  13849. --tmp;
  13850. return *tmp;
  13851. }
  13852. /*!
  13853. @brief remove element given an iterator
  13854. Removes the element specified by iterator @a pos. The iterator @a pos must
  13855. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  13856. but is not dereferenceable) cannot be used as a value for @a pos.
  13857. If called on a primitive type other than `null`, the resulting JSON value
  13858. will be `null`.
  13859. @param[in] pos iterator to the element to remove
  13860. @return Iterator following the last removed element. If the iterator @a
  13861. pos refers to the last element, the `end()` iterator is returned.
  13862. @tparam IteratorType an @ref iterator or @ref const_iterator
  13863. @post Invalidates iterators and references at or after the point of the
  13864. erase, including the `end()` iterator.
  13865. @throw type_error.307 if called on a `null` value; example: `"cannot use
  13866. erase() with null"`
  13867. @throw invalid_iterator.202 if called on an iterator which does not belong
  13868. to the current JSON value; example: `"iterator does not fit current
  13869. value"`
  13870. @throw invalid_iterator.205 if called on a primitive type with invalid
  13871. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  13872. out of range"`
  13873. @complexity The complexity depends on the type:
  13874. - objects: amortized constant
  13875. - arrays: linear in distance between @a pos and the end of the container
  13876. - strings: linear in the length of the string
  13877. - other types: constant
  13878. @liveexample{The example shows the result of `erase()` for different JSON
  13879. types.,erase__IteratorType}
  13880. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  13881. the given range
  13882. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  13883. from an object at the given key
  13884. @sa @ref erase(const size_type) -- removes the element from an array at
  13885. the given index
  13886. @since version 1.0.0
  13887. */
  13888. template<class IteratorType, typename std::enable_if<
  13889. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  13890. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  13891. = 0>
  13892. IteratorType erase(IteratorType pos)
  13893. {
  13894. // make sure iterator fits the current value
  13895. if (JSON_UNLIKELY(this != pos.m_object))
  13896. {
  13897. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  13898. }
  13899. IteratorType result = end();
  13900. switch (m_type)
  13901. {
  13902. case value_t::boolean:
  13903. case value_t::number_float:
  13904. case value_t::number_integer:
  13905. case value_t::number_unsigned:
  13906. case value_t::string:
  13907. {
  13908. if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  13909. {
  13910. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  13911. }
  13912. if (is_string())
  13913. {
  13914. AllocatorType<string_t> alloc;
  13915. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  13916. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  13917. m_value.string = nullptr;
  13918. }
  13919. m_type = value_t::null;
  13920. assert_invariant();
  13921. break;
  13922. }
  13923. case value_t::object:
  13924. {
  13925. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  13926. break;
  13927. }
  13928. case value_t::array:
  13929. {
  13930. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  13931. break;
  13932. }
  13933. default:
  13934. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  13935. }
  13936. return result;
  13937. }
  13938. /*!
  13939. @brief remove elements given an iterator range
  13940. Removes the element specified by the range `[first; last)`. The iterator
  13941. @a first does not need to be dereferenceable if `first == last`: erasing
  13942. an empty range is a no-op.
  13943. If called on a primitive type other than `null`, the resulting JSON value
  13944. will be `null`.
  13945. @param[in] first iterator to the beginning of the range to remove
  13946. @param[in] last iterator past the end of the range to remove
  13947. @return Iterator following the last removed element. If the iterator @a
  13948. second refers to the last element, the `end()` iterator is returned.
  13949. @tparam IteratorType an @ref iterator or @ref const_iterator
  13950. @post Invalidates iterators and references at or after the point of the
  13951. erase, including the `end()` iterator.
  13952. @throw type_error.307 if called on a `null` value; example: `"cannot use
  13953. erase() with null"`
  13954. @throw invalid_iterator.203 if called on iterators which does not belong
  13955. to the current JSON value; example: `"iterators do not fit current value"`
  13956. @throw invalid_iterator.204 if called on a primitive type with invalid
  13957. iterators (i.e., if `first != begin()` and `last != end()`); example:
  13958. `"iterators out of range"`
  13959. @complexity The complexity depends on the type:
  13960. - objects: `log(size()) + std::distance(first, last)`
  13961. - arrays: linear in the distance between @a first and @a last, plus linear
  13962. in the distance between @a last and end of the container
  13963. - strings: linear in the length of the string
  13964. - other types: constant
  13965. @liveexample{The example shows the result of `erase()` for different JSON
  13966. types.,erase__IteratorType_IteratorType}
  13967. @sa @ref erase(IteratorType) -- removes the element at a given position
  13968. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  13969. from an object at the given key
  13970. @sa @ref erase(const size_type) -- removes the element from an array at
  13971. the given index
  13972. @since version 1.0.0
  13973. */
  13974. template<class IteratorType, typename std::enable_if<
  13975. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  13976. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  13977. = 0>
  13978. IteratorType erase(IteratorType first, IteratorType last)
  13979. {
  13980. // make sure iterator fits the current value
  13981. if (JSON_UNLIKELY(this != first.m_object or this != last.m_object))
  13982. {
  13983. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  13984. }
  13985. IteratorType result = end();
  13986. switch (m_type)
  13987. {
  13988. case value_t::boolean:
  13989. case value_t::number_float:
  13990. case value_t::number_integer:
  13991. case value_t::number_unsigned:
  13992. case value_t::string:
  13993. {
  13994. if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin()
  13995. or not last.m_it.primitive_iterator.is_end()))
  13996. {
  13997. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  13998. }
  13999. if (is_string())
  14000. {
  14001. AllocatorType<string_t> alloc;
  14002. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  14003. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  14004. m_value.string = nullptr;
  14005. }
  14006. m_type = value_t::null;
  14007. assert_invariant();
  14008. break;
  14009. }
  14010. case value_t::object:
  14011. {
  14012. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  14013. last.m_it.object_iterator);
  14014. break;
  14015. }
  14016. case value_t::array:
  14017. {
  14018. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  14019. last.m_it.array_iterator);
  14020. break;
  14021. }
  14022. default:
  14023. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  14024. }
  14025. return result;
  14026. }
  14027. /*!
  14028. @brief remove element from a JSON object given a key
  14029. Removes elements from a JSON object with the key value @a key.
  14030. @param[in] key value of the elements to remove
  14031. @return Number of elements removed. If @a ObjectType is the default
  14032. `std::map` type, the return value will always be `0` (@a key was not
  14033. found) or `1` (@a key was found).
  14034. @post References and iterators to the erased elements are invalidated.
  14035. Other references and iterators are not affected.
  14036. @throw type_error.307 when called on a type other than JSON object;
  14037. example: `"cannot use erase() with null"`
  14038. @complexity `log(size()) + count(key)`
  14039. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  14040. @sa @ref erase(IteratorType) -- removes the element at a given position
  14041. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  14042. the given range
  14043. @sa @ref erase(const size_type) -- removes the element from an array at
  14044. the given index
  14045. @since version 1.0.0
  14046. */
  14047. size_type erase(const typename object_t::key_type& key)
  14048. {
  14049. // this erase only works for objects
  14050. if (JSON_LIKELY(is_object()))
  14051. {
  14052. return m_value.object->erase(key);
  14053. }
  14054. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  14055. }
  14056. /*!
  14057. @brief remove element from a JSON array given an index
  14058. Removes element from a JSON array at the index @a idx.
  14059. @param[in] idx index of the element to remove
  14060. @throw type_error.307 when called on a type other than JSON object;
  14061. example: `"cannot use erase() with null"`
  14062. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  14063. is out of range"`
  14064. @complexity Linear in distance between @a idx and the end of the container.
  14065. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  14066. @sa @ref erase(IteratorType) -- removes the element at a given position
  14067. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  14068. the given range
  14069. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  14070. from an object at the given key
  14071. @since version 1.0.0
  14072. */
  14073. void erase(const size_type idx)
  14074. {
  14075. // this erase only works for arrays
  14076. if (JSON_LIKELY(is_array()))
  14077. {
  14078. if (JSON_UNLIKELY(idx >= size()))
  14079. {
  14080. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  14081. }
  14082. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  14083. }
  14084. else
  14085. {
  14086. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  14087. }
  14088. }
  14089. /// @}
  14090. ////////////
  14091. // lookup //
  14092. ////////////
  14093. /// @name lookup
  14094. /// @{
  14095. /*!
  14096. @brief find an element in a JSON object
  14097. Finds an element in a JSON object with key equivalent to @a key. If the
  14098. element is not found or the JSON value is not an object, end() is
  14099. returned.
  14100. @note This method always returns @ref end() when executed on a JSON type
  14101. that is not an object.
  14102. @param[in] key key value of the element to search for.
  14103. @return Iterator to an element with key equivalent to @a key. If no such
  14104. element is found or the JSON value is not an object, past-the-end (see
  14105. @ref end()) iterator is returned.
  14106. @complexity Logarithmic in the size of the JSON object.
  14107. @liveexample{The example shows how `find()` is used.,find__key_type}
  14108. @sa @ref contains(KeyT&&) const -- checks whether a key exists
  14109. @since version 1.0.0
  14110. */
  14111. template<typename KeyT>
  14112. iterator find(KeyT&& key)
  14113. {
  14114. auto result = end();
  14115. if (is_object())
  14116. {
  14117. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  14118. }
  14119. return result;
  14120. }
  14121. /*!
  14122. @brief find an element in a JSON object
  14123. @copydoc find(KeyT&&)
  14124. */
  14125. template<typename KeyT>
  14126. const_iterator find(KeyT&& key) const
  14127. {
  14128. auto result = cend();
  14129. if (is_object())
  14130. {
  14131. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  14132. }
  14133. return result;
  14134. }
  14135. /*!
  14136. @brief returns the number of occurrences of a key in a JSON object
  14137. Returns the number of elements with key @a key. If ObjectType is the
  14138. default `std::map` type, the return value will always be `0` (@a key was
  14139. not found) or `1` (@a key was found).
  14140. @note This method always returns `0` when executed on a JSON type that is
  14141. not an object.
  14142. @param[in] key key value of the element to count
  14143. @return Number of elements with key @a key. If the JSON value is not an
  14144. object, the return value will be `0`.
  14145. @complexity Logarithmic in the size of the JSON object.
  14146. @liveexample{The example shows how `count()` is used.,count}
  14147. @since version 1.0.0
  14148. */
  14149. template<typename KeyT>
  14150. size_type count(KeyT&& key) const
  14151. {
  14152. // return 0 for all nonobject types
  14153. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  14154. }
  14155. /*!
  14156. @brief check the existence of an element in a JSON object
  14157. Check whether an element exists in a JSON object with key equivalent to
  14158. @a key. If the element is not found or the JSON value is not an object,
  14159. false is returned.
  14160. @note This method always returns false when executed on a JSON type
  14161. that is not an object.
  14162. @param[in] key key value to check its existence.
  14163. @return true if an element with specified @a key exists. If no such
  14164. element with such key is found or the JSON value is not an object,
  14165. false is returned.
  14166. @complexity Logarithmic in the size of the JSON object.
  14167. @liveexample{The following code shows an example for `contains()`.,contains}
  14168. @sa @ref find(KeyT&&) -- returns an iterator to an object element
  14169. @since version 3.6.0
  14170. */
  14171. template<typename KeyT>
  14172. bool contains(KeyT&& key) const
  14173. {
  14174. return is_object() and m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  14175. }
  14176. /// @}
  14177. ///////////////
  14178. // iterators //
  14179. ///////////////
  14180. /// @name iterators
  14181. /// @{
  14182. /*!
  14183. @brief returns an iterator to the first element
  14184. Returns an iterator to the first element.
  14185. @image html range-begin-end.svg "Illustration from cppreference.com"
  14186. @return iterator to the first element
  14187. @complexity Constant.
  14188. @requirement This function helps `basic_json` satisfying the
  14189. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14190. requirements:
  14191. - The complexity is constant.
  14192. @liveexample{The following code shows an example for `begin()`.,begin}
  14193. @sa @ref cbegin() -- returns a const iterator to the beginning
  14194. @sa @ref end() -- returns an iterator to the end
  14195. @sa @ref cend() -- returns a const iterator to the end
  14196. @since version 1.0.0
  14197. */
  14198. iterator begin() noexcept
  14199. {
  14200. iterator result(this);
  14201. result.set_begin();
  14202. return result;
  14203. }
  14204. /*!
  14205. @copydoc basic_json::cbegin()
  14206. */
  14207. const_iterator begin() const noexcept
  14208. {
  14209. return cbegin();
  14210. }
  14211. /*!
  14212. @brief returns a const iterator to the first element
  14213. Returns a const iterator to the first element.
  14214. @image html range-begin-end.svg "Illustration from cppreference.com"
  14215. @return const iterator to the first element
  14216. @complexity Constant.
  14217. @requirement This function helps `basic_json` satisfying the
  14218. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14219. requirements:
  14220. - The complexity is constant.
  14221. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  14222. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  14223. @sa @ref begin() -- returns an iterator to the beginning
  14224. @sa @ref end() -- returns an iterator to the end
  14225. @sa @ref cend() -- returns a const iterator to the end
  14226. @since version 1.0.0
  14227. */
  14228. const_iterator cbegin() const noexcept
  14229. {
  14230. const_iterator result(this);
  14231. result.set_begin();
  14232. return result;
  14233. }
  14234. /*!
  14235. @brief returns an iterator to one past the last element
  14236. Returns an iterator to one past the last element.
  14237. @image html range-begin-end.svg "Illustration from cppreference.com"
  14238. @return iterator one past the last element
  14239. @complexity Constant.
  14240. @requirement This function helps `basic_json` satisfying the
  14241. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14242. requirements:
  14243. - The complexity is constant.
  14244. @liveexample{The following code shows an example for `end()`.,end}
  14245. @sa @ref cend() -- returns a const iterator to the end
  14246. @sa @ref begin() -- returns an iterator to the beginning
  14247. @sa @ref cbegin() -- returns a const iterator to the beginning
  14248. @since version 1.0.0
  14249. */
  14250. iterator end() noexcept
  14251. {
  14252. iterator result(this);
  14253. result.set_end();
  14254. return result;
  14255. }
  14256. /*!
  14257. @copydoc basic_json::cend()
  14258. */
  14259. const_iterator end() const noexcept
  14260. {
  14261. return cend();
  14262. }
  14263. /*!
  14264. @brief returns a const iterator to one past the last element
  14265. Returns a const iterator to one past the last element.
  14266. @image html range-begin-end.svg "Illustration from cppreference.com"
  14267. @return const iterator one past the last element
  14268. @complexity Constant.
  14269. @requirement This function helps `basic_json` satisfying the
  14270. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14271. requirements:
  14272. - The complexity is constant.
  14273. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  14274. @liveexample{The following code shows an example for `cend()`.,cend}
  14275. @sa @ref end() -- returns an iterator to the end
  14276. @sa @ref begin() -- returns an iterator to the beginning
  14277. @sa @ref cbegin() -- returns a const iterator to the beginning
  14278. @since version 1.0.0
  14279. */
  14280. const_iterator cend() const noexcept
  14281. {
  14282. const_iterator result(this);
  14283. result.set_end();
  14284. return result;
  14285. }
  14286. /*!
  14287. @brief returns an iterator to the reverse-beginning
  14288. Returns an iterator to the reverse-beginning; that is, the last element.
  14289. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  14290. @complexity Constant.
  14291. @requirement This function helps `basic_json` satisfying the
  14292. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  14293. requirements:
  14294. - The complexity is constant.
  14295. - Has the semantics of `reverse_iterator(end())`.
  14296. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  14297. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  14298. @sa @ref rend() -- returns a reverse iterator to the end
  14299. @sa @ref crend() -- returns a const reverse iterator to the end
  14300. @since version 1.0.0
  14301. */
  14302. reverse_iterator rbegin() noexcept
  14303. {
  14304. return reverse_iterator(end());
  14305. }
  14306. /*!
  14307. @copydoc basic_json::crbegin()
  14308. */
  14309. const_reverse_iterator rbegin() const noexcept
  14310. {
  14311. return crbegin();
  14312. }
  14313. /*!
  14314. @brief returns an iterator to the reverse-end
  14315. Returns an iterator to the reverse-end; that is, one before the first
  14316. element.
  14317. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  14318. @complexity Constant.
  14319. @requirement This function helps `basic_json` satisfying the
  14320. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  14321. requirements:
  14322. - The complexity is constant.
  14323. - Has the semantics of `reverse_iterator(begin())`.
  14324. @liveexample{The following code shows an example for `rend()`.,rend}
  14325. @sa @ref crend() -- returns a const reverse iterator to the end
  14326. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  14327. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  14328. @since version 1.0.0
  14329. */
  14330. reverse_iterator rend() noexcept
  14331. {
  14332. return reverse_iterator(begin());
  14333. }
  14334. /*!
  14335. @copydoc basic_json::crend()
  14336. */
  14337. const_reverse_iterator rend() const noexcept
  14338. {
  14339. return crend();
  14340. }
  14341. /*!
  14342. @brief returns a const reverse iterator to the last element
  14343. Returns a const iterator to the reverse-beginning; that is, the last
  14344. element.
  14345. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  14346. @complexity Constant.
  14347. @requirement This function helps `basic_json` satisfying the
  14348. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  14349. requirements:
  14350. - The complexity is constant.
  14351. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  14352. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  14353. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  14354. @sa @ref rend() -- returns a reverse iterator to the end
  14355. @sa @ref crend() -- returns a const reverse iterator to the end
  14356. @since version 1.0.0
  14357. */
  14358. const_reverse_iterator crbegin() const noexcept
  14359. {
  14360. return const_reverse_iterator(cend());
  14361. }
  14362. /*!
  14363. @brief returns a const reverse iterator to one before the first
  14364. Returns a const reverse iterator to the reverse-end; that is, one before
  14365. the first element.
  14366. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  14367. @complexity Constant.
  14368. @requirement This function helps `basic_json` satisfying the
  14369. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  14370. requirements:
  14371. - The complexity is constant.
  14372. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  14373. @liveexample{The following code shows an example for `crend()`.,crend}
  14374. @sa @ref rend() -- returns a reverse iterator to the end
  14375. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  14376. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  14377. @since version 1.0.0
  14378. */
  14379. const_reverse_iterator crend() const noexcept
  14380. {
  14381. return const_reverse_iterator(cbegin());
  14382. }
  14383. public:
  14384. /*!
  14385. @brief wrapper to access iterator member functions in range-based for
  14386. This function allows to access @ref iterator::key() and @ref
  14387. iterator::value() during range-based for loops. In these loops, a
  14388. reference to the JSON values is returned, so there is no access to the
  14389. underlying iterator.
  14390. For loop without iterator_wrapper:
  14391. @code{cpp}
  14392. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  14393. {
  14394. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  14395. }
  14396. @endcode
  14397. Range-based for loop without iterator proxy:
  14398. @code{cpp}
  14399. for (auto it : j_object)
  14400. {
  14401. // "it" is of type json::reference and has no key() member
  14402. std::cout << "value: " << it << '\n';
  14403. }
  14404. @endcode
  14405. Range-based for loop with iterator proxy:
  14406. @code{cpp}
  14407. for (auto it : json::iterator_wrapper(j_object))
  14408. {
  14409. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  14410. }
  14411. @endcode
  14412. @note When iterating over an array, `key()` will return the index of the
  14413. element as string (see example).
  14414. @param[in] ref reference to a JSON value
  14415. @return iteration proxy object wrapping @a ref with an interface to use in
  14416. range-based for loops
  14417. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  14418. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14419. changes in the JSON value.
  14420. @complexity Constant.
  14421. @note The name of this function is not yet final and may change in the
  14422. future.
  14423. @deprecated This stream operator is deprecated and will be removed in
  14424. future 4.0.0 of the library. Please use @ref items() instead;
  14425. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  14426. */
  14427. JSON_DEPRECATED
  14428. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  14429. {
  14430. return ref.items();
  14431. }
  14432. /*!
  14433. @copydoc iterator_wrapper(reference)
  14434. */
  14435. JSON_DEPRECATED
  14436. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  14437. {
  14438. return ref.items();
  14439. }
  14440. /*!
  14441. @brief helper to access iterator member functions in range-based for
  14442. This function allows to access @ref iterator::key() and @ref
  14443. iterator::value() during range-based for loops. In these loops, a
  14444. reference to the JSON values is returned, so there is no access to the
  14445. underlying iterator.
  14446. For loop without `items()` function:
  14447. @code{cpp}
  14448. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  14449. {
  14450. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  14451. }
  14452. @endcode
  14453. Range-based for loop without `items()` function:
  14454. @code{cpp}
  14455. for (auto it : j_object)
  14456. {
  14457. // "it" is of type json::reference and has no key() member
  14458. std::cout << "value: " << it << '\n';
  14459. }
  14460. @endcode
  14461. Range-based for loop with `items()` function:
  14462. @code{cpp}
  14463. for (auto& el : j_object.items())
  14464. {
  14465. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  14466. }
  14467. @endcode
  14468. The `items()` function also allows to use
  14469. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  14470. (C++17):
  14471. @code{cpp}
  14472. for (auto& [key, val] : j_object.items())
  14473. {
  14474. std::cout << "key: " << key << ", value:" << val << '\n';
  14475. }
  14476. @endcode
  14477. @note When iterating over an array, `key()` will return the index of the
  14478. element as string (see example). For primitive types (e.g., numbers),
  14479. `key()` returns an empty string.
  14480. @return iteration proxy object wrapping @a ref with an interface to use in
  14481. range-based for loops
  14482. @liveexample{The following code shows how the function is used.,items}
  14483. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14484. changes in the JSON value.
  14485. @complexity Constant.
  14486. @since version 3.1.0, structured bindings support since 3.5.0.
  14487. */
  14488. iteration_proxy<iterator> items() noexcept
  14489. {
  14490. return iteration_proxy<iterator>(*this);
  14491. }
  14492. /*!
  14493. @copydoc items()
  14494. */
  14495. iteration_proxy<const_iterator> items() const noexcept
  14496. {
  14497. return iteration_proxy<const_iterator>(*this);
  14498. }
  14499. /// @}
  14500. //////////////
  14501. // capacity //
  14502. //////////////
  14503. /// @name capacity
  14504. /// @{
  14505. /*!
  14506. @brief checks whether the container is empty.
  14507. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  14508. @return The return value depends on the different types and is
  14509. defined as follows:
  14510. Value type | return value
  14511. ----------- | -------------
  14512. null | `true`
  14513. boolean | `false`
  14514. string | `false`
  14515. number | `false`
  14516. object | result of function `object_t::empty()`
  14517. array | result of function `array_t::empty()`
  14518. @liveexample{The following code uses `empty()` to check if a JSON
  14519. object contains any elements.,empty}
  14520. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  14521. the Container concept; that is, their `empty()` functions have constant
  14522. complexity.
  14523. @iterators No changes.
  14524. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14525. @note This function does not return whether a string stored as JSON value
  14526. is empty - it returns whether the JSON container itself is empty which is
  14527. false in the case of a string.
  14528. @requirement This function helps `basic_json` satisfying the
  14529. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14530. requirements:
  14531. - The complexity is constant.
  14532. - Has the semantics of `begin() == end()`.
  14533. @sa @ref size() -- returns the number of elements
  14534. @since version 1.0.0
  14535. */
  14536. bool empty() const noexcept
  14537. {
  14538. switch (m_type)
  14539. {
  14540. case value_t::null:
  14541. {
  14542. // null values are empty
  14543. return true;
  14544. }
  14545. case value_t::array:
  14546. {
  14547. // delegate call to array_t::empty()
  14548. return m_value.array->empty();
  14549. }
  14550. case value_t::object:
  14551. {
  14552. // delegate call to object_t::empty()
  14553. return m_value.object->empty();
  14554. }
  14555. default:
  14556. {
  14557. // all other types are nonempty
  14558. return false;
  14559. }
  14560. }
  14561. }
  14562. /*!
  14563. @brief returns the number of elements
  14564. Returns the number of elements in a JSON value.
  14565. @return The return value depends on the different types and is
  14566. defined as follows:
  14567. Value type | return value
  14568. ----------- | -------------
  14569. null | `0`
  14570. boolean | `1`
  14571. string | `1`
  14572. number | `1`
  14573. object | result of function object_t::size()
  14574. array | result of function array_t::size()
  14575. @liveexample{The following code calls `size()` on the different value
  14576. types.,size}
  14577. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  14578. the Container concept; that is, their size() functions have constant
  14579. complexity.
  14580. @iterators No changes.
  14581. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14582. @note This function does not return the length of a string stored as JSON
  14583. value - it returns the number of elements in the JSON value which is 1 in
  14584. the case of a string.
  14585. @requirement This function helps `basic_json` satisfying the
  14586. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14587. requirements:
  14588. - The complexity is constant.
  14589. - Has the semantics of `std::distance(begin(), end())`.
  14590. @sa @ref empty() -- checks whether the container is empty
  14591. @sa @ref max_size() -- returns the maximal number of elements
  14592. @since version 1.0.0
  14593. */
  14594. size_type size() const noexcept
  14595. {
  14596. switch (m_type)
  14597. {
  14598. case value_t::null:
  14599. {
  14600. // null values are empty
  14601. return 0;
  14602. }
  14603. case value_t::array:
  14604. {
  14605. // delegate call to array_t::size()
  14606. return m_value.array->size();
  14607. }
  14608. case value_t::object:
  14609. {
  14610. // delegate call to object_t::size()
  14611. return m_value.object->size();
  14612. }
  14613. default:
  14614. {
  14615. // all other types have size 1
  14616. return 1;
  14617. }
  14618. }
  14619. }
  14620. /*!
  14621. @brief returns the maximum possible number of elements
  14622. Returns the maximum number of elements a JSON value is able to hold due to
  14623. system or library implementation limitations, i.e. `std::distance(begin(),
  14624. end())` for the JSON value.
  14625. @return The return value depends on the different types and is
  14626. defined as follows:
  14627. Value type | return value
  14628. ----------- | -------------
  14629. null | `0` (same as `size()`)
  14630. boolean | `1` (same as `size()`)
  14631. string | `1` (same as `size()`)
  14632. number | `1` (same as `size()`)
  14633. object | result of function `object_t::max_size()`
  14634. array | result of function `array_t::max_size()`
  14635. @liveexample{The following code calls `max_size()` on the different value
  14636. types. Note the output is implementation specific.,max_size}
  14637. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  14638. the Container concept; that is, their `max_size()` functions have constant
  14639. complexity.
  14640. @iterators No changes.
  14641. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14642. @requirement This function helps `basic_json` satisfying the
  14643. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14644. requirements:
  14645. - The complexity is constant.
  14646. - Has the semantics of returning `b.size()` where `b` is the largest
  14647. possible JSON value.
  14648. @sa @ref size() -- returns the number of elements
  14649. @since version 1.0.0
  14650. */
  14651. size_type max_size() const noexcept
  14652. {
  14653. switch (m_type)
  14654. {
  14655. case value_t::array:
  14656. {
  14657. // delegate call to array_t::max_size()
  14658. return m_value.array->max_size();
  14659. }
  14660. case value_t::object:
  14661. {
  14662. // delegate call to object_t::max_size()
  14663. return m_value.object->max_size();
  14664. }
  14665. default:
  14666. {
  14667. // all other types have max_size() == size()
  14668. return size();
  14669. }
  14670. }
  14671. }
  14672. /// @}
  14673. ///////////////
  14674. // modifiers //
  14675. ///////////////
  14676. /// @name modifiers
  14677. /// @{
  14678. /*!
  14679. @brief clears the contents
  14680. Clears the content of a JSON value and resets it to the default value as
  14681. if @ref basic_json(value_t) would have been called with the current value
  14682. type from @ref type():
  14683. Value type | initial value
  14684. ----------- | -------------
  14685. null | `null`
  14686. boolean | `false`
  14687. string | `""`
  14688. number | `0`
  14689. object | `{}`
  14690. array | `[]`
  14691. @post Has the same effect as calling
  14692. @code {.cpp}
  14693. *this = basic_json(type());
  14694. @endcode
  14695. @liveexample{The example below shows the effect of `clear()` to different
  14696. JSON types.,clear}
  14697. @complexity Linear in the size of the JSON value.
  14698. @iterators All iterators, pointers and references related to this container
  14699. are invalidated.
  14700. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14701. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  14702. same value than calling `clear()`
  14703. @since version 1.0.0
  14704. */
  14705. void clear() noexcept
  14706. {
  14707. switch (m_type)
  14708. {
  14709. case value_t::number_integer:
  14710. {
  14711. m_value.number_integer = 0;
  14712. break;
  14713. }
  14714. case value_t::number_unsigned:
  14715. {
  14716. m_value.number_unsigned = 0;
  14717. break;
  14718. }
  14719. case value_t::number_float:
  14720. {
  14721. m_value.number_float = 0.0;
  14722. break;
  14723. }
  14724. case value_t::boolean:
  14725. {
  14726. m_value.boolean = false;
  14727. break;
  14728. }
  14729. case value_t::string:
  14730. {
  14731. m_value.string->clear();
  14732. break;
  14733. }
  14734. case value_t::array:
  14735. {
  14736. m_value.array->clear();
  14737. break;
  14738. }
  14739. case value_t::object:
  14740. {
  14741. m_value.object->clear();
  14742. break;
  14743. }
  14744. default:
  14745. break;
  14746. }
  14747. }
  14748. /*!
  14749. @brief add an object to an array
  14750. Appends the given element @a val to the end of the JSON value. If the
  14751. function is called on a JSON null value, an empty array is created before
  14752. appending @a val.
  14753. @param[in] val the value to add to the JSON array
  14754. @throw type_error.308 when called on a type other than JSON array or
  14755. null; example: `"cannot use push_back() with number"`
  14756. @complexity Amortized constant.
  14757. @liveexample{The example shows how `push_back()` and `+=` can be used to
  14758. add elements to a JSON array. Note how the `null` value was silently
  14759. converted to a JSON array.,push_back}
  14760. @since version 1.0.0
  14761. */
  14762. void push_back(basic_json&& val)
  14763. {
  14764. // push_back only works for null objects or arrays
  14765. if (JSON_UNLIKELY(not(is_null() or is_array())))
  14766. {
  14767. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  14768. }
  14769. // transform null object into an array
  14770. if (is_null())
  14771. {
  14772. m_type = value_t::array;
  14773. m_value = value_t::array;
  14774. assert_invariant();
  14775. }
  14776. // add element to array (move semantics)
  14777. m_value.array->push_back(std::move(val));
  14778. // invalidate object: mark it null so we do not call the destructor
  14779. // cppcheck-suppress accessMoved
  14780. val.m_type = value_t::null;
  14781. }
  14782. /*!
  14783. @brief add an object to an array
  14784. @copydoc push_back(basic_json&&)
  14785. */
  14786. reference operator+=(basic_json&& val)
  14787. {
  14788. push_back(std::move(val));
  14789. return *this;
  14790. }
  14791. /*!
  14792. @brief add an object to an array
  14793. @copydoc push_back(basic_json&&)
  14794. */
  14795. void push_back(const basic_json& val)
  14796. {
  14797. // push_back only works for null objects or arrays
  14798. if (JSON_UNLIKELY(not(is_null() or is_array())))
  14799. {
  14800. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  14801. }
  14802. // transform null object into an array
  14803. if (is_null())
  14804. {
  14805. m_type = value_t::array;
  14806. m_value = value_t::array;
  14807. assert_invariant();
  14808. }
  14809. // add element to array
  14810. m_value.array->push_back(val);
  14811. }
  14812. /*!
  14813. @brief add an object to an array
  14814. @copydoc push_back(basic_json&&)
  14815. */
  14816. reference operator+=(const basic_json& val)
  14817. {
  14818. push_back(val);
  14819. return *this;
  14820. }
  14821. /*!
  14822. @brief add an object to an object
  14823. Inserts the given element @a val to the JSON object. If the function is
  14824. called on a JSON null value, an empty object is created before inserting
  14825. @a val.
  14826. @param[in] val the value to add to the JSON object
  14827. @throw type_error.308 when called on a type other than JSON object or
  14828. null; example: `"cannot use push_back() with number"`
  14829. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  14830. @liveexample{The example shows how `push_back()` and `+=` can be used to
  14831. add elements to a JSON object. Note how the `null` value was silently
  14832. converted to a JSON object.,push_back__object_t__value}
  14833. @since version 1.0.0
  14834. */
  14835. void push_back(const typename object_t::value_type& val)
  14836. {
  14837. // push_back only works for null objects or objects
  14838. if (JSON_UNLIKELY(not(is_null() or is_object())))
  14839. {
  14840. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  14841. }
  14842. // transform null object into an object
  14843. if (is_null())
  14844. {
  14845. m_type = value_t::object;
  14846. m_value = value_t::object;
  14847. assert_invariant();
  14848. }
  14849. // add element to array
  14850. m_value.object->insert(val);
  14851. }
  14852. /*!
  14853. @brief add an object to an object
  14854. @copydoc push_back(const typename object_t::value_type&)
  14855. */
  14856. reference operator+=(const typename object_t::value_type& val)
  14857. {
  14858. push_back(val);
  14859. return *this;
  14860. }
  14861. /*!
  14862. @brief add an object to an object
  14863. This function allows to use `push_back` with an initializer list. In case
  14864. 1. the current value is an object,
  14865. 2. the initializer list @a init contains only two elements, and
  14866. 3. the first element of @a init is a string,
  14867. @a init is converted into an object element and added using
  14868. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  14869. is converted to a JSON value and added using @ref push_back(basic_json&&).
  14870. @param[in] init an initializer list
  14871. @complexity Linear in the size of the initializer list @a init.
  14872. @note This function is required to resolve an ambiguous overload error,
  14873. because pairs like `{"key", "value"}` can be both interpreted as
  14874. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  14875. https://github.com/nlohmann/json/issues/235 for more information.
  14876. @liveexample{The example shows how initializer lists are treated as
  14877. objects when possible.,push_back__initializer_list}
  14878. */
  14879. void push_back(initializer_list_t init)
  14880. {
  14881. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  14882. {
  14883. basic_json&& key = init.begin()->moved_or_copied();
  14884. push_back(typename object_t::value_type(
  14885. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  14886. }
  14887. else
  14888. {
  14889. push_back(basic_json(init));
  14890. }
  14891. }
  14892. /*!
  14893. @brief add an object to an object
  14894. @copydoc push_back(initializer_list_t)
  14895. */
  14896. reference operator+=(initializer_list_t init)
  14897. {
  14898. push_back(init);
  14899. return *this;
  14900. }
  14901. /*!
  14902. @brief add an object to an array
  14903. Creates a JSON value from the passed parameters @a args to the end of the
  14904. JSON value. If the function is called on a JSON null value, an empty array
  14905. is created before appending the value created from @a args.
  14906. @param[in] args arguments to forward to a constructor of @ref basic_json
  14907. @tparam Args compatible types to create a @ref basic_json object
  14908. @throw type_error.311 when called on a type other than JSON array or
  14909. null; example: `"cannot use emplace_back() with number"`
  14910. @complexity Amortized constant.
  14911. @liveexample{The example shows how `push_back()` can be used to add
  14912. elements to a JSON array. Note how the `null` value was silently converted
  14913. to a JSON array.,emplace_back}
  14914. @since version 2.0.8
  14915. */
  14916. template<class... Args>
  14917. void emplace_back(Args&& ... args)
  14918. {
  14919. // emplace_back only works for null objects or arrays
  14920. if (JSON_UNLIKELY(not(is_null() or is_array())))
  14921. {
  14922. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  14923. }
  14924. // transform null object into an array
  14925. if (is_null())
  14926. {
  14927. m_type = value_t::array;
  14928. m_value = value_t::array;
  14929. assert_invariant();
  14930. }
  14931. // add element to array (perfect forwarding)
  14932. m_value.array->emplace_back(std::forward<Args>(args)...);
  14933. }
  14934. /*!
  14935. @brief add an object to an object if key does not exist
  14936. Inserts a new element into a JSON object constructed in-place with the
  14937. given @a args if there is no element with the key in the container. If the
  14938. function is called on a JSON null value, an empty object is created before
  14939. appending the value created from @a args.
  14940. @param[in] args arguments to forward to a constructor of @ref basic_json
  14941. @tparam Args compatible types to create a @ref basic_json object
  14942. @return a pair consisting of an iterator to the inserted element, or the
  14943. already-existing element if no insertion happened, and a bool
  14944. denoting whether the insertion took place.
  14945. @throw type_error.311 when called on a type other than JSON object or
  14946. null; example: `"cannot use emplace() with number"`
  14947. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  14948. @liveexample{The example shows how `emplace()` can be used to add elements
  14949. to a JSON object. Note how the `null` value was silently converted to a
  14950. JSON object. Further note how no value is added if there was already one
  14951. value stored with the same key.,emplace}
  14952. @since version 2.0.8
  14953. */
  14954. template<class... Args>
  14955. std::pair<iterator, bool> emplace(Args&& ... args)
  14956. {
  14957. // emplace only works for null objects or arrays
  14958. if (JSON_UNLIKELY(not(is_null() or is_object())))
  14959. {
  14960. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  14961. }
  14962. // transform null object into an object
  14963. if (is_null())
  14964. {
  14965. m_type = value_t::object;
  14966. m_value = value_t::object;
  14967. assert_invariant();
  14968. }
  14969. // add element to array (perfect forwarding)
  14970. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  14971. // create result iterator and set iterator to the result of emplace
  14972. auto it = begin();
  14973. it.m_it.object_iterator = res.first;
  14974. // return pair of iterator and boolean
  14975. return {it, res.second};
  14976. }
  14977. /// Helper for insertion of an iterator
  14978. /// @note: This uses std::distance to support GCC 4.8,
  14979. /// see https://github.com/nlohmann/json/pull/1257
  14980. template<typename... Args>
  14981. iterator insert_iterator(const_iterator pos, Args&& ... args)
  14982. {
  14983. iterator result(this);
  14984. assert(m_value.array != nullptr);
  14985. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  14986. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  14987. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  14988. // This could have been written as:
  14989. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  14990. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  14991. return result;
  14992. }
  14993. /*!
  14994. @brief inserts element
  14995. Inserts element @a val before iterator @a pos.
  14996. @param[in] pos iterator before which the content will be inserted; may be
  14997. the end() iterator
  14998. @param[in] val element to insert
  14999. @return iterator pointing to the inserted @a val.
  15000. @throw type_error.309 if called on JSON values other than arrays;
  15001. example: `"cannot use insert() with string"`
  15002. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  15003. example: `"iterator does not fit current value"`
  15004. @complexity Constant plus linear in the distance between @a pos and end of
  15005. the container.
  15006. @liveexample{The example shows how `insert()` is used.,insert}
  15007. @since version 1.0.0
  15008. */
  15009. iterator insert(const_iterator pos, const basic_json& val)
  15010. {
  15011. // insert only works for arrays
  15012. if (JSON_LIKELY(is_array()))
  15013. {
  15014. // check if iterator pos fits to this JSON value
  15015. if (JSON_UNLIKELY(pos.m_object != this))
  15016. {
  15017. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  15018. }
  15019. // insert to array and return iterator
  15020. return insert_iterator(pos, val);
  15021. }
  15022. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  15023. }
  15024. /*!
  15025. @brief inserts element
  15026. @copydoc insert(const_iterator, const basic_json&)
  15027. */
  15028. iterator insert(const_iterator pos, basic_json&& val)
  15029. {
  15030. return insert(pos, val);
  15031. }
  15032. /*!
  15033. @brief inserts elements
  15034. Inserts @a cnt copies of @a val before iterator @a pos.
  15035. @param[in] pos iterator before which the content will be inserted; may be
  15036. the end() iterator
  15037. @param[in] cnt number of copies of @a val to insert
  15038. @param[in] val element to insert
  15039. @return iterator pointing to the first element inserted, or @a pos if
  15040. `cnt==0`
  15041. @throw type_error.309 if called on JSON values other than arrays; example:
  15042. `"cannot use insert() with string"`
  15043. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  15044. example: `"iterator does not fit current value"`
  15045. @complexity Linear in @a cnt plus linear in the distance between @a pos
  15046. and end of the container.
  15047. @liveexample{The example shows how `insert()` is used.,insert__count}
  15048. @since version 1.0.0
  15049. */
  15050. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  15051. {
  15052. // insert only works for arrays
  15053. if (JSON_LIKELY(is_array()))
  15054. {
  15055. // check if iterator pos fits to this JSON value
  15056. if (JSON_UNLIKELY(pos.m_object != this))
  15057. {
  15058. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  15059. }
  15060. // insert to array and return iterator
  15061. return insert_iterator(pos, cnt, val);
  15062. }
  15063. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  15064. }
  15065. /*!
  15066. @brief inserts elements
  15067. Inserts elements from range `[first, last)` before iterator @a pos.
  15068. @param[in] pos iterator before which the content will be inserted; may be
  15069. the end() iterator
  15070. @param[in] first begin of the range of elements to insert
  15071. @param[in] last end of the range of elements to insert
  15072. @throw type_error.309 if called on JSON values other than arrays; example:
  15073. `"cannot use insert() with string"`
  15074. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  15075. example: `"iterator does not fit current value"`
  15076. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  15077. same JSON value; example: `"iterators do not fit"`
  15078. @throw invalid_iterator.211 if @a first or @a last are iterators into
  15079. container for which insert is called; example: `"passed iterators may not
  15080. belong to container"`
  15081. @return iterator pointing to the first element inserted, or @a pos if
  15082. `first==last`
  15083. @complexity Linear in `std::distance(first, last)` plus linear in the
  15084. distance between @a pos and end of the container.
  15085. @liveexample{The example shows how `insert()` is used.,insert__range}
  15086. @since version 1.0.0
  15087. */
  15088. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  15089. {
  15090. // insert only works for arrays
  15091. if (JSON_UNLIKELY(not is_array()))
  15092. {
  15093. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  15094. }
  15095. // check if iterator pos fits to this JSON value
  15096. if (JSON_UNLIKELY(pos.m_object != this))
  15097. {
  15098. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  15099. }
  15100. // check if range iterators belong to the same JSON object
  15101. if (JSON_UNLIKELY(first.m_object != last.m_object))
  15102. {
  15103. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  15104. }
  15105. if (JSON_UNLIKELY(first.m_object == this))
  15106. {
  15107. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  15108. }
  15109. // insert to array and return iterator
  15110. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  15111. }
  15112. /*!
  15113. @brief inserts elements
  15114. Inserts elements from initializer list @a ilist before iterator @a pos.
  15115. @param[in] pos iterator before which the content will be inserted; may be
  15116. the end() iterator
  15117. @param[in] ilist initializer list to insert the values from
  15118. @throw type_error.309 if called on JSON values other than arrays; example:
  15119. `"cannot use insert() with string"`
  15120. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  15121. example: `"iterator does not fit current value"`
  15122. @return iterator pointing to the first element inserted, or @a pos if
  15123. `ilist` is empty
  15124. @complexity Linear in `ilist.size()` plus linear in the distance between
  15125. @a pos and end of the container.
  15126. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  15127. @since version 1.0.0
  15128. */
  15129. iterator insert(const_iterator pos, initializer_list_t ilist)
  15130. {
  15131. // insert only works for arrays
  15132. if (JSON_UNLIKELY(not is_array()))
  15133. {
  15134. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  15135. }
  15136. // check if iterator pos fits to this JSON value
  15137. if (JSON_UNLIKELY(pos.m_object != this))
  15138. {
  15139. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  15140. }
  15141. // insert to array and return iterator
  15142. return insert_iterator(pos, ilist.begin(), ilist.end());
  15143. }
  15144. /*!
  15145. @brief inserts elements
  15146. Inserts elements from range `[first, last)`.
  15147. @param[in] first begin of the range of elements to insert
  15148. @param[in] last end of the range of elements to insert
  15149. @throw type_error.309 if called on JSON values other than objects; example:
  15150. `"cannot use insert() with string"`
  15151. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  15152. point to an object; example: `"iterators first and last must point to
  15153. objects"`
  15154. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  15155. same JSON value; example: `"iterators do not fit"`
  15156. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  15157. of elements to insert.
  15158. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  15159. @since version 3.0.0
  15160. */
  15161. void insert(const_iterator first, const_iterator last)
  15162. {
  15163. // insert only works for objects
  15164. if (JSON_UNLIKELY(not is_object()))
  15165. {
  15166. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  15167. }
  15168. // check if range iterators belong to the same JSON object
  15169. if (JSON_UNLIKELY(first.m_object != last.m_object))
  15170. {
  15171. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  15172. }
  15173. // passed iterators must belong to objects
  15174. if (JSON_UNLIKELY(not first.m_object->is_object()))
  15175. {
  15176. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  15177. }
  15178. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  15179. }
  15180. /*!
  15181. @brief updates a JSON object from another object, overwriting existing keys
  15182. Inserts all values from JSON object @a j and overwrites existing keys.
  15183. @param[in] j JSON object to read values from
  15184. @throw type_error.312 if called on JSON values other than objects; example:
  15185. `"cannot use update() with string"`
  15186. @complexity O(N*log(size() + N)), where N is the number of elements to
  15187. insert.
  15188. @liveexample{The example shows how `update()` is used.,update}
  15189. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  15190. @since version 3.0.0
  15191. */
  15192. void update(const_reference j)
  15193. {
  15194. // implicitly convert null value to an empty object
  15195. if (is_null())
  15196. {
  15197. m_type = value_t::object;
  15198. m_value.object = create<object_t>();
  15199. assert_invariant();
  15200. }
  15201. if (JSON_UNLIKELY(not is_object()))
  15202. {
  15203. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  15204. }
  15205. if (JSON_UNLIKELY(not j.is_object()))
  15206. {
  15207. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  15208. }
  15209. for (auto it = j.cbegin(); it != j.cend(); ++it)
  15210. {
  15211. m_value.object->operator[](it.key()) = it.value();
  15212. }
  15213. }
  15214. /*!
  15215. @brief updates a JSON object from another object, overwriting existing keys
  15216. Inserts all values from from range `[first, last)` and overwrites existing
  15217. keys.
  15218. @param[in] first begin of the range of elements to insert
  15219. @param[in] last end of the range of elements to insert
  15220. @throw type_error.312 if called on JSON values other than objects; example:
  15221. `"cannot use update() with string"`
  15222. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  15223. point to an object; example: `"iterators first and last must point to
  15224. objects"`
  15225. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  15226. same JSON value; example: `"iterators do not fit"`
  15227. @complexity O(N*log(size() + N)), where N is the number of elements to
  15228. insert.
  15229. @liveexample{The example shows how `update()` is used__range.,update}
  15230. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  15231. @since version 3.0.0
  15232. */
  15233. void update(const_iterator first, const_iterator last)
  15234. {
  15235. // implicitly convert null value to an empty object
  15236. if (is_null())
  15237. {
  15238. m_type = value_t::object;
  15239. m_value.object = create<object_t>();
  15240. assert_invariant();
  15241. }
  15242. if (JSON_UNLIKELY(not is_object()))
  15243. {
  15244. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  15245. }
  15246. // check if range iterators belong to the same JSON object
  15247. if (JSON_UNLIKELY(first.m_object != last.m_object))
  15248. {
  15249. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  15250. }
  15251. // passed iterators must belong to objects
  15252. if (JSON_UNLIKELY(not first.m_object->is_object()
  15253. or not last.m_object->is_object()))
  15254. {
  15255. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  15256. }
  15257. for (auto it = first; it != last; ++it)
  15258. {
  15259. m_value.object->operator[](it.key()) = it.value();
  15260. }
  15261. }
  15262. /*!
  15263. @brief exchanges the values
  15264. Exchanges the contents of the JSON value with those of @a other. Does not
  15265. invoke any move, copy, or swap operations on individual elements. All
  15266. iterators and references remain valid. The past-the-end iterator is
  15267. invalidated.
  15268. @param[in,out] other JSON value to exchange the contents with
  15269. @complexity Constant.
  15270. @liveexample{The example below shows how JSON values can be swapped with
  15271. `swap()`.,swap__reference}
  15272. @since version 1.0.0
  15273. */
  15274. void swap(reference other) noexcept (
  15275. std::is_nothrow_move_constructible<value_t>::value and
  15276. std::is_nothrow_move_assignable<value_t>::value and
  15277. std::is_nothrow_move_constructible<json_value>::value and
  15278. std::is_nothrow_move_assignable<json_value>::value
  15279. )
  15280. {
  15281. std::swap(m_type, other.m_type);
  15282. std::swap(m_value, other.m_value);
  15283. assert_invariant();
  15284. }
  15285. /*!
  15286. @brief exchanges the values
  15287. Exchanges the contents of a JSON array with those of @a other. Does not
  15288. invoke any move, copy, or swap operations on individual elements. All
  15289. iterators and references remain valid. The past-the-end iterator is
  15290. invalidated.
  15291. @param[in,out] other array to exchange the contents with
  15292. @throw type_error.310 when JSON value is not an array; example: `"cannot
  15293. use swap() with string"`
  15294. @complexity Constant.
  15295. @liveexample{The example below shows how arrays can be swapped with
  15296. `swap()`.,swap__array_t}
  15297. @since version 1.0.0
  15298. */
  15299. void swap(array_t& other)
  15300. {
  15301. // swap only works for arrays
  15302. if (JSON_LIKELY(is_array()))
  15303. {
  15304. std::swap(*(m_value.array), other);
  15305. }
  15306. else
  15307. {
  15308. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  15309. }
  15310. }
  15311. /*!
  15312. @brief exchanges the values
  15313. Exchanges the contents of a JSON object with those of @a other. Does not
  15314. invoke any move, copy, or swap operations on individual elements. All
  15315. iterators and references remain valid. The past-the-end iterator is
  15316. invalidated.
  15317. @param[in,out] other object to exchange the contents with
  15318. @throw type_error.310 when JSON value is not an object; example:
  15319. `"cannot use swap() with string"`
  15320. @complexity Constant.
  15321. @liveexample{The example below shows how objects can be swapped with
  15322. `swap()`.,swap__object_t}
  15323. @since version 1.0.0
  15324. */
  15325. void swap(object_t& other)
  15326. {
  15327. // swap only works for objects
  15328. if (JSON_LIKELY(is_object()))
  15329. {
  15330. std::swap(*(m_value.object), other);
  15331. }
  15332. else
  15333. {
  15334. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  15335. }
  15336. }
  15337. /*!
  15338. @brief exchanges the values
  15339. Exchanges the contents of a JSON string with those of @a other. Does not
  15340. invoke any move, copy, or swap operations on individual elements. All
  15341. iterators and references remain valid. The past-the-end iterator is
  15342. invalidated.
  15343. @param[in,out] other string to exchange the contents with
  15344. @throw type_error.310 when JSON value is not a string; example: `"cannot
  15345. use swap() with boolean"`
  15346. @complexity Constant.
  15347. @liveexample{The example below shows how strings can be swapped with
  15348. `swap()`.,swap__string_t}
  15349. @since version 1.0.0
  15350. */
  15351. void swap(string_t& other)
  15352. {
  15353. // swap only works for strings
  15354. if (JSON_LIKELY(is_string()))
  15355. {
  15356. std::swap(*(m_value.string), other);
  15357. }
  15358. else
  15359. {
  15360. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  15361. }
  15362. }
  15363. /// @}
  15364. public:
  15365. //////////////////////////////////////////
  15366. // lexicographical comparison operators //
  15367. //////////////////////////////////////////
  15368. /// @name lexicographical comparison operators
  15369. /// @{
  15370. /*!
  15371. @brief comparison: equal
  15372. Compares two JSON values for equality according to the following rules:
  15373. - Two JSON values are equal if (1) they are from the same type and (2)
  15374. their stored values are the same according to their respective
  15375. `operator==`.
  15376. - Integer and floating-point numbers are automatically converted before
  15377. comparison. Note than two NaN values are always treated as unequal.
  15378. - Two JSON null values are equal.
  15379. @note Floating-point inside JSON values numbers are compared with
  15380. `json::number_float_t::operator==` which is `double::operator==` by
  15381. default. To compare floating-point while respecting an epsilon, an alternative
  15382. [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
  15383. could be used, for instance
  15384. @code {.cpp}
  15385. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  15386. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  15387. {
  15388. return std::abs(a - b) <= epsilon;
  15389. }
  15390. @endcode
  15391. @note NaN values never compare equal to themselves or to other NaN values.
  15392. @param[in] lhs first JSON value to consider
  15393. @param[in] rhs second JSON value to consider
  15394. @return whether the values @a lhs and @a rhs are equal
  15395. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15396. @complexity Linear.
  15397. @liveexample{The example demonstrates comparing several JSON
  15398. types.,operator__equal}
  15399. @since version 1.0.0
  15400. */
  15401. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  15402. {
  15403. const auto lhs_type = lhs.type();
  15404. const auto rhs_type = rhs.type();
  15405. if (lhs_type == rhs_type)
  15406. {
  15407. switch (lhs_type)
  15408. {
  15409. case value_t::array:
  15410. return *lhs.m_value.array == *rhs.m_value.array;
  15411. case value_t::object:
  15412. return *lhs.m_value.object == *rhs.m_value.object;
  15413. case value_t::null:
  15414. return true;
  15415. case value_t::string:
  15416. return *lhs.m_value.string == *rhs.m_value.string;
  15417. case value_t::boolean:
  15418. return lhs.m_value.boolean == rhs.m_value.boolean;
  15419. case value_t::number_integer:
  15420. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  15421. case value_t::number_unsigned:
  15422. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  15423. case value_t::number_float:
  15424. return lhs.m_value.number_float == rhs.m_value.number_float;
  15425. default:
  15426. return false;
  15427. }
  15428. }
  15429. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  15430. {
  15431. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  15432. }
  15433. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  15434. {
  15435. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  15436. }
  15437. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  15438. {
  15439. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  15440. }
  15441. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  15442. {
  15443. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  15444. }
  15445. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  15446. {
  15447. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  15448. }
  15449. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  15450. {
  15451. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  15452. }
  15453. return false;
  15454. }
  15455. /*!
  15456. @brief comparison: equal
  15457. @copydoc operator==(const_reference, const_reference)
  15458. */
  15459. template<typename ScalarType, typename std::enable_if<
  15460. std::is_scalar<ScalarType>::value, int>::type = 0>
  15461. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  15462. {
  15463. return lhs == basic_json(rhs);
  15464. }
  15465. /*!
  15466. @brief comparison: equal
  15467. @copydoc operator==(const_reference, const_reference)
  15468. */
  15469. template<typename ScalarType, typename std::enable_if<
  15470. std::is_scalar<ScalarType>::value, int>::type = 0>
  15471. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  15472. {
  15473. return basic_json(lhs) == rhs;
  15474. }
  15475. /*!
  15476. @brief comparison: not equal
  15477. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  15478. @param[in] lhs first JSON value to consider
  15479. @param[in] rhs second JSON value to consider
  15480. @return whether the values @a lhs and @a rhs are not equal
  15481. @complexity Linear.
  15482. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15483. @liveexample{The example demonstrates comparing several JSON
  15484. types.,operator__notequal}
  15485. @since version 1.0.0
  15486. */
  15487. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  15488. {
  15489. return not (lhs == rhs);
  15490. }
  15491. /*!
  15492. @brief comparison: not equal
  15493. @copydoc operator!=(const_reference, const_reference)
  15494. */
  15495. template<typename ScalarType, typename std::enable_if<
  15496. std::is_scalar<ScalarType>::value, int>::type = 0>
  15497. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  15498. {
  15499. return lhs != basic_json(rhs);
  15500. }
  15501. /*!
  15502. @brief comparison: not equal
  15503. @copydoc operator!=(const_reference, const_reference)
  15504. */
  15505. template<typename ScalarType, typename std::enable_if<
  15506. std::is_scalar<ScalarType>::value, int>::type = 0>
  15507. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  15508. {
  15509. return basic_json(lhs) != rhs;
  15510. }
  15511. /*!
  15512. @brief comparison: less than
  15513. Compares whether one JSON value @a lhs is less than another JSON value @a
  15514. rhs according to the following rules:
  15515. - If @a lhs and @a rhs have the same type, the values are compared using
  15516. the default `<` operator.
  15517. - Integer and floating-point numbers are automatically converted before
  15518. comparison
  15519. - In case @a lhs and @a rhs have different types, the values are ignored
  15520. and the order of the types is considered, see
  15521. @ref operator<(const value_t, const value_t).
  15522. @param[in] lhs first JSON value to consider
  15523. @param[in] rhs second JSON value to consider
  15524. @return whether @a lhs is less than @a rhs
  15525. @complexity Linear.
  15526. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15527. @liveexample{The example demonstrates comparing several JSON
  15528. types.,operator__less}
  15529. @since version 1.0.0
  15530. */
  15531. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  15532. {
  15533. const auto lhs_type = lhs.type();
  15534. const auto rhs_type = rhs.type();
  15535. if (lhs_type == rhs_type)
  15536. {
  15537. switch (lhs_type)
  15538. {
  15539. case value_t::array:
  15540. // note parentheses are necessary, see
  15541. // https://github.com/nlohmann/json/issues/1530
  15542. return (*lhs.m_value.array) < (*rhs.m_value.array);
  15543. case value_t::object:
  15544. return *lhs.m_value.object < *rhs.m_value.object;
  15545. case value_t::null:
  15546. return false;
  15547. case value_t::string:
  15548. return *lhs.m_value.string < *rhs.m_value.string;
  15549. case value_t::boolean:
  15550. return lhs.m_value.boolean < rhs.m_value.boolean;
  15551. case value_t::number_integer:
  15552. return lhs.m_value.number_integer < rhs.m_value.number_integer;
  15553. case value_t::number_unsigned:
  15554. return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
  15555. case value_t::number_float:
  15556. return lhs.m_value.number_float < rhs.m_value.number_float;
  15557. default:
  15558. return false;
  15559. }
  15560. }
  15561. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  15562. {
  15563. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  15564. }
  15565. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  15566. {
  15567. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  15568. }
  15569. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  15570. {
  15571. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  15572. }
  15573. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  15574. {
  15575. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  15576. }
  15577. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  15578. {
  15579. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  15580. }
  15581. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  15582. {
  15583. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  15584. }
  15585. // We only reach this line if we cannot compare values. In that case,
  15586. // we compare types. Note we have to call the operator explicitly,
  15587. // because MSVC has problems otherwise.
  15588. return operator<(lhs_type, rhs_type);
  15589. }
  15590. /*!
  15591. @brief comparison: less than
  15592. @copydoc operator<(const_reference, const_reference)
  15593. */
  15594. template<typename ScalarType, typename std::enable_if<
  15595. std::is_scalar<ScalarType>::value, int>::type = 0>
  15596. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  15597. {
  15598. return lhs < basic_json(rhs);
  15599. }
  15600. /*!
  15601. @brief comparison: less than
  15602. @copydoc operator<(const_reference, const_reference)
  15603. */
  15604. template<typename ScalarType, typename std::enable_if<
  15605. std::is_scalar<ScalarType>::value, int>::type = 0>
  15606. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  15607. {
  15608. return basic_json(lhs) < rhs;
  15609. }
  15610. /*!
  15611. @brief comparison: less than or equal
  15612. Compares whether one JSON value @a lhs is less than or equal to another
  15613. JSON value by calculating `not (rhs < lhs)`.
  15614. @param[in] lhs first JSON value to consider
  15615. @param[in] rhs second JSON value to consider
  15616. @return whether @a lhs is less than or equal to @a rhs
  15617. @complexity Linear.
  15618. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15619. @liveexample{The example demonstrates comparing several JSON
  15620. types.,operator__greater}
  15621. @since version 1.0.0
  15622. */
  15623. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  15624. {
  15625. return not (rhs < lhs);
  15626. }
  15627. /*!
  15628. @brief comparison: less than or equal
  15629. @copydoc operator<=(const_reference, const_reference)
  15630. */
  15631. template<typename ScalarType, typename std::enable_if<
  15632. std::is_scalar<ScalarType>::value, int>::type = 0>
  15633. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  15634. {
  15635. return lhs <= basic_json(rhs);
  15636. }
  15637. /*!
  15638. @brief comparison: less than or equal
  15639. @copydoc operator<=(const_reference, const_reference)
  15640. */
  15641. template<typename ScalarType, typename std::enable_if<
  15642. std::is_scalar<ScalarType>::value, int>::type = 0>
  15643. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  15644. {
  15645. return basic_json(lhs) <= rhs;
  15646. }
  15647. /*!
  15648. @brief comparison: greater than
  15649. Compares whether one JSON value @a lhs is greater than another
  15650. JSON value by calculating `not (lhs <= rhs)`.
  15651. @param[in] lhs first JSON value to consider
  15652. @param[in] rhs second JSON value to consider
  15653. @return whether @a lhs is greater than to @a rhs
  15654. @complexity Linear.
  15655. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15656. @liveexample{The example demonstrates comparing several JSON
  15657. types.,operator__lessequal}
  15658. @since version 1.0.0
  15659. */
  15660. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  15661. {
  15662. return not (lhs <= rhs);
  15663. }
  15664. /*!
  15665. @brief comparison: greater than
  15666. @copydoc operator>(const_reference, const_reference)
  15667. */
  15668. template<typename ScalarType, typename std::enable_if<
  15669. std::is_scalar<ScalarType>::value, int>::type = 0>
  15670. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  15671. {
  15672. return lhs > basic_json(rhs);
  15673. }
  15674. /*!
  15675. @brief comparison: greater than
  15676. @copydoc operator>(const_reference, const_reference)
  15677. */
  15678. template<typename ScalarType, typename std::enable_if<
  15679. std::is_scalar<ScalarType>::value, int>::type = 0>
  15680. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  15681. {
  15682. return basic_json(lhs) > rhs;
  15683. }
  15684. /*!
  15685. @brief comparison: greater than or equal
  15686. Compares whether one JSON value @a lhs is greater than or equal to another
  15687. JSON value by calculating `not (lhs < rhs)`.
  15688. @param[in] lhs first JSON value to consider
  15689. @param[in] rhs second JSON value to consider
  15690. @return whether @a lhs is greater than or equal to @a rhs
  15691. @complexity Linear.
  15692. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15693. @liveexample{The example demonstrates comparing several JSON
  15694. types.,operator__greaterequal}
  15695. @since version 1.0.0
  15696. */
  15697. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  15698. {
  15699. return not (lhs < rhs);
  15700. }
  15701. /*!
  15702. @brief comparison: greater than or equal
  15703. @copydoc operator>=(const_reference, const_reference)
  15704. */
  15705. template<typename ScalarType, typename std::enable_if<
  15706. std::is_scalar<ScalarType>::value, int>::type = 0>
  15707. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  15708. {
  15709. return lhs >= basic_json(rhs);
  15710. }
  15711. /*!
  15712. @brief comparison: greater than or equal
  15713. @copydoc operator>=(const_reference, const_reference)
  15714. */
  15715. template<typename ScalarType, typename std::enable_if<
  15716. std::is_scalar<ScalarType>::value, int>::type = 0>
  15717. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  15718. {
  15719. return basic_json(lhs) >= rhs;
  15720. }
  15721. /// @}
  15722. ///////////////////
  15723. // serialization //
  15724. ///////////////////
  15725. /// @name serialization
  15726. /// @{
  15727. /*!
  15728. @brief serialize to stream
  15729. Serialize the given JSON value @a j to the output stream @a o. The JSON
  15730. value will be serialized using the @ref dump member function.
  15731. - The indentation of the output can be controlled with the member variable
  15732. `width` of the output stream @a o. For instance, using the manipulator
  15733. `std::setw(4)` on @a o sets the indentation level to `4` and the
  15734. serialization result is the same as calling `dump(4)`.
  15735. - The indentation character can be controlled with the member variable
  15736. `fill` of the output stream @a o. For instance, the manipulator
  15737. `std::setfill('\\t')` sets indentation to use a tab character rather than
  15738. the default space character.
  15739. @param[in,out] o stream to serialize to
  15740. @param[in] j JSON value to serialize
  15741. @return the stream @a o
  15742. @throw type_error.316 if a string stored inside the JSON value is not
  15743. UTF-8 encoded
  15744. @complexity Linear.
  15745. @liveexample{The example below shows the serialization with different
  15746. parameters to `width` to adjust the indentation level.,operator_serialize}
  15747. @since version 1.0.0; indentation character added in version 3.0.0
  15748. */
  15749. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  15750. {
  15751. // read width member and use it as indentation parameter if nonzero
  15752. const bool pretty_print = o.width() > 0;
  15753. const auto indentation = pretty_print ? o.width() : 0;
  15754. // reset width to 0 for subsequent calls to this stream
  15755. o.width(0);
  15756. // do the actual serialization
  15757. serializer s(detail::output_adapter<char>(o), o.fill());
  15758. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  15759. return o;
  15760. }
  15761. /*!
  15762. @brief serialize to stream
  15763. @deprecated This stream operator is deprecated and will be removed in
  15764. future 4.0.0 of the library. Please use
  15765. @ref operator<<(std::ostream&, const basic_json&)
  15766. instead; that is, replace calls like `j >> o;` with `o << j;`.
  15767. @since version 1.0.0; deprecated since version 3.0.0
  15768. */
  15769. JSON_DEPRECATED
  15770. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  15771. {
  15772. return o << j;
  15773. }
  15774. /// @}
  15775. /////////////////////
  15776. // deserialization //
  15777. /////////////////////
  15778. /// @name deserialization
  15779. /// @{
  15780. /*!
  15781. @brief deserialize from a compatible input
  15782. This function reads from a compatible input. Examples are:
  15783. - an array of 1-byte values
  15784. - strings with character/literal type with size of 1 byte
  15785. - input streams
  15786. - container with contiguous storage of 1-byte values. Compatible container
  15787. types include `std::vector`, `std::string`, `std::array`,
  15788. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  15789. arrays can be used with `std::begin()`/`std::end()`. User-defined
  15790. containers can be used as long as they implement random-access iterators
  15791. and a contiguous storage.
  15792. @pre Each element of the container has a size of 1 byte. Violating this
  15793. precondition yields undefined behavior. **This precondition is enforced
  15794. with a static assertion.**
  15795. @pre The container storage is contiguous. Violating this precondition
  15796. yields undefined behavior. **This precondition is enforced with an
  15797. assertion.**
  15798. @warning There is no way to enforce all preconditions at compile-time. If
  15799. the function is called with a noncompliant container and with
  15800. assertions switched off, the behavior is undefined and will most
  15801. likely yield segmentation violation.
  15802. @param[in] i input to read from
  15803. @param[in] cb a parser callback function of type @ref parser_callback_t
  15804. which is used to control the deserialization by filtering unwanted values
  15805. (optional)
  15806. @param[in] allow_exceptions whether to throw exceptions in case of a
  15807. parse error (optional, true by default)
  15808. @return deserialized JSON value; in case of a parse error and
  15809. @a allow_exceptions set to `false`, the return value will be
  15810. value_t::discarded.
  15811. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  15812. of input; expected string literal""`
  15813. @throw parse_error.102 if to_unicode fails or surrogate error
  15814. @throw parse_error.103 if to_unicode fails
  15815. @complexity Linear in the length of the input. The parser is a predictive
  15816. LL(1) parser. The complexity can be higher if the parser callback function
  15817. @a cb has a super-linear complexity.
  15818. @note A UTF-8 byte order mark is silently ignored.
  15819. @liveexample{The example below demonstrates the `parse()` function reading
  15820. from an array.,parse__array__parser_callback_t}
  15821. @liveexample{The example below demonstrates the `parse()` function with
  15822. and without callback function.,parse__string__parser_callback_t}
  15823. @liveexample{The example below demonstrates the `parse()` function with
  15824. and without callback function.,parse__istream__parser_callback_t}
  15825. @liveexample{The example below demonstrates the `parse()` function reading
  15826. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  15827. @since version 2.0.3 (contiguous containers)
  15828. */
  15829. JSON_NODISCARD
  15830. static basic_json parse(detail::input_adapter&& i,
  15831. const parser_callback_t cb = nullptr,
  15832. const bool allow_exceptions = true)
  15833. {
  15834. basic_json result;
  15835. parser(i, cb, allow_exceptions).parse(true, result);
  15836. return result;
  15837. }
  15838. static bool accept(detail::input_adapter&& i)
  15839. {
  15840. return parser(i).accept(true);
  15841. }
  15842. /*!
  15843. @brief generate SAX events
  15844. The SAX event lister must follow the interface of @ref json_sax.
  15845. This function reads from a compatible input. Examples are:
  15846. - an array of 1-byte values
  15847. - strings with character/literal type with size of 1 byte
  15848. - input streams
  15849. - container with contiguous storage of 1-byte values. Compatible container
  15850. types include `std::vector`, `std::string`, `std::array`,
  15851. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  15852. arrays can be used with `std::begin()`/`std::end()`. User-defined
  15853. containers can be used as long as they implement random-access iterators
  15854. and a contiguous storage.
  15855. @pre Each element of the container has a size of 1 byte. Violating this
  15856. precondition yields undefined behavior. **This precondition is enforced
  15857. with a static assertion.**
  15858. @pre The container storage is contiguous. Violating this precondition
  15859. yields undefined behavior. **This precondition is enforced with an
  15860. assertion.**
  15861. @warning There is no way to enforce all preconditions at compile-time. If
  15862. the function is called with a noncompliant container and with
  15863. assertions switched off, the behavior is undefined and will most
  15864. likely yield segmentation violation.
  15865. @param[in] i input to read from
  15866. @param[in,out] sax SAX event listener
  15867. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  15868. @param[in] strict whether the input has to be consumed completely
  15869. @return return value of the last processed SAX event
  15870. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  15871. of input; expected string literal""`
  15872. @throw parse_error.102 if to_unicode fails or surrogate error
  15873. @throw parse_error.103 if to_unicode fails
  15874. @complexity Linear in the length of the input. The parser is a predictive
  15875. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  15876. a super-linear complexity.
  15877. @note A UTF-8 byte order mark is silently ignored.
  15878. @liveexample{The example below demonstrates the `sax_parse()` function
  15879. reading from string and processing the events with a user-defined SAX
  15880. event consumer.,sax_parse}
  15881. @since version 3.2.0
  15882. */
  15883. template <typename SAX>
  15884. static bool sax_parse(detail::input_adapter&& i, SAX* sax,
  15885. input_format_t format = input_format_t::json,
  15886. const bool strict = true)
  15887. {
  15888. assert(sax);
  15889. return format == input_format_t::json
  15890. ? parser(std::move(i)).sax_parse(sax, strict)
  15891. : detail::binary_reader<basic_json, SAX>(std::move(i)).sax_parse(format, sax, strict);
  15892. }
  15893. /*!
  15894. @brief deserialize from an iterator range with contiguous storage
  15895. This function reads from an iterator range of a container with contiguous
  15896. storage of 1-byte values. Compatible container types include
  15897. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  15898. `std::initializer_list`. Furthermore, C-style arrays can be used with
  15899. `std::begin()`/`std::end()`. User-defined containers can be used as long
  15900. as they implement random-access iterators and a contiguous storage.
  15901. @pre The iterator range is contiguous. Violating this precondition yields
  15902. undefined behavior. **This precondition is enforced with an assertion.**
  15903. @pre Each element in the range has a size of 1 byte. Violating this
  15904. precondition yields undefined behavior. **This precondition is enforced
  15905. with a static assertion.**
  15906. @warning There is no way to enforce all preconditions at compile-time. If
  15907. the function is called with noncompliant iterators and with
  15908. assertions switched off, the behavior is undefined and will most
  15909. likely yield segmentation violation.
  15910. @tparam IteratorType iterator of container with contiguous storage
  15911. @param[in] first begin of the range to parse (included)
  15912. @param[in] last end of the range to parse (excluded)
  15913. @param[in] cb a parser callback function of type @ref parser_callback_t
  15914. which is used to control the deserialization by filtering unwanted values
  15915. (optional)
  15916. @param[in] allow_exceptions whether to throw exceptions in case of a
  15917. parse error (optional, true by default)
  15918. @return deserialized JSON value; in case of a parse error and
  15919. @a allow_exceptions set to `false`, the return value will be
  15920. value_t::discarded.
  15921. @throw parse_error.101 in case of an unexpected token
  15922. @throw parse_error.102 if to_unicode fails or surrogate error
  15923. @throw parse_error.103 if to_unicode fails
  15924. @complexity Linear in the length of the input. The parser is a predictive
  15925. LL(1) parser. The complexity can be higher if the parser callback function
  15926. @a cb has a super-linear complexity.
  15927. @note A UTF-8 byte order mark is silently ignored.
  15928. @liveexample{The example below demonstrates the `parse()` function reading
  15929. from an iterator range.,parse__iteratortype__parser_callback_t}
  15930. @since version 2.0.3
  15931. */
  15932. template<class IteratorType, typename std::enable_if<
  15933. std::is_base_of<
  15934. std::random_access_iterator_tag,
  15935. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  15936. static basic_json parse(IteratorType first, IteratorType last,
  15937. const parser_callback_t cb = nullptr,
  15938. const bool allow_exceptions = true)
  15939. {
  15940. basic_json result;
  15941. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  15942. return result;
  15943. }
  15944. template<class IteratorType, typename std::enable_if<
  15945. std::is_base_of<
  15946. std::random_access_iterator_tag,
  15947. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  15948. static bool accept(IteratorType first, IteratorType last)
  15949. {
  15950. return parser(detail::input_adapter(first, last)).accept(true);
  15951. }
  15952. template<class IteratorType, class SAX, typename std::enable_if<
  15953. std::is_base_of<
  15954. std::random_access_iterator_tag,
  15955. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  15956. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
  15957. {
  15958. return parser(detail::input_adapter(first, last)).sax_parse(sax);
  15959. }
  15960. /*!
  15961. @brief deserialize from stream
  15962. @deprecated This stream operator is deprecated and will be removed in
  15963. version 4.0.0 of the library. Please use
  15964. @ref operator>>(std::istream&, basic_json&)
  15965. instead; that is, replace calls like `j << i;` with `i >> j;`.
  15966. @since version 1.0.0; deprecated since version 3.0.0
  15967. */
  15968. JSON_DEPRECATED
  15969. friend std::istream& operator<<(basic_json& j, std::istream& i)
  15970. {
  15971. return operator>>(i, j);
  15972. }
  15973. /*!
  15974. @brief deserialize from stream
  15975. Deserializes an input stream to a JSON value.
  15976. @param[in,out] i input stream to read a serialized JSON value from
  15977. @param[in,out] j JSON value to write the deserialized input to
  15978. @throw parse_error.101 in case of an unexpected token
  15979. @throw parse_error.102 if to_unicode fails or surrogate error
  15980. @throw parse_error.103 if to_unicode fails
  15981. @complexity Linear in the length of the input. The parser is a predictive
  15982. LL(1) parser.
  15983. @note A UTF-8 byte order mark is silently ignored.
  15984. @liveexample{The example below shows how a JSON value is constructed by
  15985. reading a serialization from a stream.,operator_deserialize}
  15986. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  15987. parser callback function to filter values while parsing
  15988. @since version 1.0.0
  15989. */
  15990. friend std::istream& operator>>(std::istream& i, basic_json& j)
  15991. {
  15992. parser(detail::input_adapter(i)).parse(false, j);
  15993. return i;
  15994. }
  15995. /// @}
  15996. ///////////////////////////
  15997. // convenience functions //
  15998. ///////////////////////////
  15999. /*!
  16000. @brief return the type as string
  16001. Returns the type name as string to be used in error messages - usually to
  16002. indicate that a function was called on a wrong JSON type.
  16003. @return a string representation of a the @a m_type member:
  16004. Value type | return value
  16005. ----------- | -------------
  16006. null | `"null"`
  16007. boolean | `"boolean"`
  16008. string | `"string"`
  16009. number | `"number"` (for all number types)
  16010. object | `"object"`
  16011. array | `"array"`
  16012. discarded | `"discarded"`
  16013. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16014. @complexity Constant.
  16015. @liveexample{The following code exemplifies `type_name()` for all JSON
  16016. types.,type_name}
  16017. @sa @ref type() -- return the type of the JSON value
  16018. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  16019. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  16020. since 3.0.0
  16021. */
  16022. const char* type_name() const noexcept
  16023. {
  16024. {
  16025. switch (m_type)
  16026. {
  16027. case value_t::null:
  16028. return "null";
  16029. case value_t::object:
  16030. return "object";
  16031. case value_t::array:
  16032. return "array";
  16033. case value_t::string:
  16034. return "string";
  16035. case value_t::boolean:
  16036. return "boolean";
  16037. case value_t::discarded:
  16038. return "discarded";
  16039. default:
  16040. return "number";
  16041. }
  16042. }
  16043. }
  16044. private:
  16045. //////////////////////
  16046. // member variables //
  16047. //////////////////////
  16048. /// the type of the current element
  16049. value_t m_type = value_t::null;
  16050. /// the value of the current element
  16051. json_value m_value = {};
  16052. //////////////////////////////////////////
  16053. // binary serialization/deserialization //
  16054. //////////////////////////////////////////
  16055. /// @name binary serialization/deserialization support
  16056. /// @{
  16057. public:
  16058. /*!
  16059. @brief create a CBOR serialization of a given JSON value
  16060. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  16061. Binary Object Representation) serialization format. CBOR is a binary
  16062. serialization format which aims to be more compact than JSON itself, yet
  16063. more efficient to parse.
  16064. The library uses the following mapping from JSON values types to
  16065. CBOR types according to the CBOR specification (RFC 7049):
  16066. JSON value type | value/range | CBOR type | first byte
  16067. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  16068. null | `null` | Null | 0xF6
  16069. boolean | `true` | True | 0xF5
  16070. boolean | `false` | False | 0xF4
  16071. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  16072. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  16073. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  16074. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  16075. number_integer | -24..-1 | Negative integer | 0x20..0x37
  16076. number_integer | 0..23 | Integer | 0x00..0x17
  16077. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  16078. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  16079. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  16080. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  16081. number_unsigned | 0..23 | Integer | 0x00..0x17
  16082. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  16083. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  16084. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  16085. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  16086. number_float | *any value* | Double-Precision Float | 0xFB
  16087. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  16088. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  16089. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  16090. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  16091. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  16092. array | *size*: 0..23 | array | 0x80..0x97
  16093. array | *size*: 23..255 | array (1 byte follow) | 0x98
  16094. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  16095. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  16096. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  16097. object | *size*: 0..23 | map | 0xA0..0xB7
  16098. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  16099. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  16100. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  16101. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  16102. @note The mapping is **complete** in the sense that any JSON value type
  16103. can be converted to a CBOR value.
  16104. @note If NaN or Infinity are stored inside a JSON number, they are
  16105. serialized properly. This behavior differs from the @ref dump()
  16106. function which serializes NaN or Infinity to `null`.
  16107. @note The following CBOR types are not used in the conversion:
  16108. - byte strings (0x40..0x5F)
  16109. - UTF-8 strings terminated by "break" (0x7F)
  16110. - arrays terminated by "break" (0x9F)
  16111. - maps terminated by "break" (0xBF)
  16112. - date/time (0xC0..0xC1)
  16113. - bignum (0xC2..0xC3)
  16114. - decimal fraction (0xC4)
  16115. - bigfloat (0xC5)
  16116. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  16117. - expected conversions (0xD5..0xD7)
  16118. - simple values (0xE0..0xF3, 0xF8)
  16119. - undefined (0xF7)
  16120. - half and single-precision floats (0xF9-0xFA)
  16121. - break (0xFF)
  16122. @param[in] j JSON value to serialize
  16123. @return MessagePack serialization as byte vector
  16124. @complexity Linear in the size of the JSON value @a j.
  16125. @liveexample{The example shows the serialization of a JSON value to a byte
  16126. vector in CBOR format.,to_cbor}
  16127. @sa http://cbor.io
  16128. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  16129. analogous deserialization
  16130. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  16131. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  16132. related UBJSON format
  16133. @since version 2.0.9
  16134. */
  16135. static std::vector<uint8_t> to_cbor(const basic_json& j)
  16136. {
  16137. std::vector<uint8_t> result;
  16138. to_cbor(j, result);
  16139. return result;
  16140. }
  16141. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  16142. {
  16143. binary_writer<uint8_t>(o).write_cbor(j);
  16144. }
  16145. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  16146. {
  16147. binary_writer<char>(o).write_cbor(j);
  16148. }
  16149. /*!
  16150. @brief create a MessagePack serialization of a given JSON value
  16151. Serializes a given JSON value @a j to a byte vector using the MessagePack
  16152. serialization format. MessagePack is a binary serialization format which
  16153. aims to be more compact than JSON itself, yet more efficient to parse.
  16154. The library uses the following mapping from JSON values types to
  16155. MessagePack types according to the MessagePack specification:
  16156. JSON value type | value/range | MessagePack type | first byte
  16157. --------------- | --------------------------------- | ---------------- | ----------
  16158. null | `null` | nil | 0xC0
  16159. boolean | `true` | true | 0xC3
  16160. boolean | `false` | false | 0xC2
  16161. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  16162. number_integer | -2147483648..-32769 | int32 | 0xD2
  16163. number_integer | -32768..-129 | int16 | 0xD1
  16164. number_integer | -128..-33 | int8 | 0xD0
  16165. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  16166. number_integer | 0..127 | positive fixint | 0x00..0x7F
  16167. number_integer | 128..255 | uint 8 | 0xCC
  16168. number_integer | 256..65535 | uint 16 | 0xCD
  16169. number_integer | 65536..4294967295 | uint 32 | 0xCE
  16170. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  16171. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  16172. number_unsigned | 128..255 | uint 8 | 0xCC
  16173. number_unsigned | 256..65535 | uint 16 | 0xCD
  16174. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  16175. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  16176. number_float | *any value* | float 64 | 0xCB
  16177. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  16178. string | *length*: 32..255 | str 8 | 0xD9
  16179. string | *length*: 256..65535 | str 16 | 0xDA
  16180. string | *length*: 65536..4294967295 | str 32 | 0xDB
  16181. array | *size*: 0..15 | fixarray | 0x90..0x9F
  16182. array | *size*: 16..65535 | array 16 | 0xDC
  16183. array | *size*: 65536..4294967295 | array 32 | 0xDD
  16184. object | *size*: 0..15 | fix map | 0x80..0x8F
  16185. object | *size*: 16..65535 | map 16 | 0xDE
  16186. object | *size*: 65536..4294967295 | map 32 | 0xDF
  16187. @note The mapping is **complete** in the sense that any JSON value type
  16188. can be converted to a MessagePack value.
  16189. @note The following values can **not** be converted to a MessagePack value:
  16190. - strings with more than 4294967295 bytes
  16191. - arrays with more than 4294967295 elements
  16192. - objects with more than 4294967295 elements
  16193. @note The following MessagePack types are not used in the conversion:
  16194. - bin 8 - bin 32 (0xC4..0xC6)
  16195. - ext 8 - ext 32 (0xC7..0xC9)
  16196. - float 32 (0xCA)
  16197. - fixext 1 - fixext 16 (0xD4..0xD8)
  16198. @note Any MessagePack output created @ref to_msgpack can be successfully
  16199. parsed by @ref from_msgpack.
  16200. @note If NaN or Infinity are stored inside a JSON number, they are
  16201. serialized properly. This behavior differs from the @ref dump()
  16202. function which serializes NaN or Infinity to `null`.
  16203. @param[in] j JSON value to serialize
  16204. @return MessagePack serialization as byte vector
  16205. @complexity Linear in the size of the JSON value @a j.
  16206. @liveexample{The example shows the serialization of a JSON value to a byte
  16207. vector in MessagePack format.,to_msgpack}
  16208. @sa http://msgpack.org
  16209. @sa @ref from_msgpack for the analogous deserialization
  16210. @sa @ref to_cbor(const basic_json& for the related CBOR format
  16211. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  16212. related UBJSON format
  16213. @since version 2.0.9
  16214. */
  16215. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  16216. {
  16217. std::vector<uint8_t> result;
  16218. to_msgpack(j, result);
  16219. return result;
  16220. }
  16221. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  16222. {
  16223. binary_writer<uint8_t>(o).write_msgpack(j);
  16224. }
  16225. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  16226. {
  16227. binary_writer<char>(o).write_msgpack(j);
  16228. }
  16229. /*!
  16230. @brief create a UBJSON serialization of a given JSON value
  16231. Serializes a given JSON value @a j to a byte vector using the UBJSON
  16232. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  16233. than JSON itself, yet more efficient to parse.
  16234. The library uses the following mapping from JSON values types to
  16235. UBJSON types according to the UBJSON specification:
  16236. JSON value type | value/range | UBJSON type | marker
  16237. --------------- | --------------------------------- | ----------- | ------
  16238. null | `null` | null | `Z`
  16239. boolean | `true` | true | `T`
  16240. boolean | `false` | false | `F`
  16241. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  16242. number_integer | -2147483648..-32769 | int32 | `l`
  16243. number_integer | -32768..-129 | int16 | `I`
  16244. number_integer | -128..127 | int8 | `i`
  16245. number_integer | 128..255 | uint8 | `U`
  16246. number_integer | 256..32767 | int16 | `I`
  16247. number_integer | 32768..2147483647 | int32 | `l`
  16248. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  16249. number_unsigned | 0..127 | int8 | `i`
  16250. number_unsigned | 128..255 | uint8 | `U`
  16251. number_unsigned | 256..32767 | int16 | `I`
  16252. number_unsigned | 32768..2147483647 | int32 | `l`
  16253. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  16254. number_float | *any value* | float64 | `D`
  16255. string | *with shortest length indicator* | string | `S`
  16256. array | *see notes on optimized format* | array | `[`
  16257. object | *see notes on optimized format* | map | `{`
  16258. @note The mapping is **complete** in the sense that any JSON value type
  16259. can be converted to a UBJSON value.
  16260. @note The following values can **not** be converted to a UBJSON value:
  16261. - strings with more than 9223372036854775807 bytes (theoretical)
  16262. - unsigned integer numbers above 9223372036854775807
  16263. @note The following markers are not used in the conversion:
  16264. - `Z`: no-op values are not created.
  16265. - `C`: single-byte strings are serialized with `S` markers.
  16266. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  16267. by @ref from_ubjson.
  16268. @note If NaN or Infinity are stored inside a JSON number, they are
  16269. serialized properly. This behavior differs from the @ref dump()
  16270. function which serializes NaN or Infinity to `null`.
  16271. @note The optimized formats for containers are supported: Parameter
  16272. @a use_size adds size information to the beginning of a container and
  16273. removes the closing marker. Parameter @a use_type further checks
  16274. whether all elements of a container have the same type and adds the
  16275. type marker to the beginning of the container. The @a use_type
  16276. parameter must only be used together with @a use_size = true. Note
  16277. that @a use_size = true alone may result in larger representations -
  16278. the benefit of this parameter is that the receiving side is
  16279. immediately informed on the number of elements of the container.
  16280. @param[in] j JSON value to serialize
  16281. @param[in] use_size whether to add size annotations to container types
  16282. @param[in] use_type whether to add type annotations to container types
  16283. (must be combined with @a use_size = true)
  16284. @return UBJSON serialization as byte vector
  16285. @complexity Linear in the size of the JSON value @a j.
  16286. @liveexample{The example shows the serialization of a JSON value to a byte
  16287. vector in UBJSON format.,to_ubjson}
  16288. @sa http://ubjson.org
  16289. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  16290. analogous deserialization
  16291. @sa @ref to_cbor(const basic_json& for the related CBOR format
  16292. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  16293. @since version 3.1.0
  16294. */
  16295. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  16296. const bool use_size = false,
  16297. const bool use_type = false)
  16298. {
  16299. std::vector<uint8_t> result;
  16300. to_ubjson(j, result, use_size, use_type);
  16301. return result;
  16302. }
  16303. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  16304. const bool use_size = false, const bool use_type = false)
  16305. {
  16306. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  16307. }
  16308. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  16309. const bool use_size = false, const bool use_type = false)
  16310. {
  16311. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  16312. }
  16313. /*!
  16314. @brief Serializes the given JSON object `j` to BSON and returns a vector
  16315. containing the corresponding BSON-representation.
  16316. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  16317. stored as a single entity (a so-called document).
  16318. The library uses the following mapping from JSON values types to BSON types:
  16319. JSON value type | value/range | BSON type | marker
  16320. --------------- | --------------------------------- | ----------- | ------
  16321. null | `null` | null | 0x0A
  16322. boolean | `true`, `false` | boolean | 0x08
  16323. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  16324. number_integer | -2147483648..2147483647 | int32 | 0x10
  16325. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  16326. number_unsigned | 0..2147483647 | int32 | 0x10
  16327. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  16328. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  16329. number_float | *any value* | double | 0x01
  16330. string | *any value* | string | 0x02
  16331. array | *any value* | document | 0x04
  16332. object | *any value* | document | 0x03
  16333. @warning The mapping is **incomplete**, since only JSON-objects (and things
  16334. contained therein) can be serialized to BSON.
  16335. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  16336. and the keys may not contain U+0000, since they are serialized a
  16337. zero-terminated c-strings.
  16338. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  16339. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  16340. @throw type_error.317 if `!j.is_object()`
  16341. @pre The input `j` is required to be an object: `j.is_object() == true`.
  16342. @note Any BSON output created via @ref to_bson can be successfully parsed
  16343. by @ref from_bson.
  16344. @param[in] j JSON value to serialize
  16345. @return BSON serialization as byte vector
  16346. @complexity Linear in the size of the JSON value @a j.
  16347. @liveexample{The example shows the serialization of a JSON value to a byte
  16348. vector in BSON format.,to_bson}
  16349. @sa http://bsonspec.org/spec.html
  16350. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  16351. analogous deserialization
  16352. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  16353. related UBJSON format
  16354. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  16355. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  16356. */
  16357. static std::vector<uint8_t> to_bson(const basic_json& j)
  16358. {
  16359. std::vector<uint8_t> result;
  16360. to_bson(j, result);
  16361. return result;
  16362. }
  16363. /*!
  16364. @brief Serializes the given JSON object `j` to BSON and forwards the
  16365. corresponding BSON-representation to the given output_adapter `o`.
  16366. @param j The JSON object to convert to BSON.
  16367. @param o The output adapter that receives the binary BSON representation.
  16368. @pre The input `j` shall be an object: `j.is_object() == true`
  16369. @sa @ref to_bson(const basic_json&)
  16370. */
  16371. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  16372. {
  16373. binary_writer<uint8_t>(o).write_bson(j);
  16374. }
  16375. /*!
  16376. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  16377. */
  16378. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  16379. {
  16380. binary_writer<char>(o).write_bson(j);
  16381. }
  16382. /*!
  16383. @brief create a JSON value from an input in CBOR format
  16384. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  16385. Binary Object Representation) serialization format.
  16386. The library maps CBOR types to JSON value types as follows:
  16387. CBOR type | JSON value type | first byte
  16388. ---------------------- | --------------- | ----------
  16389. Integer | number_unsigned | 0x00..0x17
  16390. Unsigned integer | number_unsigned | 0x18
  16391. Unsigned integer | number_unsigned | 0x19
  16392. Unsigned integer | number_unsigned | 0x1A
  16393. Unsigned integer | number_unsigned | 0x1B
  16394. Negative integer | number_integer | 0x20..0x37
  16395. Negative integer | number_integer | 0x38
  16396. Negative integer | number_integer | 0x39
  16397. Negative integer | number_integer | 0x3A
  16398. Negative integer | number_integer | 0x3B
  16399. Negative integer | number_integer | 0x40..0x57
  16400. UTF-8 string | string | 0x60..0x77
  16401. UTF-8 string | string | 0x78
  16402. UTF-8 string | string | 0x79
  16403. UTF-8 string | string | 0x7A
  16404. UTF-8 string | string | 0x7B
  16405. UTF-8 string | string | 0x7F
  16406. array | array | 0x80..0x97
  16407. array | array | 0x98
  16408. array | array | 0x99
  16409. array | array | 0x9A
  16410. array | array | 0x9B
  16411. array | array | 0x9F
  16412. map | object | 0xA0..0xB7
  16413. map | object | 0xB8
  16414. map | object | 0xB9
  16415. map | object | 0xBA
  16416. map | object | 0xBB
  16417. map | object | 0xBF
  16418. False | `false` | 0xF4
  16419. True | `true` | 0xF5
  16420. Null | `null` | 0xF6
  16421. Half-Precision Float | number_float | 0xF9
  16422. Single-Precision Float | number_float | 0xFA
  16423. Double-Precision Float | number_float | 0xFB
  16424. @warning The mapping is **incomplete** in the sense that not all CBOR
  16425. types can be converted to a JSON value. The following CBOR types
  16426. are not supported and will yield parse errors (parse_error.112):
  16427. - byte strings (0x40..0x5F)
  16428. - date/time (0xC0..0xC1)
  16429. - bignum (0xC2..0xC3)
  16430. - decimal fraction (0xC4)
  16431. - bigfloat (0xC5)
  16432. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  16433. - expected conversions (0xD5..0xD7)
  16434. - simple values (0xE0..0xF3, 0xF8)
  16435. - undefined (0xF7)
  16436. @warning CBOR allows map keys of any type, whereas JSON only allows
  16437. strings as keys in object values. Therefore, CBOR maps with keys
  16438. other than UTF-8 strings are rejected (parse_error.113).
  16439. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  16440. @ref from_cbor.
  16441. @param[in] i an input in CBOR format convertible to an input adapter
  16442. @param[in] strict whether to expect the input to be consumed until EOF
  16443. (true by default)
  16444. @param[in] allow_exceptions whether to throw exceptions in case of a
  16445. parse error (optional, true by default)
  16446. @return deserialized JSON value; in case of a parse error and
  16447. @a allow_exceptions set to `false`, the return value will be
  16448. value_t::discarded.
  16449. @throw parse_error.110 if the given input ends prematurely or the end of
  16450. file was not reached when @a strict was set to true
  16451. @throw parse_error.112 if unsupported features from CBOR were
  16452. used in the given input @a v or if the input is not valid CBOR
  16453. @throw parse_error.113 if a string was expected as map key, but not found
  16454. @complexity Linear in the size of the input @a i.
  16455. @liveexample{The example shows the deserialization of a byte vector in CBOR
  16456. format to a JSON value.,from_cbor}
  16457. @sa http://cbor.io
  16458. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  16459. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  16460. related MessagePack format
  16461. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  16462. related UBJSON format
  16463. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  16464. consume input adapters, removed start_index parameter, and added
  16465. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  16466. since 3.2.0
  16467. */
  16468. JSON_NODISCARD
  16469. static basic_json from_cbor(detail::input_adapter&& i,
  16470. const bool strict = true,
  16471. const bool allow_exceptions = true)
  16472. {
  16473. basic_json result;
  16474. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16475. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict);
  16476. return res ? result : basic_json(value_t::discarded);
  16477. }
  16478. /*!
  16479. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
  16480. */
  16481. template<typename A1, typename A2,
  16482. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  16483. JSON_NODISCARD
  16484. static basic_json from_cbor(A1 && a1, A2 && a2,
  16485. const bool strict = true,
  16486. const bool allow_exceptions = true)
  16487. {
  16488. basic_json result;
  16489. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16490. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::cbor, &sdp, strict);
  16491. return res ? result : basic_json(value_t::discarded);
  16492. }
  16493. /*!
  16494. @brief create a JSON value from an input in MessagePack format
  16495. Deserializes a given input @a i to a JSON value using the MessagePack
  16496. serialization format.
  16497. The library maps MessagePack types to JSON value types as follows:
  16498. MessagePack type | JSON value type | first byte
  16499. ---------------- | --------------- | ----------
  16500. positive fixint | number_unsigned | 0x00..0x7F
  16501. fixmap | object | 0x80..0x8F
  16502. fixarray | array | 0x90..0x9F
  16503. fixstr | string | 0xA0..0xBF
  16504. nil | `null` | 0xC0
  16505. false | `false` | 0xC2
  16506. true | `true` | 0xC3
  16507. float 32 | number_float | 0xCA
  16508. float 64 | number_float | 0xCB
  16509. uint 8 | number_unsigned | 0xCC
  16510. uint 16 | number_unsigned | 0xCD
  16511. uint 32 | number_unsigned | 0xCE
  16512. uint 64 | number_unsigned | 0xCF
  16513. int 8 | number_integer | 0xD0
  16514. int 16 | number_integer | 0xD1
  16515. int 32 | number_integer | 0xD2
  16516. int 64 | number_integer | 0xD3
  16517. str 8 | string | 0xD9
  16518. str 16 | string | 0xDA
  16519. str 32 | string | 0xDB
  16520. array 16 | array | 0xDC
  16521. array 32 | array | 0xDD
  16522. map 16 | object | 0xDE
  16523. map 32 | object | 0xDF
  16524. negative fixint | number_integer | 0xE0-0xFF
  16525. @warning The mapping is **incomplete** in the sense that not all
  16526. MessagePack types can be converted to a JSON value. The following
  16527. MessagePack types are not supported and will yield parse errors:
  16528. - bin 8 - bin 32 (0xC4..0xC6)
  16529. - ext 8 - ext 32 (0xC7..0xC9)
  16530. - fixext 1 - fixext 16 (0xD4..0xD8)
  16531. @note Any MessagePack output created @ref to_msgpack can be successfully
  16532. parsed by @ref from_msgpack.
  16533. @param[in] i an input in MessagePack format convertible to an input
  16534. adapter
  16535. @param[in] strict whether to expect the input to be consumed until EOF
  16536. (true by default)
  16537. @param[in] allow_exceptions whether to throw exceptions in case of a
  16538. parse error (optional, true by default)
  16539. @return deserialized JSON value; in case of a parse error and
  16540. @a allow_exceptions set to `false`, the return value will be
  16541. value_t::discarded.
  16542. @throw parse_error.110 if the given input ends prematurely or the end of
  16543. file was not reached when @a strict was set to true
  16544. @throw parse_error.112 if unsupported features from MessagePack were
  16545. used in the given input @a i or if the input is not valid MessagePack
  16546. @throw parse_error.113 if a string was expected as map key, but not found
  16547. @complexity Linear in the size of the input @a i.
  16548. @liveexample{The example shows the deserialization of a byte vector in
  16549. MessagePack format to a JSON value.,from_msgpack}
  16550. @sa http://msgpack.org
  16551. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  16552. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  16553. related CBOR format
  16554. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  16555. the related UBJSON format
  16556. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  16557. the related BSON format
  16558. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  16559. consume input adapters, removed start_index parameter, and added
  16560. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  16561. since 3.2.0
  16562. */
  16563. JSON_NODISCARD
  16564. static basic_json from_msgpack(detail::input_adapter&& i,
  16565. const bool strict = true,
  16566. const bool allow_exceptions = true)
  16567. {
  16568. basic_json result;
  16569. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16570. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict);
  16571. return res ? result : basic_json(value_t::discarded);
  16572. }
  16573. /*!
  16574. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  16575. */
  16576. template<typename A1, typename A2,
  16577. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  16578. JSON_NODISCARD
  16579. static basic_json from_msgpack(A1 && a1, A2 && a2,
  16580. const bool strict = true,
  16581. const bool allow_exceptions = true)
  16582. {
  16583. basic_json result;
  16584. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16585. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::msgpack, &sdp, strict);
  16586. return res ? result : basic_json(value_t::discarded);
  16587. }
  16588. /*!
  16589. @brief create a JSON value from an input in UBJSON format
  16590. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  16591. Binary JSON) serialization format.
  16592. The library maps UBJSON types to JSON value types as follows:
  16593. UBJSON type | JSON value type | marker
  16594. ----------- | --------------------------------------- | ------
  16595. no-op | *no value, next value is read* | `N`
  16596. null | `null` | `Z`
  16597. false | `false` | `F`
  16598. true | `true` | `T`
  16599. float32 | number_float | `d`
  16600. float64 | number_float | `D`
  16601. uint8 | number_unsigned | `U`
  16602. int8 | number_integer | `i`
  16603. int16 | number_integer | `I`
  16604. int32 | number_integer | `l`
  16605. int64 | number_integer | `L`
  16606. string | string | `S`
  16607. char | string | `C`
  16608. array | array (optimized values are supported) | `[`
  16609. object | object (optimized values are supported) | `{`
  16610. @note The mapping is **complete** in the sense that any UBJSON value can
  16611. be converted to a JSON value.
  16612. @param[in] i an input in UBJSON format convertible to an input adapter
  16613. @param[in] strict whether to expect the input to be consumed until EOF
  16614. (true by default)
  16615. @param[in] allow_exceptions whether to throw exceptions in case of a
  16616. parse error (optional, true by default)
  16617. @return deserialized JSON value; in case of a parse error and
  16618. @a allow_exceptions set to `false`, the return value will be
  16619. value_t::discarded.
  16620. @throw parse_error.110 if the given input ends prematurely or the end of
  16621. file was not reached when @a strict was set to true
  16622. @throw parse_error.112 if a parse error occurs
  16623. @throw parse_error.113 if a string could not be parsed successfully
  16624. @complexity Linear in the size of the input @a i.
  16625. @liveexample{The example shows the deserialization of a byte vector in
  16626. UBJSON format to a JSON value.,from_ubjson}
  16627. @sa http://ubjson.org
  16628. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  16629. analogous serialization
  16630. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  16631. related CBOR format
  16632. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  16633. the related MessagePack format
  16634. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  16635. the related BSON format
  16636. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  16637. */
  16638. JSON_NODISCARD
  16639. static basic_json from_ubjson(detail::input_adapter&& i,
  16640. const bool strict = true,
  16641. const bool allow_exceptions = true)
  16642. {
  16643. basic_json result;
  16644. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16645. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict);
  16646. return res ? result : basic_json(value_t::discarded);
  16647. }
  16648. /*!
  16649. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  16650. */
  16651. template<typename A1, typename A2,
  16652. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  16653. JSON_NODISCARD
  16654. static basic_json from_ubjson(A1 && a1, A2 && a2,
  16655. const bool strict = true,
  16656. const bool allow_exceptions = true)
  16657. {
  16658. basic_json result;
  16659. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16660. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::ubjson, &sdp, strict);
  16661. return res ? result : basic_json(value_t::discarded);
  16662. }
  16663. /*!
  16664. @brief Create a JSON value from an input in BSON format
  16665. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  16666. serialization format.
  16667. The library maps BSON record types to JSON value types as follows:
  16668. BSON type | BSON marker byte | JSON value type
  16669. --------------- | ---------------- | ---------------------------
  16670. double | 0x01 | number_float
  16671. string | 0x02 | string
  16672. document | 0x03 | object
  16673. array | 0x04 | array
  16674. binary | 0x05 | still unsupported
  16675. undefined | 0x06 | still unsupported
  16676. ObjectId | 0x07 | still unsupported
  16677. boolean | 0x08 | boolean
  16678. UTC Date-Time | 0x09 | still unsupported
  16679. null | 0x0A | null
  16680. Regular Expr. | 0x0B | still unsupported
  16681. DB Pointer | 0x0C | still unsupported
  16682. JavaScript Code | 0x0D | still unsupported
  16683. Symbol | 0x0E | still unsupported
  16684. JavaScript Code | 0x0F | still unsupported
  16685. int32 | 0x10 | number_integer
  16686. Timestamp | 0x11 | still unsupported
  16687. 128-bit decimal float | 0x13 | still unsupported
  16688. Max Key | 0x7F | still unsupported
  16689. Min Key | 0xFF | still unsupported
  16690. @warning The mapping is **incomplete**. The unsupported mappings
  16691. are indicated in the table above.
  16692. @param[in] i an input in BSON format convertible to an input adapter
  16693. @param[in] strict whether to expect the input to be consumed until EOF
  16694. (true by default)
  16695. @param[in] allow_exceptions whether to throw exceptions in case of a
  16696. parse error (optional, true by default)
  16697. @return deserialized JSON value; in case of a parse error and
  16698. @a allow_exceptions set to `false`, the return value will be
  16699. value_t::discarded.
  16700. @throw parse_error.114 if an unsupported BSON record type is encountered
  16701. @complexity Linear in the size of the input @a i.
  16702. @liveexample{The example shows the deserialization of a byte vector in
  16703. BSON format to a JSON value.,from_bson}
  16704. @sa http://bsonspec.org/spec.html
  16705. @sa @ref to_bson(const basic_json&) for the analogous serialization
  16706. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  16707. related CBOR format
  16708. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  16709. the related MessagePack format
  16710. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  16711. related UBJSON format
  16712. */
  16713. JSON_NODISCARD
  16714. static basic_json from_bson(detail::input_adapter&& i,
  16715. const bool strict = true,
  16716. const bool allow_exceptions = true)
  16717. {
  16718. basic_json result;
  16719. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16720. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::bson, &sdp, strict);
  16721. return res ? result : basic_json(value_t::discarded);
  16722. }
  16723. /*!
  16724. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  16725. */
  16726. template<typename A1, typename A2,
  16727. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  16728. JSON_NODISCARD
  16729. static basic_json from_bson(A1 && a1, A2 && a2,
  16730. const bool strict = true,
  16731. const bool allow_exceptions = true)
  16732. {
  16733. basic_json result;
  16734. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16735. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::bson, &sdp, strict);
  16736. return res ? result : basic_json(value_t::discarded);
  16737. }
  16738. /// @}
  16739. //////////////////////////
  16740. // JSON Pointer support //
  16741. //////////////////////////
  16742. /// @name JSON Pointer functions
  16743. /// @{
  16744. /*!
  16745. @brief access specified element via JSON Pointer
  16746. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  16747. No bound checking is performed. Similar to @ref operator[](const typename
  16748. object_t::key_type&), `null` values are created in arrays and objects if
  16749. necessary.
  16750. In particular:
  16751. - If the JSON pointer points to an object key that does not exist, it
  16752. is created an filled with a `null` value before a reference to it
  16753. is returned.
  16754. - If the JSON pointer points to an array index that does not exist, it
  16755. is created an filled with a `null` value before a reference to it
  16756. is returned. All indices between the current maximum and the given
  16757. index are also filled with `null`.
  16758. - The special value `-` is treated as a synonym for the index past the
  16759. end.
  16760. @param[in] ptr a JSON pointer
  16761. @return reference to the element pointed to by @a ptr
  16762. @complexity Constant.
  16763. @throw parse_error.106 if an array index begins with '0'
  16764. @throw parse_error.109 if an array index was not a number
  16765. @throw out_of_range.404 if the JSON pointer can not be resolved
  16766. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  16767. @since version 2.0.0
  16768. */
  16769. reference operator[](const json_pointer& ptr)
  16770. {
  16771. return ptr.get_unchecked(this);
  16772. }
  16773. /*!
  16774. @brief access specified element via JSON Pointer
  16775. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  16776. No bound checking is performed. The function does not change the JSON
  16777. value; no `null` values are created. In particular, the the special value
  16778. `-` yields an exception.
  16779. @param[in] ptr JSON pointer to the desired element
  16780. @return const reference to the element pointed to by @a ptr
  16781. @complexity Constant.
  16782. @throw parse_error.106 if an array index begins with '0'
  16783. @throw parse_error.109 if an array index was not a number
  16784. @throw out_of_range.402 if the array index '-' is used
  16785. @throw out_of_range.404 if the JSON pointer can not be resolved
  16786. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  16787. @since version 2.0.0
  16788. */
  16789. const_reference operator[](const json_pointer& ptr) const
  16790. {
  16791. return ptr.get_unchecked(this);
  16792. }
  16793. /*!
  16794. @brief access specified element via JSON Pointer
  16795. Returns a reference to the element at with specified JSON pointer @a ptr,
  16796. with bounds checking.
  16797. @param[in] ptr JSON pointer to the desired element
  16798. @return reference to the element pointed to by @a ptr
  16799. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  16800. begins with '0'. See example below.
  16801. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  16802. is not a number. See example below.
  16803. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  16804. is out of range. See example below.
  16805. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  16806. pointer @a ptr. As `at` provides checked access (and no elements are
  16807. implicitly inserted), the index '-' is always invalid. See example below.
  16808. @throw out_of_range.403 if the JSON pointer describes a key of an object
  16809. which cannot be found. See example below.
  16810. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  16811. See example below.
  16812. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16813. changes in the JSON value.
  16814. @complexity Constant.
  16815. @since version 2.0.0
  16816. @liveexample{The behavior is shown in the example.,at_json_pointer}
  16817. */
  16818. reference at(const json_pointer& ptr)
  16819. {
  16820. return ptr.get_checked(this);
  16821. }
  16822. /*!
  16823. @brief access specified element via JSON Pointer
  16824. Returns a const reference to the element at with specified JSON pointer @a
  16825. ptr, with bounds checking.
  16826. @param[in] ptr JSON pointer to the desired element
  16827. @return reference to the element pointed to by @a ptr
  16828. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  16829. begins with '0'. See example below.
  16830. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  16831. is not a number. See example below.
  16832. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  16833. is out of range. See example below.
  16834. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  16835. pointer @a ptr. As `at` provides checked access (and no elements are
  16836. implicitly inserted), the index '-' is always invalid. See example below.
  16837. @throw out_of_range.403 if the JSON pointer describes a key of an object
  16838. which cannot be found. See example below.
  16839. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  16840. See example below.
  16841. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16842. changes in the JSON value.
  16843. @complexity Constant.
  16844. @since version 2.0.0
  16845. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  16846. */
  16847. const_reference at(const json_pointer& ptr) const
  16848. {
  16849. return ptr.get_checked(this);
  16850. }
  16851. /*!
  16852. @brief return flattened JSON value
  16853. The function creates a JSON object whose keys are JSON pointers (see [RFC
  16854. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  16855. primitive. The original JSON value can be restored using the @ref
  16856. unflatten() function.
  16857. @return an object that maps JSON pointers to primitive values
  16858. @note Empty objects and arrays are flattened to `null` and will not be
  16859. reconstructed correctly by the @ref unflatten() function.
  16860. @complexity Linear in the size the JSON value.
  16861. @liveexample{The following code shows how a JSON object is flattened to an
  16862. object whose keys consist of JSON pointers.,flatten}
  16863. @sa @ref unflatten() for the reverse function
  16864. @since version 2.0.0
  16865. */
  16866. basic_json flatten() const
  16867. {
  16868. basic_json result(value_t::object);
  16869. json_pointer::flatten("", *this, result);
  16870. return result;
  16871. }
  16872. /*!
  16873. @brief unflatten a previously flattened JSON value
  16874. The function restores the arbitrary nesting of a JSON value that has been
  16875. flattened before using the @ref flatten() function. The JSON value must
  16876. meet certain constraints:
  16877. 1. The value must be an object.
  16878. 2. The keys must be JSON pointers (see
  16879. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  16880. 3. The mapped values must be primitive JSON types.
  16881. @return the original JSON from a flattened version
  16882. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  16883. values and can not unflattened to their original type. Apart from
  16884. this example, for a JSON value `j`, the following is always true:
  16885. `j == j.flatten().unflatten()`.
  16886. @complexity Linear in the size the JSON value.
  16887. @throw type_error.314 if value is not an object
  16888. @throw type_error.315 if object values are not primitive
  16889. @liveexample{The following code shows how a flattened JSON object is
  16890. unflattened into the original nested JSON object.,unflatten}
  16891. @sa @ref flatten() for the reverse function
  16892. @since version 2.0.0
  16893. */
  16894. basic_json unflatten() const
  16895. {
  16896. return json_pointer::unflatten(*this);
  16897. }
  16898. /// @}
  16899. //////////////////////////
  16900. // JSON Patch functions //
  16901. //////////////////////////
  16902. /// @name JSON Patch functions
  16903. /// @{
  16904. /*!
  16905. @brief applies a JSON patch
  16906. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  16907. expressing a sequence of operations to apply to a JSON) document. With
  16908. this function, a JSON Patch is applied to the current JSON value by
  16909. executing all operations from the patch.
  16910. @param[in] json_patch JSON patch document
  16911. @return patched document
  16912. @note The application of a patch is atomic: Either all operations succeed
  16913. and the patched document is returned or an exception is thrown. In
  16914. any case, the original value is not changed: the patch is applied
  16915. to a copy of the value.
  16916. @throw parse_error.104 if the JSON patch does not consist of an array of
  16917. objects
  16918. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  16919. attributes are missing); example: `"operation add must have member path"`
  16920. @throw out_of_range.401 if an array index is out of range.
  16921. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  16922. resolved successfully in the current JSON value; example: `"key baz not
  16923. found"`
  16924. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  16925. "move")
  16926. @throw other_error.501 if "test" operation was unsuccessful
  16927. @complexity Linear in the size of the JSON value and the length of the
  16928. JSON patch. As usually only a fraction of the JSON value is affected by
  16929. the patch, the complexity can usually be neglected.
  16930. @liveexample{The following code shows how a JSON patch is applied to a
  16931. value.,patch}
  16932. @sa @ref diff -- create a JSON patch by comparing two JSON values
  16933. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  16934. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  16935. @since version 2.0.0
  16936. */
  16937. basic_json patch(const basic_json& json_patch) const
  16938. {
  16939. // make a working copy to apply the patch to
  16940. basic_json result = *this;
  16941. // the valid JSON Patch operations
  16942. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  16943. const auto get_op = [](const std::string & op)
  16944. {
  16945. if (op == "add")
  16946. {
  16947. return patch_operations::add;
  16948. }
  16949. if (op == "remove")
  16950. {
  16951. return patch_operations::remove;
  16952. }
  16953. if (op == "replace")
  16954. {
  16955. return patch_operations::replace;
  16956. }
  16957. if (op == "move")
  16958. {
  16959. return patch_operations::move;
  16960. }
  16961. if (op == "copy")
  16962. {
  16963. return patch_operations::copy;
  16964. }
  16965. if (op == "test")
  16966. {
  16967. return patch_operations::test;
  16968. }
  16969. return patch_operations::invalid;
  16970. };
  16971. // wrapper for "add" operation; add value at ptr
  16972. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  16973. {
  16974. // adding to the root of the target document means replacing it
  16975. if (ptr.empty())
  16976. {
  16977. result = val;
  16978. return;
  16979. }
  16980. // make sure the top element of the pointer exists
  16981. json_pointer top_pointer = ptr.top();
  16982. if (top_pointer != ptr)
  16983. {
  16984. result.at(top_pointer);
  16985. }
  16986. // get reference to parent of JSON pointer ptr
  16987. const auto last_path = ptr.back();
  16988. ptr.pop_back();
  16989. basic_json& parent = result[ptr];
  16990. switch (parent.m_type)
  16991. {
  16992. case value_t::null:
  16993. case value_t::object:
  16994. {
  16995. // use operator[] to add value
  16996. parent[last_path] = val;
  16997. break;
  16998. }
  16999. case value_t::array:
  17000. {
  17001. if (last_path == "-")
  17002. {
  17003. // special case: append to back
  17004. parent.push_back(val);
  17005. }
  17006. else
  17007. {
  17008. const auto idx = json_pointer::array_index(last_path);
  17009. if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  17010. {
  17011. // avoid undefined behavior
  17012. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  17013. }
  17014. // default case: insert add offset
  17015. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  17016. }
  17017. break;
  17018. }
  17019. // if there exists a parent it cannot be primitive
  17020. default: // LCOV_EXCL_LINE
  17021. assert(false); // LCOV_EXCL_LINE
  17022. }
  17023. };
  17024. // wrapper for "remove" operation; remove value at ptr
  17025. const auto operation_remove = [&result](json_pointer & ptr)
  17026. {
  17027. // get reference to parent of JSON pointer ptr
  17028. const auto last_path = ptr.back();
  17029. ptr.pop_back();
  17030. basic_json& parent = result.at(ptr);
  17031. // remove child
  17032. if (parent.is_object())
  17033. {
  17034. // perform range check
  17035. auto it = parent.find(last_path);
  17036. if (JSON_LIKELY(it != parent.end()))
  17037. {
  17038. parent.erase(it);
  17039. }
  17040. else
  17041. {
  17042. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  17043. }
  17044. }
  17045. else if (parent.is_array())
  17046. {
  17047. // note erase performs range check
  17048. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  17049. }
  17050. };
  17051. // type check: top level value must be an array
  17052. if (JSON_UNLIKELY(not json_patch.is_array()))
  17053. {
  17054. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  17055. }
  17056. // iterate and apply the operations
  17057. for (const auto& val : json_patch)
  17058. {
  17059. // wrapper to get a value for an operation
  17060. const auto get_value = [&val](const std::string & op,
  17061. const std::string & member,
  17062. bool string_type) -> basic_json &
  17063. {
  17064. // find value
  17065. auto it = val.m_value.object->find(member);
  17066. // context-sensitive error message
  17067. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  17068. // check if desired value is present
  17069. if (JSON_UNLIKELY(it == val.m_value.object->end()))
  17070. {
  17071. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  17072. }
  17073. // check if result is of type string
  17074. if (JSON_UNLIKELY(string_type and not it->second.is_string()))
  17075. {
  17076. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  17077. }
  17078. // no error: return value
  17079. return it->second;
  17080. };
  17081. // type check: every element of the array must be an object
  17082. if (JSON_UNLIKELY(not val.is_object()))
  17083. {
  17084. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  17085. }
  17086. // collect mandatory members
  17087. const std::string op = get_value("op", "op", true);
  17088. const std::string path = get_value(op, "path", true);
  17089. json_pointer ptr(path);
  17090. switch (get_op(op))
  17091. {
  17092. case patch_operations::add:
  17093. {
  17094. operation_add(ptr, get_value("add", "value", false));
  17095. break;
  17096. }
  17097. case patch_operations::remove:
  17098. {
  17099. operation_remove(ptr);
  17100. break;
  17101. }
  17102. case patch_operations::replace:
  17103. {
  17104. // the "path" location must exist - use at()
  17105. result.at(ptr) = get_value("replace", "value", false);
  17106. break;
  17107. }
  17108. case patch_operations::move:
  17109. {
  17110. const std::string from_path = get_value("move", "from", true);
  17111. json_pointer from_ptr(from_path);
  17112. // the "from" location must exist - use at()
  17113. basic_json v = result.at(from_ptr);
  17114. // The move operation is functionally identical to a
  17115. // "remove" operation on the "from" location, followed
  17116. // immediately by an "add" operation at the target
  17117. // location with the value that was just removed.
  17118. operation_remove(from_ptr);
  17119. operation_add(ptr, v);
  17120. break;
  17121. }
  17122. case patch_operations::copy:
  17123. {
  17124. const std::string from_path = get_value("copy", "from", true);
  17125. const json_pointer from_ptr(from_path);
  17126. // the "from" location must exist - use at()
  17127. basic_json v = result.at(from_ptr);
  17128. // The copy is functionally identical to an "add"
  17129. // operation at the target location using the value
  17130. // specified in the "from" member.
  17131. operation_add(ptr, v);
  17132. break;
  17133. }
  17134. case patch_operations::test:
  17135. {
  17136. bool success = false;
  17137. JSON_TRY
  17138. {
  17139. // check if "value" matches the one at "path"
  17140. // the "path" location must exist - use at()
  17141. success = (result.at(ptr) == get_value("test", "value", false));
  17142. }
  17143. JSON_INTERNAL_CATCH (out_of_range&)
  17144. {
  17145. // ignore out of range errors: success remains false
  17146. }
  17147. // throw an exception if test fails
  17148. if (JSON_UNLIKELY(not success))
  17149. {
  17150. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  17151. }
  17152. break;
  17153. }
  17154. default:
  17155. {
  17156. // op must be "add", "remove", "replace", "move", "copy", or
  17157. // "test"
  17158. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  17159. }
  17160. }
  17161. }
  17162. return result;
  17163. }
  17164. /*!
  17165. @brief creates a diff as a JSON patch
  17166. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  17167. be changed into the value @a target by calling @ref patch function.
  17168. @invariant For two JSON values @a source and @a target, the following code
  17169. yields always `true`:
  17170. @code {.cpp}
  17171. source.patch(diff(source, target)) == target;
  17172. @endcode
  17173. @note Currently, only `remove`, `add`, and `replace` operations are
  17174. generated.
  17175. @param[in] source JSON value to compare from
  17176. @param[in] target JSON value to compare against
  17177. @param[in] path helper value to create JSON pointers
  17178. @return a JSON patch to convert the @a source to @a target
  17179. @complexity Linear in the lengths of @a source and @a target.
  17180. @liveexample{The following code shows how a JSON patch is created as a
  17181. diff for two JSON values.,diff}
  17182. @sa @ref patch -- apply a JSON patch
  17183. @sa @ref merge_patch -- apply a JSON Merge Patch
  17184. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  17185. @since version 2.0.0
  17186. */
  17187. JSON_NODISCARD
  17188. static basic_json diff(const basic_json& source, const basic_json& target,
  17189. const std::string& path = "")
  17190. {
  17191. // the patch
  17192. basic_json result(value_t::array);
  17193. // if the values are the same, return empty patch
  17194. if (source == target)
  17195. {
  17196. return result;
  17197. }
  17198. if (source.type() != target.type())
  17199. {
  17200. // different types: replace value
  17201. result.push_back(
  17202. {
  17203. {"op", "replace"}, {"path", path}, {"value", target}
  17204. });
  17205. return result;
  17206. }
  17207. switch (source.type())
  17208. {
  17209. case value_t::array:
  17210. {
  17211. // first pass: traverse common elements
  17212. std::size_t i = 0;
  17213. while (i < source.size() and i < target.size())
  17214. {
  17215. // recursive call to compare array values at index i
  17216. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  17217. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  17218. ++i;
  17219. }
  17220. // i now reached the end of at least one array
  17221. // in a second pass, traverse the remaining elements
  17222. // remove my remaining elements
  17223. const auto end_index = static_cast<difference_type>(result.size());
  17224. while (i < source.size())
  17225. {
  17226. // add operations in reverse order to avoid invalid
  17227. // indices
  17228. result.insert(result.begin() + end_index, object(
  17229. {
  17230. {"op", "remove"},
  17231. {"path", path + "/" + std::to_string(i)}
  17232. }));
  17233. ++i;
  17234. }
  17235. // add other remaining elements
  17236. while (i < target.size())
  17237. {
  17238. result.push_back(
  17239. {
  17240. {"op", "add"},
  17241. {"path", path + "/" + std::to_string(i)},
  17242. {"value", target[i]}
  17243. });
  17244. ++i;
  17245. }
  17246. break;
  17247. }
  17248. case value_t::object:
  17249. {
  17250. // first pass: traverse this object's elements
  17251. for (auto it = source.cbegin(); it != source.cend(); ++it)
  17252. {
  17253. // escape the key name to be used in a JSON patch
  17254. const auto key = json_pointer::escape(it.key());
  17255. if (target.find(it.key()) != target.end())
  17256. {
  17257. // recursive call to compare object values at key it
  17258. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  17259. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  17260. }
  17261. else
  17262. {
  17263. // found a key that is not in o -> remove it
  17264. result.push_back(object(
  17265. {
  17266. {"op", "remove"}, {"path", path + "/" + key}
  17267. }));
  17268. }
  17269. }
  17270. // second pass: traverse other object's elements
  17271. for (auto it = target.cbegin(); it != target.cend(); ++it)
  17272. {
  17273. if (source.find(it.key()) == source.end())
  17274. {
  17275. // found a key that is not in this -> add it
  17276. const auto key = json_pointer::escape(it.key());
  17277. result.push_back(
  17278. {
  17279. {"op", "add"}, {"path", path + "/" + key},
  17280. {"value", it.value()}
  17281. });
  17282. }
  17283. }
  17284. break;
  17285. }
  17286. default:
  17287. {
  17288. // both primitive type: replace value
  17289. result.push_back(
  17290. {
  17291. {"op", "replace"}, {"path", path}, {"value", target}
  17292. });
  17293. break;
  17294. }
  17295. }
  17296. return result;
  17297. }
  17298. /// @}
  17299. ////////////////////////////////
  17300. // JSON Merge Patch functions //
  17301. ////////////////////////////////
  17302. /// @name JSON Merge Patch functions
  17303. /// @{
  17304. /*!
  17305. @brief applies a JSON Merge Patch
  17306. The merge patch format is primarily intended for use with the HTTP PATCH
  17307. method as a means of describing a set of modifications to a target
  17308. resource's content. This function applies a merge patch to the current
  17309. JSON value.
  17310. The function implements the following algorithm from Section 2 of
  17311. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  17312. ```
  17313. define MergePatch(Target, Patch):
  17314. if Patch is an Object:
  17315. if Target is not an Object:
  17316. Target = {} // Ignore the contents and set it to an empty Object
  17317. for each Name/Value pair in Patch:
  17318. if Value is null:
  17319. if Name exists in Target:
  17320. remove the Name/Value pair from Target
  17321. else:
  17322. Target[Name] = MergePatch(Target[Name], Value)
  17323. return Target
  17324. else:
  17325. return Patch
  17326. ```
  17327. Thereby, `Target` is the current object; that is, the patch is applied to
  17328. the current value.
  17329. @param[in] apply_patch the patch to apply
  17330. @complexity Linear in the lengths of @a patch.
  17331. @liveexample{The following code shows how a JSON Merge Patch is applied to
  17332. a JSON document.,merge_patch}
  17333. @sa @ref patch -- apply a JSON patch
  17334. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  17335. @since version 3.0.0
  17336. */
  17337. void merge_patch(const basic_json& apply_patch)
  17338. {
  17339. if (apply_patch.is_object())
  17340. {
  17341. if (not is_object())
  17342. {
  17343. *this = object();
  17344. }
  17345. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  17346. {
  17347. if (it.value().is_null())
  17348. {
  17349. erase(it.key());
  17350. }
  17351. else
  17352. {
  17353. operator[](it.key()).merge_patch(it.value());
  17354. }
  17355. }
  17356. }
  17357. else
  17358. {
  17359. *this = apply_patch;
  17360. }
  17361. }
  17362. /// @}
  17363. };
  17364. /*!
  17365. @brief user-defined to_string function for JSON values
  17366. This function implements a user-defined to_string for JSON objects.
  17367. @param[in] j a JSON object
  17368. @return a std::string object
  17369. */
  17370. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  17371. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  17372. {
  17373. return j.dump();
  17374. }
  17375. } // namespace nlohmann
  17376. ///////////////////////
  17377. // nonmember support //
  17378. ///////////////////////
  17379. // specialization of std::swap, and std::hash
  17380. namespace std
  17381. {
  17382. /// hash value for JSON objects
  17383. template<>
  17384. struct hash<nlohmann::json>
  17385. {
  17386. /*!
  17387. @brief return a hash value for a JSON object
  17388. @since version 1.0.0
  17389. */
  17390. std::size_t operator()(const nlohmann::json& j) const
  17391. {
  17392. // a naive hashing via the string representation
  17393. const auto& h = hash<nlohmann::json::string_t>();
  17394. return h(j.dump());
  17395. }
  17396. };
  17397. /// specialization for std::less<value_t>
  17398. /// @note: do not remove the space after '<',
  17399. /// see https://github.com/nlohmann/json/pull/679
  17400. template<>
  17401. struct less< ::nlohmann::detail::value_t>
  17402. {
  17403. /*!
  17404. @brief compare two value_t enum values
  17405. @since version 3.0.0
  17406. */
  17407. bool operator()(nlohmann::detail::value_t lhs,
  17408. nlohmann::detail::value_t rhs) const noexcept
  17409. {
  17410. return nlohmann::detail::operator<(lhs, rhs);
  17411. }
  17412. };
  17413. /*!
  17414. @brief exchanges the values of two JSON objects
  17415. @since version 1.0.0
  17416. */
  17417. template<>
  17418. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  17419. is_nothrow_move_constructible<nlohmann::json>::value and
  17420. is_nothrow_move_assignable<nlohmann::json>::value
  17421. )
  17422. {
  17423. j1.swap(j2);
  17424. }
  17425. } // namespace std
  17426. /*!
  17427. @brief user-defined string literal for JSON values
  17428. This operator implements a user-defined string literal for JSON objects. It
  17429. can be used by adding `"_json"` to a string literal and returns a JSON object
  17430. if no parse error occurred.
  17431. @param[in] s a string representation of a JSON object
  17432. @param[in] n the length of string @a s
  17433. @return a JSON object
  17434. @since version 1.0.0
  17435. */
  17436. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  17437. {
  17438. return nlohmann::json::parse(s, s + n);
  17439. }
  17440. /*!
  17441. @brief user-defined string literal for JSON pointer
  17442. This operator implements a user-defined string literal for JSON Pointers. It
  17443. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  17444. object if no parse error occurred.
  17445. @param[in] s a string representation of a JSON Pointer
  17446. @param[in] n the length of string @a s
  17447. @return a JSON pointer object
  17448. @since version 2.0.0
  17449. */
  17450. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  17451. {
  17452. return nlohmann::json::json_pointer(std::string(s, n));
  17453. }
  17454. // #include <nlohmann/detail/macro_unscope.hpp>
  17455. // restore GCC/clang diagnostic settings
  17456. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  17457. #pragma GCC diagnostic pop
  17458. #endif
  17459. #if defined(__clang__)
  17460. #pragma GCC diagnostic pop
  17461. #endif
  17462. // clean up
  17463. #undef JSON_INTERNAL_CATCH
  17464. #undef JSON_CATCH
  17465. #undef JSON_THROW
  17466. #undef JSON_TRY
  17467. #undef JSON_LIKELY
  17468. #undef JSON_UNLIKELY
  17469. #undef JSON_DEPRECATED
  17470. #undef JSON_NODISCARD
  17471. #undef JSON_HAS_CPP_14
  17472. #undef JSON_HAS_CPP_17
  17473. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  17474. #undef NLOHMANN_BASIC_JSON_TPL
  17475. #endif // INCLUDE_NLOHMANN_JSON_HPP_