JSON for Modern C++  3.0.0
json.hpp
1 /*
2  __ _____ _____ _____
3  __| | __| | | | JSON for Modern C++
4 | | |__ | | | | | | version 3.0.0
5 |_____|_____|_____|_|___| https://github.com/nlohmann/json
6 
7 Licensed under the MIT License <http://opensource.org/licenses/MIT>.
8 Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>.
9 
10 Permission is hereby granted, free of charge, to any person obtaining a copy
11 of this software and associated documentation files (the "Software"), to deal
12 in the Software without restriction, including without limitation the rights
13 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 copies of the Software, and to permit persons to whom the Software is
15 furnished to do so, subject to the following conditions:
16 
17 The above copyright notice and this permission notice shall be included in all
18 copies or substantial portions of the Software.
19 
20 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26 SOFTWARE.
27 */
28 
29 #ifndef NLOHMANN_JSON_HPP
30 #define NLOHMANN_JSON_HPP
31 
32 #include <algorithm> // all_of, copy, fill, find, for_each, generate_n, none_of, remove, reverse, transform
33 #include <array> // array
34 #include <cassert> // assert
35 #include <ciso646> // and, not, or
36 #include <clocale> // lconv, localeconv
37 #include <cmath> // isfinite, labs, ldexp, signbit
38 #include <cstddef> // nullptr_t, ptrdiff_t, size_t
39 #include <cstdint> // int64_t, uint64_t
40 #include <cstdlib> // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull
41 #include <cstring> // memcpy, strlen
42 #include <forward_list> // forward_list
43 #include <functional> // function, hash, less
44 #include <initializer_list> // initializer_list
45 #include <iomanip> // hex
46 #include <iosfwd> // istream, ostream
47 #include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator
48 #include <limits> // numeric_limits
49 #include <locale> // locale
50 #include <map> // map
51 #include <memory> // addressof, allocator, allocator_traits, unique_ptr
52 #include <numeric> // accumulate
53 #include <sstream> // stringstream
54 #include <string> // getline, stoi, string, to_string
55 #include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type
56 #include <utility> // declval, forward, make_pair, move, pair, swap
57 #include <valarray> // valarray
58 #include <vector> // vector
59 
60 // exclude unsupported compilers
61 #if defined(__clang__)
62  #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
63  #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
64  #endif
65 #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
66  #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900
67  #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
68  #endif
69 #endif
70 
71 // disable float-equal warnings on GCC/clang
72 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
73  #pragma GCC diagnostic push
74  #pragma GCC diagnostic ignored "-Wfloat-equal"
75 #endif
76 
77 // disable documentation warnings on clang
78 #if defined(__clang__)
79  #pragma GCC diagnostic push
80  #pragma GCC diagnostic ignored "-Wdocumentation"
81 #endif
82 
83 // allow for portable deprecation warnings
84 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
85  #define JSON_DEPRECATED __attribute__((deprecated))
86 #elif defined(_MSC_VER)
87  #define JSON_DEPRECATED __declspec(deprecated)
88 #else
89  #define JSON_DEPRECATED
90 #endif
91 
92 // allow to disable exceptions
93 #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && not defined(JSON_NOEXCEPTION)
94  #define JSON_THROW(exception) throw exception
95  #define JSON_TRY try
96  #define JSON_CATCH(exception) catch(exception)
97 #else
98  #define JSON_THROW(exception) std::abort()
99  #define JSON_TRY if(true)
100  #define JSON_CATCH(exception) if(false)
101 #endif
102 
103 // manual branch prediction
104 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
105  #define JSON_LIKELY(x) __builtin_expect(!!(x), 1)
106  #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
107 #else
108  #define JSON_LIKELY(x) x
109  #define JSON_UNLIKELY(x) x
110 #endif
111 
112 // C++ language standard detection
113 #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
114  #define JSON_HAS_CPP_17
115  #define JSON_HAS_CPP_14
116 #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
117  #define JSON_HAS_CPP_14
118 #endif
119 
120 /*!
121 @brief namespace for Niels Lohmann
122 @see https://github.com/nlohmann
123 @since version 1.0.0
124 */
125 namespace nlohmann
126 {
127 template<typename = void, typename = void>
128 struct adl_serializer;
129 
130 // forward declaration of basic_json (required to split the class)
131 template<template<typename, typename, typename...> class ObjectType = std::map,
132  template<typename, typename...> class ArrayType = std::vector,
133  class StringType = std::string, class BooleanType = bool,
134  class NumberIntegerType = std::int64_t,
135  class NumberUnsignedType = std::uint64_t,
136  class NumberFloatType = double,
137  template<typename> class AllocatorType = std::allocator,
138  template<typename, typename = void> class JSONSerializer = adl_serializer>
140 
141 // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
142 // may be removed in the future once the class is split.
143 
144 #define NLOHMANN_BASIC_JSON_TPL_DECLARATION
145  template<template<typename, typename, typename...> class ObjectType,
146  template<typename, typename...> class ArrayType,
147  class StringType, class BooleanType, class NumberIntegerType,
148  class NumberUnsignedType, class NumberFloatType,
149  template<typename> class AllocatorType,
150  template<typename, typename = void> class JSONSerializer>
151 
152 #define NLOHMANN_BASIC_JSON_TPL
153  basic_json<ObjectType, ArrayType, StringType, BooleanType,
154  NumberIntegerType, NumberUnsignedType, NumberFloatType,
155  AllocatorType, JSONSerializer>
156 
157 
158 /*!
159 @brief unnamed namespace with internal helper functions
160 
161 This namespace collects some functions that could not be defined inside the
162 @ref basic_json class.
163 
164 @since version 2.1.0
165 */
166 namespace detail
167 {
168 ////////////////
169 // exceptions //
170 ////////////////
171 
172 /*!
173 @brief general exception of the @ref basic_json class
174 
175 This class is an extension of `std::exception` objects with a member @a id for
176 exception ids. It is used as the base class for all exceptions thrown by the
177 @ref basic_json class. This class can hence be used as "wildcard" to catch
178 exceptions.
179 
180 Subclasses:
181 - @ref parse_error for exceptions indicating a parse error
182 - @ref invalid_iterator for exceptions indicating errors with iterators
183 - @ref type_error for exceptions indicating executing a member function with
184  a wrong type
185 - @ref out_of_range for exceptions indicating access out of the defined range
186 - @ref other_error for exceptions indicating other library errors
187 
188 @internal
189 @note To have nothrow-copy-constructible exceptions, we internally use
190  `std::runtime_error` which can cope with arbitrary-length error messages.
191  Intermediate strings are built with static functions and then passed to
192  the actual constructor.
193 @endinternal
194 
195 @liveexample{The following code shows how arbitrary library exceptions can be
196 caught.,exception}
197 
198 @since version 3.0.0
199 */
200 class exception : public std::exception
201 {
202  public:
203  /// returns the explanatory string
204  const char* what() const noexcept override
205  {
206  return m.what();
207  }
208 
209  /// the id of the exception
210  const int id;
211 
212  protected:
213  exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
214 
215  static std::string name(const std::string& ename, int id_)
216  {
217  return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
218  }
219 
220  private:
221  /// an exception object as storage for error messages
222  std::runtime_error m;
223 };
224 
225 /*!
226 @brief exception indicating a parse error
227 
228 This exception is thrown by the library when a parse error occurs. Parse errors
229 can occur during the deserialization of JSON text, CBOR, MessagePack, as well
230 as when using JSON Patch.
231 
232 Member @a byte holds the byte index of the last read character in the input
233 file.
234 
235 Exceptions have ids 1xx.
236 
237 name / id | example message | description
238 ------------------------------ | --------------- | -------------------------
239 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.
240 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.
241 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.
242 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.
243 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.
244 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`.
245 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.
246 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.
247 json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
248 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.
249 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.
250 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.
251 
252 @note For an input with n bytes, 1 is the index of the first character and n+1
253  is the index of the terminating null byte or the end of file. This also
254  holds true when reading a byte vector (CBOR or MessagePack).
255 
256 @liveexample{The following code shows how a `parse_error` exception can be
257 caught.,parse_error}
258 
259 @sa @ref exception for the base class of the library exceptions
260 @sa @ref invalid_iterator for exceptions indicating errors with iterators
261 @sa @ref type_error for exceptions indicating executing a member function with
262  a wrong type
263 @sa @ref out_of_range for exceptions indicating access out of the defined range
264 @sa @ref other_error for exceptions indicating other library errors
265 
266 @since version 3.0.0
267 */
268 class parse_error : public exception
269 {
270  public:
271  /*!
272  @brief create a parse error exception
273  @param[in] id_ the id of the exception
274  @param[in] byte_ the byte index where the error occurred (or 0 if the
275  position cannot be determined)
276  @param[in] what_arg the explanatory string
277  @return parse_error object
278  */
279  static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
280  {
281  std::string w = exception::name("parse_error", id_) + "parse error" +
282  (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") +
283  ": " + what_arg;
284  return parse_error(id_, byte_, w.c_str());
285  }
286 
287  /*!
288  @brief byte index of the parse error
289 
290  The byte index of the last read character in the input file.
291 
292  @note For an input with n bytes, 1 is the index of the first character and
293  n+1 is the index of the terminating null byte or the end of file.
294  This also holds true when reading a byte vector (CBOR or MessagePack).
295  */
296  const std::size_t byte;
297 
298  private:
299  parse_error(int id_, std::size_t byte_, const char* what_arg)
300  : exception(id_, what_arg), byte(byte_) {}
301 };
302 
303 /*!
304 @brief exception indicating errors with iterators
305 
306 This exception is thrown if iterators passed to a library function do not match
307 the expected semantics.
308 
309 Exceptions have ids 2xx.
310 
311 name / id | example message | description
312 ----------------------------------- | --------------- | -------------------------
313 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.
314 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.
315 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.
316 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.
317 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.
318 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.
319 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.
320 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.
321 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.
322 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.
323 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.
324 json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
325 json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
326 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().
327 
328 @liveexample{The following code shows how an `invalid_iterator` exception can be
329 caught.,invalid_iterator}
330 
331 @sa @ref exception for the base class of the library exceptions
332 @sa @ref parse_error for exceptions indicating a parse error
333 @sa @ref type_error for exceptions indicating executing a member function with
334  a wrong type
335 @sa @ref out_of_range for exceptions indicating access out of the defined range
336 @sa @ref other_error for exceptions indicating other library errors
337 
338 @since version 3.0.0
339 */
340 class invalid_iterator : public exception
341 {
342  public:
343  static invalid_iterator create(int id_, const std::string& what_arg)
344  {
345  std::string w = exception::name("invalid_iterator", id_) + what_arg;
346  return invalid_iterator(id_, w.c_str());
347  }
348 
349  private:
350  invalid_iterator(int id_, const char* what_arg)
351  : exception(id_, what_arg) {}
352 };
353 
354 /*!
355 @brief exception indicating executing a member function with a wrong type
356 
357 This exception is thrown in case of a type error; that is, a library function is
358 executed on a JSON value whose type does not match the expected semantics.
359 
360 Exceptions have ids 3xx.
361 
362 name / id | example message | description
363 ----------------------------- | --------------- | -------------------------
364 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.
365 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.
366 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&.
367 json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
368 json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
369 json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
370 json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
371 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.
372 json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
373 json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
374 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.
375 json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
376 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.
377 json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
378 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.
379 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. |
380 
381 @liveexample{The following code shows how a `type_error` exception can be
382 caught.,type_error}
383 
384 @sa @ref exception for the base class of the library exceptions
385 @sa @ref parse_error for exceptions indicating a parse error
386 @sa @ref invalid_iterator for exceptions indicating errors with iterators
387 @sa @ref out_of_range for exceptions indicating access out of the defined range
388 @sa @ref other_error for exceptions indicating other library errors
389 
390 @since version 3.0.0
391 */
392 class type_error : public exception
393 {
394  public:
395  static type_error create(int id_, const std::string& what_arg)
396  {
397  std::string w = exception::name("type_error", id_) + what_arg;
398  return type_error(id_, w.c_str());
399  }
400 
401  private:
402  type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
403 };
404 
405 /*!
406 @brief exception indicating access out of the defined range
407 
408 This exception is thrown in case a library function is called on an input
409 parameter that exceeds the expected range, for instance in case of array
410 indices or nonexisting object keys.
411 
412 Exceptions have ids 4xx.
413 
414 name / id | example message | description
415 ------------------------------- | --------------- | -------------------------
416 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.
417 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.
418 json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
419 json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
420 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.
421 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.
422 
423 @liveexample{The following code shows how an `out_of_range` exception can be
424 caught.,out_of_range}
425 
426 @sa @ref exception for the base class of the library exceptions
427 @sa @ref parse_error for exceptions indicating a parse error
428 @sa @ref invalid_iterator for exceptions indicating errors with iterators
429 @sa @ref type_error for exceptions indicating executing a member function with
430  a wrong type
431 @sa @ref other_error for exceptions indicating other library errors
432 
433 @since version 3.0.0
434 */
435 class out_of_range : public exception
436 {
437  public:
438  static out_of_range create(int id_, const std::string& what_arg)
439  {
440  std::string w = exception::name("out_of_range", id_) + what_arg;
441  return out_of_range(id_, w.c_str());
442  }
443 
444  private:
445  out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
446 };
447 
448 /*!
449 @brief exception indicating other library errors
450 
451 This exception is thrown in case of errors that cannot be classified with the
452 other exception types.
453 
454 Exceptions have ids 5xx.
455 
456 name / id | example message | description
457 ------------------------------ | --------------- | -------------------------
458 json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
459 
460 @sa @ref exception for the base class of the library exceptions
461 @sa @ref parse_error for exceptions indicating a parse error
462 @sa @ref invalid_iterator for exceptions indicating errors with iterators
463 @sa @ref type_error for exceptions indicating executing a member function with
464  a wrong type
465 @sa @ref out_of_range for exceptions indicating access out of the defined range
466 
467 @liveexample{The following code shows how an `other_error` exception can be
468 caught.,other_error}
469 
470 @since version 3.0.0
471 */
472 class other_error : public exception
473 {
474  public:
475  static other_error create(int id_, const std::string& what_arg)
476  {
477  std::string w = exception::name("other_error", id_) + what_arg;
478  return other_error(id_, w.c_str());
479  }
480 
481  private:
482  other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
483 };
484 
485 
486 
487 ///////////////////////////
488 // JSON type enumeration //
489 ///////////////////////////
490 
491 /*!
492 @brief the JSON type enumeration
493 
494 This enumeration collects the different JSON types. It is internally used to
495 distinguish the stored values, and the functions @ref basic_json::is_null(),
496 @ref basic_json::is_object(), @ref basic_json::is_array(),
497 @ref basic_json::is_string(), @ref basic_json::is_boolean(),
498 @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
499 @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
500 @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
501 @ref basic_json::is_structured() rely on it.
502 
503 @note There are three enumeration entries (number_integer, number_unsigned, and
504 number_float), because the library distinguishes these three types for numbers:
505 @ref basic_json::number_unsigned_t is used for unsigned integers,
506 @ref basic_json::number_integer_t is used for signed integers, and
507 @ref basic_json::number_float_t is used for floating-point numbers or to
508 approximate integers which do not fit in the limits of their respective type.
509 
510 @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
511 value with the default value for a given type
512 
513 @since version 1.0.0
514 */
515 enum class value_t : uint8_t
516 {
517  null, ///< null value
518  object, ///< object (unordered set of name/value pairs)
519  array, ///< array (ordered collection of values)
520  string, ///< string value
521  boolean, ///< boolean value
522  number_integer, ///< number value (signed integer)
523  number_unsigned, ///< number value (unsigned integer)
524  number_float, ///< number value (floating-point)
525  discarded ///< discarded by the the parser callback function
526 };
527 
528 /*!
529 @brief comparison operator for JSON types
530 
531 Returns an ordering that is similar to Python:
532 - order: null < boolean < number < object < array < string
533 - furthermore, each type is not smaller than itself
534 - discarded values are not comparable
535 
536 @since version 1.0.0
537 */
538 inline bool operator<(const value_t lhs, const value_t rhs) noexcept
539 {
540  static constexpr std::array<uint8_t, 8> order = {{
541  0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
542  1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
543  }
544  };
545 
546  const auto l_index = static_cast<std::size_t>(lhs);
547  const auto r_index = static_cast<std::size_t>(rhs);
548  return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
549 }
550 
551 
552 /////////////
553 // helpers //
554 /////////////
555 
556 template<typename> struct is_basic_json : std::false_type {};
557 
559 struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
560 
561 // alias templates to reduce boilerplate
562 template<bool B, typename T = void>
563 using enable_if_t = typename std::enable_if<B, T>::type;
564 
565 template<typename T>
566 using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
567 
568 // implementation of C++14 index_sequence and affiliates
569 // source: https://stackoverflow.com/a/32223343
570 template<std::size_t... Ints>
571 struct index_sequence
572 {
573  using type = index_sequence;
574  using value_type = std::size_t;
575  static constexpr std::size_t size() noexcept
576  {
577  return sizeof...(Ints);
578  }
579 };
580 
581 template<class Sequence1, class Sequence2>
582 struct merge_and_renumber;
583 
584 template<std::size_t... I1, std::size_t... I2>
585 struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
586  : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
587 
588 template<std::size_t N>
589 struct make_index_sequence
590  : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
591  typename make_index_sequence < N - N / 2 >::type > {};
592 
593 template<> struct make_index_sequence<0> : index_sequence<> {};
594 template<> struct make_index_sequence<1> : index_sequence<0> {};
595 
596 template<typename... Ts>
597 using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
598 
599 /*
600 Implementation of two C++17 constructs: conjunction, negation. This is needed
601 to avoid evaluating all the traits in a condition
602 
603 For example: not std::is_same<void, T>::value and has_value_type<T>::value
604 will not compile when T = void (on MSVC at least). Whereas
605 conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
606 stop evaluating if negation<...>::value == false
607 
608 Please note that those constructs must be used with caution, since symbols can
609 become very long quickly (which can slow down compilation and cause MSVC
610 internal compiler errors). Only use it when you have to (see example ahead).
611 */
612 template<class...> struct conjunction : std::true_type {};
613 template<class B1> struct conjunction<B1> : B1 {};
614 template<class B1, class... Bn>
615 struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
616 
617 template<class B> struct negation : std::integral_constant<bool, not B::value> {};
618 
619 // dispatch utility (taken from ranges-v3)
620 template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
621 template<> struct priority_tag<0> {};
622 
623 
624 //////////////////
625 // constructors //
626 //////////////////
627 
628 template<value_t> struct external_constructor;
629 
630 template<>
631 struct external_constructor<value_t::boolean>
632 {
633  template<typename BasicJsonType>
634  static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
635  {
636  j.m_type = value_t::boolean;
637  j.m_value = b;
638  j.assert_invariant();
639  }
640 };
641 
642 template<>
643 struct external_constructor<value_t::string>
644 {
645  template<typename BasicJsonType>
646  static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
647  {
648  j.m_type = value_t::string;
649  j.m_value = s;
650  j.assert_invariant();
651  }
652 
653  template<typename BasicJsonType>
654  static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
655  {
656  j.m_type = value_t::string;
657  j.m_value = std::move(s);
658  j.assert_invariant();
659  }
660 };
661 
662 template<>
663 struct external_constructor<value_t::number_float>
664 {
665  template<typename BasicJsonType>
666  static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
667  {
668  j.m_type = value_t::number_float;
669  j.m_value = val;
670  j.assert_invariant();
671  }
672 };
673 
674 template<>
675 struct external_constructor<value_t::number_unsigned>
676 {
677  template<typename BasicJsonType>
678  static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
679  {
680  j.m_type = value_t::number_unsigned;
681  j.m_value = val;
682  j.assert_invariant();
683  }
684 };
685 
686 template<>
687 struct external_constructor<value_t::number_integer>
688 {
689  template<typename BasicJsonType>
690  static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
691  {
692  j.m_type = value_t::number_integer;
693  j.m_value = val;
694  j.assert_invariant();
695  }
696 };
697 
698 template<>
699 struct external_constructor<value_t::array>
700 {
701  template<typename BasicJsonType>
702  static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
703  {
704  j.m_type = value_t::array;
705  j.m_value = arr;
706  j.assert_invariant();
707  }
708 
709  template<typename BasicJsonType>
710  static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
711  {
712  j.m_type = value_t::array;
713  j.m_value = std::move(arr);
714  j.assert_invariant();
715  }
716 
717  template<typename BasicJsonType, typename CompatibleArrayType,
718  enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
719  int> = 0>
720  static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
721  {
722  using std::begin;
723  using std::end;
724  j.m_type = value_t::array;
725  j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
726  j.assert_invariant();
727  }
728 
729  template<typename BasicJsonType>
730  static void construct(BasicJsonType& j, const std::vector<bool>& arr)
731  {
732  j.m_type = value_t::array;
733  j.m_value = value_t::array;
734  j.m_value.array->reserve(arr.size());
735  for (bool x : arr)
736  {
737  j.m_value.array->push_back(x);
738  }
739  j.assert_invariant();
740  }
741 
742  template<typename BasicJsonType, typename T,
743  enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
744  static void construct(BasicJsonType& j, const std::valarray<T>& arr)
745  {
746  j.m_type = value_t::array;
747  j.m_value = value_t::array;
748  j.m_value.array->resize(arr.size());
749  std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
750  j.assert_invariant();
751  }
752 };
753 
754 template<>
755 struct external_constructor<value_t::object>
756 {
757  template<typename BasicJsonType>
758  static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
759  {
760  j.m_type = value_t::object;
761  j.m_value = obj;
762  j.assert_invariant();
763  }
764 
765  template<typename BasicJsonType>
766  static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
767  {
768  j.m_type = value_t::object;
769  j.m_value = std::move(obj);
770  j.assert_invariant();
771  }
772 
773  template<typename BasicJsonType, typename CompatibleObjectType,
774  enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
775  static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
776  {
777  using std::begin;
778  using std::end;
779 
780  j.m_type = value_t::object;
781  j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
782  j.assert_invariant();
783  }
784 };
785 
786 
787 ////////////////////////
788 // has_/is_ functions //
789 ////////////////////////
790 
791 /*!
792 @brief Helper to determine whether there's a key_type for T.
793 
794 This helper is used to tell associative containers apart from other containers
795 such as sequence containers. For instance, `std::map` passes the test as it
796 contains a `mapped_type`, whereas `std::vector` fails the test.
797 
798 @sa http://stackoverflow.com/a/7728728/266378
799 @since version 1.0.0, overworked in version 2.0.6
800 */
801 #define NLOHMANN_JSON_HAS_HELPER(type)
802  template<typename T> struct has_##type {
803  private:
804  template<typename U, typename = typename U::type>
805  static int detect(U &&);
806  static void detect(...);
807  public:
808  static constexpr bool value =
809  std::is_integral<decltype(detect(std::declval<T>()))>::value;
810  }
811 
812 NLOHMANN_JSON_HAS_HELPER(mapped_type);
813 NLOHMANN_JSON_HAS_HELPER(key_type);
814 NLOHMANN_JSON_HAS_HELPER(value_type);
815 NLOHMANN_JSON_HAS_HELPER(iterator);
816 
817 #undef NLOHMANN_JSON_HAS_HELPER
818 
819 
820 template<bool B, class RealType, class CompatibleObjectType>
821 struct is_compatible_object_type_impl : std::false_type {};
822 
823 template<class RealType, class CompatibleObjectType>
824 struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
825 {
826  static constexpr auto value =
827  std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and
828  std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value;
829 };
830 
831 template<class BasicJsonType, class CompatibleObjectType>
832 struct is_compatible_object_type
833 {
834  static auto constexpr value = is_compatible_object_type_impl <
835  conjunction<negation<std::is_same<void, CompatibleObjectType>>,
836  has_mapped_type<CompatibleObjectType>,
837  has_key_type<CompatibleObjectType>>::value,
838  typename BasicJsonType::object_t, CompatibleObjectType >::value;
839 };
840 
841 template<typename BasicJsonType, typename T>
842 struct is_basic_json_nested_type
843 {
844  static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
845  std::is_same<T, typename BasicJsonType::const_iterator>::value or
846  std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
847  std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value;
848 };
849 
850 template<class BasicJsonType, class CompatibleArrayType>
851 struct is_compatible_array_type
852 {
853  static auto constexpr value =
854  conjunction<negation<std::is_same<void, CompatibleArrayType>>,
855  negation<is_compatible_object_type<
856  BasicJsonType, CompatibleArrayType>>,
857  negation<std::is_constructible<typename BasicJsonType::string_t,
858  CompatibleArrayType>>,
859  negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
860  has_value_type<CompatibleArrayType>,
861  has_iterator<CompatibleArrayType>>::value;
862 };
863 
864 template<bool, typename, typename>
865 struct is_compatible_integer_type_impl : std::false_type {};
866 
867 template<typename RealIntegerType, typename CompatibleNumberIntegerType>
868 struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
869 {
870  // is there an assert somewhere on overflows?
871  using RealLimits = std::numeric_limits<RealIntegerType>;
872  using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
873 
874  static constexpr auto value =
875  std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and
876  CompatibleLimits::is_integer and
877  RealLimits::is_signed == CompatibleLimits::is_signed;
878 };
879 
880 template<typename RealIntegerType, typename CompatibleNumberIntegerType>
881 struct is_compatible_integer_type
882 {
883  static constexpr auto value =
884  is_compatible_integer_type_impl <
885  std::is_integral<CompatibleNumberIntegerType>::value and
886  not std::is_same<bool, CompatibleNumberIntegerType>::value,
887  RealIntegerType, CompatibleNumberIntegerType >::value;
888 };
889 
890 
891 // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
892 template<typename BasicJsonType, typename T>
893 struct has_from_json
894 {
895  private:
896  // also check the return type of from_json
897  template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
898  std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
899  static int detect(U&&);
900  static void detect(...);
901 
902  public:
903  static constexpr bool value = std::is_integral<decltype(
904  detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
905 };
906 
907 // This trait checks if JSONSerializer<T>::from_json(json const&) exists
908 // this overload is used for non-default-constructible user-defined-types
909 template<typename BasicJsonType, typename T>
910 struct has_non_default_from_json
911 {
912  private:
913  template<typename U, typename =
914  enable_if_t<std::is_same<T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value>>
915  static int detect(U&&);
916  static void detect(...);
917 
918  public:
919  static constexpr bool value = std::is_integral<decltype(detect(
920  std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
921 };
922 
923 // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
924 template<typename BasicJsonType, typename T>
925 struct has_to_json
926 {
927  private:
928  template<typename U, typename = decltype(uncvref_t<U>::to_json(
929  std::declval<BasicJsonType&>(), std::declval<T>()))>
930  static int detect(U&&);
931  static void detect(...);
932 
933  public:
934  static constexpr bool value = std::is_integral<decltype(detect(
935  std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
936 };
937 
938 
939 /////////////
940 // to_json //
941 /////////////
942 
943 template<typename BasicJsonType, typename T,
944  enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
945 void to_json(BasicJsonType& j, T b) noexcept
946 {
947  external_constructor<value_t::boolean>::construct(j, b);
948 }
949 
950 template<typename BasicJsonType, typename CompatibleString,
951  enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
952 void to_json(BasicJsonType& j, const CompatibleString& s)
953 {
954  external_constructor<value_t::string>::construct(j, s);
955 }
956 
957 template<typename BasicJsonType>
958 void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
959 {
960  external_constructor<value_t::string>::construct(j, std::move(s));
961 }
962 
963 template<typename BasicJsonType, typename FloatType,
964  enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
965 void to_json(BasicJsonType& j, FloatType val) noexcept
966 {
967  external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
968 }
969 
970 template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
971  enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
972 void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
973 {
974  external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
975 }
976 
977 template<typename BasicJsonType, typename CompatibleNumberIntegerType,
978  enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
979 void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
980 {
981  external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
982 }
983 
984 template<typename BasicJsonType, typename EnumType,
985  enable_if_t<std::is_enum<EnumType>::value, int> = 0>
986 void to_json(BasicJsonType& j, EnumType e) noexcept
987 {
988  using underlying_type = typename std::underlying_type<EnumType>::type;
989  external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
990 }
991 
992 template<typename BasicJsonType>
993 void to_json(BasicJsonType& j, const std::vector<bool>& e)
994 {
995  external_constructor<value_t::array>::construct(j, e);
996 }
997 
998 template<typename BasicJsonType, typename CompatibleArrayType,
999  enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
1000  std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
1001  int> = 0>
1002 void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
1003 {
1004  external_constructor<value_t::array>::construct(j, arr);
1005 }
1006 
1007 template<typename BasicJsonType, typename T,
1008  enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
1009 void to_json(BasicJsonType& j, std::valarray<T> arr)
1010 {
1011  external_constructor<value_t::array>::construct(j, std::move(arr));
1012 }
1013 
1014 template<typename BasicJsonType>
1015 void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
1016 {
1017  external_constructor<value_t::array>::construct(j, std::move(arr));
1018 }
1019 
1020 template<typename BasicJsonType, typename CompatibleObjectType,
1021  enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
1022 void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
1023 {
1024  external_constructor<value_t::object>::construct(j, obj);
1025 }
1026 
1027 template<typename BasicJsonType>
1028 void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
1029 {
1030  external_constructor<value_t::object>::construct(j, std::move(obj));
1031 }
1032 
1033 template<typename BasicJsonType, typename T, std::size_t N,
1034  enable_if_t<not std::is_constructible<typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0>
1035 void to_json(BasicJsonType& j, T (&arr)[N])
1036 {
1037  external_constructor<value_t::array>::construct(j, arr);
1038 }
1039 
1040 template<typename BasicJsonType, typename... Args>
1041 void to_json(BasicJsonType& j, const std::pair<Args...>& p)
1042 {
1043  j = {p.first, p.second};
1044 }
1045 
1046 template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
1047 void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>)
1048 {
1049  j = {std::get<Idx>(t)...};
1050 }
1051 
1052 template<typename BasicJsonType, typename... Args>
1053 void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
1054 {
1055  to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
1056 }
1057 
1058 ///////////////
1059 // from_json //
1060 ///////////////
1061 
1062 // overloads for basic_json template parameters
1063 template<typename BasicJsonType, typename ArithmeticType,
1064  enable_if_t<std::is_arithmetic<ArithmeticType>::value and
1065  not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
1066  int> = 0>
1067 void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
1068 {
1069  switch (static_cast<value_t>(j))
1070  {
1071  case value_t::number_unsigned:
1072  {
1073  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
1074  break;
1075  }
1076  case value_t::number_integer:
1077  {
1078  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
1079  break;
1080  }
1081  case value_t::number_float:
1082  {
1083  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
1084  break;
1085  }
1086 
1087  default:
1088  JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
1089  }
1090 }
1091 
1092 template<typename BasicJsonType>
1093 void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
1094 {
1095  if (JSON_UNLIKELY(not j.is_boolean()))
1096  {
1097  JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
1098  }
1099  b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
1100 }
1101 
1102 template<typename BasicJsonType>
1103 void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
1104 {
1105  if (JSON_UNLIKELY(not j.is_string()))
1106  {
1107  JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
1108  }
1109  s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
1110 }
1111 
1112 template<typename BasicJsonType>
1113 void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
1114 {
1115  get_arithmetic_value(j, val);
1116 }
1117 
1118 template<typename BasicJsonType>
1119 void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
1120 {
1121  get_arithmetic_value(j, val);
1122 }
1123 
1124 template<typename BasicJsonType>
1125 void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
1126 {
1127  get_arithmetic_value(j, val);
1128 }
1129 
1130 template<typename BasicJsonType, typename EnumType,
1131  enable_if_t<std::is_enum<EnumType>::value, int> = 0>
1132 void from_json(const BasicJsonType& j, EnumType& e)
1133 {
1134  typename std::underlying_type<EnumType>::type val;
1135  get_arithmetic_value(j, val);
1136  e = static_cast<EnumType>(val);
1137 }
1138 
1139 template<typename BasicJsonType>
1140 void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
1141 {
1142  if (JSON_UNLIKELY(not j.is_array()))
1143  {
1144  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1145  }
1146  arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
1147 }
1148 
1149 // forward_list doesn't have an insert method
1150 template<typename BasicJsonType, typename T, typename Allocator,
1151  enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
1152 void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
1153 {
1154  if (JSON_UNLIKELY(not j.is_array()))
1155  {
1156  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1157  }
1158  std::transform(j.rbegin(), j.rend(),
1159  std::front_inserter(l), [](const BasicJsonType & i)
1160  {
1161  return i.template get<T>();
1162  });
1163 }
1164 
1165 // valarray doesn't have an insert method
1166 template<typename BasicJsonType, typename T,
1167  enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
1168 void from_json(const BasicJsonType& j, std::valarray<T>& l)
1169 {
1170  if (JSON_UNLIKELY(not j.is_array()))
1171  {
1172  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1173  }
1174  l.resize(j.size());
1175  std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
1176 }
1177 
1178 template<typename BasicJsonType, typename CompatibleArrayType>
1179 void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/)
1180 {
1181  using std::end;
1182 
1183  std::transform(j.begin(), j.end(),
1184  std::inserter(arr, end(arr)), [](const BasicJsonType & i)
1185  {
1186  // get<BasicJsonType>() returns *this, this won't call a from_json
1187  // method when value_type is BasicJsonType
1188  return i.template get<typename CompatibleArrayType::value_type>();
1189  });
1190 }
1191 
1192 template<typename BasicJsonType, typename CompatibleArrayType>
1193 auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/)
1194 -> decltype(
1195  arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
1196  void())
1197 {
1198  using std::end;
1199 
1200  arr.reserve(j.size());
1201  std::transform(j.begin(), j.end(),
1202  std::inserter(arr, end(arr)), [](const BasicJsonType & i)
1203  {
1204  // get<BasicJsonType>() returns *this, this won't call a from_json
1205  // method when value_type is BasicJsonType
1206  return i.template get<typename CompatibleArrayType::value_type>();
1207  });
1208 }
1209 
1210 template<typename BasicJsonType, typename T, std::size_t N>
1211 void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/)
1212 {
1213  for (std::size_t i = 0; i < N; ++i)
1214  {
1215  arr[i] = j.at(i).template get<T>();
1216  }
1217 }
1218 
1219 template<typename BasicJsonType, typename CompatibleArrayType,
1220  enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
1221  std::is_convertible<BasicJsonType, typename CompatibleArrayType::value_type>::value and
1222  not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0>
1223 void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
1224 {
1225  if (JSON_UNLIKELY(not j.is_array()))
1226  {
1227  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1228  }
1229 
1230  from_json_array_impl(j, arr, priority_tag<2> {});
1231 }
1232 
1233 template<typename BasicJsonType, typename CompatibleObjectType,
1234  enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
1235 void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
1236 {
1237  if (JSON_UNLIKELY(not j.is_object()))
1238  {
1239  JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
1240  }
1241 
1242  auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
1243  using value_type = typename CompatibleObjectType::value_type;
1244  std::transform(
1245  inner_object->begin(), inner_object->end(),
1246  std::inserter(obj, obj.begin()),
1247  [](typename BasicJsonType::object_t::value_type const & p)
1248  {
1249  return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>());
1250  });
1251 }
1252 
1253 // overload for arithmetic types, not chosen for basic_json template arguments
1254 // (BooleanType, etc..); note: Is it really necessary to provide explicit
1255 // overloads for boolean_t etc. in case of a custom BooleanType which is not
1256 // an arithmetic type?
1257 template<typename BasicJsonType, typename ArithmeticType,
1258  enable_if_t <
1259  std::is_arithmetic<ArithmeticType>::value and
1260  not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
1261  not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
1262  not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
1263  not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
1264  int> = 0>
1265 void from_json(const BasicJsonType& j, ArithmeticType& val)
1266 {
1267  switch (static_cast<value_t>(j))
1268  {
1269  case value_t::number_unsigned:
1270  {
1271  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
1272  break;
1273  }
1274  case value_t::number_integer:
1275  {
1276  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
1277  break;
1278  }
1279  case value_t::number_float:
1280  {
1281  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
1282  break;
1283  }
1284  case value_t::boolean:
1285  {
1286  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
1287  break;
1288  }
1289 
1290  default:
1291  JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
1292  }
1293 }
1294 
1295 template<typename BasicJsonType, typename A1, typename A2>
1296 void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
1297 {
1298  p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
1299 }
1300 
1301 template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
1302 void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>)
1303 {
1304  t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
1305 }
1306 
1307 template<typename BasicJsonType, typename... Args>
1308 void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
1309 {
1310  from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
1311 }
1312 
1313 struct to_json_fn
1314 {
1315  private:
1316  template<typename BasicJsonType, typename T>
1317  auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
1318  -> decltype(to_json(j, std::forward<T>(val)), void())
1319  {
1320  return to_json(j, std::forward<T>(val));
1321  }
1322 
1323  template<typename BasicJsonType, typename T>
1324  void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept
1325  {
1326  static_assert(sizeof(BasicJsonType) == 0,
1327  "could not find to_json() method in T's namespace");
1328 
1329 #ifdef _MSC_VER
1330  // MSVC does not show a stacktrace for the above assert
1331  using decayed = uncvref_t<T>;
1332  static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
1333  "forcing MSVC stacktrace to show which T we're talking about.");
1334 #endif
1335  }
1336 
1337  public:
1338  template<typename BasicJsonType, typename T>
1339  void operator()(BasicJsonType& j, T&& val) const
1340  noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
1341  {
1342  return call(j, std::forward<T>(val), priority_tag<1> {});
1343  }
1344 };
1345 
1346 struct from_json_fn
1347 {
1348  private:
1349  template<typename BasicJsonType, typename T>
1350  auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const
1351  noexcept(noexcept(from_json(j, val)))
1352  -> decltype(from_json(j, val), void())
1353  {
1354  return from_json(j, val);
1355  }
1356 
1357  template<typename BasicJsonType, typename T>
1358  void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept
1359  {
1360  static_assert(sizeof(BasicJsonType) == 0,
1361  "could not find from_json() method in T's namespace");
1362 #ifdef _MSC_VER
1363  // MSVC does not show a stacktrace for the above assert
1364  using decayed = uncvref_t<T>;
1365  static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
1366  "forcing MSVC stacktrace to show which T we're talking about.");
1367 #endif
1368  }
1369 
1370  public:
1371  template<typename BasicJsonType, typename T>
1372  void operator()(const BasicJsonType& j, T& val) const
1373  noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
1374  {
1375  return call(j, val, priority_tag<1> {});
1376  }
1377 };
1378 
1379 // taken from ranges-v3
1380 template<typename T>
1381 struct static_const
1382 {
1383  static constexpr T value{};
1384 };
1385 
1386 template<typename T>
1387 constexpr T static_const<T>::value;
1388 
1389 ////////////////////
1390 // input adapters //
1391 ////////////////////
1392 
1393 /*!
1394 @brief abstract input adapter interface
1395 
1396 Produces a stream of std::char_traits<char>::int_type characters from a
1397 std::istream, a buffer, or some other input type. Accepts the return of exactly
1398 one non-EOF character for future input. The int_type characters returned
1399 consist of all valid char values as positive values (typically unsigned char),
1400 plus an EOF value outside that range, specified by the value of the function
1401 std::char_traits<char>::eof(). This value is typically -1, but could be any
1402 arbitrary value which is not a valid char value.
1403 */
1404 struct input_adapter_protocol
1405 {
1406  /// get a character [0,255] or std::char_traits<char>::eof().
1407  virtual std::char_traits<char>::int_type get_character() = 0;
1408  /// restore the last non-eof() character to input
1409  virtual void unget_character() = 0;
1410  virtual ~input_adapter_protocol() = default;
1411 };
1412 
1413 /// a type to simplify interfaces
1414 using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
1415 
1416 /*!
1417 Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
1418 beginning of input. Does not support changing the underlying std::streambuf
1419 in mid-input. Maintains underlying std::istream and std::streambuf to support
1420 subsequent use of standard std::istream operations to process any input
1421 characters following those used in parsing the JSON input. Clears the
1422 std::istream flags; any input errors (e.g., EOF) will be detected by the first
1423 subsequent call for input from the std::istream.
1424 */
1425 class input_stream_adapter : public input_adapter_protocol
1426 {
1427  public:
1428  ~input_stream_adapter() override
1429  {
1430  // clear stream flags; we use underlying streambuf I/O, do not
1431  // maintain ifstream flags
1432  is.clear();
1433  }
1434 
1435  explicit input_stream_adapter(std::istream& i)
1436  : is(i), sb(*i.rdbuf())
1437  {
1438  // skip byte order mark
1439  std::char_traits<char>::int_type c;
1440  if ((c = get_character()) == 0xEF)
1441  {
1442  if ((c = get_character()) == 0xBB)
1443  {
1444  if ((c = get_character()) == 0xBF)
1445  {
1446  return; // Ignore BOM
1447  }
1448  else if (c != std::char_traits<char>::eof())
1449  {
1450  is.unget();
1451  }
1452  is.putback('\xBB');
1453  }
1454  else if (c != std::char_traits<char>::eof())
1455  {
1456  is.unget();
1457  }
1458  is.putback('\xEF');
1459  }
1460  else if (c != std::char_traits<char>::eof())
1461  {
1462  is.unget(); // no byte order mark; process as usual
1463  }
1464  }
1465 
1466  // delete because of pointer members
1467  input_stream_adapter(const input_stream_adapter&) = delete;
1468  input_stream_adapter& operator=(input_stream_adapter&) = delete;
1469 
1470  // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
1471  // ensure that std::char_traits<char>::eof() and the character 0xFF do not
1472  // end up as the same value, eg. 0xFFFFFFFF.
1473  std::char_traits<char>::int_type get_character() override
1474  {
1475  return sb.sbumpc();
1476  }
1477 
1478  void unget_character() override
1479  {
1480  sb.sungetc(); // is.unget() avoided for performance
1481  }
1482 
1483  private:
1484  /// the associated input stream
1485  std::istream& is;
1486  std::streambuf& sb;
1487 };
1488 
1489 /// input adapter for buffer input
1490 class input_buffer_adapter : public input_adapter_protocol
1491 {
1492  public:
1493  input_buffer_adapter(const char* b, const std::size_t l)
1494  : cursor(b), limit(b + l), start(b)
1495  {
1496  // skip byte order mark
1497  if (l >= 3 and b[0] == '\xEF' and b[1] == '\xBB' and b[2] == '\xBF')
1498  {
1499  cursor += 3;
1500  }
1501  }
1502 
1503  // delete because of pointer members
1504  input_buffer_adapter(const input_buffer_adapter&) = delete;
1505  input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
1506 
1507  std::char_traits<char>::int_type get_character() noexcept override
1508  {
1509  if (JSON_LIKELY(cursor < limit))
1510  {
1511  return std::char_traits<char>::to_int_type(*(cursor++));
1512  }
1513 
1514  return std::char_traits<char>::eof();
1515  }
1516 
1517  void unget_character() noexcept override
1518  {
1519  if (JSON_LIKELY(cursor > start))
1520  {
1521  --cursor;
1522  }
1523  }
1524 
1525  private:
1526  /// pointer to the current character
1527  const char* cursor;
1528  /// pointer past the last character
1529  const char* limit;
1530  /// pointer to the first character
1531  const char* start;
1532 };
1533 
1534 class input_adapter
1535 {
1536  public:
1537  // native support
1538 
1539  /// input adapter for input stream
1540  input_adapter(std::istream& i)
1541  : ia(std::make_shared<input_stream_adapter>(i)) {}
1542 
1543  /// input adapter for input stream
1544  input_adapter(std::istream&& i)
1545  : ia(std::make_shared<input_stream_adapter>(i)) {}
1546 
1547  /// input adapter for buffer
1548  template<typename CharT,
1549  typename std::enable_if<
1550  std::is_pointer<CharT>::value and
1551  std::is_integral<typename std::remove_pointer<CharT>::type>::value and
1552  sizeof(typename std::remove_pointer<CharT>::type) == 1,
1553  int>::type = 0>
1554  input_adapter(CharT b, std::size_t l)
1555  : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
1556 
1557  // derived support
1558 
1559  /// input adapter for string literal
1560  template<typename CharT,
1561  typename std::enable_if<
1562  std::is_pointer<CharT>::value and
1563  std::is_integral<typename std::remove_pointer<CharT>::type>::value and
1564  sizeof(typename std::remove_pointer<CharT>::type) == 1,
1565  int>::type = 0>
1566  input_adapter(CharT b)
1567  : input_adapter(reinterpret_cast<const char*>(b),
1568  std::strlen(reinterpret_cast<const char*>(b))) {}
1569 
1570  /// input adapter for iterator range with contiguous storage
1571  template<class IteratorType,
1572  typename std::enable_if<
1573  std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
1574  int>::type = 0>
1575  input_adapter(IteratorType first, IteratorType last)
1576  {
1577  // assertion to check that the iterator range is indeed contiguous,
1578  // see http://stackoverflow.com/a/35008842/266378 for more discussion
1579  assert(std::accumulate(
1580  first, last, std::pair<bool, int>(true, 0),
1581  [&first](std::pair<bool, int> res, decltype(*first) val)
1582  {
1583  res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
1584  return res;
1585  }).first);
1586 
1587  // assertion to check that each element is 1 byte long
1588  static_assert(
1589  sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
1590  "each element in the iterator range must have the size of 1 byte");
1591 
1592  const auto len = static_cast<size_t>(std::distance(first, last));
1593  if (JSON_LIKELY(len > 0))
1594  {
1595  // there is at least one element: use the address of first
1596  ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
1597  }
1598  else
1599  {
1600  // the address of first cannot be used: use nullptr
1601  ia = std::make_shared<input_buffer_adapter>(nullptr, len);
1602  }
1603  }
1604 
1605  /// input adapter for array
1606  template<class T, std::size_t N>
1607  input_adapter(T (&array)[N])
1608  : input_adapter(std::begin(array), std::end(array)) {}
1609 
1610  /// input adapter for contiguous container
1611  template<class ContiguousContainer, typename
1612  std::enable_if<not std::is_pointer<ContiguousContainer>::value and
1613  std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
1614  int>::type = 0>
1615  input_adapter(const ContiguousContainer& c)
1616  : input_adapter(std::begin(c), std::end(c)) {}
1617 
1618  operator input_adapter_t()
1619  {
1620  return ia;
1621  }
1622 
1623  private:
1624  /// the actual adapter
1625  input_adapter_t ia = nullptr;
1626 };
1627 
1628 //////////////////////
1629 // lexer and parser //
1630 //////////////////////
1631 
1632 /*!
1633 @brief lexical analysis
1634 
1635 This class organizes the lexical analysis during JSON deserialization.
1636 */
1637 template<typename BasicJsonType>
1638 class lexer
1639 {
1640  using number_integer_t = typename BasicJsonType::number_integer_t;
1641  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
1642  using number_float_t = typename BasicJsonType::number_float_t;
1643 
1644  public:
1645  /// token types for the parser
1646  enum class token_type
1647  {
1648  uninitialized, ///< indicating the scanner is uninitialized
1649  literal_true, ///< the `true` literal
1650  literal_false, ///< the `false` literal
1651  literal_null, ///< the `null` literal
1652  value_string, ///< a string -- use get_string() for actual value
1653  value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
1654  value_integer, ///< a signed integer -- use get_number_integer() for actual value
1655  value_float, ///< an floating point number -- use get_number_float() for actual value
1656  begin_array, ///< the character for array begin `[`
1657  begin_object, ///< the character for object begin `{`
1658  end_array, ///< the character for array end `]`
1659  end_object, ///< the character for object end `}`
1660  name_separator, ///< the name separator `:`
1661  value_separator, ///< the value separator `,`
1662  parse_error, ///< indicating a parse error
1663  end_of_input, ///< indicating the end of the input buffer
1664  literal_or_value ///< a literal or the begin of a value (only for diagnostics)
1665  };
1666 
1667  /// return name of values of type token_type (only used for errors)
1668  static const char* token_type_name(const token_type t) noexcept
1669  {
1670  switch (t)
1671  {
1672  case token_type::uninitialized:
1673  return "<uninitialized>";
1674  case token_type::literal_true:
1675  return "true literal";
1676  case token_type::literal_false:
1677  return "false literal";
1678  case token_type::literal_null:
1679  return "null literal";
1680  case token_type::value_string:
1681  return "string literal";
1682  case lexer::token_type::value_unsigned:
1683  case lexer::token_type::value_integer:
1684  case lexer::token_type::value_float:
1685  return "number literal";
1686  case token_type::begin_array:
1687  return "'['";
1688  case token_type::begin_object:
1689  return "'{'";
1690  case token_type::end_array:
1691  return "']'";
1692  case token_type::end_object:
1693  return "'}'";
1694  case token_type::name_separator:
1695  return "':'";
1696  case token_type::value_separator:
1697  return "','";
1698  case token_type::parse_error:
1699  return "<parse error>";
1700  case token_type::end_of_input:
1701  return "end of input";
1702  case token_type::literal_or_value:
1703  return "'[', '{', or a literal";
1704  default: // catch non-enum values
1705  return "unknown token"; // LCOV_EXCL_LINE
1706  }
1707  }
1708 
1709  explicit lexer(detail::input_adapter_t adapter)
1710  : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
1711 
1712  // delete because of pointer members
1713  lexer(const lexer&) = delete;
1714  lexer& operator=(lexer&) = delete;
1715 
1716  private:
1717  /////////////////////
1718  // locales
1719  /////////////////////
1720 
1721  /// return the locale-dependent decimal point
1722  static char get_decimal_point() noexcept
1723  {
1724  const auto loc = localeconv();
1725  assert(loc != nullptr);
1726  return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
1727  }
1728 
1729  /////////////////////
1730  // scan functions
1731  /////////////////////
1732 
1733  /*!
1734  @brief get codepoint from 4 hex characters following `\u`
1735 
1736  For input "\u c1 c2 c3 c4" the codepoint is:
1737  (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
1738  = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
1739 
1740  Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
1741  must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
1742  conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
1743  between the ASCII value of the character and the desired integer value.
1744 
1745  @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
1746  non-hex character)
1747  */
1748  int get_codepoint()
1749  {
1750  // this function only makes sense after reading `\u`
1751  assert(current == 'u');
1752  int codepoint = 0;
1753 
1754  const auto factors = { 12, 8, 4, 0 };
1755  for (const auto factor : factors)
1756  {
1757  get();
1758 
1759  if (current >= '0' and current <= '9')
1760  {
1761  codepoint += ((current - 0x30) << factor);
1762  }
1763  else if (current >= 'A' and current <= 'F')
1764  {
1765  codepoint += ((current - 0x37) << factor);
1766  }
1767  else if (current >= 'a' and current <= 'f')
1768  {
1769  codepoint += ((current - 0x57) << factor);
1770  }
1771  else
1772  {
1773  return -1;
1774  }
1775  }
1776 
1777  assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
1778  return codepoint;
1779  }
1780 
1781  /*!
1782  @brief check if the next byte(s) are inside a given range
1783 
1784  Adds the current byte and, for each passed range, reads a new byte and
1785  checks if it is inside the range. If a violation was detected, set up an
1786  error message and return false. Otherwise, return true.
1787 
1788  @param[in] ranges list of integers; interpreted as list of pairs of
1789  inclusive lower and upper bound, respectively
1790 
1791  @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
1792  1, 2, or 3 pairs. This precondition is enforced by an assertion.
1793 
1794  @return true if and only if no range violation was detected
1795  */
1796  bool next_byte_in_range(std::initializer_list<int> ranges)
1797  {
1798  assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
1799  add(current);
1800 
1801  for (auto range = ranges.begin(); range != ranges.end(); ++range)
1802  {
1803  get();
1804  if (JSON_LIKELY(*range <= current and current <= *(++range)))
1805  {
1806  add(current);
1807  }
1808  else
1809  {
1810  error_message = "invalid string: ill-formed UTF-8 byte";
1811  return false;
1812  }
1813  }
1814 
1815  return true;
1816  }
1817 
1818  /*!
1819  @brief scan a string literal
1820 
1821  This function scans a string according to Sect. 7 of RFC 7159. While
1822  scanning, bytes are escaped and copied into buffer yytext. Then the function
1823  returns successfully, yytext is *not* null-terminated (as it may contain \0
1824  bytes), and yytext.size() is the number of bytes in the string.
1825 
1826  @return token_type::value_string if string could be successfully scanned,
1827  token_type::parse_error otherwise
1828 
1829  @note In case of errors, variable error_message contains a textual
1830  description.
1831  */
1832  token_type scan_string()
1833  {
1834  // reset yytext (ignore opening quote)
1835  reset();
1836 
1837  // we entered the function by reading an open quote
1838  assert(current == '\"');
1839 
1840  while (true)
1841  {
1842  // get next character
1843  switch (get())
1844  {
1845  // end of file while parsing string
1846  case std::char_traits<char>::eof():
1847  {
1848  error_message = "invalid string: missing closing quote";
1849  return token_type::parse_error;
1850  }
1851 
1852  // closing quote
1853  case '\"':
1854  {
1855  return token_type::value_string;
1856  }
1857 
1858  // escapes
1859  case '\\':
1860  {
1861  switch (get())
1862  {
1863  // quotation mark
1864  case '\"':
1865  add('\"');
1866  break;
1867  // reverse solidus
1868  case '\\':
1869  add('\\');
1870  break;
1871  // solidus
1872  case '/':
1873  add('/');
1874  break;
1875  // backspace
1876  case 'b':
1877  add('\b');
1878  break;
1879  // form feed
1880  case 'f':
1881  add('\f');
1882  break;
1883  // line feed
1884  case 'n':
1885  add('\n');
1886  break;
1887  // carriage return
1888  case 'r':
1889  add('\r');
1890  break;
1891  // tab
1892  case 't':
1893  add('\t');
1894  break;
1895 
1896  // unicode escapes
1897  case 'u':
1898  {
1899  const int codepoint1 = get_codepoint();
1900  int codepoint = codepoint1; // start with codepoint1
1901 
1902  if (JSON_UNLIKELY(codepoint1 == -1))
1903  {
1904  error_message = "invalid string: '\\u' must be followed by 4 hex digits";
1905  return token_type::parse_error;
1906  }
1907 
1908  // check if code point is a high surrogate
1909  if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
1910  {
1911  // expect next \uxxxx entry
1912  if (JSON_LIKELY(get() == '\\' and get() == 'u'))
1913  {
1914  const int codepoint2 = get_codepoint();
1915 
1916  if (JSON_UNLIKELY(codepoint2 == -1))
1917  {
1918  error_message = "invalid string: '\\u' must be followed by 4 hex digits";
1919  return token_type::parse_error;
1920  }
1921 
1922  // check if codepoint2 is a low surrogate
1923  if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
1924  {
1925  // overwrite codepoint
1926  codepoint =
1927  // high surrogate occupies the most significant 22 bits
1928  (codepoint1 << 10)
1929  // low surrogate occupies the least significant 15 bits
1930  + codepoint2
1931  // there is still the 0xD800, 0xDC00 and 0x10000 noise
1932  // in the result so we have to subtract with:
1933  // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
1934  - 0x35FDC00;
1935  }
1936  else
1937  {
1938  error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
1939  return token_type::parse_error;
1940  }
1941  }
1942  else
1943  {
1944  error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
1945  return token_type::parse_error;
1946  }
1947  }
1948  else
1949  {
1950  if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
1951  {
1952  error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
1953  return token_type::parse_error;
1954  }
1955  }
1956 
1957  // result of the above calculation yields a proper codepoint
1958  assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
1959 
1960  // translate codepoint into bytes
1961  if (codepoint < 0x80)
1962  {
1963  // 1-byte characters: 0xxxxxxx (ASCII)
1964  add(codepoint);
1965  }
1966  else if (codepoint <= 0x7FF)
1967  {
1968  // 2-byte characters: 110xxxxx 10xxxxxx
1969  add(0xC0 | (codepoint >> 6));
1970  add(0x80 | (codepoint & 0x3F));
1971  }
1972  else if (codepoint <= 0xFFFF)
1973  {
1974  // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
1975  add(0xE0 | (codepoint >> 12));
1976  add(0x80 | ((codepoint >> 6) & 0x3F));
1977  add(0x80 | (codepoint & 0x3F));
1978  }
1979  else
1980  {
1981  // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1982  add(0xF0 | (codepoint >> 18));
1983  add(0x80 | ((codepoint >> 12) & 0x3F));
1984  add(0x80 | ((codepoint >> 6) & 0x3F));
1985  add(0x80 | (codepoint & 0x3F));
1986  }
1987 
1988  break;
1989  }
1990 
1991  // other characters after escape
1992  default:
1993  error_message = "invalid string: forbidden character after backslash";
1994  return token_type::parse_error;
1995  }
1996 
1997  break;
1998  }
1999 
2000  // invalid control characters
2001  case 0x00:
2002  case 0x01:
2003  case 0x02:
2004  case 0x03:
2005  case 0x04:
2006  case 0x05:
2007  case 0x06:
2008  case 0x07:
2009  case 0x08:
2010  case 0x09:
2011  case 0x0A:
2012  case 0x0B:
2013  case 0x0C:
2014  case 0x0D:
2015  case 0x0E:
2016  case 0x0F:
2017  case 0x10:
2018  case 0x11:
2019  case 0x12:
2020  case 0x13:
2021  case 0x14:
2022  case 0x15:
2023  case 0x16:
2024  case 0x17:
2025  case 0x18:
2026  case 0x19:
2027  case 0x1A:
2028  case 0x1B:
2029  case 0x1C:
2030  case 0x1D:
2031  case 0x1E:
2032  case 0x1F:
2033  {
2034  error_message = "invalid string: control character must be escaped";
2035  return token_type::parse_error;
2036  }
2037 
2038  // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
2039  case 0x20:
2040  case 0x21:
2041  case 0x23:
2042  case 0x24:
2043  case 0x25:
2044  case 0x26:
2045  case 0x27:
2046  case 0x28:
2047  case 0x29:
2048  case 0x2A:
2049  case 0x2B:
2050  case 0x2C:
2051  case 0x2D:
2052  case 0x2E:
2053  case 0x2F:
2054  case 0x30:
2055  case 0x31:
2056  case 0x32:
2057  case 0x33:
2058  case 0x34:
2059  case 0x35:
2060  case 0x36:
2061  case 0x37:
2062  case 0x38:
2063  case 0x39:
2064  case 0x3A:
2065  case 0x3B:
2066  case 0x3C:
2067  case 0x3D:
2068  case 0x3E:
2069  case 0x3F:
2070  case 0x40:
2071  case 0x41:
2072  case 0x42:
2073  case 0x43:
2074  case 0x44:
2075  case 0x45:
2076  case 0x46:
2077  case 0x47:
2078  case 0x48:
2079  case 0x49:
2080  case 0x4A:
2081  case 0x4B:
2082  case 0x4C:
2083  case 0x4D:
2084  case 0x4E:
2085  case 0x4F:
2086  case 0x50:
2087  case 0x51:
2088  case 0x52:
2089  case 0x53:
2090  case 0x54:
2091  case 0x55:
2092  case 0x56:
2093  case 0x57:
2094  case 0x58:
2095  case 0x59:
2096  case 0x5A:
2097  case 0x5B:
2098  case 0x5D:
2099  case 0x5E:
2100  case 0x5F:
2101  case 0x60:
2102  case 0x61:
2103  case 0x62:
2104  case 0x63:
2105  case 0x64:
2106  case 0x65:
2107  case 0x66:
2108  case 0x67:
2109  case 0x68:
2110  case 0x69:
2111  case 0x6A:
2112  case 0x6B:
2113  case 0x6C:
2114  case 0x6D:
2115  case 0x6E:
2116  case 0x6F:
2117  case 0x70:
2118  case 0x71:
2119  case 0x72:
2120  case 0x73:
2121  case 0x74:
2122  case 0x75:
2123  case 0x76:
2124  case 0x77:
2125  case 0x78:
2126  case 0x79:
2127  case 0x7A:
2128  case 0x7B:
2129  case 0x7C:
2130  case 0x7D:
2131  case 0x7E:
2132  case 0x7F:
2133  {
2134  add(current);
2135  break;
2136  }
2137 
2138  // U+0080..U+07FF: bytes C2..DF 80..BF
2139  case 0xC2:
2140  case 0xC3:
2141  case 0xC4:
2142  case 0xC5:
2143  case 0xC6:
2144  case 0xC7:
2145  case 0xC8:
2146  case 0xC9:
2147  case 0xCA:
2148  case 0xCB:
2149  case 0xCC:
2150  case 0xCD:
2151  case 0xCE:
2152  case 0xCF:
2153  case 0xD0:
2154  case 0xD1:
2155  case 0xD2:
2156  case 0xD3:
2157  case 0xD4:
2158  case 0xD5:
2159  case 0xD6:
2160  case 0xD7:
2161  case 0xD8:
2162  case 0xD9:
2163  case 0xDA:
2164  case 0xDB:
2165  case 0xDC:
2166  case 0xDD:
2167  case 0xDE:
2168  case 0xDF:
2169  {
2170  if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
2171  {
2172  return token_type::parse_error;
2173  }
2174  break;
2175  }
2176 
2177  // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
2178  case 0xE0:
2179  {
2180  if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
2181  {
2182  return token_type::parse_error;
2183  }
2184  break;
2185  }
2186 
2187  // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
2188  // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
2189  case 0xE1:
2190  case 0xE2:
2191  case 0xE3:
2192  case 0xE4:
2193  case 0xE5:
2194  case 0xE6:
2195  case 0xE7:
2196  case 0xE8:
2197  case 0xE9:
2198  case 0xEA:
2199  case 0xEB:
2200  case 0xEC:
2201  case 0xEE:
2202  case 0xEF:
2203  {
2204  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
2205  {
2206  return token_type::parse_error;
2207  }
2208  break;
2209  }
2210 
2211  // U+D000..U+D7FF: bytes ED 80..9F 80..BF
2212  case 0xED:
2213  {
2214  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
2215  {
2216  return token_type::parse_error;
2217  }
2218  break;
2219  }
2220 
2221  // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
2222  case 0xF0:
2223  {
2224  if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
2225  {
2226  return token_type::parse_error;
2227  }
2228  break;
2229  }
2230 
2231  // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
2232  case 0xF1:
2233  case 0xF2:
2234  case 0xF3:
2235  {
2236  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
2237  {
2238  return token_type::parse_error;
2239  }
2240  break;
2241  }
2242 
2243  // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
2244  case 0xF4:
2245  {
2246  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
2247  {
2248  return token_type::parse_error;
2249  }
2250  break;
2251  }
2252 
2253  // remaining bytes (80..C1 and F5..FF) are ill-formed
2254  default:
2255  {
2256  error_message = "invalid string: ill-formed UTF-8 byte";
2257  return token_type::parse_error;
2258  }
2259  }
2260  }
2261  }
2262 
2263  static void strtof(float& f, const char* str, char** endptr) noexcept
2264  {
2265  f = std::strtof(str, endptr);
2266  }
2267 
2268  static void strtof(double& f, const char* str, char** endptr) noexcept
2269  {
2270  f = std::strtod(str, endptr);
2271  }
2272 
2273  static void strtof(long double& f, const char* str, char** endptr) noexcept
2274  {
2275  f = std::strtold(str, endptr);
2276  }
2277 
2278  /*!
2279  @brief scan a number literal
2280 
2281  This function scans a string according to Sect. 6 of RFC 7159.
2282 
2283  The function is realized with a deterministic finite state machine derived
2284  from the grammar described in RFC 7159. Starting in state "init", the
2285  input is read and used to determined the next state. Only state "done"
2286  accepts the number. State "error" is a trap state to model errors. In the
2287  table below, "anything" means any character but the ones listed before.
2288 
2289  state | 0 | 1-9 | e E | + | - | . | anything
2290  ---------|----------|----------|----------|---------|---------|----------|-----------
2291  init | zero | any1 | [error] | [error] | minus | [error] | [error]
2292  minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
2293  zero | done | done | exponent | done | done | decimal1 | done
2294  any1 | any1 | any1 | exponent | done | done | decimal1 | done
2295  decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
2296  decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
2297  exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
2298  sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
2299  any2 | any2 | any2 | done | done | done | done | done
2300 
2301  The state machine is realized with one label per state (prefixed with
2302  "scan_number_") and `goto` statements between them. The state machine
2303  contains cycles, but any cycle can be left when EOF is read. Therefore,
2304  the function is guaranteed to terminate.
2305 
2306  During scanning, the read bytes are stored in yytext. This string is
2307  then converted to a signed integer, an unsigned integer, or a
2308  floating-point number.
2309 
2310  @return token_type::value_unsigned, token_type::value_integer, or
2311  token_type::value_float if number could be successfully scanned,
2312  token_type::parse_error otherwise
2313 
2314  @note The scanner is independent of the current locale. Internally, the
2315  locale's decimal point is used instead of `.` to work with the
2316  locale-dependent converters.
2317  */
2318  token_type scan_number()
2319  {
2320  // reset yytext to store the number's bytes
2321  reset();
2322 
2323  // the type of the parsed number; initially set to unsigned; will be
2324  // changed if minus sign, decimal point or exponent is read
2325  token_type number_type = token_type::value_unsigned;
2326 
2327  // state (init): we just found out we need to scan a number
2328  switch (current)
2329  {
2330  case '-':
2331  {
2332  add(current);
2333  goto scan_number_minus;
2334  }
2335 
2336  case '0':
2337  {
2338  add(current);
2339  goto scan_number_zero;
2340  }
2341 
2342  case '1':
2343  case '2':
2344  case '3':
2345  case '4':
2346  case '5':
2347  case '6':
2348  case '7':
2349  case '8':
2350  case '9':
2351  {
2352  add(current);
2353  goto scan_number_any1;
2354  }
2355 
2356  default:
2357  {
2358  // all other characters are rejected outside scan_number()
2359  assert(false); // LCOV_EXCL_LINE
2360  }
2361  }
2362 
2363 scan_number_minus:
2364  // state: we just parsed a leading minus sign
2365  number_type = token_type::value_integer;
2366  switch (get())
2367  {
2368  case '0':
2369  {
2370  add(current);
2371  goto scan_number_zero;
2372  }
2373 
2374  case '1':
2375  case '2':
2376  case '3':
2377  case '4':
2378  case '5':
2379  case '6':
2380  case '7':
2381  case '8':
2382  case '9':
2383  {
2384  add(current);
2385  goto scan_number_any1;
2386  }
2387 
2388  default:
2389  {
2390  error_message = "invalid number; expected digit after '-'";
2391  return token_type::parse_error;
2392  }
2393  }
2394 
2395 scan_number_zero:
2396  // state: we just parse a zero (maybe with a leading minus sign)
2397  switch (get())
2398  {
2399  case '.':
2400  {
2401  add(decimal_point_char);
2402  goto scan_number_decimal1;
2403  }
2404 
2405  case 'e':
2406  case 'E':
2407  {
2408  add(current);
2409  goto scan_number_exponent;
2410  }
2411 
2412  default:
2413  goto scan_number_done;
2414  }
2415 
2416 scan_number_any1:
2417  // state: we just parsed a number 0-9 (maybe with a leading minus sign)
2418  switch (get())
2419  {
2420  case '0':
2421  case '1':
2422  case '2':
2423  case '3':
2424  case '4':
2425  case '5':
2426  case '6':
2427  case '7':
2428  case '8':
2429  case '9':
2430  {
2431  add(current);
2432  goto scan_number_any1;
2433  }
2434 
2435  case '.':
2436  {
2437  add(decimal_point_char);
2438  goto scan_number_decimal1;
2439  }
2440 
2441  case 'e':
2442  case 'E':
2443  {
2444  add(current);
2445  goto scan_number_exponent;
2446  }
2447 
2448  default:
2449  goto scan_number_done;
2450  }
2451 
2452 scan_number_decimal1:
2453  // state: we just parsed a decimal point
2454  number_type = token_type::value_float;
2455  switch (get())
2456  {
2457  case '0':
2458  case '1':
2459  case '2':
2460  case '3':
2461  case '4':
2462  case '5':
2463  case '6':
2464  case '7':
2465  case '8':
2466  case '9':
2467  {
2468  add(current);
2469  goto scan_number_decimal2;
2470  }
2471 
2472  default:
2473  {
2474  error_message = "invalid number; expected digit after '.'";
2475  return token_type::parse_error;
2476  }
2477  }
2478 
2479 scan_number_decimal2:
2480  // we just parsed at least one number after a decimal point
2481  switch (get())
2482  {
2483  case '0':
2484  case '1':
2485  case '2':
2486  case '3':
2487  case '4':
2488  case '5':
2489  case '6':
2490  case '7':
2491  case '8':
2492  case '9':
2493  {
2494  add(current);
2495  goto scan_number_decimal2;
2496  }
2497 
2498  case 'e':
2499  case 'E':
2500  {
2501  add(current);
2502  goto scan_number_exponent;
2503  }
2504 
2505  default:
2506  goto scan_number_done;
2507  }
2508 
2509 scan_number_exponent:
2510  // we just parsed an exponent
2511  number_type = token_type::value_float;
2512  switch (get())
2513  {
2514  case '+':
2515  case '-':
2516  {
2517  add(current);
2518  goto scan_number_sign;
2519  }
2520 
2521  case '0':
2522  case '1':
2523  case '2':
2524  case '3':
2525  case '4':
2526  case '5':
2527  case '6':
2528  case '7':
2529  case '8':
2530  case '9':
2531  {
2532  add(current);
2533  goto scan_number_any2;
2534  }
2535 
2536  default:
2537  {
2538  error_message =
2539  "invalid number; expected '+', '-', or digit after exponent";
2540  return token_type::parse_error;
2541  }
2542  }
2543 
2544 scan_number_sign:
2545  // we just parsed an exponent sign
2546  switch (get())
2547  {
2548  case '0':
2549  case '1':
2550  case '2':
2551  case '3':
2552  case '4':
2553  case '5':
2554  case '6':
2555  case '7':
2556  case '8':
2557  case '9':
2558  {
2559  add(current);
2560  goto scan_number_any2;
2561  }
2562 
2563  default:
2564  {
2565  error_message = "invalid number; expected digit after exponent sign";
2566  return token_type::parse_error;
2567  }
2568  }
2569 
2570 scan_number_any2:
2571  // we just parsed a number after the exponent or exponent sign
2572  switch (get())
2573  {
2574  case '0':
2575  case '1':
2576  case '2':
2577  case '3':
2578  case '4':
2579  case '5':
2580  case '6':
2581  case '7':
2582  case '8':
2583  case '9':
2584  {
2585  add(current);
2586  goto scan_number_any2;
2587  }
2588 
2589  default:
2590  goto scan_number_done;
2591  }
2592 
2593 scan_number_done:
2594  // unget the character after the number (we only read it to know that
2595  // we are done scanning a number)
2596  unget();
2597 
2598  char* endptr = nullptr;
2599  errno = 0;
2600 
2601  // try to parse integers first and fall back to floats
2602  if (number_type == token_type::value_unsigned)
2603  {
2604  const auto x = std::strtoull(yytext.data(), &endptr, 10);
2605 
2606  // we checked the number format before
2607  assert(endptr == yytext.data() + yytext.size());
2608 
2609  if (errno == 0)
2610  {
2611  value_unsigned = static_cast<number_unsigned_t>(x);
2612  if (value_unsigned == x)
2613  {
2614  return token_type::value_unsigned;
2615  }
2616  }
2617  }
2618  else if (number_type == token_type::value_integer)
2619  {
2620  const auto x = std::strtoll(yytext.data(), &endptr, 10);
2621 
2622  // we checked the number format before
2623  assert(endptr == yytext.data() + yytext.size());
2624 
2625  if (errno == 0)
2626  {
2627  value_integer = static_cast<number_integer_t>(x);
2628  if (value_integer == x)
2629  {
2630  return token_type::value_integer;
2631  }
2632  }
2633  }
2634 
2635  // this code is reached if we parse a floating-point number or if an
2636  // integer conversion above failed
2637  strtof(value_float, yytext.data(), &endptr);
2638 
2639  // we checked the number format before
2640  assert(endptr == yytext.data() + yytext.size());
2641 
2642  return token_type::value_float;
2643  }
2644 
2645  /*!
2646  @param[in] literal_text the literal text to expect
2647  @param[in] length the length of the passed literal text
2648  @param[in] return_type the token type to return on success
2649  */
2650  token_type scan_literal(const char* literal_text, const std::size_t length,
2651  token_type return_type)
2652  {
2653  assert(current == literal_text[0]);
2654  for (std::size_t i = 1; i < length; ++i)
2655  {
2656  if (JSON_UNLIKELY(get() != literal_text[i]))
2657  {
2658  error_message = "invalid literal";
2659  return token_type::parse_error;
2660  }
2661  }
2662  return return_type;
2663  }
2664 
2665  /////////////////////
2666  // input management
2667  /////////////////////
2668 
2669  /// reset yytext; current character is beginning of token
2670  void reset() noexcept
2671  {
2672  yytext.clear();
2673  token_string.clear();
2674  token_string.push_back(std::char_traits<char>::to_char_type(current));
2675  }
2676 
2677  /*
2678  @brief get next character from the input
2679 
2680  This function provides the interface to the used input adapter. It does
2681  not throw in case the input reached EOF, but returns a
2682  `std::char_traits<char>::eof()` in that case. Stores the scanned characters
2683  for use in error messages.
2684 
2685  @return character read from the input
2686  */
2687  std::char_traits<char>::int_type get()
2688  {
2689  ++chars_read;
2690  current = ia->get_character();
2691  if (JSON_LIKELY(current != std::char_traits<char>::eof()))
2692  {
2693  token_string.push_back(std::char_traits<char>::to_char_type(current));
2694  }
2695  return current;
2696  }
2697 
2698  /// unget current character (return it again on next get)
2699  void unget()
2700  {
2701  --chars_read;
2702  if (JSON_LIKELY(current != std::char_traits<char>::eof()))
2703  {
2704  ia->unget_character();
2705  assert(token_string.size() != 0);
2706  token_string.pop_back();
2707  }
2708  }
2709 
2710  /// add a character to yytext
2711  void add(int c)
2712  {
2713  yytext.push_back(std::char_traits<char>::to_char_type(c));
2714  }
2715 
2716  public:
2717  /////////////////////
2718  // value getters
2719  /////////////////////
2720 
2721  /// return integer value
2722  constexpr number_integer_t get_number_integer() const noexcept
2723  {
2724  return value_integer;
2725  }
2726 
2727  /// return unsigned integer value
2728  constexpr number_unsigned_t get_number_unsigned() const noexcept
2729  {
2730  return value_unsigned;
2731  }
2732 
2733  /// return floating-point value
2734  constexpr number_float_t get_number_float() const noexcept
2735  {
2736  return value_float;
2737  }
2738 
2739  /// return current string value (implicitly resets the token; useful only once)
2740  std::string move_string()
2741  {
2742  return std::move(yytext);
2743  }
2744 
2745  /////////////////////
2746  // diagnostics
2747  /////////////////////
2748 
2749  /// return position of last read token
2750  constexpr std::size_t get_position() const noexcept
2751  {
2752  return chars_read;
2753  }
2754 
2755  /// return the last read token (for errors only). Will never contain EOF
2756  /// (an arbitrary value that is not a valid char value, often -1), because
2757  /// 255 may legitimately occur. May contain NUL, which should be escaped.
2758  std::string get_token_string() const
2759  {
2760  // escape control characters
2761  std::string result;
2762  for (auto c : token_string)
2763  {
2764  if ('\x00' <= c and c <= '\x1F')
2765  {
2766  // escape control characters
2767  std::stringstream ss;
2768  ss << "<U+" << std::setw(4) << std::uppercase << std::setfill('0')
2769  << std::hex << static_cast<int>(c) << ">";
2770  result += ss.str();
2771  }
2772  else
2773  {
2774  // add character as is
2775  result.push_back(c);
2776  }
2777  }
2778 
2779  return result;
2780  }
2781 
2782  /// return syntax error message
2783  constexpr const char* get_error_message() const noexcept
2784  {
2785  return error_message;
2786  }
2787 
2788  /////////////////////
2789  // actual scanner
2790  /////////////////////
2791 
2792  token_type scan()
2793  {
2794  // read next character and ignore whitespace
2795  do
2796  {
2797  get();
2798  }
2799  while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
2800 
2801  switch (current)
2802  {
2803  // structural characters
2804  case '[':
2805  return token_type::begin_array;
2806  case ']':
2807  return token_type::end_array;
2808  case '{':
2809  return token_type::begin_object;
2810  case '}':
2811  return token_type::end_object;
2812  case ':':
2813  return token_type::name_separator;
2814  case ',':
2815  return token_type::value_separator;
2816 
2817  // literals
2818  case 't':
2819  return scan_literal("true", 4, token_type::literal_true);
2820  case 'f':
2821  return scan_literal("false", 5, token_type::literal_false);
2822  case 'n':
2823  return scan_literal("null", 4, token_type::literal_null);
2824 
2825  // string
2826  case '\"':
2827  return scan_string();
2828 
2829  // number
2830  case '-':
2831  case '0':
2832  case '1':
2833  case '2':
2834  case '3':
2835  case '4':
2836  case '5':
2837  case '6':
2838  case '7':
2839  case '8':
2840  case '9':
2841  return scan_number();
2842 
2843  // end of input (the null byte is needed when parsing from
2844  // string literals)
2845  case '\0':
2846  case std::char_traits<char>::eof():
2847  return token_type::end_of_input;
2848 
2849  // error
2850  default:
2851  error_message = "invalid literal";
2852  return token_type::parse_error;
2853  }
2854  }
2855 
2856  private:
2857  /// input adapter
2858  detail::input_adapter_t ia = nullptr;
2859 
2860  /// the current character
2861  std::char_traits<char>::int_type current = std::char_traits<char>::eof();
2862 
2863  /// the number of characters read
2864  std::size_t chars_read = 0;
2865 
2866  /// raw input token string (for error messages)
2867  std::vector<char> token_string {};
2868 
2869  /// buffer for variable-length tokens (numbers, strings)
2870  std::string yytext {};
2871 
2872  /// a description of occurred lexer errors
2873  const char* error_message = "";
2874 
2875  // number values
2876  number_integer_t value_integer = 0;
2877  number_unsigned_t value_unsigned = 0;
2878  number_float_t value_float = 0;
2879 
2880  /// the decimal point
2881  const char decimal_point_char = '.';
2882 };
2883 
2884 /*!
2885 @brief syntax analysis
2886 
2887 This class implements a recursive decent parser.
2888 */
2889 template<typename BasicJsonType>
2890 class parser
2891 {
2892  using number_integer_t = typename BasicJsonType::number_integer_t;
2893  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
2894  using number_float_t = typename BasicJsonType::number_float_t;
2895  using lexer_t = lexer<BasicJsonType>;
2896  using token_type = typename lexer_t::token_type;
2897 
2898  public:
2899  enum class parse_event_t : uint8_t
2900  {
2901  /// the parser read `{` and started to process a JSON object
2902  object_start,
2903  /// the parser read `}` and finished processing a JSON object
2904  object_end,
2905  /// the parser read `[` and started to process a JSON array
2906  array_start,
2907  /// the parser read `]` and finished processing a JSON array
2908  array_end,
2909  /// the parser read a key of a value in an object
2910  key,
2911  /// the parser finished reading a JSON value
2912  value
2913  };
2914 
2915  using parser_callback_t =
2916  std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
2917 
2918  /// a parser reading from an input adapter
2919  explicit parser(detail::input_adapter_t adapter,
2920  const parser_callback_t cb = nullptr,
2921  const bool allow_exceptions_ = true)
2922  : callback(cb), m_lexer(adapter), allow_exceptions(allow_exceptions_)
2923  {}
2924 
2925  /*!
2926  @brief public parser interface
2927 
2928  @param[in] strict whether to expect the last token to be EOF
2929  @param[in,out] result parsed JSON value
2930 
2931  @throw parse_error.101 in case of an unexpected token
2932  @throw parse_error.102 if to_unicode fails or surrogate error
2933  @throw parse_error.103 if to_unicode fails
2934  */
2935  void parse(const bool strict, BasicJsonType& result)
2936  {
2937  // read first token
2938  get_token();
2939 
2940  parse_internal(true, result);
2941  result.assert_invariant();
2942 
2943  // in strict mode, input must be completely read
2944  if (strict)
2945  {
2946  get_token();
2947  expect(token_type::end_of_input);
2948  }
2949 
2950  // in case of an error, return discarded value
2951  if (errored)
2952  {
2953  result = value_t::discarded;
2954  return;
2955  }
2956 
2957  // set top-level value to null if it was discarded by the callback
2958  // function
2959  if (result.is_discarded())
2960  {
2961  result = nullptr;
2962  }
2963  }
2964 
2965  /*!
2966  @brief public accept interface
2967 
2968  @param[in] strict whether to expect the last token to be EOF
2969  @return whether the input is a proper JSON text
2970  */
2971  bool accept(const bool strict = true)
2972  {
2973  // read first token
2974  get_token();
2975 
2976  if (not accept_internal())
2977  {
2978  return false;
2979  }
2980 
2981  // strict => last token must be EOF
2982  return not strict or (get_token() == token_type::end_of_input);
2983  }
2984 
2985  private:
2986  /*!
2987  @brief the actual parser
2988  @throw parse_error.101 in case of an unexpected token
2989  @throw parse_error.102 if to_unicode fails or surrogate error
2990  @throw parse_error.103 if to_unicode fails
2991  */
2992  void parse_internal(bool keep, BasicJsonType& result)
2993  {
2994  // never parse after a parse error was detected
2995  assert(not errored);
2996 
2997  // start with a discarded value
2998  if (not result.is_discarded())
2999  {
3000  result.m_value.destroy(result.m_type);
3001  result.m_type = value_t::discarded;
3002  }
3003 
3004  switch (last_token)
3005  {
3006  case token_type::begin_object:
3007  {
3008  if (keep)
3009  {
3010  if (callback)
3011  {
3012  keep = callback(depth++, parse_event_t::object_start, result);
3013  }
3014 
3015  if (not callback or keep)
3016  {
3017  // explicitly set result to object to cope with {}
3018  result.m_type = value_t::object;
3019  result.m_value = value_t::object;
3020  }
3021  }
3022 
3023  // read next token
3024  get_token();
3025 
3026  // closing } -> we are done
3027  if (last_token == token_type::end_object)
3028  {
3029  if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
3030  {
3031  result.m_value.destroy(result.m_type);
3032  result.m_type = value_t::discarded;
3033  }
3034  break;
3035  }
3036 
3037  // parse values
3038  std::string key;
3039  BasicJsonType value;
3040  while (true)
3041  {
3042  // store key
3043  if (not expect(token_type::value_string))
3044  {
3045  return;
3046  }
3047  key = m_lexer.move_string();
3048 
3049  bool keep_tag = false;
3050  if (keep)
3051  {
3052  if (callback)
3053  {
3054  BasicJsonType k(key);
3055  keep_tag = callback(depth, parse_event_t::key, k);
3056  }
3057  else
3058  {
3059  keep_tag = true;
3060  }
3061  }
3062 
3063  // parse separator (:)
3064  get_token();
3065  if (not expect(token_type::name_separator))
3066  {
3067  return;
3068  }
3069 
3070  // parse and add value
3071  get_token();
3072  value.m_value.destroy(value.m_type);
3073  value.m_type = value_t::discarded;
3074  parse_internal(keep, value);
3075 
3076  if (JSON_UNLIKELY(errored))
3077  {
3078  return;
3079  }
3080 
3081  if (keep and keep_tag and not value.is_discarded())
3082  {
3083  result.m_value.object->emplace(std::move(key), std::move(value));
3084  }
3085 
3086  // comma -> next value
3087  get_token();
3088  if (last_token == token_type::value_separator)
3089  {
3090  get_token();
3091  continue;
3092  }
3093 
3094  // closing }
3095  if (not expect(token_type::end_object))
3096  {
3097  return;
3098  }
3099  break;
3100  }
3101 
3102  if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
3103  {
3104  result.m_value.destroy(result.m_type);
3105  result.m_type = value_t::discarded;
3106  }
3107  break;
3108  }
3109 
3110  case token_type::begin_array:
3111  {
3112  if (keep)
3113  {
3114  if (callback)
3115  {
3116  keep = callback(depth++, parse_event_t::array_start, result);
3117  }
3118 
3119  if (not callback or keep)
3120  {
3121  // explicitly set result to array to cope with []
3122  result.m_type = value_t::array;
3123  result.m_value = value_t::array;
3124  }
3125  }
3126 
3127  // read next token
3128  get_token();
3129 
3130  // closing ] -> we are done
3131  if (last_token == token_type::end_array)
3132  {
3133  if (callback and not callback(--depth, parse_event_t::array_end, result))
3134  {
3135  result.m_value.destroy(result.m_type);
3136  result.m_type = value_t::discarded;
3137  }
3138  break;
3139  }
3140 
3141  // parse values
3142  BasicJsonType value;
3143  while (true)
3144  {
3145  // parse value
3146  value.m_value.destroy(value.m_type);
3147  value.m_type = value_t::discarded;
3148  parse_internal(keep, value);
3149 
3150  if (JSON_UNLIKELY(errored))
3151  {
3152  return;
3153  }
3154 
3155  if (keep and not value.is_discarded())
3156  {
3157  result.m_value.array->push_back(std::move(value));
3158  }
3159 
3160  // comma -> next value
3161  get_token();
3162  if (last_token == token_type::value_separator)
3163  {
3164  get_token();
3165  continue;
3166  }
3167 
3168  // closing ]
3169  if (not expect(token_type::end_array))
3170  {
3171  return;
3172  }
3173  break;
3174  }
3175 
3176  if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
3177  {
3178  result.m_value.destroy(result.m_type);
3179  result.m_type = value_t::discarded;
3180  }
3181  break;
3182  }
3183 
3184  case token_type::literal_null:
3185  {
3186  result.m_type = value_t::null;
3187  break;
3188  }
3189 
3190  case token_type::value_string:
3191  {
3192  result.m_type = value_t::string;
3193  result.m_value = m_lexer.move_string();
3194  break;
3195  }
3196 
3197  case token_type::literal_true:
3198  {
3199  result.m_type = value_t::boolean;
3200  result.m_value = true;
3201  break;
3202  }
3203 
3204  case token_type::literal_false:
3205  {
3206  result.m_type = value_t::boolean;
3207  result.m_value = false;
3208  break;
3209  }
3210 
3211  case token_type::value_unsigned:
3212  {
3213  result.m_type = value_t::number_unsigned;
3214  result.m_value = m_lexer.get_number_unsigned();
3215  break;
3216  }
3217 
3218  case token_type::value_integer:
3219  {
3220  result.m_type = value_t::number_integer;
3221  result.m_value = m_lexer.get_number_integer();
3222  break;
3223  }
3224 
3225  case token_type::value_float:
3226  {
3227  result.m_type = value_t::number_float;
3228  result.m_value = m_lexer.get_number_float();
3229 
3230  // throw in case of infinity or NAN
3231  if (JSON_UNLIKELY(not std::isfinite(result.m_value.number_float)))
3232  {
3233  if (allow_exceptions)
3234  {
3235  JSON_THROW(out_of_range::create(406, "number overflow parsing '" +
3236  m_lexer.get_token_string() + "'"));
3237  }
3238  expect(token_type::uninitialized);
3239  }
3240  break;
3241  }
3242 
3243  case token_type::parse_error:
3244  {
3245  // using "uninitialized" to avoid "expected" message
3246  if (not expect(token_type::uninitialized))
3247  {
3248  return;
3249  }
3250  break; // LCOV_EXCL_LINE
3251  }
3252 
3253  default:
3254  {
3255  // the last token was unexpected; we expected a value
3256  if (not expect(token_type::literal_or_value))
3257  {
3258  return;
3259  }
3260  break; // LCOV_EXCL_LINE
3261  }
3262  }
3263 
3264  if (keep and callback and not callback(depth, parse_event_t::value, result))
3265  {
3266  result.m_type = value_t::discarded;
3267  }
3268  }
3269 
3270  /*!
3271  @brief the actual acceptor
3272 
3273  @invariant 1. The last token is not yet processed. Therefore, the caller
3274  of this function must make sure a token has been read.
3275  2. When this function returns, the last token is processed.
3276  That is, the last read character was already considered.
3277 
3278  This invariant makes sure that no token needs to be "unput".
3279  */
3280  bool accept_internal()
3281  {
3282  switch (last_token)
3283  {
3284  case token_type::begin_object:
3285  {
3286  // read next token
3287  get_token();
3288 
3289  // closing } -> we are done
3290  if (last_token == token_type::end_object)
3291  {
3292  return true;
3293  }
3294 
3295  // parse values
3296  while (true)
3297  {
3298  // parse key
3299  if (last_token != token_type::value_string)
3300  {
3301  return false;
3302  }
3303 
3304  // parse separator (:)
3305  get_token();
3306  if (last_token != token_type::name_separator)
3307  {
3308  return false;
3309  }
3310 
3311  // parse value
3312  get_token();
3313  if (not accept_internal())
3314  {
3315  return false;
3316  }
3317 
3318  // comma -> next value
3319  get_token();
3320  if (last_token == token_type::value_separator)
3321  {
3322  get_token();
3323  continue;
3324  }
3325 
3326  // closing }
3327  return (last_token == token_type::end_object);
3328  }
3329  }
3330 
3331  case token_type::begin_array:
3332  {
3333  // read next token
3334  get_token();
3335 
3336  // closing ] -> we are done
3337  if (last_token == token_type::end_array)
3338  {
3339  return true;
3340  }
3341 
3342  // parse values
3343  while (true)
3344  {
3345  // parse value
3346  if (not accept_internal())
3347  {
3348  return false;
3349  }
3350 
3351  // comma -> next value
3352  get_token();
3353  if (last_token == token_type::value_separator)
3354  {
3355  get_token();
3356  continue;
3357  }
3358 
3359  // closing ]
3360  return (last_token == token_type::end_array);
3361  }
3362  }
3363 
3364  case token_type::value_float:
3365  {
3366  // reject infinity or NAN
3367  return std::isfinite(m_lexer.get_number_float());
3368  }
3369 
3370  case token_type::literal_false:
3371  case token_type::literal_null:
3372  case token_type::literal_true:
3373  case token_type::value_integer:
3374  case token_type::value_string:
3375  case token_type::value_unsigned:
3376  return true;
3377 
3378  default: // the last token was unexpected
3379  return false;
3380  }
3381  }
3382 
3383  /// get next token from lexer
3384  token_type get_token()
3385  {
3386  return (last_token = m_lexer.scan());
3387  }
3388 
3389  /*!
3390  @throw parse_error.101 if expected token did not occur
3391  */
3392  bool expect(token_type t)
3393  {
3394  if (JSON_UNLIKELY(t != last_token))
3395  {
3396  errored = true;
3397  expected = t;
3398  if (allow_exceptions)
3399  {
3400  throw_exception();
3401  }
3402  else
3403  {
3404  return false;
3405  }
3406  }
3407 
3408  return true;
3409  }
3410 
3411  [[noreturn]] void throw_exception() const
3412  {
3413  std::string error_msg = "syntax error - ";
3414  if (last_token == token_type::parse_error)
3415  {
3416  error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
3417  m_lexer.get_token_string() + "'";
3418  }
3419  else
3420  {
3421  error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
3422  }
3423 
3424  if (expected != token_type::uninitialized)
3425  {
3426  error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
3427  }
3428 
3429  JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg));
3430  }
3431 
3432  private:
3433  /// current level of recursion
3434  int depth = 0;
3435  /// callback function
3436  const parser_callback_t callback = nullptr;
3437  /// the type of the last read token
3438  token_type last_token = token_type::uninitialized;
3439  /// the lexer
3440  lexer_t m_lexer;
3441  /// whether a syntax error occurred
3442  bool errored = false;
3443  /// possible reason for the syntax error
3444  token_type expected = token_type::uninitialized;
3445  /// whether to throw exceptions in case of errors
3446  const bool allow_exceptions = true;
3447 };
3448 
3449 ///////////////
3450 // iterators //
3451 ///////////////
3452 
3453 /*!
3454 @brief an iterator for primitive JSON types
3455 
3456 This class models an iterator for primitive JSON types (boolean, number,
3457 string). It's only purpose is to allow the iterator/const_iterator classes
3458 to "iterate" over primitive values. Internally, the iterator is modeled by
3459 a `difference_type` variable. Value begin_value (`0`) models the begin,
3460 end_value (`1`) models past the end.
3461 */
3462 class primitive_iterator_t
3463 {
3464  public:
3465  using difference_type = std::ptrdiff_t;
3466 
3467  constexpr difference_type get_value() const noexcept
3468  {
3469  return m_it;
3470  }
3471 
3472  /// set iterator to a defined beginning
3473  void set_begin() noexcept
3474  {
3475  m_it = begin_value;
3476  }
3477 
3478  /// set iterator to a defined past the end
3479  void set_end() noexcept
3480  {
3481  m_it = end_value;
3482  }
3483 
3484  /// return whether the iterator can be dereferenced
3485  constexpr bool is_begin() const noexcept
3486  {
3487  return m_it == begin_value;
3488  }
3489 
3490  /// return whether the iterator is at end
3491  constexpr bool is_end() const noexcept
3492  {
3493  return m_it == end_value;
3494  }
3495 
3496  friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3497  {
3498  return lhs.m_it == rhs.m_it;
3499  }
3500 
3501  friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3502  {
3503  return lhs.m_it < rhs.m_it;
3504  }
3505 
3506  primitive_iterator_t operator+(difference_type i)
3507  {
3508  auto result = *this;
3509  result += i;
3510  return result;
3511  }
3512 
3513  friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3514  {
3515  return lhs.m_it - rhs.m_it;
3516  }
3517 
3518  friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it)
3519  {
3520  return os << it.m_it;
3521  }
3522 
3523  primitive_iterator_t& operator++()
3524  {
3525  ++m_it;
3526  return *this;
3527  }
3528 
3529  primitive_iterator_t operator++(int)
3530  {
3531  auto result = *this;
3532  m_it++;
3533  return result;
3534  }
3535 
3536  primitive_iterator_t& operator--()
3537  {
3538  --m_it;
3539  return *this;
3540  }
3541 
3542  primitive_iterator_t operator--(int)
3543  {
3544  auto result = *this;
3545  m_it--;
3546  return result;
3547  }
3548 
3549  primitive_iterator_t& operator+=(difference_type n)
3550  {
3551  m_it += n;
3552  return *this;
3553  }
3554 
3555  primitive_iterator_t& operator-=(difference_type n)
3556  {
3557  m_it -= n;
3558  return *this;
3559  }
3560 
3561  private:
3562  static constexpr difference_type begin_value = 0;
3563  static constexpr difference_type end_value = begin_value + 1;
3564 
3565  /// iterator as signed integer type
3566  difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
3567 };
3568 
3569 /*!
3570 @brief an iterator value
3571 
3572 @note This structure could easily be a union, but MSVC currently does not allow
3573 unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
3574 */
3575 template<typename BasicJsonType> struct internal_iterator
3576 {
3577  /// iterator for JSON objects
3578  typename BasicJsonType::object_t::iterator object_iterator {};
3579  /// iterator for JSON arrays
3580  typename BasicJsonType::array_t::iterator array_iterator {};
3581  /// generic iterator for all other types
3582  primitive_iterator_t primitive_iterator {};
3583 };
3584 
3585 template<typename IteratorType> class iteration_proxy;
3586 
3587 /*!
3588 @brief a template for a bidirectional iterator for the @ref basic_json class
3589 
3590 This class implements a both iterators (iterator and const_iterator) for the
3591 @ref basic_json class.
3592 
3593 @note An iterator is called *initialized* when a pointer to a JSON value has
3594  been set (e.g., by a constructor or a copy assignment). If the iterator is
3595  default-constructed, it is *uninitialized* and most methods are undefined.
3596  **The library uses assertions to detect calls on uninitialized iterators.**
3597 
3598 @requirement The class satisfies the following concept requirements:
3599 -
3600 [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):
3601  The iterator that can be moved can be moved in both directions (i.e.
3602  incremented and decremented).
3603 
3604 @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
3605  iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
3606 */
3607 template<typename BasicJsonType>
3608 class iter_impl
3609 {
3610  /// allow basic_json to access private members
3611  friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
3612  friend BasicJsonType;
3613  friend iteration_proxy<iter_impl>;
3614 
3615  using object_t = typename BasicJsonType::object_t;
3616  using array_t = typename BasicJsonType::array_t;
3617  // make sure BasicJsonType is basic_json or const basic_json
3618  static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
3619  "iter_impl only accepts (const) basic_json");
3620 
3621  public:
3622 
3623  /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
3624  /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
3625  /// A user-defined iterator should provide publicly accessible typedefs named
3626  /// iterator_category, value_type, difference_type, pointer, and reference.
3627  /// Note that value_type is required to be non-const, even for constant iterators.
3628  using iterator_category = std::bidirectional_iterator_tag;
3629 
3630  /// the type of the values when the iterator is dereferenced
3631  using value_type = typename BasicJsonType::value_type;
3632  /// a type to represent differences between iterators
3633  using difference_type = typename BasicJsonType::difference_type;
3634  /// defines a pointer to the type iterated over (value_type)
3635  using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
3636  typename BasicJsonType::const_pointer,
3637  typename BasicJsonType::pointer>::type;
3638  /// defines a reference to the type iterated over (value_type)
3639  using reference =
3640  typename std::conditional<std::is_const<BasicJsonType>::value,
3641  typename BasicJsonType::const_reference,
3642  typename BasicJsonType::reference>::type;
3643 
3644  /// default constructor
3645  iter_impl() = default;
3646 
3647  /*!
3648  @brief constructor for a given JSON instance
3649  @param[in] object pointer to a JSON object for this iterator
3650  @pre object != nullptr
3651  @post The iterator is initialized; i.e. `m_object != nullptr`.
3652  */
3653  explicit iter_impl(pointer object) noexcept : m_object(object)
3654  {
3655  assert(m_object != nullptr);
3656 
3657  switch (m_object->m_type)
3658  {
3659  case value_t::object:
3660  {
3661  m_it.object_iterator = typename object_t::iterator();
3662  break;
3663  }
3664 
3665  case value_t::array:
3666  {
3667  m_it.array_iterator = typename array_t::iterator();
3668  break;
3669  }
3670 
3671  default:
3672  {
3673  m_it.primitive_iterator = primitive_iterator_t();
3674  break;
3675  }
3676  }
3677  }
3678 
3679  /*!
3680  @note The conventional copy constructor and copy assignment are implicitly
3681  defined. Combined with the following converting constructor and
3682  assignment, they support: (1) copy from iterator to iterator, (2)
3683  copy from const iterator to const iterator, and (3) conversion from
3684  iterator to const iterator. However conversion from const iterator
3685  to iterator is not defined.
3686  */
3687 
3688  /*!
3689  @brief converting constructor
3690  @param[in] other non-const iterator to copy from
3691  @note It is not checked whether @a other is initialized.
3692  */
3693  iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
3694  : m_object(other.m_object), m_it(other.m_it) {}
3695 
3696  /*!
3697  @brief converting assignment
3698  @param[in,out] other non-const iterator to copy from
3699  @return const/non-const iterator
3700  @note It is not checked whether @a other is initialized.
3701  */
3702  iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
3703  {
3704  m_object = other.m_object;
3705  m_it = other.m_it;
3706  return *this;
3707  }
3708 
3709  private:
3710  /*!
3711  @brief set the iterator to the first value
3712  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3713  */
3714  void set_begin() noexcept
3715  {
3716  assert(m_object != nullptr);
3717 
3718  switch (m_object->m_type)
3719  {
3720  case value_t::object:
3721  {
3722  m_it.object_iterator = m_object->m_value.object->begin();
3723  break;
3724  }
3725 
3726  case value_t::array:
3727  {
3728  m_it.array_iterator = m_object->m_value.array->begin();
3729  break;
3730  }
3731 
3732  case value_t::null:
3733  {
3734  // set to end so begin()==end() is true: null is empty
3735  m_it.primitive_iterator.set_end();
3736  break;
3737  }
3738 
3739  default:
3740  {
3741  m_it.primitive_iterator.set_begin();
3742  break;
3743  }
3744  }
3745  }
3746 
3747  /*!
3748  @brief set the iterator past the last value
3749  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3750  */
3751  void set_end() noexcept
3752  {
3753  assert(m_object != nullptr);
3754 
3755  switch (m_object->m_type)
3756  {
3757  case value_t::object:
3758  {
3759  m_it.object_iterator = m_object->m_value.object->end();
3760  break;
3761  }
3762 
3763  case value_t::array:
3764  {
3765  m_it.array_iterator = m_object->m_value.array->end();
3766  break;
3767  }
3768 
3769  default:
3770  {
3771  m_it.primitive_iterator.set_end();
3772  break;
3773  }
3774  }
3775  }
3776 
3777  public:
3778  /*!
3779  @brief return a reference to the value pointed to by the iterator
3780  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3781  */
3782  reference operator*() const
3783  {
3784  assert(m_object != nullptr);
3785 
3786  switch (m_object->m_type)
3787  {
3788  case value_t::object:
3789  {
3790  assert(m_it.object_iterator != m_object->m_value.object->end());
3791  return m_it.object_iterator->second;
3792  }
3793 
3794  case value_t::array:
3795  {
3796  assert(m_it.array_iterator != m_object->m_value.array->end());
3797  return *m_it.array_iterator;
3798  }
3799 
3800  case value_t::null:
3801  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
3802 
3803  default:
3804  {
3805  if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
3806  {
3807  return *m_object;
3808  }
3809 
3810  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
3811  }
3812  }
3813  }
3814 
3815  /*!
3816  @brief dereference the iterator
3817  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3818  */
3819  pointer operator->() const
3820  {
3821  assert(m_object != nullptr);
3822 
3823  switch (m_object->m_type)
3824  {
3825  case value_t::object:
3826  {
3827  assert(m_it.object_iterator != m_object->m_value.object->end());
3828  return &(m_it.object_iterator->second);
3829  }
3830 
3831  case value_t::array:
3832  {
3833  assert(m_it.array_iterator != m_object->m_value.array->end());
3834  return &*m_it.array_iterator;
3835  }
3836 
3837  default:
3838  {
3839  if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
3840  {
3841  return m_object;
3842  }
3843 
3844  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
3845  }
3846  }
3847  }
3848 
3849  /*!
3850  @brief post-increment (it++)
3851  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3852  */
3853  iter_impl operator++(int)
3854  {
3855  auto result = *this;
3856  ++(*this);
3857  return result;
3858  }
3859 
3860  /*!
3861  @brief pre-increment (++it)
3862  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3863  */
3864  iter_impl& operator++()
3865  {
3866  assert(m_object != nullptr);
3867 
3868  switch (m_object->m_type)
3869  {
3870  case value_t::object:
3871  {
3872  std::advance(m_it.object_iterator, 1);
3873  break;
3874  }
3875 
3876  case value_t::array:
3877  {
3878  std::advance(m_it.array_iterator, 1);
3879  break;
3880  }
3881 
3882  default:
3883  {
3884  ++m_it.primitive_iterator;
3885  break;
3886  }
3887  }
3888 
3889  return *this;
3890  }
3891 
3892  /*!
3893  @brief post-decrement (it--)
3894  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3895  */
3896  iter_impl operator--(int)
3897  {
3898  auto result = *this;
3899  --(*this);
3900  return result;
3901  }
3902 
3903  /*!
3904  @brief pre-decrement (--it)
3905  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3906  */
3907  iter_impl& operator--()
3908  {
3909  assert(m_object != nullptr);
3910 
3911  switch (m_object->m_type)
3912  {
3913  case value_t::object:
3914  {
3915  std::advance(m_it.object_iterator, -1);
3916  break;
3917  }
3918 
3919  case value_t::array:
3920  {
3921  std::advance(m_it.array_iterator, -1);
3922  break;
3923  }
3924 
3925  default:
3926  {
3927  --m_it.primitive_iterator;
3928  break;
3929  }
3930  }
3931 
3932  return *this;
3933  }
3934 
3935  /*!
3936  @brief comparison: equal
3937  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3938  */
3939  bool operator==(const iter_impl& other) const
3940  {
3941  // if objects are not the same, the comparison is undefined
3942  if (JSON_UNLIKELY(m_object != other.m_object))
3943  {
3944  JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
3945  }
3946 
3947  assert(m_object != nullptr);
3948 
3949  switch (m_object->m_type)
3950  {
3951  case value_t::object:
3952  return (m_it.object_iterator == other.m_it.object_iterator);
3953 
3954  case value_t::array:
3955  return (m_it.array_iterator == other.m_it.array_iterator);
3956 
3957  default:
3958  return (m_it.primitive_iterator == other.m_it.primitive_iterator);
3959  }
3960  }
3961 
3962  /*!
3963  @brief comparison: not equal
3964  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3965  */
3966  bool operator!=(const iter_impl& other) const
3967  {
3968  return not operator==(other);
3969  }
3970 
3971  /*!
3972  @brief comparison: smaller
3973  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3974  */
3975  bool operator<(const iter_impl& other) const
3976  {
3977  // if objects are not the same, the comparison is undefined
3978  if (JSON_UNLIKELY(m_object != other.m_object))
3979  {
3980  JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
3981  }
3982 
3983  assert(m_object != nullptr);
3984 
3985  switch (m_object->m_type)
3986  {
3987  case value_t::object:
3988  JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
3989 
3990  case value_t::array:
3991  return (m_it.array_iterator < other.m_it.array_iterator);
3992 
3993  default:
3994  return (m_it.primitive_iterator < other.m_it.primitive_iterator);
3995  }
3996  }
3997 
3998  /*!
3999  @brief comparison: less than or equal
4000  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4001  */
4002  bool operator<=(const iter_impl& other) const
4003  {
4004  return not other.operator < (*this);
4005  }
4006 
4007  /*!
4008  @brief comparison: greater than
4009  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4010  */
4011  bool operator>(const iter_impl& other) const
4012  {
4013  return not operator<=(other);
4014  }
4015 
4016  /*!
4017  @brief comparison: greater than or equal
4018  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4019  */
4020  bool operator>=(const iter_impl& other) const
4021  {
4022  return not operator<(other);
4023  }
4024 
4025  /*!
4026  @brief add to iterator
4027  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4028  */
4029  iter_impl& operator+=(difference_type i)
4030  {
4031  assert(m_object != nullptr);
4032 
4033  switch (m_object->m_type)
4034  {
4035  case value_t::object:
4036  JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
4037 
4038  case value_t::array:
4039  {
4040  std::advance(m_it.array_iterator, i);
4041  break;
4042  }
4043 
4044  default:
4045  {
4046  m_it.primitive_iterator += i;
4047  break;
4048  }
4049  }
4050 
4051  return *this;
4052  }
4053 
4054  /*!
4055  @brief subtract from iterator
4056  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4057  */
4058  iter_impl& operator-=(difference_type i)
4059  {
4060  return operator+=(-i);
4061  }
4062 
4063  /*!
4064  @brief add to iterator
4065  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4066  */
4067  iter_impl operator+(difference_type i) const
4068  {
4069  auto result = *this;
4070  result += i;
4071  return result;
4072  }
4073 
4074  /*!
4075  @brief addition of distance and iterator
4076  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4077  */
4078  friend iter_impl operator+(difference_type i, const iter_impl& it)
4079  {
4080  auto result = it;
4081  result += i;
4082  return result;
4083  }
4084 
4085  /*!
4086  @brief subtract from iterator
4087  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4088  */
4089  iter_impl operator-(difference_type i) const
4090  {
4091  auto result = *this;
4092  result -= i;
4093  return result;
4094  }
4095 
4096  /*!
4097  @brief return difference
4098  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4099  */
4100  difference_type operator-(const iter_impl& other) const
4101  {
4102  assert(m_object != nullptr);
4103 
4104  switch (m_object->m_type)
4105  {
4106  case value_t::object:
4107  JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
4108 
4109  case value_t::array:
4110  return m_it.array_iterator - other.m_it.array_iterator;
4111 
4112  default:
4113  return m_it.primitive_iterator - other.m_it.primitive_iterator;
4114  }
4115  }
4116 
4117  /*!
4118  @brief access to successor
4119  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4120  */
4121  reference operator[](difference_type n) const
4122  {
4123  assert(m_object != nullptr);
4124 
4125  switch (m_object->m_type)
4126  {
4127  case value_t::object:
4128  JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
4129 
4130  case value_t::array:
4131  return *std::next(m_it.array_iterator, n);
4132 
4133  case value_t::null:
4134  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4135 
4136  default:
4137  {
4138  if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
4139  {
4140  return *m_object;
4141  }
4142 
4143  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4144  }
4145  }
4146  }
4147 
4148  /*!
4149  @brief return the key of an object iterator
4150  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4151  */
4152  typename object_t::key_type key() const
4153  {
4154  assert(m_object != nullptr);
4155 
4156  if (JSON_LIKELY(m_object->is_object()))
4157  {
4158  return m_it.object_iterator->first;
4159  }
4160 
4161  JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
4162  }
4163 
4164  /*!
4165  @brief return the value of an iterator
4166  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4167  */
4168  reference value() const
4169  {
4170  return operator*();
4171  }
4172 
4173  private:
4174  /// associated JSON instance
4175  pointer m_object = nullptr;
4176  /// the actual iterator of the associated instance
4177  internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it = {};
4178 };
4179 
4180 /// proxy class for the iterator_wrapper functions
4181 template<typename IteratorType> class iteration_proxy
4182 {
4183  private:
4184  /// helper class for iteration
4185  class iteration_proxy_internal
4186  {
4187  private:
4188  /// the iterator
4189  IteratorType anchor;
4190  /// an index for arrays (used to create key names)
4191  std::size_t array_index = 0;
4192 
4193  public:
4194  explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {}
4195 
4196  /// dereference operator (needed for range-based for)
4197  iteration_proxy_internal& operator*()
4198  {
4199  return *this;
4200  }
4201 
4202  /// increment operator (needed for range-based for)
4203  iteration_proxy_internal& operator++()
4204  {
4205  ++anchor;
4206  ++array_index;
4207 
4208  return *this;
4209  }
4210 
4211  /// inequality operator (needed for range-based for)
4212  bool operator!=(const iteration_proxy_internal& o) const noexcept
4213  {
4214  return anchor != o.anchor;
4215  }
4216 
4217  /// return key of the iterator
4218  std::string key() const
4219  {
4220  assert(anchor.m_object != nullptr);
4221 
4222  switch (anchor.m_object->type())
4223  {
4224  // use integer array index as key
4225  case value_t::array:
4226  return std::to_string(array_index);
4227 
4228  // use key from the object
4229  case value_t::object:
4230  return anchor.key();
4231 
4232  // use an empty key for all primitive types
4233  default:
4234  return "";
4235  }
4236  }
4237 
4238  /// return value of the iterator
4239  typename IteratorType::reference value() const
4240  {
4241  return anchor.value();
4242  }
4243  };
4244 
4245  /// the container to iterate
4246  typename IteratorType::reference container;
4247 
4248  public:
4249  /// construct iteration proxy from a container
4250  explicit iteration_proxy(typename IteratorType::reference cont)
4251  : container(cont) {}
4252 
4253  /// return iterator begin (needed for range-based for)
4254  iteration_proxy_internal begin() noexcept
4255  {
4256  return iteration_proxy_internal(container.begin());
4257  }
4258 
4259  /// return iterator end (needed for range-based for)
4260  iteration_proxy_internal end() noexcept
4261  {
4262  return iteration_proxy_internal(container.end());
4263  }
4264 };
4265 
4266 /*!
4267 @brief a template for a reverse iterator class
4268 
4269 @tparam Base the base iterator type to reverse. Valid types are @ref
4270 iterator (to create @ref reverse_iterator) and @ref const_iterator (to
4271 create @ref const_reverse_iterator).
4272 
4273 @requirement The class satisfies the following concept requirements:
4274 -
4275 [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):
4276  The iterator that can be moved can be moved in both directions (i.e.
4277  incremented and decremented).
4278 - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
4279  It is possible to write to the pointed-to element (only if @a Base is
4280  @ref iterator).
4281 
4282 @since version 1.0.0
4283 */
4284 template<typename Base>
4285 class json_reverse_iterator : public std::reverse_iterator<Base>
4286 {
4287  public:
4288  using difference_type = std::ptrdiff_t;
4289  /// shortcut to the reverse iterator adapter
4290  using base_iterator = std::reverse_iterator<Base>;
4291  /// the reference type for the pointed-to element
4292  using reference = typename Base::reference;
4293 
4294  /// create reverse iterator from iterator
4295  json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
4296  : base_iterator(it) {}
4297 
4298  /// create reverse iterator from base class
4299  json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
4300 
4301  /// post-increment (it++)
4302  json_reverse_iterator operator++(int)
4303  {
4304  return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
4305  }
4306 
4307  /// pre-increment (++it)
4308  json_reverse_iterator& operator++()
4309  {
4310  return static_cast<json_reverse_iterator&>(base_iterator::operator++());
4311  }
4312 
4313  /// post-decrement (it--)
4314  json_reverse_iterator operator--(int)
4315  {
4316  return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
4317  }
4318 
4319  /// pre-decrement (--it)
4320  json_reverse_iterator& operator--()
4321  {
4322  return static_cast<json_reverse_iterator&>(base_iterator::operator--());
4323  }
4324 
4325  /// add to iterator
4326  json_reverse_iterator& operator+=(difference_type i)
4327  {
4328  return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
4329  }
4330 
4331  /// add to iterator
4332  json_reverse_iterator operator+(difference_type i) const
4333  {
4334  return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
4335  }
4336 
4337  /// subtract from iterator
4338  json_reverse_iterator operator-(difference_type i) const
4339  {
4340  return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
4341  }
4342 
4343  /// return difference
4344  difference_type operator-(const json_reverse_iterator& other) const
4345  {
4346  return base_iterator(*this) - base_iterator(other);
4347  }
4348 
4349  /// access to successor
4350  reference operator[](difference_type n) const
4351  {
4352  return *(this->operator+(n));
4353  }
4354 
4355  /// return the key of an object iterator
4356  auto key() const -> decltype(std::declval<Base>().key())
4357  {
4358  auto it = --this->base();
4359  return it.key();
4360  }
4361 
4362  /// return the value of an iterator
4363  reference value() const
4364  {
4365  auto it = --this->base();
4366  return it.operator * ();
4367  }
4368 };
4369 
4370 /////////////////////
4371 // output adapters //
4372 /////////////////////
4373 
4374 /// abstract output adapter interface
4375 template<typename CharType> struct output_adapter_protocol
4376 {
4377  virtual void write_character(CharType c) = 0;
4378  virtual void write_characters(const CharType* s, std::size_t length) = 0;
4379  virtual ~output_adapter_protocol() = default;
4380 };
4381 
4382 /// a type to simplify interfaces
4383 template<typename CharType>
4384 using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
4385 
4386 /// output adapter for byte vectors
4387 template<typename CharType>
4388 class output_vector_adapter : public output_adapter_protocol<CharType>
4389 {
4390  public:
4391  explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {}
4392 
4393  void write_character(CharType c) override
4394  {
4395  v.push_back(c);
4396  }
4397 
4398  void write_characters(const CharType* s, std::size_t length) override
4399  {
4400  std::copy(s, s + length, std::back_inserter(v));
4401  }
4402 
4403  private:
4404  std::vector<CharType>& v;
4405 };
4406 
4407 /// output adapter for output streams
4408 template<typename CharType>
4409 class output_stream_adapter : public output_adapter_protocol<CharType>
4410 {
4411  public:
4412  explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {}
4413 
4414  void write_character(CharType c) override
4415  {
4416  stream.put(c);
4417  }
4418 
4419  void write_characters(const CharType* s, std::size_t length) override
4420  {
4421  stream.write(s, static_cast<std::streamsize>(length));
4422  }
4423 
4424  private:
4425  std::basic_ostream<CharType>& stream;
4426 };
4427 
4428 /// output adapter for basic_string
4429 template<typename CharType>
4430 class output_string_adapter : public output_adapter_protocol<CharType>
4431 {
4432  public:
4433  explicit output_string_adapter(std::basic_string<CharType>& s) : str(s) {}
4434 
4435  void write_character(CharType c) override
4436  {
4437  str.push_back(c);
4438  }
4439 
4440  void write_characters(const CharType* s, std::size_t length) override
4441  {
4442  str.append(s, length);
4443  }
4444 
4445  private:
4446  std::basic_string<CharType>& str;
4447 };
4448 
4449 template<typename CharType>
4450 class output_adapter
4451 {
4452  public:
4453  output_adapter(std::vector<CharType>& vec)
4454  : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
4455 
4456  output_adapter(std::basic_ostream<CharType>& s)
4457  : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
4458 
4459  output_adapter(std::basic_string<CharType>& s)
4460  : oa(std::make_shared<output_string_adapter<CharType>>(s)) {}
4461 
4462  operator output_adapter_t<CharType>()
4463  {
4464  return oa;
4465  }
4466 
4467  private:
4468  output_adapter_t<CharType> oa = nullptr;
4469 };
4470 
4471 //////////////////////////////
4472 // binary reader and writer //
4473 //////////////////////////////
4474 
4475 /*!
4476 @brief deserialization of CBOR and MessagePack values
4477 */
4478 template<typename BasicJsonType>
4479 class binary_reader
4480 {
4481  using number_integer_t = typename BasicJsonType::number_integer_t;
4482  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
4483 
4484  public:
4485  /*!
4486  @brief create a binary reader
4487 
4488  @param[in] adapter input adapter to read from
4489  */
4490  explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
4491  {
4492  assert(ia);
4493  }
4494 
4495  /*!
4496  @brief create a JSON value from CBOR input
4497 
4498  @param[in] strict whether to expect the input to be consumed completed
4499  @return JSON value created from CBOR input
4500 
4501  @throw parse_error.110 if input ended unexpectedly or the end of file was
4502  not reached when @a strict was set to true
4503  @throw parse_error.112 if unsupported byte was read
4504  */
4505  BasicJsonType parse_cbor(const bool strict)
4506  {
4507  const auto res = parse_cbor_internal();
4508  if (strict)
4509  {
4510  get();
4511  check_eof(true);
4512  }
4513  return res;
4514  }
4515 
4516  /*!
4517  @brief create a JSON value from MessagePack input
4518 
4519  @param[in] strict whether to expect the input to be consumed completed
4520  @return JSON value created from MessagePack input
4521 
4522  @throw parse_error.110 if input ended unexpectedly or the end of file was
4523  not reached when @a strict was set to true
4524  @throw parse_error.112 if unsupported byte was read
4525  */
4526  BasicJsonType parse_msgpack(const bool strict)
4527  {
4528  const auto res = parse_msgpack_internal();
4529  if (strict)
4530  {
4531  get();
4532  check_eof(true);
4533  }
4534  return res;
4535  }
4536 
4537  /*!
4538  @brief determine system byte order
4539 
4540  @return true if and only if system's byte order is little endian
4541 
4542  @note from http://stackoverflow.com/a/1001328/266378
4543  */
4544  static constexpr bool little_endianess(int num = 1) noexcept
4545  {
4546  return (*reinterpret_cast<char*>(&num) == 1);
4547  }
4548 
4549  private:
4550  /*!
4551  @param[in] get_char whether a new character should be retrieved from the
4552  input (true, default) or whether the last read
4553  character should be considered instead
4554  */
4555  BasicJsonType parse_cbor_internal(const bool get_char = true)
4556  {
4557  switch (get_char ? get() : current)
4558  {
4559  // EOF
4560  case std::char_traits<char>::eof():
4561  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
4562 
4563  // Integer 0x00..0x17 (0..23)
4564  case 0x00:
4565  case 0x01:
4566  case 0x02:
4567  case 0x03:
4568  case 0x04:
4569  case 0x05:
4570  case 0x06:
4571  case 0x07:
4572  case 0x08:
4573  case 0x09:
4574  case 0x0A:
4575  case 0x0B:
4576  case 0x0C:
4577  case 0x0D:
4578  case 0x0E:
4579  case 0x0F:
4580  case 0x10:
4581  case 0x11:
4582  case 0x12:
4583  case 0x13:
4584  case 0x14:
4585  case 0x15:
4586  case 0x16:
4587  case 0x17:
4588  return static_cast<number_unsigned_t>(current);
4589 
4590  case 0x18: // Unsigned integer (one-byte uint8_t follows)
4591  return get_number<uint8_t>();
4592 
4593  case 0x19: // Unsigned integer (two-byte uint16_t follows)
4594  return get_number<uint16_t>();
4595 
4596  case 0x1A: // Unsigned integer (four-byte uint32_t follows)
4597  return get_number<uint32_t>();
4598 
4599  case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
4600  return get_number<uint64_t>();
4601 
4602  // Negative integer -1-0x00..-1-0x17 (-1..-24)
4603  case 0x20:
4604  case 0x21:
4605  case 0x22:
4606  case 0x23:
4607  case 0x24:
4608  case 0x25:
4609  case 0x26:
4610  case 0x27:
4611  case 0x28:
4612  case 0x29:
4613  case 0x2A:
4614  case 0x2B:
4615  case 0x2C:
4616  case 0x2D:
4617  case 0x2E:
4618  case 0x2F:
4619  case 0x30:
4620  case 0x31:
4621  case 0x32:
4622  case 0x33:
4623  case 0x34:
4624  case 0x35:
4625  case 0x36:
4626  case 0x37:
4627  return static_cast<int8_t>(0x20 - 1 - current);
4628 
4629  case 0x38: // Negative integer (one-byte uint8_t follows)
4630  {
4631  // must be uint8_t !
4632  return static_cast<number_integer_t>(-1) - get_number<uint8_t>();
4633  }
4634 
4635  case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
4636  {
4637  return static_cast<number_integer_t>(-1) - get_number<uint16_t>();
4638  }
4639 
4640  case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
4641  {
4642  return static_cast<number_integer_t>(-1) - get_number<uint32_t>();
4643  }
4644 
4645  case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
4646  {
4647  return static_cast<number_integer_t>(-1) -
4648  static_cast<number_integer_t>(get_number<uint64_t>());
4649  }
4650 
4651  // UTF-8 string (0x00..0x17 bytes follow)
4652  case 0x60:
4653  case 0x61:
4654  case 0x62:
4655  case 0x63:
4656  case 0x64:
4657  case 0x65:
4658  case 0x66:
4659  case 0x67:
4660  case 0x68:
4661  case 0x69:
4662  case 0x6A:
4663  case 0x6B:
4664  case 0x6C:
4665  case 0x6D:
4666  case 0x6E:
4667  case 0x6F:
4668  case 0x70:
4669  case 0x71:
4670  case 0x72:
4671  case 0x73:
4672  case 0x74:
4673  case 0x75:
4674  case 0x76:
4675  case 0x77:
4676  case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
4677  case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
4678  case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
4679  case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
4680  case 0x7F: // UTF-8 string (indefinite length)
4681  {
4682  return get_cbor_string();
4683  }
4684 
4685  // array (0x00..0x17 data items follow)
4686  case 0x80:
4687  case 0x81:
4688  case 0x82:
4689  case 0x83:
4690  case 0x84:
4691  case 0x85:
4692  case 0x86:
4693  case 0x87:
4694  case 0x88:
4695  case 0x89:
4696  case 0x8A:
4697  case 0x8B:
4698  case 0x8C:
4699  case 0x8D:
4700  case 0x8E:
4701  case 0x8F:
4702  case 0x90:
4703  case 0x91:
4704  case 0x92:
4705  case 0x93:
4706  case 0x94:
4707  case 0x95:
4708  case 0x96:
4709  case 0x97:
4710  {
4711  return get_cbor_array(current & 0x1F);
4712  }
4713 
4714  case 0x98: // array (one-byte uint8_t for n follows)
4715  {
4716  return get_cbor_array(get_number<uint8_t>());
4717  }
4718 
4719  case 0x99: // array (two-byte uint16_t for n follow)
4720  {
4721  return get_cbor_array(get_number<uint16_t>());
4722  }
4723 
4724  case 0x9A: // array (four-byte uint32_t for n follow)
4725  {
4726  return get_cbor_array(get_number<uint32_t>());
4727  }
4728 
4729  case 0x9B: // array (eight-byte uint64_t for n follow)
4730  {
4731  return get_cbor_array(get_number<uint64_t>());
4732  }
4733 
4734  case 0x9F: // array (indefinite length)
4735  {
4736  BasicJsonType result = value_t::array;
4737  while (get() != 0xFF)
4738  {
4739  result.push_back(parse_cbor_internal(false));
4740  }
4741  return result;
4742  }
4743 
4744  // map (0x00..0x17 pairs of data items follow)
4745  case 0xA0:
4746  case 0xA1:
4747  case 0xA2:
4748  case 0xA3:
4749  case 0xA4:
4750  case 0xA5:
4751  case 0xA6:
4752  case 0xA7:
4753  case 0xA8:
4754  case 0xA9:
4755  case 0xAA:
4756  case 0xAB:
4757  case 0xAC:
4758  case 0xAD:
4759  case 0xAE:
4760  case 0xAF:
4761  case 0xB0:
4762  case 0xB1:
4763  case 0xB2:
4764  case 0xB3:
4765  case 0xB4:
4766  case 0xB5:
4767  case 0xB6:
4768  case 0xB7:
4769  {
4770  return get_cbor_object(current & 0x1F);
4771  }
4772 
4773  case 0xB8: // map (one-byte uint8_t for n follows)
4774  {
4775  return get_cbor_object(get_number<uint8_t>());
4776  }
4777 
4778  case 0xB9: // map (two-byte uint16_t for n follow)
4779  {
4780  return get_cbor_object(get_number<uint16_t>());
4781  }
4782 
4783  case 0xBA: // map (four-byte uint32_t for n follow)
4784  {
4785  return get_cbor_object(get_number<uint32_t>());
4786  }
4787 
4788  case 0xBB: // map (eight-byte uint64_t for n follow)
4789  {
4790  return get_cbor_object(get_number<uint64_t>());
4791  }
4792 
4793  case 0xBF: // map (indefinite length)
4794  {
4795  BasicJsonType result = value_t::object;
4796  while (get() != 0xFF)
4797  {
4798  auto key = get_cbor_string();
4799  result[key] = parse_cbor_internal();
4800  }
4801  return result;
4802  }
4803 
4804  case 0xF4: // false
4805  {
4806  return false;
4807  }
4808 
4809  case 0xF5: // true
4810  {
4811  return true;
4812  }
4813 
4814  case 0xF6: // null
4815  {
4816  return value_t::null;
4817  }
4818 
4819  case 0xF9: // Half-Precision Float (two-byte IEEE 754)
4820  {
4821  const int byte1 = get();
4822  check_eof();
4823  const int byte2 = get();
4824  check_eof();
4825 
4826  // code from RFC 7049, Appendix D, Figure 3:
4827  // As half-precision floating-point numbers were only added
4828  // to IEEE 754 in 2008, today's programming platforms often
4829  // still only have limited support for them. It is very
4830  // easy to include at least decoding support for them even
4831  // without such support. An example of a small decoder for
4832  // half-precision floating-point numbers in the C language
4833  // is shown in Fig. 3.
4834  const int half = (byte1 << 8) + byte2;
4835  const int exp = (half >> 10) & 0x1F;
4836  const int mant = half & 0x3FF;
4837  double val;
4838  if (exp == 0)
4839  {
4840  val = std::ldexp(mant, -24);
4841  }
4842  else if (exp != 31)
4843  {
4844  val = std::ldexp(mant + 1024, exp - 25);
4845  }
4846  else
4847  {
4848  val = (mant == 0) ? std::numeric_limits<double>::infinity()
4849  : std::numeric_limits<double>::quiet_NaN();
4850  }
4851  return (half & 0x8000) != 0 ? -val : val;
4852  }
4853 
4854  case 0xFA: // Single-Precision Float (four-byte IEEE 754)
4855  {
4856  return get_number<float>();
4857  }
4858 
4859  case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
4860  {
4861  return get_number<double>();
4862  }
4863 
4864  default: // anything else (0xFF is handled inside the other types)
4865  {
4866  std::stringstream ss;
4867  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
4868  JSON_THROW(parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + ss.str()));
4869  }
4870  }
4871  }
4872 
4873  BasicJsonType parse_msgpack_internal()
4874  {
4875  switch (get())
4876  {
4877  // EOF
4878  case std::char_traits<char>::eof():
4879  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
4880 
4881  // positive fixint
4882  case 0x00:
4883  case 0x01:
4884  case 0x02:
4885  case 0x03:
4886  case 0x04:
4887  case 0x05:
4888  case 0x06:
4889  case 0x07:
4890  case 0x08:
4891  case 0x09:
4892  case 0x0A:
4893  case 0x0B:
4894  case 0x0C:
4895  case 0x0D:
4896  case 0x0E:
4897  case 0x0F:
4898  case 0x10:
4899  case 0x11:
4900  case 0x12:
4901  case 0x13:
4902  case 0x14:
4903  case 0x15:
4904  case 0x16:
4905  case 0x17:
4906  case 0x18:
4907  case 0x19:
4908  case 0x1A:
4909  case 0x1B:
4910  case 0x1C:
4911  case 0x1D:
4912  case 0x1E:
4913  case 0x1F:
4914  case 0x20:
4915  case 0x21:
4916  case 0x22:
4917  case 0x23:
4918  case 0x24:
4919  case 0x25:
4920  case 0x26:
4921  case 0x27:
4922  case 0x28:
4923  case 0x29:
4924  case 0x2A:
4925  case 0x2B:
4926  case 0x2C:
4927  case 0x2D:
4928  case 0x2E:
4929  case 0x2F:
4930  case 0x30:
4931  case 0x31:
4932  case 0x32:
4933  case 0x33:
4934  case 0x34:
4935  case 0x35:
4936  case 0x36:
4937  case 0x37:
4938  case 0x38:
4939  case 0x39:
4940  case 0x3A:
4941  case 0x3B:
4942  case 0x3C:
4943  case 0x3D:
4944  case 0x3E:
4945  case 0x3F:
4946  case 0x40:
4947  case 0x41:
4948  case 0x42:
4949  case 0x43:
4950  case 0x44:
4951  case 0x45:
4952  case 0x46:
4953  case 0x47:
4954  case 0x48:
4955  case 0x49:
4956  case 0x4A:
4957  case 0x4B:
4958  case 0x4C:
4959  case 0x4D:
4960  case 0x4E:
4961  case 0x4F:
4962  case 0x50:
4963  case 0x51:
4964  case 0x52:
4965  case 0x53:
4966  case 0x54:
4967  case 0x55:
4968  case 0x56:
4969  case 0x57:
4970  case 0x58:
4971  case 0x59:
4972  case 0x5A:
4973  case 0x5B:
4974  case 0x5C:
4975  case 0x5D:
4976  case 0x5E:
4977  case 0x5F:
4978  case 0x60:
4979  case 0x61:
4980  case 0x62:
4981  case 0x63:
4982  case 0x64:
4983  case 0x65:
4984  case 0x66:
4985  case 0x67:
4986  case 0x68:
4987  case 0x69:
4988  case 0x6A:
4989  case 0x6B:
4990  case 0x6C:
4991  case 0x6D:
4992  case 0x6E:
4993  case 0x6F:
4994  case 0x70:
4995  case 0x71:
4996  case 0x72:
4997  case 0x73:
4998  case 0x74:
4999  case 0x75:
5000  case 0x76:
5001  case 0x77:
5002  case 0x78:
5003  case 0x79:
5004  case 0x7A:
5005  case 0x7B:
5006  case 0x7C:
5007  case 0x7D:
5008  case 0x7E:
5009  case 0x7F:
5010  return static_cast<number_unsigned_t>(current);
5011 
5012  // fixmap
5013  case 0x80:
5014  case 0x81:
5015  case 0x82:
5016  case 0x83:
5017  case 0x84:
5018  case 0x85:
5019  case 0x86:
5020  case 0x87:
5021  case 0x88:
5022  case 0x89:
5023  case 0x8A:
5024  case 0x8B:
5025  case 0x8C:
5026  case 0x8D:
5027  case 0x8E:
5028  case 0x8F:
5029  {
5030  return get_msgpack_object(current & 0x0F);
5031  }
5032 
5033  // fixarray
5034  case 0x90:
5035  case 0x91:
5036  case 0x92:
5037  case 0x93:
5038  case 0x94:
5039  case 0x95:
5040  case 0x96:
5041  case 0x97:
5042  case 0x98:
5043  case 0x99:
5044  case 0x9A:
5045  case 0x9B:
5046  case 0x9C:
5047  case 0x9D:
5048  case 0x9E:
5049  case 0x9F:
5050  {
5051  return get_msgpack_array(current & 0x0F);
5052  }
5053 
5054  // fixstr
5055  case 0xA0:
5056  case 0xA1:
5057  case 0xA2:
5058  case 0xA3:
5059  case 0xA4:
5060  case 0xA5:
5061  case 0xA6:
5062  case 0xA7:
5063  case 0xA8:
5064  case 0xA9:
5065  case 0xAA:
5066  case 0xAB:
5067  case 0xAC:
5068  case 0xAD:
5069  case 0xAE:
5070  case 0xAF:
5071  case 0xB0:
5072  case 0xB1:
5073  case 0xB2:
5074  case 0xB3:
5075  case 0xB4:
5076  case 0xB5:
5077  case 0xB6:
5078  case 0xB7:
5079  case 0xB8:
5080  case 0xB9:
5081  case 0xBA:
5082  case 0xBB:
5083  case 0xBC:
5084  case 0xBD:
5085  case 0xBE:
5086  case 0xBF:
5087  return get_msgpack_string();
5088 
5089  case 0xC0: // nil
5090  return value_t::null;
5091 
5092  case 0xC2: // false
5093  return false;
5094 
5095  case 0xC3: // true
5096  return true;
5097 
5098  case 0xCA: // float 32
5099  return get_number<float>();
5100 
5101  case 0xCB: // float 64
5102  return get_number<double>();
5103 
5104  case 0xCC: // uint 8
5105  return get_number<uint8_t>();
5106 
5107  case 0xCD: // uint 16
5108  return get_number<uint16_t>();
5109 
5110  case 0xCE: // uint 32
5111  return get_number<uint32_t>();
5112 
5113  case 0xCF: // uint 64
5114  return get_number<uint64_t>();
5115 
5116  case 0xD0: // int 8
5117  return get_number<int8_t>();
5118 
5119  case 0xD1: // int 16
5120  return get_number<int16_t>();
5121 
5122  case 0xD2: // int 32
5123  return get_number<int32_t>();
5124 
5125  case 0xD3: // int 64
5126  return get_number<int64_t>();
5127 
5128  case 0xD9: // str 8
5129  case 0xDA: // str 16
5130  case 0xDB: // str 32
5131  return get_msgpack_string();
5132 
5133  case 0xDC: // array 16
5134  {
5135  return get_msgpack_array(get_number<uint16_t>());
5136  }
5137 
5138  case 0xDD: // array 32
5139  {
5140  return get_msgpack_array(get_number<uint32_t>());
5141  }
5142 
5143  case 0xDE: // map 16
5144  {
5145  return get_msgpack_object(get_number<uint16_t>());
5146  }
5147 
5148  case 0xDF: // map 32
5149  {
5150  return get_msgpack_object(get_number<uint32_t>());
5151  }
5152 
5153  // positive fixint
5154  case 0xE0:
5155  case 0xE1:
5156  case 0xE2:
5157  case 0xE3:
5158  case 0xE4:
5159  case 0xE5:
5160  case 0xE6:
5161  case 0xE7:
5162  case 0xE8:
5163  case 0xE9:
5164  case 0xEA:
5165  case 0xEB:
5166  case 0xEC:
5167  case 0xED:
5168  case 0xEE:
5169  case 0xEF:
5170  case 0xF0:
5171  case 0xF1:
5172  case 0xF2:
5173  case 0xF3:
5174  case 0xF4:
5175  case 0xF5:
5176  case 0xF6:
5177  case 0xF7:
5178  case 0xF8:
5179  case 0xF9:
5180  case 0xFA:
5181  case 0xFB:
5182  case 0xFC:
5183  case 0xFD:
5184  case 0xFE:
5185  case 0xFF:
5186  return static_cast<int8_t>(current);
5187 
5188  default: // anything else
5189  {
5190  std::stringstream ss;
5191  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5192  JSON_THROW(parse_error::create(112, chars_read,
5193  "error reading MessagePack; last byte: 0x" + ss.str()));
5194  }
5195  }
5196  }
5197 
5198  /*!
5199  @brief get next character from the input
5200 
5201  This function provides the interface to the used input adapter. It does
5202  not throw in case the input reached EOF, but returns a -'ve valued
5203  `std::char_traits<char>::eof()` in that case.
5204 
5205  @return character read from the input
5206  */
5207  int get()
5208  {
5209  ++chars_read;
5210  return (current = ia->get_character());
5211  }
5212 
5213  /*
5214  @brief read a number from the input
5215 
5216  @tparam NumberType the type of the number
5217 
5218  @return number of type @a NumberType
5219 
5220  @note This function needs to respect the system's endianess, because
5221  bytes in CBOR and MessagePack are stored in network order (big
5222  endian) and therefore need reordering on little endian systems.
5223 
5224  @throw parse_error.110 if input has less than `sizeof(NumberType)` bytes
5225  */
5226  template<typename NumberType> NumberType get_number()
5227  {
5228  // step 1: read input into array with system's byte order
5229  std::array<uint8_t, sizeof(NumberType)> vec;
5230  for (std::size_t i = 0; i < sizeof(NumberType); ++i)
5231  {
5232  get();
5233  check_eof();
5234 
5235  // reverse byte order prior to conversion if necessary
5236  if (is_little_endian)
5237  {
5238  vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);
5239  }
5240  else
5241  {
5242  vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE
5243  }
5244  }
5245 
5246  // step 2: convert array into number of type T and return
5247  NumberType result;
5248  std::memcpy(&result, vec.data(), sizeof(NumberType));
5249  return result;
5250  }
5251 
5252  /*!
5253  @brief create a string by reading characters from the input
5254 
5255  @param[in] len number of bytes to read
5256 
5257  @note We can not reserve @a len bytes for the result, because @a len
5258  may be too large. Usually, @ref check_eof() detects the end of
5259  the input before we run out of string memory.
5260 
5261  @return string created by reading @a len bytes
5262 
5263  @throw parse_error.110 if input has less than @a len bytes
5264  */
5265  template<typename NumberType>
5266  std::string get_string(const NumberType len)
5267  {
5268  std::string result;
5269  std::generate_n(std::back_inserter(result), len, [this]()
5270  {
5271  get();
5272  check_eof();
5273  return static_cast<char>(current);
5274  });
5275  return result;
5276  }
5277 
5278  /*!
5279  @brief reads a CBOR string
5280 
5281  This function first reads starting bytes to determine the expected
5282  string length and then copies this number of bytes into a string.
5283  Additionally, CBOR's strings with indefinite lengths are supported.
5284 
5285  @return string
5286 
5287  @throw parse_error.110 if input ended
5288  @throw parse_error.113 if an unexpected byte is read
5289  */
5290  std::string get_cbor_string()
5291  {
5292  check_eof();
5293 
5294  switch (current)
5295  {
5296  // UTF-8 string (0x00..0x17 bytes follow)
5297  case 0x60:
5298  case 0x61:
5299  case 0x62:
5300  case 0x63:
5301  case 0x64:
5302  case 0x65:
5303  case 0x66:
5304  case 0x67:
5305  case 0x68:
5306  case 0x69:
5307  case 0x6A:
5308  case 0x6B:
5309  case 0x6C:
5310  case 0x6D:
5311  case 0x6E:
5312  case 0x6F:
5313  case 0x70:
5314  case 0x71:
5315  case 0x72:
5316  case 0x73:
5317  case 0x74:
5318  case 0x75:
5319  case 0x76:
5320  case 0x77:
5321  {
5322  return get_string(current & 0x1F);
5323  }
5324 
5325  case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
5326  {
5327  return get_string(get_number<uint8_t>());
5328  }
5329 
5330  case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
5331  {
5332  return get_string(get_number<uint16_t>());
5333  }
5334 
5335  case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
5336  {
5337  return get_string(get_number<uint32_t>());
5338  }
5339 
5340  case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
5341  {
5342  return get_string(get_number<uint64_t>());
5343  }
5344 
5345  case 0x7F: // UTF-8 string (indefinite length)
5346  {
5347  std::string result;
5348  while (get() != 0xFF)
5349  {
5350  check_eof();
5351  result.push_back(static_cast<char>(current));
5352  }
5353  return result;
5354  }
5355 
5356  default:
5357  {
5358  std::stringstream ss;
5359  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5360  JSON_THROW(parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + ss.str()));
5361  }
5362  }
5363  }
5364 
5365  template<typename NumberType>
5366  BasicJsonType get_cbor_array(const NumberType len)
5367  {
5368  BasicJsonType result = value_t::array;
5369  std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
5370  {
5371  return parse_cbor_internal();
5372  });
5373  return result;
5374  }
5375 
5376  template<typename NumberType>
5377  BasicJsonType get_cbor_object(const NumberType len)
5378  {
5379  BasicJsonType result = value_t::object;
5380  std::generate_n(std::inserter(*result.m_value.object,
5381  result.m_value.object->end()),
5382  len, [this]()
5383  {
5384  get();
5385  auto key = get_cbor_string();
5386  auto val = parse_cbor_internal();
5387  return std::make_pair(std::move(key), std::move(val));
5388  });
5389  return result;
5390  }
5391 
5392  /*!
5393  @brief reads a MessagePack string
5394 
5395  This function first reads starting bytes to determine the expected
5396  string length and then copies this number of bytes into a string.
5397 
5398  @return string
5399 
5400  @throw parse_error.110 if input ended
5401  @throw parse_error.113 if an unexpected byte is read
5402  */
5403  std::string get_msgpack_string()
5404  {
5405  check_eof();
5406 
5407  switch (current)
5408  {
5409  // fixstr
5410  case 0xA0:
5411  case 0xA1:
5412  case 0xA2:
5413  case 0xA3:
5414  case 0xA4:
5415  case 0xA5:
5416  case 0xA6:
5417  case 0xA7:
5418  case 0xA8:
5419  case 0xA9:
5420  case 0xAA:
5421  case 0xAB:
5422  case 0xAC:
5423  case 0xAD:
5424  case 0xAE:
5425  case 0xAF:
5426  case 0xB0:
5427  case 0xB1:
5428  case 0xB2:
5429  case 0xB3:
5430  case 0xB4:
5431  case 0xB5:
5432  case 0xB6:
5433  case 0xB7:
5434  case 0xB8:
5435  case 0xB9:
5436  case 0xBA:
5437  case 0xBB:
5438  case 0xBC:
5439  case 0xBD:
5440  case 0xBE:
5441  case 0xBF:
5442  {
5443  return get_string(current & 0x1F);
5444  }
5445 
5446  case 0xD9: // str 8
5447  {
5448  return get_string(get_number<uint8_t>());
5449  }
5450 
5451  case 0xDA: // str 16
5452  {
5453  return get_string(get_number<uint16_t>());
5454  }
5455 
5456  case 0xDB: // str 32
5457  {
5458  return get_string(get_number<uint32_t>());
5459  }
5460 
5461  default:
5462  {
5463  std::stringstream ss;
5464  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5465  JSON_THROW(parse_error::create(113, chars_read,
5466  "expected a MessagePack string; last byte: 0x" + ss.str()));
5467  }
5468  }
5469  }
5470 
5471  template<typename NumberType>
5472  BasicJsonType get_msgpack_array(const NumberType len)
5473  {
5474  BasicJsonType result = value_t::array;
5475  std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
5476  {
5477  return parse_msgpack_internal();
5478  });
5479  return result;
5480  }
5481 
5482  template<typename NumberType>
5483  BasicJsonType get_msgpack_object(const NumberType len)
5484  {
5485  BasicJsonType result = value_t::object;
5486  std::generate_n(std::inserter(*result.m_value.object,
5487  result.m_value.object->end()),
5488  len, [this]()
5489  {
5490  get();
5491  auto key = get_msgpack_string();
5492  auto val = parse_msgpack_internal();
5493  return std::make_pair(std::move(key), std::move(val));
5494  });
5495  return result;
5496  }
5497 
5498  /*!
5499  @brief check if input ended
5500  @throw parse_error.110 if input ended
5501  */
5502  void check_eof(const bool expect_eof = false) const
5503  {
5504  if (expect_eof)
5505  {
5506  if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
5507  {
5508  JSON_THROW(parse_error::create(110, chars_read, "expected end of input"));
5509  }
5510  }
5511  else
5512  {
5513  if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
5514  {
5515  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
5516  }
5517  }
5518  }
5519 
5520  private:
5521  /// input adapter
5522  input_adapter_t ia = nullptr;
5523 
5524  /// the current character
5525  int current = std::char_traits<char>::eof();
5526 
5527  /// the number of characters read
5528  std::size_t chars_read = 0;
5529 
5530  /// whether we can assume little endianess
5531  const bool is_little_endian = little_endianess();
5532 };
5533 
5534 /*!
5535 @brief serialization to CBOR and MessagePack values
5536 */
5537 template<typename BasicJsonType, typename CharType>
5538 class binary_writer
5539 {
5540  public:
5541  /*!
5542  @brief create a binary writer
5543 
5544  @param[in] adapter output adapter to write to
5545  */
5546  explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
5547  {
5548  assert(oa);
5549  }
5550 
5551  /*!
5552  @brief[in] j JSON value to serialize
5553  */
5554  void write_cbor(const BasicJsonType& j)
5555  {
5556  switch (j.type())
5557  {
5558  case value_t::null:
5559  {
5560  oa->write_character(static_cast<CharType>(0xF6));
5561  break;
5562  }
5563 
5564  case value_t::boolean:
5565  {
5566  oa->write_character(j.m_value.boolean
5567  ? static_cast<CharType>(0xF5)
5568  : static_cast<CharType>(0xF4));
5569  break;
5570  }
5571 
5572  case value_t::number_integer:
5573  {
5574  if (j.m_value.number_integer >= 0)
5575  {
5576  // CBOR does not differentiate between positive signed
5577  // integers and unsigned integers. Therefore, we used the
5578  // code from the value_t::number_unsigned case here.
5579  if (j.m_value.number_integer <= 0x17)
5580  {
5581  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5582  }
5583  else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
5584  {
5585  oa->write_character(static_cast<CharType>(0x18));
5586  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5587  }
5588  else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
5589  {
5590  oa->write_character(static_cast<CharType>(0x19));
5591  write_number(static_cast<uint16_t>(j.m_value.number_integer));
5592  }
5593  else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
5594  {
5595  oa->write_character(static_cast<CharType>(0x1A));
5596  write_number(static_cast<uint32_t>(j.m_value.number_integer));
5597  }
5598  else
5599  {
5600  oa->write_character(static_cast<CharType>(0x1B));
5601  write_number(static_cast<uint64_t>(j.m_value.number_integer));
5602  }
5603  }
5604  else
5605  {
5606  // The conversions below encode the sign in the first
5607  // byte, and the value is converted to a positive number.
5608  const auto positive_number = -1 - j.m_value.number_integer;
5609  if (j.m_value.number_integer >= -24)
5610  {
5611  write_number(static_cast<uint8_t>(0x20 + positive_number));
5612  }
5613  else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
5614  {
5615  oa->write_character(static_cast<CharType>(0x38));
5616  write_number(static_cast<uint8_t>(positive_number));
5617  }
5618  else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
5619  {
5620  oa->write_character(static_cast<CharType>(0x39));
5621  write_number(static_cast<uint16_t>(positive_number));
5622  }
5623  else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
5624  {
5625  oa->write_character(static_cast<CharType>(0x3A));
5626  write_number(static_cast<uint32_t>(positive_number));
5627  }
5628  else
5629  {
5630  oa->write_character(static_cast<CharType>(0x3B));
5631  write_number(static_cast<uint64_t>(positive_number));
5632  }
5633  }
5634  break;
5635  }
5636 
5637  case value_t::number_unsigned:
5638  {
5639  if (j.m_value.number_unsigned <= 0x17)
5640  {
5641  write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
5642  }
5643  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
5644  {
5645  oa->write_character(static_cast<CharType>(0x18));
5646  write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
5647  }
5648  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
5649  {
5650  oa->write_character(static_cast<CharType>(0x19));
5651  write_number(static_cast<uint16_t>(j.m_value.number_unsigned));
5652  }
5653  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
5654  {
5655  oa->write_character(static_cast<CharType>(0x1A));
5656  write_number(static_cast<uint32_t>(j.m_value.number_unsigned));
5657  }
5658  else
5659  {
5660  oa->write_character(static_cast<CharType>(0x1B));
5661  write_number(static_cast<uint64_t>(j.m_value.number_unsigned));
5662  }
5663  break;
5664  }
5665 
5666  case value_t::number_float: // Double-Precision Float
5667  {
5668  oa->write_character(static_cast<CharType>(0xFB));
5669  write_number(j.m_value.number_float);
5670  break;
5671  }
5672 
5673  case value_t::string:
5674  {
5675  // step 1: write control byte and the string length
5676  const auto N = j.m_value.string->size();
5677  if (N <= 0x17)
5678  {
5679  write_number(static_cast<uint8_t>(0x60 + N));
5680  }
5681  else if (N <= 0xFF)
5682  {
5683  oa->write_character(static_cast<CharType>(0x78));
5684  write_number(static_cast<uint8_t>(N));
5685  }
5686  else if (N <= 0xFFFF)
5687  {
5688  oa->write_character(static_cast<CharType>(0x79));
5689  write_number(static_cast<uint16_t>(N));
5690  }
5691  else if (N <= 0xFFFFFFFF)
5692  {
5693  oa->write_character(static_cast<CharType>(0x7A));
5694  write_number(static_cast<uint32_t>(N));
5695  }
5696  // LCOV_EXCL_START
5697  else if (N <= 0xFFFFFFFFFFFFFFFF)
5698  {
5699  oa->write_character(static_cast<CharType>(0x7B));
5700  write_number(static_cast<uint64_t>(N));
5701  }
5702  // LCOV_EXCL_STOP
5703 
5704  // step 2: write the string
5705  oa->write_characters(
5706  reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
5707  j.m_value.string->size());
5708  break;
5709  }
5710 
5711  case value_t::array:
5712  {
5713  // step 1: write control byte and the array size
5714  const auto N = j.m_value.array->size();
5715  if (N <= 0x17)
5716  {
5717  write_number(static_cast<uint8_t>(0x80 + N));
5718  }
5719  else if (N <= 0xFF)
5720  {
5721  oa->write_character(static_cast<CharType>(0x98));
5722  write_number(static_cast<uint8_t>(N));
5723  }
5724  else if (N <= 0xFFFF)
5725  {
5726  oa->write_character(static_cast<CharType>(0x99));
5727  write_number(static_cast<uint16_t>(N));
5728  }
5729  else if (N <= 0xFFFFFFFF)
5730  {
5731  oa->write_character(static_cast<CharType>(0x9A));
5732  write_number(static_cast<uint32_t>(N));
5733  }
5734  // LCOV_EXCL_START
5735  else if (N <= 0xFFFFFFFFFFFFFFFF)
5736  {
5737  oa->write_character(static_cast<CharType>(0x9B));
5738  write_number(static_cast<uint64_t>(N));
5739  }
5740  // LCOV_EXCL_STOP
5741 
5742  // step 2: write each element
5743  for (const auto& el : *j.m_value.array)
5744  {
5745  write_cbor(el);
5746  }
5747  break;
5748  }
5749 
5750  case value_t::object:
5751  {
5752  // step 1: write control byte and the object size
5753  const auto N = j.m_value.object->size();
5754  if (N <= 0x17)
5755  {
5756  write_number(static_cast<uint8_t>(0xA0 + N));
5757  }
5758  else if (N <= 0xFF)
5759  {
5760  oa->write_character(static_cast<CharType>(0xB8));
5761  write_number(static_cast<uint8_t>(N));
5762  }
5763  else if (N <= 0xFFFF)
5764  {
5765  oa->write_character(static_cast<CharType>(0xB9));
5766  write_number(static_cast<uint16_t>(N));
5767  }
5768  else if (N <= 0xFFFFFFFF)
5769  {
5770  oa->write_character(static_cast<CharType>(0xBA));
5771  write_number(static_cast<uint32_t>(N));
5772  }
5773  // LCOV_EXCL_START
5774  else if (N <= 0xFFFFFFFFFFFFFFFF)
5775  {
5776  oa->write_character(static_cast<CharType>(0xBB));
5777  write_number(static_cast<uint64_t>(N));
5778  }
5779  // LCOV_EXCL_STOP
5780 
5781  // step 2: write each element
5782  for (const auto& el : *j.m_value.object)
5783  {
5784  write_cbor(el.first);
5785  write_cbor(el.second);
5786  }
5787  break;
5788  }
5789 
5790  default:
5791  break;
5792  }
5793  }
5794 
5795  /*!
5796  @brief[in] j JSON value to serialize
5797  */
5798  void write_msgpack(const BasicJsonType& j)
5799  {
5800  switch (j.type())
5801  {
5802  case value_t::null: // nil
5803  {
5804  oa->write_character(static_cast<CharType>(0xC0));
5805  break;
5806  }
5807 
5808  case value_t::boolean: // true and false
5809  {
5810  oa->write_character(j.m_value.boolean
5811  ? static_cast<CharType>(0xC3)
5812  : static_cast<CharType>(0xC2));
5813  break;
5814  }
5815 
5816  case value_t::number_integer:
5817  {
5818  if (j.m_value.number_integer >= 0)
5819  {
5820  // MessagePack does not differentiate between positive
5821  // signed integers and unsigned integers. Therefore, we used
5822  // the code from the value_t::number_unsigned case here.
5823  if (j.m_value.number_unsigned < 128)
5824  {
5825  // positive fixnum
5826  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5827  }
5828  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
5829  {
5830  // uint 8
5831  oa->write_character(static_cast<CharType>(0xCC));
5832  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5833  }
5834  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
5835  {
5836  // uint 16
5837  oa->write_character(static_cast<CharType>(0xCD));
5838  write_number(static_cast<uint16_t>(j.m_value.number_integer));
5839  }
5840  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
5841  {
5842  // uint 32
5843  oa->write_character(static_cast<CharType>(0xCE));
5844  write_number(static_cast<uint32_t>(j.m_value.number_integer));
5845  }
5846  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
5847  {
5848  // uint 64
5849  oa->write_character(static_cast<CharType>(0xCF));
5850  write_number(static_cast<uint64_t>(j.m_value.number_integer));
5851  }
5852  }
5853  else
5854  {
5855  if (j.m_value.number_integer >= -32)
5856  {
5857  // negative fixnum
5858  write_number(static_cast<int8_t>(j.m_value.number_integer));
5859  }
5860  else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and
5861  j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
5862  {
5863  // int 8
5864  oa->write_character(static_cast<CharType>(0xD0));
5865  write_number(static_cast<int8_t>(j.m_value.number_integer));
5866  }
5867  else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and
5868  j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
5869  {
5870  // int 16
5871  oa->write_character(static_cast<CharType>(0xD1));
5872  write_number(static_cast<int16_t>(j.m_value.number_integer));
5873  }
5874  else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and
5875  j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
5876  {
5877  // int 32
5878  oa->write_character(static_cast<CharType>(0xD2));
5879  write_number(static_cast<int32_t>(j.m_value.number_integer));
5880  }
5881  else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and
5882  j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
5883  {
5884  // int 64
5885  oa->write_character(static_cast<CharType>(0xD3));
5886  write_number(static_cast<int64_t>(j.m_value.number_integer));
5887  }
5888  }
5889  break;
5890  }
5891 
5892  case value_t::number_unsigned:
5893  {
5894  if (j.m_value.number_unsigned < 128)
5895  {
5896  // positive fixnum
5897  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5898  }
5899  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
5900  {
5901  // uint 8
5902  oa->write_character(static_cast<CharType>(0xCC));
5903  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5904  }
5905  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
5906  {
5907  // uint 16
5908  oa->write_character(static_cast<CharType>(0xCD));
5909  write_number(static_cast<uint16_t>(j.m_value.number_integer));
5910  }
5911  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
5912  {
5913  // uint 32
5914  oa->write_character(static_cast<CharType>(0xCE));
5915  write_number(static_cast<uint32_t>(j.m_value.number_integer));
5916  }
5917  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
5918  {
5919  // uint 64
5920  oa->write_character(static_cast<CharType>(0xCF));
5921  write_number(static_cast<uint64_t>(j.m_value.number_integer));
5922  }
5923  break;
5924  }
5925 
5926  case value_t::number_float: // float 64
5927  {
5928  oa->write_character(static_cast<CharType>(0xCB));
5929  write_number(j.m_value.number_float);
5930  break;
5931  }
5932 
5933  case value_t::string:
5934  {
5935  // step 1: write control byte and the string length
5936  const auto N = j.m_value.string->size();
5937  if (N <= 31)
5938  {
5939  // fixstr
5940  write_number(static_cast<uint8_t>(0xA0 | N));
5941  }
5942  else if (N <= 255)
5943  {
5944  // str 8
5945  oa->write_character(static_cast<CharType>(0xD9));
5946  write_number(static_cast<uint8_t>(N));
5947  }
5948  else if (N <= 65535)
5949  {
5950  // str 16
5951  oa->write_character(static_cast<CharType>(0xDA));
5952  write_number(static_cast<uint16_t>(N));
5953  }
5954  else if (N <= 4294967295)
5955  {
5956  // str 32
5957  oa->write_character(static_cast<CharType>(0xDB));
5958  write_number(static_cast<uint32_t>(N));
5959  }
5960 
5961  // step 2: write the string
5962  oa->write_characters(
5963  reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
5964  j.m_value.string->size());
5965  break;
5966  }
5967 
5968  case value_t::array:
5969  {
5970  // step 1: write control byte and the array size
5971  const auto N = j.m_value.array->size();
5972  if (N <= 15)
5973  {
5974  // fixarray
5975  write_number(static_cast<uint8_t>(0x90 | N));
5976  }
5977  else if (N <= 0xFFFF)
5978  {
5979  // array 16
5980  oa->write_character(static_cast<CharType>(0xDC));
5981  write_number(static_cast<uint16_t>(N));
5982  }
5983  else if (N <= 0xFFFFFFFF)
5984  {
5985  // array 32
5986  oa->write_character(static_cast<CharType>(0xDD));
5987  write_number(static_cast<uint32_t>(N));
5988  }
5989 
5990  // step 2: write each element
5991  for (const auto& el : *j.m_value.array)
5992  {
5993  write_msgpack(el);
5994  }
5995  break;
5996  }
5997 
5998  case value_t::object:
5999  {
6000  // step 1: write control byte and the object size
6001  const auto N = j.m_value.object->size();
6002  if (N <= 15)
6003  {
6004  // fixmap
6005  write_number(static_cast<uint8_t>(0x80 | (N & 0xF)));
6006  }
6007  else if (N <= 65535)
6008  {
6009  // map 16
6010  oa->write_character(static_cast<CharType>(0xDE));
6011  write_number(static_cast<uint16_t>(N));
6012  }
6013  else if (N <= 4294967295)
6014  {
6015  // map 32
6016  oa->write_character(static_cast<CharType>(0xDF));
6017  write_number(static_cast<uint32_t>(N));
6018  }
6019 
6020  // step 2: write each element
6021  for (const auto& el : *j.m_value.object)
6022  {
6023  write_msgpack(el.first);
6024  write_msgpack(el.second);
6025  }
6026  break;
6027  }
6028 
6029  default:
6030  break;
6031  }
6032  }
6033 
6034  private:
6035  /*
6036  @brief write a number to output input
6037 
6038  @param[in] n number of type @a NumberType
6039  @tparam NumberType the type of the number
6040 
6041  @note This function needs to respect the system's endianess, because bytes
6042  in CBOR and MessagePack are stored in network order (big endian) and
6043  therefore need reordering on little endian systems.
6044  */
6045  template<typename NumberType> void write_number(NumberType n)
6046  {
6047  // step 1: write number to array of length NumberType
6048  std::array<CharType, sizeof(NumberType)> vec;
6049  std::memcpy(vec.data(), &n, sizeof(NumberType));
6050 
6051  // step 2: write array to output (with possible reordering)
6052  if (is_little_endian)
6053  {
6054  // reverse byte order prior to conversion if necessary
6055  std::reverse(vec.begin(), vec.end());
6056  }
6057 
6058  oa->write_characters(vec.data(), sizeof(NumberType));
6059  }
6060 
6061  private:
6062  /// whether we can assume little endianess
6063  const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
6064 
6065  /// the output
6066  output_adapter_t<CharType> oa = nullptr;
6067 };
6068 
6069 ///////////////////
6070 // serialization //
6071 ///////////////////
6072 
6073 template<typename BasicJsonType>
6074 class serializer
6075 {
6076  using string_t = typename BasicJsonType::string_t;
6077  using number_float_t = typename BasicJsonType::number_float_t;
6078  using number_integer_t = typename BasicJsonType::number_integer_t;
6079  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
6080  public:
6081  /*!
6082  @param[in] s output stream to serialize to
6083  @param[in] ichar indentation character to use
6084  */
6085  serializer(output_adapter_t<char> s, const char ichar)
6086  : o(std::move(s)), loc(std::localeconv()),
6087  thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep)),
6088  decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point)),
6089  indent_char(ichar), indent_string(512, indent_char) {}
6090 
6091  // delete because of pointer members
6092  serializer(const serializer&) = delete;
6093  serializer& operator=(const serializer&) = delete;
6094 
6095  /*!
6096  @brief internal implementation of the serialization function
6097 
6098  This function is called by the public member function dump and organizes
6099  the serialization internally. The indentation level is propagated as
6100  additional parameter. In case of arrays and objects, the function is
6101  called recursively.
6102 
6103  - strings and object keys are escaped using `escape_string()`
6104  - integer numbers are converted implicitly via `operator<<`
6105  - floating-point numbers are converted to a string using `"%g"` format
6106 
6107  @param[in] val value to serialize
6108  @param[in] pretty_print whether the output shall be pretty-printed
6109  @param[in] indent_step the indent level
6110  @param[in] current_indent the current indent level (only used internally)
6111  */
6112  void dump(const BasicJsonType& val, const bool pretty_print,
6113  const bool ensure_ascii,
6114  const unsigned int indent_step,
6115  const unsigned int current_indent = 0)
6116  {
6117  switch (val.m_type)
6118  {
6119  case value_t::object:
6120  {
6121  if (val.m_value.object->empty())
6122  {
6123  o->write_characters("{}", 2);
6124  return;
6125  }
6126 
6127  if (pretty_print)
6128  {
6129  o->write_characters("{\n", 2);
6130 
6131  // variable to hold indentation for recursive calls
6132  const auto new_indent = current_indent + indent_step;
6133  if (JSON_UNLIKELY(indent_string.size() < new_indent))
6134  {
6135  indent_string.resize(indent_string.size() * 2, ' ');
6136  }
6137 
6138  // first n-1 elements
6139  auto i = val.m_value.object->cbegin();
6140  for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
6141  {
6142  o->write_characters(indent_string.c_str(), new_indent);
6143  o->write_character('\"');
6144  dump_escaped(i->first, ensure_ascii);
6145  o->write_characters("\": ", 3);
6146  dump(i->second, true, ensure_ascii, indent_step, new_indent);
6147  o->write_characters(",\n", 2);
6148  }
6149 
6150  // last element
6151  assert(i != val.m_value.object->cend());
6152  assert(std::next(i) == val.m_value.object->cend());
6153  o->write_characters(indent_string.c_str(), new_indent);
6154  o->write_character('\"');
6155  dump_escaped(i->first, ensure_ascii);
6156  o->write_characters("\": ", 3);
6157  dump(i->second, true, ensure_ascii, indent_step, new_indent);
6158 
6159  o->write_character('\n');
6160  o->write_characters(indent_string.c_str(), current_indent);
6161  o->write_character('}');
6162  }
6163  else
6164  {
6165  o->write_character('{');
6166 
6167  // first n-1 elements
6168  auto i = val.m_value.object->cbegin();
6169  for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
6170  {
6171  o->write_character('\"');
6172  dump_escaped(i->first, ensure_ascii);
6173  o->write_characters("\":", 2);
6174  dump(i->second, false, ensure_ascii, indent_step, current_indent);
6175  o->write_character(',');
6176  }
6177 
6178  // last element
6179  assert(i != val.m_value.object->cend());
6180  assert(std::next(i) == val.m_value.object->cend());
6181  o->write_character('\"');
6182  dump_escaped(i->first, ensure_ascii);
6183  o->write_characters("\":", 2);
6184  dump(i->second, false, ensure_ascii, indent_step, current_indent);
6185 
6186  o->write_character('}');
6187  }
6188 
6189  return;
6190  }
6191 
6192  case value_t::array:
6193  {
6194  if (val.m_value.array->empty())
6195  {
6196  o->write_characters("[]", 2);
6197  return;
6198  }
6199 
6200  if (pretty_print)
6201  {
6202  o->write_characters("[\n", 2);
6203 
6204  // variable to hold indentation for recursive calls
6205  const auto new_indent = current_indent + indent_step;
6206  if (JSON_UNLIKELY(indent_string.size() < new_indent))
6207  {
6208  indent_string.resize(indent_string.size() * 2, ' ');
6209  }
6210 
6211  // first n-1 elements
6212  for (auto i = val.m_value.array->cbegin();
6213  i != val.m_value.array->cend() - 1; ++i)
6214  {
6215  o->write_characters(indent_string.c_str(), new_indent);
6216  dump(*i, true, ensure_ascii, indent_step, new_indent);
6217  o->write_characters(",\n", 2);
6218  }
6219 
6220  // last element
6221  assert(not val.m_value.array->empty());
6222  o->write_characters(indent_string.c_str(), new_indent);
6223  dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
6224 
6225  o->write_character('\n');
6226  o->write_characters(indent_string.c_str(), current_indent);
6227  o->write_character(']');
6228  }
6229  else
6230  {
6231  o->write_character('[');
6232 
6233  // first n-1 elements
6234  for (auto i = val.m_value.array->cbegin();
6235  i != val.m_value.array->cend() - 1; ++i)
6236  {
6237  dump(*i, false, ensure_ascii, indent_step, current_indent);
6238  o->write_character(',');
6239  }
6240 
6241  // last element
6242  assert(not val.m_value.array->empty());
6243  dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
6244 
6245  o->write_character(']');
6246  }
6247 
6248  return;
6249  }
6250 
6251  case value_t::string:
6252  {
6253  o->write_character('\"');
6254  dump_escaped(*val.m_value.string, ensure_ascii);
6255  o->write_character('\"');
6256  return;
6257  }
6258 
6259  case value_t::boolean:
6260  {
6261  if (val.m_value.boolean)
6262  {
6263  o->write_characters("true", 4);
6264  }
6265  else
6266  {
6267  o->write_characters("false", 5);
6268  }
6269  return;
6270  }
6271 
6272  case value_t::number_integer:
6273  {
6274  dump_integer(val.m_value.number_integer);
6275  return;
6276  }
6277 
6278  case value_t::number_unsigned:
6279  {
6280  dump_integer(val.m_value.number_unsigned);
6281  return;
6282  }
6283 
6284  case value_t::number_float:
6285  {
6286  dump_float(val.m_value.number_float);
6287  return;
6288  }
6289 
6290  case value_t::discarded:
6291  {
6292  o->write_characters("<discarded>", 11);
6293  return;
6294  }
6295 
6296  case value_t::null:
6297  {
6298  o->write_characters("null", 4);
6299  return;
6300  }
6301  }
6302  }
6303 
6304  private:
6305  /*!
6306  @brief returns the number of expected bytes following in UTF-8 string
6307 
6308  @param[in] u the first byte of a UTF-8 string
6309  @return the number of expected bytes following
6310  */
6311  static constexpr std::size_t bytes_following(const uint8_t u)
6312  {
6313  return ((u <= 127) ? 0
6314  : ((192 <= u and u <= 223) ? 1
6315  : ((224 <= u and u <= 239) ? 2
6316  : ((240 <= u and u <= 247) ? 3 : std::string::npos))));
6317  }
6318 
6319  /*!
6320  @brief calculates the extra space to escape a JSON string
6321 
6322  @param[in] s the string to escape
6323  @param[in] ensure_ascii whether to escape non-ASCII characters with
6324  \uXXXX sequences
6325  @return the number of characters required to escape string @a s
6326 
6327  @complexity Linear in the length of string @a s.
6328  */
6329  static std::size_t extra_space(const string_t& s,
6330  const bool ensure_ascii) noexcept
6331  {
6332  std::size_t res = 0;
6333 
6334  for (std::size_t i = 0; i < s.size(); ++i)
6335  {
6336  switch (s[i])
6337  {
6338  // control characters that can be escaped with a backslash
6339  case '"':
6340  case '\\':
6341  case '\b':
6342  case '\f':
6343  case '\n':
6344  case '\r':
6345  case '\t':
6346  {
6347  // from c (1 byte) to \x (2 bytes)
6348  res += 1;
6349  break;
6350  }
6351 
6352  // control characters that need \uxxxx escaping
6353  case 0x00:
6354  case 0x01:
6355  case 0x02:
6356  case 0x03:
6357  case 0x04:
6358  case 0x05:
6359  case 0x06:
6360  case 0x07:
6361  case 0x0B:
6362  case 0x0E:
6363  case 0x0F:
6364  case 0x10:
6365  case 0x11:
6366  case 0x12:
6367  case 0x13:
6368  case 0x14:
6369  case 0x15:
6370  case 0x16:
6371  case 0x17:
6372  case 0x18:
6373  case 0x19:
6374  case 0x1A:
6375  case 0x1B:
6376  case 0x1C:
6377  case 0x1D:
6378  case 0x1E:
6379  case 0x1F:
6380  {
6381  // from c (1 byte) to \uxxxx (6 bytes)
6382  res += 5;
6383  break;
6384  }
6385 
6386  default:
6387  {
6388  if (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F))
6389  {
6390  const auto bytes = bytes_following(static_cast<uint8_t>(s[i]));
6391  // invalid characters will be detected by throw_if_invalid_utf8
6392  assert (bytes != std::string::npos);
6393 
6394  if (bytes == 3)
6395  {
6396  // codepoints that need 4 bytes (i.e., 3 additional
6397  // bytes) in UTF-8 need a surrogate pair when \u
6398  // escaping is used: from 4 bytes to \uxxxx\uxxxx
6399  // (12 bytes)
6400  res += (12 - bytes - 1);
6401  }
6402  else
6403  {
6404  // from x bytes to \uxxxx (6 bytes)
6405  res += (6 - bytes - 1);
6406  }
6407 
6408  // skip the additional bytes
6409  i += bytes;
6410  }
6411  break;
6412  }
6413  }
6414  }
6415 
6416  return res;
6417  }
6418 
6419  static void escape_codepoint(int codepoint, string_t& result, std::size_t& pos)
6420  {
6421  // expecting a proper codepoint
6422  assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
6423 
6424  // the last written character was the backslash before the 'u'
6425  assert(result[pos] == '\\');
6426 
6427  // write the 'u'
6428  result[++pos] = 'u';
6429 
6430  // convert a number 0..15 to its hex representation (0..f)
6431  static const std::array<char, 16> hexify =
6432  {
6433  {
6434  '0', '1', '2', '3', '4', '5', '6', '7',
6435  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
6436  }
6437  };
6438 
6439  if (codepoint < 0x10000)
6440  {
6441  // codepoints U+0000..U+FFFF can be represented as \uxxxx.
6442  result[++pos] = hexify[(codepoint >> 12) & 0x0F];
6443  result[++pos] = hexify[(codepoint >> 8) & 0x0F];
6444  result[++pos] = hexify[(codepoint >> 4) & 0x0F];
6445  result[++pos] = hexify[codepoint & 0x0F];
6446  }
6447  else
6448  {
6449  // codepoints U+10000..U+10FFFF need a surrogate pair to be
6450  // represented as \uxxxx\uxxxx.
6451  // http://www.unicode.org/faq/utf_bom.html#utf16-4
6452  codepoint -= 0x10000;
6453  const int high_surrogate = 0xD800 | ((codepoint >> 10) & 0x3FF);
6454  const int low_surrogate = 0xDC00 | (codepoint & 0x3FF);
6455  result[++pos] = hexify[(high_surrogate >> 12) & 0x0F];
6456  result[++pos] = hexify[(high_surrogate >> 8) & 0x0F];
6457  result[++pos] = hexify[(high_surrogate >> 4) & 0x0F];
6458  result[++pos] = hexify[high_surrogate & 0x0F];
6459  ++pos; // backslash is already in output
6460  result[++pos] = 'u';
6461  result[++pos] = hexify[(low_surrogate >> 12) & 0x0F];
6462  result[++pos] = hexify[(low_surrogate >> 8) & 0x0F];
6463  result[++pos] = hexify[(low_surrogate >> 4) & 0x0F];
6464  result[++pos] = hexify[low_surrogate & 0x0F];
6465  }
6466 
6467  ++pos;
6468  }
6469 
6470  /*!
6471  @brief dump escaped string
6472 
6473  Escape a string by replacing certain special characters by a sequence of an
6474  escape character (backslash) and another character and other control
6475  characters by a sequence of "\u" followed by a four-digit hex
6476  representation. The escaped string is written to output stream @a o.
6477 
6478  @param[in] s the string to escape
6479  @param[in] ensure_ascii whether to escape non-ASCII characters with
6480  \uXXXX sequences
6481 
6482  @complexity Linear in the length of string @a s.
6483  */
6484  void dump_escaped(const string_t& s, const bool ensure_ascii) const
6485  {
6486  throw_if_invalid_utf8(s);
6487 
6488  const auto space = extra_space(s, ensure_ascii);
6489  if (space == 0)
6490  {
6491  o->write_characters(s.c_str(), s.size());
6492  return;
6493  }
6494 
6495  // create a result string of necessary size
6496  string_t result(s.size() + space, '\\');
6497  std::size_t pos = 0;
6498 
6499  for (std::size_t i = 0; i < s.size(); ++i)
6500  {
6501  switch (s[i])
6502  {
6503  case '"': // quotation mark (0x22)
6504  {
6505  result[pos + 1] = '"';
6506  pos += 2;
6507  break;
6508  }
6509 
6510  case '\\': // reverse solidus (0x5C)
6511  {
6512  // nothing to change
6513  pos += 2;
6514  break;
6515  }
6516 
6517  case '\b': // backspace (0x08)
6518  {
6519  result[pos + 1] = 'b';
6520  pos += 2;
6521  break;
6522  }
6523 
6524  case '\f': // formfeed (0x0C)
6525  {
6526  result[pos + 1] = 'f';
6527  pos += 2;
6528  break;
6529  }
6530 
6531  case '\n': // newline (0x0A)
6532  {
6533  result[pos + 1] = 'n';
6534  pos += 2;
6535  break;
6536  }
6537 
6538  case '\r': // carriage return (0x0D)
6539  {
6540  result[pos + 1] = 'r';
6541  pos += 2;
6542  break;
6543  }
6544 
6545  case '\t': // horizontal tab (0x09)
6546  {
6547  result[pos + 1] = 't';
6548  pos += 2;
6549  break;
6550  }
6551 
6552  default:
6553  {
6554  // escape control characters (0x00..0x1F) or, if
6555  // ensure_ascii parameter is used, non-ASCII characters
6556  if ((0x00 <= s[i] and s[i] <= 0x1F) or
6557  (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F)))
6558  {
6559  const auto bytes = bytes_following(static_cast<uint8_t>(s[i]));
6560  // invalid characters will be detected by throw_if_invalid_utf8
6561  assert (bytes != std::string::npos);
6562 
6563  // check that the additional bytes are present
6564  assert(i + bytes < s.size());
6565 
6566  // to use \uxxxx escaping, we first need to calculate
6567  // the codepoint from the UTF-8 bytes
6568  int codepoint = 0;
6569 
6570  assert(0 <= bytes and bytes <= 3);
6571  switch (bytes)
6572  {
6573  case 0:
6574  {
6575  codepoint = s[i] & 0xFF;
6576  break;
6577  }
6578 
6579  case 1:
6580  {
6581  codepoint = ((s[i] & 0x3F) << 6)
6582  + (s[i + 1] & 0x7F);
6583  break;
6584  }
6585 
6586  case 2:
6587  {
6588  codepoint = ((s[i] & 0x1F) << 12)
6589  + ((s[i + 1] & 0x7F) << 6)
6590  + (s[i + 2] & 0x7F);
6591  break;
6592  }
6593 
6594  case 3:
6595  {
6596  codepoint = ((s[i] & 0xF) << 18)
6597  + ((s[i + 1] & 0x7F) << 12)
6598  + ((s[i + 2] & 0x7F) << 6)
6599  + (s[i + 3] & 0x7F);
6600  break;
6601  }
6602 
6603  default:
6604  break; // LCOV_EXCL_LINE
6605  }
6606 
6607  escape_codepoint(codepoint, result, pos);
6608  i += bytes;
6609  }
6610  else
6611  {
6612  // all other characters are added as-is
6613  result[pos++] = s[i];
6614  }
6615  break;
6616  }
6617  }
6618  }
6619 
6620  assert(pos == result.size());
6621  o->write_characters(result.c_str(), result.size());
6622  }
6623 
6624  /*!
6625  @brief dump an integer
6626 
6627  Dump a given integer to output stream @a o. Works internally with
6628  @a number_buffer.
6629 
6630  @param[in] x integer number (signed or unsigned) to dump
6631  @tparam NumberType either @a number_integer_t or @a number_unsigned_t
6632  */
6633  template<typename NumberType, detail::enable_if_t<
6634  std::is_same<NumberType, number_unsigned_t>::value or
6635  std::is_same<NumberType, number_integer_t>::value,
6636  int> = 0>
6637  void dump_integer(NumberType x)
6638  {
6639  // special case for "0"
6640  if (x == 0)
6641  {
6642  o->write_character('0');
6643  return;
6644  }
6645 
6646  const bool is_negative = (x <= 0) and (x != 0); // see issue #755
6647  std::size_t i = 0;
6648 
6649  while (x != 0)
6650  {
6651  // spare 1 byte for '\0'
6652  assert(i < number_buffer.size() - 1);
6653 
6654  const auto digit = std::labs(static_cast<long>(x % 10));
6655  number_buffer[i++] = static_cast<char>('0' + digit);
6656  x /= 10;
6657  }
6658 
6659  if (is_negative)
6660  {
6661  // make sure there is capacity for the '-'
6662  assert(i < number_buffer.size() - 2);
6663  number_buffer[i++] = '-';
6664  }
6665 
6666  std::reverse(number_buffer.begin(), number_buffer.begin() + i);
6667  o->write_characters(number_buffer.data(), i);
6668  }
6669 
6670  /*!
6671  @brief dump a floating-point number
6672 
6673  Dump a given floating-point number to output stream @a o. Works internally
6674  with @a number_buffer.
6675 
6676  @param[in] x floating-point number to dump
6677  */
6678  void dump_float(number_float_t x)
6679  {
6680  // NaN / inf
6681  if (not std::isfinite(x) or std::isnan(x))
6682  {
6683  o->write_characters("null", 4);
6684  return;
6685  }
6686 
6687  // get number of digits for a text -> float -> text round-trip
6688  static constexpr auto d = std::numeric_limits<number_float_t>::digits10;
6689 
6690  // the actual conversion
6691  std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
6692 
6693  // negative value indicates an error
6694  assert(len > 0);
6695  // check if buffer was large enough
6696  assert(static_cast<std::size_t>(len) < number_buffer.size());
6697 
6698  // erase thousands separator
6699  if (thousands_sep != '\0')
6700  {
6701  const auto end = std::remove(number_buffer.begin(),
6702  number_buffer.begin() + len, thousands_sep);
6703  std::fill(end, number_buffer.end(), '\0');
6704  assert((end - number_buffer.begin()) <= len);
6705  len = (end - number_buffer.begin());
6706  }
6707 
6708  // convert decimal point to '.'
6709  if (decimal_point != '\0' and decimal_point != '.')
6710  {
6711  const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
6712  if (dec_pos != number_buffer.end())
6713  {
6714  *dec_pos = '.';
6715  }
6716  }
6717 
6718  o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
6719 
6720  // determine if need to append ".0"
6721  const bool value_is_int_like =
6722  std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
6723  [](char c)
6724  {
6725  return (c == '.' or c == 'e');
6726  });
6727 
6728  if (value_is_int_like)
6729  {
6730  o->write_characters(".0", 2);
6731  }
6732  }
6733 
6734  /*!
6735  @brief check whether a string is UTF-8 encoded
6736 
6737  The function checks each byte of a string whether it is UTF-8 encoded. The
6738  result of the check is stored in the @a state parameter. The function must
6739  be called initially with state 0 (accept). State 1 means the string must
6740  be rejected, because the current byte is not allowed. If the string is
6741  completely processed, but the state is non-zero, the string ended
6742  prematurely; that is, the last byte indicated more bytes should have
6743  followed.
6744 
6745  @param[in,out] state the state of the decoding
6746  @param[in] byte next byte to decode
6747 
6748  @note The function has been edited: a std::array is used and the code
6749  point is not calculated.
6750 
6751  @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
6752  @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
6753  */
6754  static void decode(uint8_t& state, const uint8_t byte)
6755  {
6756  static const std::array<uint8_t, 400> utf8d =
6757  {
6758  {
6759  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
6760  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
6761  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
6762  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
6763  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
6764  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
6765  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
6766  0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
6767  0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
6768  0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
6769  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
6770  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
6771  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
6772  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
6773  }
6774  };
6775 
6776  const uint8_t type = utf8d[byte];
6777  state = utf8d[256u + state * 16u + type];
6778  }
6779 
6780  /*!
6781  @brief throw an exception if a string is not UTF-8 encoded
6782 
6783  @param[in] str UTF-8 string to check
6784  @throw type_error.316 if passed string is not UTF-8 encoded
6785 
6786  @since version 3.0.0
6787  */
6788  static void throw_if_invalid_utf8(const std::string& str)
6789  {
6790  // start with state 0 (= accept)
6791  uint8_t state = 0;
6792 
6793  for (size_t i = 0; i < str.size(); ++i)
6794  {
6795  const auto byte = static_cast<uint8_t>(str[i]);
6796  decode(state, byte);
6797  if (state == 1)
6798  {
6799  // state 1 means reject
6800  std::stringstream ss;
6801  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(byte);
6802  JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str()));
6803  }
6804  }
6805 
6806  if (state != 0)
6807  {
6808  // we finish reading, but do not accept: string was incomplete
6809  std::stringstream ss;
6810  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(static_cast<uint8_t>(str.back()));
6811  JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str()));
6812  }
6813  }
6814 
6815  private:
6816  /// the output of the serializer
6817  output_adapter_t<char> o = nullptr;
6818 
6819  /// a (hopefully) large enough character buffer
6820  std::array<char, 64> number_buffer{{}};
6821 
6822  /// the locale
6823  const std::lconv* loc = nullptr;
6824  /// the locale's thousand separator character
6825  const char thousands_sep = '\0';
6826  /// the locale's decimal point character
6827  const char decimal_point = '\0';
6828 
6829  /// the indentation character
6830  const char indent_char;
6831 
6832  /// the indentation string
6833  string_t indent_string;
6834 };
6835 
6836 template<typename BasicJsonType>
6837 class json_ref
6838 {
6839  public:
6840  using value_type = BasicJsonType;
6841 
6842  json_ref(value_type&& value)
6843  : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
6844  {}
6845 
6846  json_ref(const value_type& value)
6847  : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
6848  {}
6849 
6850  json_ref(std::initializer_list<json_ref> init)
6851  : owned_value(init), value_ref(&owned_value), is_rvalue(true)
6852  {}
6853 
6854  template<class... Args>
6855  json_ref(Args&& ... args)
6856  : owned_value(std::forward<Args>(args)...), value_ref(&owned_value), is_rvalue(true)
6857  {}
6858 
6859  // class should be movable only
6860  json_ref(json_ref&&) = default;
6861  json_ref(const json_ref&) = delete;
6862  json_ref& operator=(const json_ref&) = delete;
6863 
6864  value_type moved_or_copied() const
6865  {
6866  if (is_rvalue)
6867  {
6868  return std::move(*value_ref);
6869  }
6870  return *value_ref;
6871  }
6872 
6873  value_type const& operator*() const
6874  {
6875  return *static_cast<value_type const*>(value_ref);
6876  }
6877 
6878  value_type const* operator->() const
6879  {
6880  return static_cast<value_type const*>(value_ref);
6881  }
6882 
6883  private:
6884  mutable value_type owned_value = nullptr;
6885  value_type* value_ref = nullptr;
6886  const bool is_rvalue;
6887 };
6888 
6889 } // namespace detail
6890 
6891 /// namespace to hold default `to_json` / `from_json` functions
6892 namespace
6893 {
6894 constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
6895 constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
6896 }
6897 
6898 
6899 /*!
6900 @brief default JSONSerializer template argument
6901 
6902 This serializer ignores the template arguments and uses ADL
6903 ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl))
6904 for serialization.
6905 */
6906 template<typename, typename>
6907 struct adl_serializer
6908 {
6909  /*!
6910  @brief convert a JSON value to any value type
6911 
6912  This function is usually called by the `get()` function of the
6913  @ref basic_json class (either explicit or via conversion operators).
6914 
6915  @param[in] j JSON value to read from
6916  @param[in,out] val value to write to
6917  */
6918  template<typename BasicJsonType, typename ValueType>
6919  static void from_json(BasicJsonType&& j, ValueType& val) noexcept(
6920  noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
6921  {
6922  ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
6923  }
6924 
6925  /*!
6926  @brief convert any value type to a JSON value
6927 
6928  This function is usually called by the constructors of the @ref basic_json
6929  class.
6930 
6931  @param[in,out] j JSON value to write to
6932  @param[in] val value to read from
6933  */
6934  template<typename BasicJsonType, typename ValueType>
6935  static void to_json(BasicJsonType& j, ValueType&& val) noexcept(
6936  noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
6937  {
6938  ::nlohmann::to_json(j, std::forward<ValueType>(val));
6939  }
6940 };
6941 
6942 /*!
6943 @brief JSON Pointer
6944 
6945 A JSON pointer defines a string syntax for identifying a specific value
6946 within a JSON document. It can be used with functions `at` and
6947 `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
6948 
6949 @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
6950 
6951 @since version 2.0.0
6952 */
6954 {
6955  /// allow basic_json to access private members
6957  friend class basic_json;
6958 
6959  public:
6960  /*!
6961  @brief create JSON pointer
6962 
6963  Create a JSON pointer according to the syntax described in
6964  [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
6965 
6966  @param[in] s string representing the JSON pointer; if omitted, the empty
6967  string is assumed which references the whole JSON value
6968 
6969  @throw parse_error.107 if the given JSON pointer @a s is nonempty and
6970  does not begin with a slash (`/`); see example below
6971 
6972  @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s
6973  is not followed by `0` (representing `~`) or `1` (representing `/`);
6974  see example below
6975 
6976  @liveexample{The example shows the construction several valid JSON
6977  pointers as well as the exceptional behavior.,json_pointer}
6978 
6979  @since version 2.0.0
6980  */
6981  explicit json_pointer(const std::string& s = "") : reference_tokens(split(s)) {}
6982 
6983  /*!
6984  @brief return a string representation of the JSON pointer
6985 
6986  @invariant For each JSON pointer `ptr`, it holds:
6987  @code {.cpp}
6988  ptr == json_pointer(ptr.to_string());
6989  @endcode
6990 
6991  @return a string representation of the JSON pointer
6992 
6993  @liveexample{The example shows the result of `to_string`.,
6994  json_pointer__to_string}
6995 
6996  @since version 2.0.0
6997  */
6998  std::string to_string() const noexcept
6999  {
7000  return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
7001  std::string{},
7002  [](const std::string & a, const std::string & b)
7003  {
7004  return a + "/" + escape(b);
7005  });
7006  }
7007 
7008  /// @copydoc to_string()
7009  operator std::string() const
7010  {
7011  return to_string();
7012  }
7013 
7014  private:
7015  /*!
7016  @brief remove and return last reference pointer
7017  @throw out_of_range.405 if JSON pointer has no parent
7018  */
7019  std::string pop_back()
7020  {
7021  if (JSON_UNLIKELY(is_root()))
7022  {
7023  JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
7024  }
7025 
7026  auto last = reference_tokens.back();
7027  reference_tokens.pop_back();
7028  return last;
7029  }
7030 
7031  /// return whether pointer points to the root document
7032  bool is_root() const
7033  {
7034  return reference_tokens.empty();
7035  }
7036 
7037  json_pointer top() const
7038  {
7039  if (JSON_UNLIKELY(is_root()))
7040  {
7041  JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
7042  }
7043 
7044  json_pointer result = *this;
7045  result.reference_tokens = {reference_tokens[0]};
7046  return result;
7047  }
7048 
7049 
7050  /*!
7051  @brief create and return a reference to the pointed to value
7052 
7053  @complexity Linear in the number of reference tokens.
7054 
7055  @throw parse_error.109 if array index is not a number
7056  @throw type_error.313 if value cannot be unflattened
7057  */
7059  NLOHMANN_BASIC_JSON_TPL& get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const;
7060 
7061  /*!
7062  @brief return a reference to the pointed to value
7063 
7064  @note This version does not throw if a value is not present, but tries to
7065  create nested values instead. For instance, calling this function
7066  with pointer `"/this/that"` on a null value is equivalent to calling
7067  `operator[]("this").operator[]("that")` on that value, effectively
7068  changing the null value to an object.
7069 
7070  @param[in] ptr a JSON value
7071 
7072  @return reference to the JSON value pointed to by the JSON pointer
7073 
7074  @complexity Linear in the length of the JSON pointer.
7075 
7076  @throw parse_error.106 if an array index begins with '0'
7077  @throw parse_error.109 if an array index was not a number
7078  @throw out_of_range.404 if the JSON pointer can not be resolved
7079  */
7081  NLOHMANN_BASIC_JSON_TPL& get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const;
7082 
7083  /*!
7084  @throw parse_error.106 if an array index begins with '0'
7085  @throw parse_error.109 if an array index was not a number
7086  @throw out_of_range.402 if the array index '-' is used
7087  @throw out_of_range.404 if the JSON pointer can not be resolved
7088  */
7090  NLOHMANN_BASIC_JSON_TPL& get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const;
7091 
7092  /*!
7093  @brief return a const reference to the pointed to value
7094 
7095  @param[in] ptr a JSON value
7096 
7097  @return const reference to the JSON value pointed to by the JSON
7098  pointer
7099 
7100  @throw parse_error.106 if an array index begins with '0'
7101  @throw parse_error.109 if an array index was not a number
7102  @throw out_of_range.402 if the array index '-' is used
7103  @throw out_of_range.404 if the JSON pointer can not be resolved
7104  */
7106  const NLOHMANN_BASIC_JSON_TPL& get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const;
7107 
7108  /*!
7109  @throw parse_error.106 if an array index begins with '0'
7110  @throw parse_error.109 if an array index was not a number
7111  @throw out_of_range.402 if the array index '-' is used
7112  @throw out_of_range.404 if the JSON pointer can not be resolved
7113  */
7115  const NLOHMANN_BASIC_JSON_TPL& get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const;
7116 
7117  /*!
7118  @brief split the string input to reference tokens
7119 
7120  @note This function is only called by the json_pointer constructor.
7121  All exceptions below are documented there.
7122 
7123  @throw parse_error.107 if the pointer is not empty or begins with '/'
7124  @throw parse_error.108 if character '~' is not followed by '0' or '1'
7125  */
7126  static std::vector<std::string> split(const std::string& reference_string)
7127  {
7128  std::vector<std::string> result;
7129 
7130  // special case: empty reference string -> no reference tokens
7131  if (reference_string.empty())
7132  {
7133  return result;
7134  }
7135 
7136  // check if nonempty reference string begins with slash
7137  if (JSON_UNLIKELY(reference_string[0] != '/'))
7138  {
7139  JSON_THROW(detail::parse_error::create(107, 1,
7140  "JSON pointer must be empty or begin with '/' - was: '" +
7141  reference_string + "'"));
7142  }
7143 
7144  // extract the reference tokens:
7145  // - slash: position of the last read slash (or end of string)
7146  // - start: position after the previous slash
7147  for (
7148  // search for the first slash after the first character
7149  std::size_t slash = reference_string.find_first_of('/', 1),
7150  // set the beginning of the first reference token
7151  start = 1;
7152  // we can stop if start == string::npos+1 = 0
7153  start != 0;
7154  // set the beginning of the next reference token
7155  // (will eventually be 0 if slash == std::string::npos)
7156  start = slash + 1,
7157  // find next slash
7158  slash = reference_string.find_first_of('/', start))
7159  {
7160  // use the text between the beginning of the reference token
7161  // (start) and the last slash (slash).
7162  auto reference_token = reference_string.substr(start, slash - start);
7163 
7164  // check reference tokens are properly escaped
7165  for (std::size_t pos = reference_token.find_first_of('~');
7166  pos != std::string::npos;
7167  pos = reference_token.find_first_of('~', pos + 1))
7168  {
7169  assert(reference_token[pos] == '~');
7170 
7171  // ~ must be followed by 0 or 1
7172  if (JSON_UNLIKELY(pos == reference_token.size() - 1 or
7173  (reference_token[pos + 1] != '0' and
7174  reference_token[pos + 1] != '1')))
7175  {
7176  JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
7177  }
7178  }
7179 
7180  // finally, store the reference token
7181  unescape(reference_token);
7182  result.push_back(reference_token);
7183  }
7184 
7185  return result;
7186  }
7187 
7188  /*!
7189  @brief replace all occurrences of a substring by another string
7190 
7191  @param[in,out] s the string to manipulate; changed so that all
7192  occurrences of @a f are replaced with @a t
7193  @param[in] f the substring to replace with @a t
7194  @param[in] t the string to replace @a f
7195 
7196  @pre The search string @a f must not be empty. **This precondition is
7197  enforced with an assertion.**
7198 
7199  @since version 2.0.0
7200  */
7201  static void replace_substring(std::string& s, const std::string& f,
7202  const std::string& t)
7203  {
7204  assert(not f.empty());
7205  for (auto pos = s.find(f); // find first occurrence of f
7206  pos != std::string::npos; // make sure f was found
7207  s.replace(pos, f.size(), t), // replace with t, and
7208  pos = s.find(f, pos + t.size())) // find next occurrence of f
7209  {}
7210  }
7211 
7212  /// escape "~"" to "~0" and "/" to "~1"
7213  static std::string escape(std::string s)
7214  {
7215  replace_substring(s, "~", "~0");
7216  replace_substring(s, "/", "~1");
7217  return s;
7218  }
7219 
7220  /// unescape "~1" to tilde and "~0" to slash (order is important!)
7221  static void unescape(std::string& s)
7222  {
7223  replace_substring(s, "~1", "/");
7224  replace_substring(s, "~0", "~");
7225  }
7226 
7227  /*!
7228  @param[in] reference_string the reference string to the current value
7229  @param[in] value the value to consider
7230  @param[in,out] result the result object to insert values to
7231 
7232  @note Empty objects or arrays are flattened to `null`.
7233  */
7235  static void flatten(const std::string& reference_string,
7236  const NLOHMANN_BASIC_JSON_TPL& value,
7237  NLOHMANN_BASIC_JSON_TPL& result);
7238 
7239  /*!
7240  @param[in] value flattened JSON
7241 
7242  @return unflattened JSON
7243 
7244  @throw parse_error.109 if array index is not a number
7245  @throw type_error.314 if value is not an object
7246  @throw type_error.315 if object values are not primitive
7247  @throw type_error.313 if value cannot be unflattened
7248  */
7251  unflatten(const NLOHMANN_BASIC_JSON_TPL& value);
7252 
7253  friend bool operator==(json_pointer const& lhs,
7254  json_pointer const& rhs) noexcept;
7255 
7256  friend bool operator!=(json_pointer const& lhs,
7257  json_pointer const& rhs) noexcept;
7258 
7259  /// the reference tokens
7260  std::vector<std::string> reference_tokens;
7261 };
7262 
7263 /*!
7264 @brief a class to store JSON values
7265 
7266 @tparam ObjectType type for JSON objects (`std::map` by default; will be used
7267 in @ref object_t)
7268 @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
7269 in @ref array_t)
7270 @tparam StringType type for JSON strings and object keys (`std::string` by
7271 default; will be used in @ref string_t)
7272 @tparam BooleanType type for JSON booleans (`bool` by default; will be used
7273 in @ref boolean_t)
7274 @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
7275 default; will be used in @ref number_integer_t)
7276 @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
7277 `uint64_t` by default; will be used in @ref number_unsigned_t)
7278 @tparam NumberFloatType type for JSON floating-point numbers (`double` by
7279 default; will be used in @ref number_float_t)
7280 @tparam AllocatorType type of the allocator to use (`std::allocator` by
7281 default)
7282 @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
7283 and `from_json()` (@ref adl_serializer by default)
7284 
7285 @requirement The class satisfies the following concept requirements:
7286 - Basic
7287  - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
7288  JSON values can be default constructed. The result will be a JSON null
7289  value.
7290  - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
7291  A JSON value can be constructed from an rvalue argument.
7292  - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
7293  A JSON value can be copy-constructed from an lvalue expression.
7294  - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
7295  A JSON value van be assigned from an rvalue argument.
7296  - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
7297  A JSON value can be copy-assigned from an lvalue expression.
7298  - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
7299  JSON values can be destructed.
7300 - Layout
7301  - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
7302  JSON values have
7303  [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
7304  All non-static data members are private and standard layout types, the
7305  class has no virtual functions or (virtual) base classes.
7306 - Library-wide
7307  - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
7308  JSON values can be compared with `==`, see @ref
7309  operator==(const_reference,const_reference).
7310  - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
7311  JSON values can be compared with `<`, see @ref
7312  operator<(const_reference,const_reference).
7313  - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
7314  Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
7315  other compatible types, using unqualified function call @ref swap().
7316  - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
7317  JSON values can be compared against `std::nullptr_t` objects which are used
7318  to model the `null` value.
7319 - Container
7320  - [Container](http://en.cppreference.com/w/cpp/concept/Container):
7321  JSON values can be used like STL containers and provide iterator access.
7322  - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
7323  JSON values can be used like STL containers and provide reverse iterator
7324  access.
7325 
7326 @invariant The member variables @a m_value and @a m_type have the following
7327 relationship:
7328 - If `m_type == value_t::object`, then `m_value.object != nullptr`.
7329 - If `m_type == value_t::array`, then `m_value.array != nullptr`.
7330 - If `m_type == value_t::string`, then `m_value.string != nullptr`.
7331 The invariants are checked by member function assert_invariant().
7332 
7333 @internal
7334 @note ObjectType trick from http://stackoverflow.com/a/9860911
7335 @endinternal
7336 
7337 @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
7338 Format](http://rfc7159.net/rfc7159)
7339 
7340 @since version 1.0.0
7341 
7342 @nosubgrouping
7343 */
7345 class basic_json
7346 {
7347  private:
7348  template<detail::value_t> friend struct detail::external_constructor;
7349  friend ::nlohmann::json_pointer;
7350  friend ::nlohmann::detail::parser<basic_json>;
7351  friend ::nlohmann::detail::serializer<basic_json>;
7352  template<typename BasicJsonType>
7353  friend class ::nlohmann::detail::iter_impl;
7354  template<typename BasicJsonType, typename CharType>
7355  friend class ::nlohmann::detail::binary_writer;
7356  template<typename BasicJsonType>
7357  friend class ::nlohmann::detail::binary_reader;
7358 
7359  /// workaround type for MSVC
7360  using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
7361 
7362  // convenience aliases for types residing in namespace detail;
7363  using lexer = ::nlohmann::detail::lexer<basic_json>;
7364  using parser = ::nlohmann::detail::parser<basic_json>;
7365 
7366  using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
7367  template<typename BasicJsonType>
7368  using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
7369  template<typename BasicJsonType>
7370  using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
7371  template<typename Iterator>
7372  using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
7373  template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
7374 
7375  template<typename CharType>
7376  using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
7377 
7378  using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
7379  template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
7380 
7381  using serializer = ::nlohmann::detail::serializer<basic_json>;
7382 
7383  public:
7384  using value_t = detail::value_t;
7385  /// @copydoc nlohmann::json_pointer
7386  using json_pointer = ::nlohmann::json_pointer;
7387  template<typename T, typename SFINAE>
7388  using json_serializer = JSONSerializer<T, SFINAE>;
7389  /// helper type for initializer lists of basic_json values
7390  using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
7392  ////////////////
7393  // exceptions //
7394  ////////////////
7396  /// @name exceptions
7397  /// Classes to implement user-defined exceptions.
7398  /// @{
7399 
7400  /// @copydoc detail::exception
7401  using exception = detail::exception;
7402  /// @copydoc detail::parse_error
7403  using parse_error = detail::parse_error;
7404  /// @copydoc detail::invalid_iterator
7405  using invalid_iterator = detail::invalid_iterator;
7406  /// @copydoc detail::type_error
7407  using type_error = detail::type_error;
7408  /// @copydoc detail::out_of_range
7409  using out_of_range = detail::out_of_range;
7410  /// @copydoc detail::other_error
7411  using other_error = detail::other_error;
7413  /// @}
7415 
7416  /////////////////////
7417  // container types //
7418  /////////////////////
7419 
7420  /// @name container types
7421  /// The canonic container types to use @ref basic_json like any other STL
7422  /// container.
7423  /// @{
7424 
7425  /// the type of elements in a basic_json container
7426  using value_type = basic_json;
7427 
7428  /// the type of an element reference
7429  using reference = value_type&;
7430  /// the type of an element const reference
7431  using const_reference = const value_type&;
7432 
7433  /// a type to represent differences between iterators
7434  using difference_type = std::ptrdiff_t;
7435  /// a type to represent container sizes
7436  using size_type = std::size_t;
7437 
7438  /// the allocator type
7439  using allocator_type = AllocatorType<basic_json>;
7440 
7441  /// the type of an element pointer
7442  using pointer = typename std::allocator_traits<allocator_type>::pointer;
7443  /// the type of an element const pointer
7444  using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
7445 
7446  /// an iterator for a basic_json container
7447  using iterator = iter_impl<basic_json>;
7448  /// a const iterator for a basic_json container
7449  using const_iterator = iter_impl<const basic_json>;
7450  /// a reverse iterator for a basic_json container
7451  using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
7452  /// a const reverse iterator for a basic_json container
7453  using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
7455  /// @}
7457 
7458  /*!
7459  @brief returns the allocator associated with the container
7460  */
7461  static allocator_type get_allocator()
7462  {
7463  return allocator_type();
7464  }
7465 
7466  /*!
7467  @brief returns version information on the library
7468 
7469  This function returns a JSON object with information about the library,
7470  including the version number and information on the platform and compiler.
7471 
7472  @return JSON object holding version information
7473  key | description
7474  ----------- | ---------------
7475  `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).
7476  `copyright` | The copyright line for the library as string.
7477  `name` | The name of the library as string.
7478  `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
7479  `url` | The URL of the project as string.
7480  `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).
7481 
7482  @liveexample{The following code shows an example output of the `meta()`
7483  function.,meta}
7484 
7485  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
7486  changes to any JSON value.
7487 
7488  @complexity Constant.
7489 
7490  @since 2.1.0
7491  */
7492  static basic_json meta()
7493  {
7494  basic_json result;
7495 
7496  result["copyright"] = "(C) 2013-2017 Niels Lohmann";
7497  result["name"] = "JSON for Modern C++";
7498  result["url"] = "https://github.com/nlohmann/json";
7499  result["version"] =
7500  {
7501  {"string", "3.0.0"}, {"major", 3}, {"minor", 0}, {"patch", 0}
7502  };
7503 
7504 #ifdef _WIN32
7505  result["platform"] = "win32";
7506 #elif defined __linux__
7507  result["platform"] = "linux";
7508 #elif defined __APPLE__
7509  result["platform"] = "apple";
7510 #elif defined __unix__
7511  result["platform"] = "unix";
7512 #else
7513  result["platform"] = "unknown";
7514 #endif
7515 
7516 #if defined(__ICC) || defined(__INTEL_COMPILER)
7517  result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
7518 #elif defined(__clang__)
7519  result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
7520 #elif defined(__GNUC__) || defined(__GNUG__)
7521  result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
7522 #elif defined(__HP_cc) || defined(__HP_aCC)
7523  result["compiler"] = "hp"
7524 #elif defined(__IBMCPP__)
7525  result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
7526 #elif defined(_MSC_VER)
7527  result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
7528 #elif defined(__PGI)
7529  result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
7530 #elif defined(__SUNPRO_CC)
7531  result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
7532 #else
7533  result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
7534 #endif
7535 
7536 #ifdef __cplusplus
7537  result["compiler"]["c++"] = std::to_string(__cplusplus);
7538 #else
7539  result["compiler"]["c++"] = "unknown";
7540 #endif
7541  return result;
7542  }
7543 
7544 
7545  ///////////////////////////
7546  // JSON value data types //
7547  ///////////////////////////
7548 
7549  /// @name JSON value data types
7550  /// The data types to store a JSON value. These types are derived from
7551  /// the template arguments passed to class @ref basic_json.
7552  /// @{
7553 
7554 #if defined(JSON_HAS_CPP_14)
7555  // Use transparent comparator if possible, combined with perfect forwarding
7556  // on find() and count() calls prevents unnecessary string construction.
7557  using object_comparator_t = std::less<>;
7558 #else
7559  using object_comparator_t = std::less<StringType>;
7560 #endif
7561 
7562  /*!
7563  @brief a type for an object
7565  [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
7566  > An object is an unordered collection of zero or more name/value pairs,
7567  > where a name is a string and a value is a string, number, boolean, null,
7568  > object, or array.
7569 
7570  To store objects in C++, a type is defined by the template parameters
7571  described below.
7572 
7573  @tparam ObjectType the container to store objects (e.g., `std::map` or
7574  `std::unordered_map`)
7575  @tparam StringType the type of the keys or names (e.g., `std::string`).
7576  The comparison function `std::less<StringType>` is used to order elements
7577  inside the container.
7578  @tparam AllocatorType the allocator to use for objects (e.g.,
7579  `std::allocator`)
7580 
7581  #### Default type
7582 
7583  With the default values for @a ObjectType (`std::map`), @a StringType
7584  (`std::string`), and @a AllocatorType (`std::allocator`), the default
7585  value for @a object_t is:
7586 
7587  @code {.cpp}
7588  std::map<
7589  std::string, // key_type
7590  basic_json, // value_type
7591  std::less<std::string>, // key_compare
7592  std::allocator<std::pair<const std::string, basic_json>> // allocator_type
7593  >
7594  @endcode
7595 
7596  #### Behavior
7597 
7598  The choice of @a object_t influences the behavior of the JSON class. With
7599  the default type, objects have the following behavior:
7600 
7601  - When all names are unique, objects will be interoperable in the sense
7602  that all software implementations receiving that object will agree on
7603  the name-value mappings.
7604  - When the names within an object are not unique, later stored name/value
7605  pairs overwrite previously stored name/value pairs, leaving the used
7606  names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will
7607  be treated as equal and both stored as `{"key": 1}`.
7608  - Internally, name/value pairs are stored in lexicographical order of the
7609  names. Objects will also be serialized (see @ref dump) in this order.
7610  For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
7611  and serialized as `{"a": 2, "b": 1}`.
7612  - When comparing objects, the order of the name/value pairs is irrelevant.
7613  This makes objects interoperable in the sense that they will not be
7614  affected by these differences. For instance, `{"b": 1, "a": 2}` and
7615  `{"a": 2, "b": 1}` will be treated as equal.
7616 
7617  #### Limits
7618 
7619  [RFC 7159](http://rfc7159.net/rfc7159) specifies:
7620  > An implementation may set limits on the maximum depth of nesting.
7621 
7622  In this class, the object's limit of nesting is not explicitly constrained.
7623  However, a maximum depth of nesting may be introduced by the compiler or
7624  runtime environment. A theoretical limit can be queried by calling the
7625  @ref max_size function of a JSON object.
7626 
7627  #### Storage
7628 
7629  Objects are stored as pointers in a @ref basic_json type. That is, for any
7630  access to object values, a pointer of type `object_t*` must be
7631  dereferenced.
7632 
7633  @sa @ref array_t -- type for an array value
7634 
7635  @since version 1.0.0
7636 
7637  @note The order name/value pairs are added to the object is *not*
7638  preserved by the library. Therefore, iterating an object may return
7639  name/value pairs in a different order than they were originally stored. In
7640  fact, keys will be traversed in alphabetical order as `std::map` with
7641  `std::less` is used by default. Please note this behavior conforms to [RFC
7642  7159](http://rfc7159.net/rfc7159), because any order implements the
7643  specified "unordered" nature of JSON objects.
7644  */
7645  using object_t = ObjectType<StringType,
7646  basic_json,
7647  object_comparator_t,
7648  AllocatorType<std::pair<const StringType,
7649  basic_json>>>;
7650 
7651  /*!
7652  @brief a type for an array
7653 
7654  [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
7655  > An array is an ordered sequence of zero or more values.
7656 
7657  To store objects in C++, a type is defined by the template parameters
7658  explained below.
7659 
7660  @tparam ArrayType container type to store arrays (e.g., `std::vector` or
7661  `std::list`)
7662  @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
7663 
7664  #### Default type
7665 
7666  With the default values for @a ArrayType (`std::vector`) and @a
7667  AllocatorType (`std::allocator`), the default value for @a array_t is:
7668 
7669  @code {.cpp}
7670  std::vector<
7671  basic_json, // value_type
7672  std::allocator<basic_json> // allocator_type
7673  >
7674  @endcode
7675 
7676  #### Limits
7677 
7678  [RFC 7159](http://rfc7159.net/rfc7159) specifies:
7679  > An implementation may set limits on the maximum depth of nesting.
7680 
7681  In this class, the array's limit of nesting is not explicitly constrained.
7682  However, a maximum depth of nesting may be introduced by the compiler or
7683  runtime environment. A theoretical limit can be queried by calling the
7684  @ref max_size function of a JSON array.
7685 
7686  #### Storage
7687 
7688  Arrays are stored as pointers in a @ref basic_json type. That is, for any
7689  access to array values, a pointer of type `array_t*` must be dereferenced.
7690 
7691  @sa @ref object_t -- type for an object value
7692 
7693  @since version 1.0.0
7694  */
7695  using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
7696 
7697  /*!
7698  @brief a type for a string
7699 
7700  [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
7701  > A string is a sequence of zero or more Unicode characters.
7702 
7703  To store objects in C++, a type is defined by the template parameter
7704  described below. Unicode values are split by the JSON class into
7705  byte-sized characters during deserialization.
7706 
7707  @tparam StringType the container to store strings (e.g., `std::string`).
7708  Note this container is used for keys/names in objects, see @ref object_t.
7709 
7710  #### Default type
7711 
7712  With the default values for @a StringType (`std::string`), the default
7713  value for @a string_t is:
7714 
7715  @code {.cpp}
7716  std::string
7717  @endcode
7718 
7719  #### Encoding
7720 
7721  Strings are stored in UTF-8 encoding. Therefore, functions like
7722  `std::string::size()` or `std::string::length()` return the number of
7723  bytes in the string rather than the number of characters or glyphs.
7724 
7725  #### String comparison
7726 
7727  [RFC 7159](http://rfc7159.net/rfc7159) states:
7728  > Software implementations are typically required to test names of object
7729  > members for equality. Implementations that transform the textual
7730  > representation into sequences of Unicode code units and then perform the
7731  > comparison numerically, code unit by code unit, are interoperable in the
7732  > sense that implementations will agree in all cases on equality or
7733  > inequality of two strings. For example, implementations that compare
7734  > strings with escaped characters unconverted may incorrectly find that
7735  > `"a\\b"` and `"a\u005Cb"` are not equal.
7736 
7737  This implementation is interoperable as it does compare strings code unit
7738  by code unit.
7739 
7740  #### Storage
7741 
7742  String values are stored as pointers in a @ref basic_json type. That is,
7743  for any access to string values, a pointer of type `string_t*` must be
7744  dereferenced.
7745 
7746  @since version 1.0.0
7747  */
7748  using string_t = StringType;
7749 
7750  /*!
7751  @brief a type for a boolean
7752 
7753  [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
7754  type which differentiates the two literals `true` and `false`.
7755 
7756  To store objects in C++, a type is defined by the template parameter @a
7757  BooleanType which chooses the type to use.
7758 
7759  #### Default type
7760 
7761  With the default values for @a BooleanType (`bool`), the default value for
7762  @a boolean_t is:
7763 
7764  @code {.cpp}
7765  bool
7766  @endcode
7767 
7768  #### Storage
7769 
7770  Boolean values are stored directly inside a @ref basic_json type.
7771 
7772  @since version 1.0.0
7773  */
7774  using boolean_t = BooleanType;
7775 
7776  /*!
7777  @brief a type for a number (integer)
7778 
7779  [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
7780  > The representation of numbers is similar to that used in most
7781  > programming languages. A number is represented in base 10 using decimal
7782  > digits. It contains an integer component that may be prefixed with an
7783  > optional minus sign, which may be followed by a fraction part and/or an
7784  > exponent part. Leading zeros are not allowed. (...) Numeric values that
7785  > cannot be represented in the grammar below (such as Infinity and NaN)
7786  > are not permitted.
7787 
7788  This description includes both integer and floating-point numbers.
7789  However, C++ allows more precise storage if it is known whether the number
7790  is a signed integer, an unsigned integer or a floating-point number.
7791  Therefore, three different types, @ref number_integer_t, @ref
7792  number_unsigned_t and @ref number_float_t are used.
7793 
7794  To store integer numbers in C++, a type is defined by the template
7795  parameter @a NumberIntegerType which chooses the type to use.
7796 
7797  #### Default type
7798 
7799  With the default values for @a NumberIntegerType (`int64_t`), the default
7800  value for @a number_integer_t is:
7801 
7802  @code {.cpp}
7803  int64_t
7804  @endcode
7805 
7806  #### Default behavior
7807 
7808  - The restrictions about leading zeros is not enforced in C++. Instead,
7809  leading zeros in integer literals lead to an interpretation as octal
7810  number. Internally, the value will be stored as decimal number. For
7811  instance, the C++ integer literal `010` will be serialized to `8`.
7812  During deserialization, leading zeros yield an error.
7813  - Not-a-number (NaN) values will be serialized to `null`.
7814 
7815  #### Limits
7816 
7817  [RFC 7159](http://rfc7159.net/rfc7159) specifies:
7818  > An implementation may set limits on the range and precision of numbers.
7819 
7820  When the default type is used, the maximal integer number that can be
7821  stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
7822  that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
7823  that are out of range will yield over/underflow when used in a
7824  constructor. During deserialization, too large or small integer numbers
7825  will be automatically be stored as @ref number_unsigned_t or @ref
7826  number_float_t.
7827 
7828  [RFC 7159](http://rfc7159.net/rfc7159) further states:
7829  > Note that when such software is used, numbers that are integers and are
7830  > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
7831  > that implementations will agree exactly on their numeric values.
7832 
7833  As this range is a subrange of the exactly supported range [INT64_MIN,
7834  INT64_MAX], this class's integer type is interoperable.
7835 
7836  #### Storage
7837 
7838  Integer number values are stored directly inside a @ref basic_json type.
7839 
7840  @sa @ref number_float_t -- type for number values (floating-point)
7841 
7842  @sa @ref number_unsigned_t -- type for number values (unsigned integer)
7843 
7844  @since version 1.0.0
7845  */
7846  using number_integer_t = NumberIntegerType;
7847 
7848  /*!
7849  @brief a type for a number (unsigned)
7850 
7851  [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
7852  > The representation of numbers is similar to that used in most
7853  > programming languages. A number is represented in base 10 using decimal
7854  > digits. It contains an integer component that may be prefixed with an
7855  > optional minus sign, which may be followed by a fraction part and/or an
7856  > exponent part. Leading zeros are not allowed. (...) Numeric values that
7857  > cannot be represented in the grammar below (such as Infinity and NaN)
7858  > are not permitted.
7859 
7860  This description includes both integer and floating-point numbers.
7861  However, C++ allows more precise storage if it is known whether the number
7862  is a signed integer, an unsigned integer or a floating-point number.
7863  Therefore, three different types, @ref number_integer_t, @ref
7864  number_unsigned_t and @ref number_float_t are used.
7865 
7866  To store unsigned integer numbers in C++, a type is defined by the
7867  template parameter @a NumberUnsignedType which chooses the type to use.
7868 
7869  #### Default type
7870 
7871  With the default values for @a NumberUnsignedType (`uint64_t`), the
7872  default value for @a number_unsigned_t is:
7873 
7874  @code {.cpp}
7875  uint64_t
7876  @endcode
7877 
7878  #### Default behavior
7879 
7880  - The restrictions about leading zeros is not enforced in C++. Instead,
7881  leading zeros in integer literals lead to an interpretation as octal
7882  number. Internally, the value will be stored as decimal number. For
7883  instance, the C++ integer literal `010` will be serialized to `8`.
7884  During deserialization, leading zeros yield an error.
7885  - Not-a-number (NaN) values will be serialized to `null`.
7886 
7887  #### Limits
7888 
7889  [RFC 7159](http://rfc7159.net/rfc7159) specifies:
7890  > An implementation may set limits on the range and precision of numbers.
7891 
7892  When the default type is used, the maximal integer number that can be
7893  stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
7894  number that can be stored is `0`. Integer numbers that are out of range
7895  will yield over/underflow when used in a constructor. During
7896  deserialization, too large or small integer numbers will be automatically
7897  be stored as @ref number_integer_t or @ref number_float_t.
7898 
7899  [RFC 7159](http://rfc7159.net/rfc7159) further states:
7900  > Note that when such software is used, numbers that are integers and are
7901  > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
7902  > that implementations will agree exactly on their numeric values.
7903 
7904  As this range is a subrange (when considered in conjunction with the
7905  number_integer_t type) of the exactly supported range [0, UINT64_MAX],
7906  this class's integer type is interoperable.
7907 
7908  #### Storage
7909 
7910  Integer number values are stored directly inside a @ref basic_json type.
7911 
7912  @sa @ref number_float_t -- type for number values (floating-point)
7913  @sa @ref number_integer_t -- type for number values (integer)
7914 
7915  @since version 2.0.0
7916  */
7917  using number_unsigned_t = NumberUnsignedType;
7918 
7919  /*!
7920  @brief a type for a number (floating-point)
7921 
7922  [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
7923  > The representation of numbers is similar to that used in most
7924  > programming languages. A number is represented in base 10 using decimal
7925  > digits. It contains an integer component that may be prefixed with an
7926  > optional minus sign, which may be followed by a fraction part and/or an
7927  > exponent part. Leading zeros are not allowed. (...) Numeric values that
7928  > cannot be represented in the grammar below (such as Infinity and NaN)
7929  > are not permitted.
7930 
7931  This description includes both integer and floating-point numbers.
7932  However, C++ allows more precise storage if it is known whether the number
7933  is a signed integer, an unsigned integer or a floating-point number.
7934  Therefore, three different types, @ref number_integer_t, @ref
7935  number_unsigned_t and @ref number_float_t are used.
7936 
7937  To store floating-point numbers in C++, a type is defined by the template
7938  parameter @a NumberFloatType which chooses the type to use.
7939 
7940  #### Default type
7941 
7942  With the default values for @a NumberFloatType (`double`), the default
7943  value for @a number_float_t is:
7944 
7945  @code {.cpp}
7946  double
7947  @endcode
7948 
7949  #### Default behavior
7950 
7951  - The restrictions about leading zeros is not enforced in C++. Instead,
7952  leading zeros in floating-point literals will be ignored. Internally,
7953  the value will be stored as decimal number. For instance, the C++
7954  floating-point literal `01.2` will be serialized to `1.2`. During
7955  deserialization, leading zeros yield an error.
7956  - Not-a-number (NaN) values will be serialized to `null`.
7957 
7958  #### Limits
7959 
7960  [RFC 7159](http://rfc7159.net/rfc7159) states:
7961  > This specification allows implementations to set limits on the range and
7962  > precision of numbers accepted. Since software that implements IEEE
7963  > 754-2008 binary64 (double precision) numbers is generally available and
7964  > widely used, good interoperability can be achieved by implementations
7965  > that expect no more precision or range than these provide, in the sense
7966  > that implementations will approximate JSON numbers within the expected
7967  > precision.
7968 
7969  This implementation does exactly follow this approach, as it uses double
7970  precision floating-point numbers. Note values smaller than
7971  `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
7972  will be stored as NaN internally and be serialized to `null`.
7973 
7974  #### Storage
7975 
7976  Floating-point number values are stored directly inside a @ref basic_json
7977  type.
7978 
7979  @sa @ref number_integer_t -- type for number values (integer)
7980 
7981  @sa @ref number_unsigned_t -- type for number values (unsigned integer)
7982 
7983  @since version 1.0.0
7984  */
7985  using number_float_t = NumberFloatType;
7986 
7987  /// @}
7988 
7989  private:
7991  /// helper for exception-safe object creation
7992  template<typename T, typename... Args>
7993  static T* create(Args&& ... args)
7994  {
7995  AllocatorType<T> alloc;
7996  using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
7997 
7998  auto deleter = [&](T * object)
7999  {
8000  AllocatorTraits::deallocate(alloc, object, 1);
8001  };
8002  std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
8003  AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
8004  assert(object != nullptr);
8005  return object.release();
8006  }
8007 
8008  ////////////////////////
8009  // JSON value storage //
8010  ////////////////////////
8011 
8012  /*!
8013  @brief a JSON value
8014 
8015  The actual storage for a JSON value of the @ref basic_json class. This
8016  union combines the different storage types for the JSON value types
8017  defined in @ref value_t.
8018 
8019  JSON type | value_t type | used type
8020  --------- | --------------- | ------------------------
8021  object | object | pointer to @ref object_t
8022  array | array | pointer to @ref array_t
8023  string | string | pointer to @ref string_t
8024  boolean | boolean | @ref boolean_t
8025  number | number_integer | @ref number_integer_t
8026  number | number_unsigned | @ref number_unsigned_t
8027  number | number_float | @ref number_float_t
8028  null | null | *no value is stored*
8029 
8030  @note Variable-length types (objects, arrays, and strings) are stored as
8031  pointers. The size of the union should not exceed 64 bits if the default
8032  value types are used.
8033 
8034  @since version 1.0.0
8035  */
8036  union json_value
8037  {
8038  /// object (stored with pointer to save storage)
8039  object_t* object;
8040  /// array (stored with pointer to save storage)
8041  array_t* array;
8042  /// string (stored with pointer to save storage)
8043  string_t* string;
8044  /// boolean
8045  boolean_t boolean;
8046  /// number (integer)
8047  number_integer_t number_integer;
8048  /// number (unsigned integer)
8049  number_unsigned_t number_unsigned;
8050  /// number (floating-point)
8051  number_float_t number_float;
8052 
8053  /// default constructor (for null values)
8054  json_value() = default;
8055  /// constructor for booleans
8056  json_value(boolean_t v) noexcept : boolean(v) {}
8057  /// constructor for numbers (integer)
8058  json_value(number_integer_t v) noexcept : number_integer(v) {}
8059  /// constructor for numbers (unsigned)
8060  json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
8061  /// constructor for numbers (floating-point)
8062  json_value(number_float_t v) noexcept : number_float(v) {}
8063  /// constructor for empty values of a given type
8064  json_value(value_t t)
8065  {
8066  switch (t)
8067  {
8068  case value_t::object:
8069  {
8070  object = create<object_t>();
8071  break;
8072  }
8073 
8074  case value_t::array:
8075  {
8076  array = create<array_t>();
8077  break;
8078  }
8079 
8080  case value_t::string:
8081  {
8082  string = create<string_t>("");
8083  break;
8084  }
8085 
8086  case value_t::boolean:
8087  {
8088  boolean = boolean_t(false);
8089  break;
8090  }
8091 
8092  case value_t::number_integer:
8093  {
8094  number_integer = number_integer_t(0);
8095  break;
8096  }
8097 
8098  case value_t::number_unsigned:
8099  {
8100  number_unsigned = number_unsigned_t(0);
8101  break;
8102  }
8103 
8104  case value_t::number_float:
8105  {
8106  number_float = number_float_t(0.0);
8107  break;
8108  }
8109 
8110  case value_t::null:
8111  {
8112  object = nullptr; // silence warning, see #821
8113  break;
8114  }
8115 
8116  default:
8117  {
8118  object = nullptr; // silence warning, see #821
8119  if (JSON_UNLIKELY(t == value_t::null))
8120  {
8121  JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.0.0")); // LCOV_EXCL_LINE
8122  }
8123  break;
8124  }
8125  }
8126  }
8127 
8128  /// constructor for strings
8129  json_value(const string_t& value)
8130  {
8131  string = create<string_t>(value);
8132  }
8133 
8134  /// constructor for rvalue strings
8135  json_value(string_t&& value)
8136  {
8137  string = create<string_t>(std::move(value));
8138  }
8139 
8140  /// constructor for objects
8141  json_value(const object_t& value)
8142  {
8143  object = create<object_t>(value);
8144  }
8145 
8146  /// constructor for rvalue objects
8147  json_value(object_t&& value)
8148  {
8149  object = create<object_t>(std::move(value));
8150  }
8151 
8152  /// constructor for arrays
8153  json_value(const array_t& value)
8154  {
8155  array = create<array_t>(value);
8156  }
8157 
8158  /// constructor for rvalue arrays
8159  json_value(array_t&& value)
8160  {
8161  array = create<array_t>(std::move(value));
8162  }
8163 
8164  void destroy(value_t t)
8165  {
8166  switch (t)
8167  {
8168  case value_t::object:
8169  {
8170  AllocatorType<object_t> alloc;
8171  std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
8172  std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
8173  break;
8174  }
8175 
8176  case value_t::array:
8177  {
8178  AllocatorType<array_t> alloc;
8179  std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
8180  std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
8181  break;
8182  }
8183 
8184  case value_t::string:
8185  {
8186  AllocatorType<string_t> alloc;
8187  std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
8188  std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
8189  break;
8190  }
8191 
8192  default:
8193  {
8194  break;
8195  }
8196  }
8197  }
8198  };
8199 
8200  /*!
8201  @brief checks the class invariants
8202 
8203  This function asserts the class invariants. It needs to be called at the
8204  end of every constructor to make sure that created objects respect the
8205  invariant. Furthermore, it has to be called each time the type of a JSON
8206  value is changed, because the invariant expresses a relationship between
8207  @a m_type and @a m_value.
8208  */
8209  void assert_invariant() const
8210  {
8211  assert(m_type != value_t::object or m_value.object != nullptr);
8212  assert(m_type != value_t::array or m_value.array != nullptr);
8213  assert(m_type != value_t::string or m_value.string != nullptr);
8214  }
8215 
8216  public:
8217  //////////////////////////
8218  // JSON parser callback //
8219  //////////////////////////
8220 
8221  /*!
8222  @brief parser event types
8223 
8224  The parser callback distinguishes the following events:
8225  - `object_start`: the parser read `{` and started to process a JSON object
8226  - `key`: the parser read a key of a value in an object
8227  - `object_end`: the parser read `}` and finished processing a JSON object
8228  - `array_start`: the parser read `[` and started to process a JSON array
8229  - `array_end`: the parser read `]` and finished processing a JSON array
8230  - `value`: the parser finished reading a JSON value
8231 
8232  @image html callback_events.png "Example when certain parse events are triggered"
8233 
8234  @sa @ref parser_callback_t for more information and examples
8235  */
8236  using parse_event_t = typename parser::parse_event_t;
8237 
8238  /*!
8239  @brief per-element parser callback type
8240 
8241  With a parser callback function, the result of parsing a JSON text can be
8242  influenced. When passed to @ref parse, it is called on certain events
8243  (passed as @ref parse_event_t via parameter @a event) with a set recursion
8244  depth @a depth and context JSON value @a parsed. The return value of the
8245  callback function is a boolean indicating whether the element that emitted
8246  the callback shall be kept or not.
8247 
8248  We distinguish six scenarios (determined by the event type) in which the
8249  callback function can be called. The following table describes the values
8250  of the parameters @a depth, @a event, and @a parsed.
8251 
8252  parameter @a event | description | parameter @a depth | parameter @a parsed
8253  ------------------ | ----------- | ------------------ | -------------------
8254  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
8255  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
8256  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
8257  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
8258  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
8259  parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
8260 
8261  @image html callback_events.png "Example when certain parse events are triggered"
8262 
8263  Discarding a value (i.e., returning `false`) has different effects
8264  depending on the context in which function was called:
8265 
8266  - Discarded values in structured types are skipped. That is, the parser
8267  will behave as if the discarded value was never read.
8268  - In case a value outside a structured type is skipped, it is replaced
8269  with `null`. This case happens if the top-level element is skipped.
8270 
8271  @param[in] depth the depth of the recursion during parsing
8272 
8273  @param[in] event an event of type parse_event_t indicating the context in
8274  the callback function has been called
8275 
8276  @param[in,out] parsed the current intermediate parse result; note that
8277  writing to this value has no effect for parse_event_t::key events
8278 
8279  @return Whether the JSON value which called the function during parsing
8280  should be kept (`true`) or not (`false`). In the latter case, it is either
8281  skipped completely or replaced by an empty discarded object.
8282 
8283  @sa @ref parse for examples
8284 
8285  @since version 1.0.0
8286  */
8287  using parser_callback_t = typename parser::parser_callback_t;
8288 
8289 
8290  //////////////////
8291  // constructors //
8292  //////////////////
8293 
8294  /// @name constructors and destructors
8295  /// Constructors of class @ref basic_json, copy/move constructor, copy
8296  /// assignment, static functions creating objects, and the destructor.
8297  /// @{
8298 
8299  /*!
8300  @brief create an empty value with a given type
8301 
8302  Create an empty JSON value with a given type. The value will be default
8303  initialized with an empty value which depends on the type:
8304 
8305  Value type | initial value
8306  ----------- | -------------
8307  null | `null`
8308  boolean | `false`
8309  string | `""`
8310  number | `0`
8311  object | `{}`
8312  array | `[]`
8313 
8314  @param[in] v the type of the value to create
8315 
8316  @complexity Constant.
8317 
8318  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8319  changes to any JSON value.
8320 
8321  @liveexample{The following code shows the constructor for different @ref
8322  value_t values,basic_json__value_t}
8323 
8324  @sa @ref clear() -- restores the postcondition of this constructor
8325 
8326  @since version 1.0.0
8327  */
8328  basic_json(const value_t v)
8329  : m_type(v), m_value(v)
8330  {
8331  assert_invariant();
8332  }
8334  /*!
8335  @brief create a null object
8336 
8337  Create a `null` JSON value. It either takes a null pointer as parameter
8338  (explicitly creating `null`) or no parameter (implicitly creating `null`).
8339  The passed null pointer itself is not read -- it is only used to choose
8340  the right constructor.
8341 
8342  @complexity Constant.
8343 
8344  @exceptionsafety No-throw guarantee: this constructor never throws
8345  exceptions.
8346 
8347  @liveexample{The following code shows the constructor with and without a
8348  null pointer parameter.,basic_json__nullptr_t}
8349 
8350  @since version 1.0.0
8351  */
8352  basic_json(std::nullptr_t = nullptr) noexcept
8353  : basic_json(value_t::null)
8354  {
8355  assert_invariant();
8356  }
8358  /*!
8359  @brief create a JSON value
8360 
8361  This is a "catch all" constructor for all compatible JSON types; that is,
8362  types for which a `to_json()` method exists. The constructor forwards the
8363  parameter @a val to that method (to `json_serializer<U>::to_json` method
8364  with `U = uncvref_t<CompatibleType>`, to be exact).
8365 
8366  Template type @a CompatibleType includes, but is not limited to, the
8367  following types:
8368  - **arrays**: @ref array_t and all kinds of compatible containers such as
8369  `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
8370  `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
8371  `std::multiset`, and `std::unordered_multiset` with a `value_type` from
8372  which a @ref basic_json value can be constructed.
8373  - **objects**: @ref object_t and all kinds of compatible associative
8374  containers such as `std::map`, `std::unordered_map`, `std::multimap`,
8375  and `std::unordered_multimap` with a `key_type` compatible to
8376  @ref string_t and a `value_type` from which a @ref basic_json value can
8377  be constructed.
8378  - **strings**: @ref string_t, string literals, and all compatible string
8379  containers can be used.
8380  - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
8381  @ref number_float_t, and all convertible number types such as `int`,
8382  `size_t`, `int64_t`, `float` or `double` can be used.
8383  - **boolean**: @ref boolean_t / `bool` can be used.
8384 
8385  See the examples below.
8386 
8387  @tparam CompatibleType a type such that:
8388  - @a CompatibleType is not derived from `std::istream`,
8389  - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
8390  constructors),
8391  - @a CompatibleType is not a @ref basic_json nested type (e.g.,
8392  @ref json_pointer, @ref iterator, etc ...)
8393  - @ref @ref json_serializer<U> has a
8394  `to_json(basic_json_t&, CompatibleType&&)` method
8395 
8396  @tparam U = `uncvref_t<CompatibleType>`
8397 
8398  @param[in] val the value to be forwarded to the respective constructor
8399 
8400  @complexity Usually linear in the size of the passed @a val, also
8401  depending on the implementation of the called `to_json()`
8402  method.
8403 
8404  @exceptionsafety Depends on the called constructor. For types directly
8405  supported by the library (i.e., all types for which no `to_json()` function
8406  was provided), strong guarantee holds: if an exception is thrown, there are
8407  no changes to any JSON value.
8408 
8409  @liveexample{The following code shows the constructor with several
8410  compatible types.,basic_json__CompatibleType}
8411 
8412  @since version 2.1.0
8413  */
8414  template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>,
8415  detail::enable_if_t<not std::is_base_of<std::istream, U>::value and
8416  not std::is_same<U, basic_json_t>::value and
8417  not detail::is_basic_json_nested_type<
8418  basic_json_t, U>::value and
8419  detail::has_to_json<basic_json, U>::value,
8420  int> = 0>
8421  basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json(
8422  std::declval<basic_json_t&>(), std::forward<CompatibleType>(val))))
8423  {
8424  JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
8425  assert_invariant();
8426  }
8427 
8428  /*!
8429  @brief create a container (array or object) from an initializer list
8430 
8431  Creates a JSON value of type array or object from the passed initializer
8432  list @a init. In case @a type_deduction is `true` (default), the type of
8433  the JSON value to be created is deducted from the initializer list @a init
8434  according to the following rules:
8435 
8436  1. If the list is empty, an empty JSON object value `{}` is created.
8437  2. If the list consists of pairs whose first element is a string, a JSON
8438  object value is created where the first elements of the pairs are
8439  treated as keys and the second elements are as values.
8440  3. In all other cases, an array is created.
8441 
8442  The rules aim to create the best fit between a C++ initializer list and
8443  JSON values. The rationale is as follows:
8444 
8445  1. The empty initializer list is written as `{}` which is exactly an empty
8446  JSON object.
8447  2. C++ has no way of describing mapped types other than to list a list of
8448  pairs. As JSON requires that keys must be of type string, rule 2 is the
8449  weakest constraint one can pose on initializer lists to interpret them
8450  as an object.
8451  3. In all other cases, the initializer list could not be interpreted as
8452  JSON object type, so interpreting it as JSON array type is safe.
8453 
8454  With the rules described above, the following JSON values cannot be
8455  expressed by an initializer list:
8456 
8457  - the empty array (`[]`): use @ref array(initializer_list_t)
8458  with an empty initializer list in this case
8459  - arrays whose elements satisfy rule 2: use @ref
8460  array(initializer_list_t) with the same initializer list
8461  in this case
8462 
8463  @note When used without parentheses around an empty initializer list, @ref
8464  basic_json() is called instead of this function, yielding the JSON null
8465  value.
8466 
8467  @param[in] init initializer list with JSON values
8468 
8469  @param[in] type_deduction internal parameter; when set to `true`, the type
8470  of the JSON value is deducted from the initializer list @a init; when set
8471  to `false`, the type provided via @a manual_type is forced. This mode is
8472  used by the functions @ref array(initializer_list_t) and
8473  @ref object(initializer_list_t).
8474 
8475  @param[in] manual_type internal parameter; when @a type_deduction is set
8476  to `false`, the created JSON value will use the provided type (only @ref
8477  value_t::array and @ref value_t::object are valid); when @a type_deduction
8478  is set to `true`, this parameter has no effect
8479 
8480  @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
8481  `value_t::object`, but @a init contains an element which is not a pair
8482  whose first element is a string. In this case, the constructor could not
8483  create an object. If @a type_deduction would have be `true`, an array
8484  would have been created. See @ref object(initializer_list_t)
8485  for an example.
8486 
8487  @complexity Linear in the size of the initializer list @a init.
8488 
8489  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8490  changes to any JSON value.
8491 
8492  @liveexample{The example below shows how JSON values are created from
8493  initializer lists.,basic_json__list_init_t}
8494 
8495  @sa @ref array(initializer_list_t) -- create a JSON array
8496  value from an initializer list
8497  @sa @ref object(initializer_list_t) -- create a JSON object
8498  value from an initializer list
8499 
8500  @since version 1.0.0
8501  */
8502  basic_json(initializer_list_t init,
8503  bool type_deduction = true,
8504  value_t manual_type = value_t::array)
8505  {
8506  // check if each element is an array with two elements whose first
8507  // element is a string
8508  bool is_an_object = std::all_of(init.begin(), init.end(),
8509  [](const detail::json_ref<basic_json>& element_ref)
8510  {
8511  return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string());
8512  });
8513 
8514  // adjust type if type deduction is not wanted
8515  if (not type_deduction)
8516  {
8517  // if array is wanted, do not create an object though possible
8518  if (manual_type == value_t::array)
8519  {
8520  is_an_object = false;
8521  }
8522 
8523  // if object is wanted but impossible, throw an exception
8524  if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object))
8525  {
8526  JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
8527  }
8528  }
8529 
8530  if (is_an_object)
8531  {
8532  // the initializer list is a list of pairs -> create object
8533  m_type = value_t::object;
8534  m_value = value_t::object;
8535 
8536  std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
8537  {
8538  auto element = element_ref.moved_or_copied();
8539  m_value.object->emplace(
8540  std::move(*((*element.m_value.array)[0].m_value.string)),
8541  std::move((*element.m_value.array)[1]));
8542  });
8543  }
8544  else
8545  {
8546  // the initializer list describes an array -> create array
8547  m_type = value_t::array;
8548  m_value.array = create<array_t>(init.begin(), init.end());
8549  }
8550 
8551  assert_invariant();
8552  }
8553 
8554  /*!
8555  @brief explicitly create an array from an initializer list
8556 
8557  Creates a JSON array value from a given initializer list. That is, given a
8558  list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
8559  initializer list is empty, the empty array `[]` is created.
8560 
8561  @note This function is only needed to express two edge cases that cannot
8562  be realized with the initializer list constructor (@ref
8563  basic_json(initializer_list_t, bool, value_t)). These cases
8564  are:
8565  1. creating an array whose elements are all pairs whose first element is a
8566  string -- in this case, the initializer list constructor would create an
8567  object, taking the first elements as keys
8568  2. creating an empty array -- passing the empty initializer list to the
8569  initializer list constructor yields an empty object
8570 
8571  @param[in] init initializer list with JSON values to create an array from
8572  (optional)
8573 
8574  @return JSON array value
8575 
8576  @complexity Linear in the size of @a init.
8577 
8578  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8579  changes to any JSON value.
8580 
8581  @liveexample{The following code shows an example for the `array`
8582  function.,array}
8583 
8584  @sa @ref basic_json(initializer_list_t, bool, value_t) --
8585  create a JSON value from an initializer list
8586  @sa @ref object(initializer_list_t) -- create a JSON object
8587  value from an initializer list
8588 
8589  @since version 1.0.0
8590  */
8591  static basic_json array(initializer_list_t init = {})
8592  {
8593  return basic_json(init, false, value_t::array);
8594  }
8595 
8596  /*!
8597  @brief explicitly create an object from an initializer list
8598 
8599  Creates a JSON object value from a given initializer list. The initializer
8600  lists elements must be pairs, and their first elements must be strings. If
8601  the initializer list is empty, the empty object `{}` is created.
8602 
8603  @note This function is only added for symmetry reasons. In contrast to the
8604  related function @ref array(initializer_list_t), there are
8605  no cases which can only be expressed by this function. That is, any
8606  initializer list @a init can also be passed to the initializer list
8607  constructor @ref basic_json(initializer_list_t, bool, value_t).
8608 
8609  @param[in] init initializer list to create an object from (optional)
8610 
8611  @return JSON object value
8612 
8613  @throw type_error.301 if @a init is not a list of pairs whose first
8614  elements are strings. In this case, no object can be created. When such a
8615  value is passed to @ref basic_json(initializer_list_t, bool, value_t),
8616  an array would have been created from the passed initializer list @a init.
8617  See example below.
8618 
8619  @complexity Linear in the size of @a init.
8620 
8621  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8622  changes to any JSON value.
8623 
8624  @liveexample{The following code shows an example for the `object`
8625  function.,object}
8626 
8627  @sa @ref basic_json(initializer_list_t, bool, value_t) --
8628  create a JSON value from an initializer list
8629  @sa @ref array(initializer_list_t) -- create a JSON array
8630  value from an initializer list
8631 
8632  @since version 1.0.0
8633  */
8634  static basic_json object(initializer_list_t init = {})
8635  {
8636  return basic_json(init, false, value_t::object);
8637  }
8638 
8639  /*!
8640  @brief construct an array with count copies of given value
8641 
8642  Constructs a JSON array value by creating @a cnt copies of a passed value.
8643  In case @a cnt is `0`, an empty array is created.
8644 
8645  @param[in] cnt the number of JSON copies of @a val to create
8646  @param[in] val the JSON value to copy
8647 
8648  @post `std::distance(begin(),end()) == cnt` holds.
8649 
8650  @complexity Linear in @a cnt.
8651 
8652  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8653  changes to any JSON value.
8654 
8655  @liveexample{The following code shows examples for the @ref
8656  basic_json(size_type\, const basic_json&)
8657  constructor.,basic_json__size_type_basic_json}
8658 
8659  @since version 1.0.0
8660  */
8661  basic_json(size_type cnt, const basic_json& val)
8662  : m_type(value_t::array)
8663  {
8664  m_value.array = create<array_t>(cnt, val);
8665  assert_invariant();
8666  }
8667 
8668  /*!
8669  @brief construct a JSON container given an iterator range
8670 
8671  Constructs the JSON value with the contents of the range `[first, last)`.
8672  The semantics depends on the different types a JSON value can have:
8673  - In case of a null type, invalid_iterator.206 is thrown.
8674  - In case of other primitive types (number, boolean, or string), @a first
8675  must be `begin()` and @a last must be `end()`. In this case, the value is
8676  copied. Otherwise, invalid_iterator.204 is thrown.
8677  - In case of structured types (array, object), the constructor behaves as
8678  similar versions for `std::vector` or `std::map`; that is, a JSON array
8679  or object is constructed from the values in the range.
8680 
8681  @tparam InputIT an input iterator type (@ref iterator or @ref
8682  const_iterator)
8683 
8684  @param[in] first begin of the range to copy from (included)
8685  @param[in] last end of the range to copy from (excluded)
8686 
8687  @pre Iterators @a first and @a last must be initialized. **This
8688  precondition is enforced with an assertion (see warning).** If
8689  assertions are switched off, a violation of this precondition yields
8690  undefined behavior.
8691 
8692  @pre Range `[first, last)` is valid. Usually, this precondition cannot be
8693  checked efficiently. Only certain edge cases are detected; see the
8694  description of the exceptions below. A violation of this precondition
8695  yields undefined behavior.
8696 
8697  @warning A precondition is enforced with a runtime assertion that will
8698  result in calling `std::abort` if this precondition is not met.
8699  Assertions can be disabled by defining `NDEBUG` at compile time.
8700  See http://en.cppreference.com/w/cpp/error/assert for more
8701  information.
8702 
8703  @throw invalid_iterator.201 if iterators @a first and @a last are not
8704  compatible (i.e., do not belong to the same JSON value). In this case,
8705  the range `[first, last)` is undefined.
8706  @throw invalid_iterator.204 if iterators @a first and @a last belong to a
8707  primitive type (number, boolean, or string), but @a first does not point
8708  to the first element any more. In this case, the range `[first, last)` is
8709  undefined. See example code below.
8710  @throw invalid_iterator.206 if iterators @a first and @a last belong to a
8711  null value. In this case, the range `[first, last)` is undefined.
8712 
8713  @complexity Linear in distance between @a first and @a last.
8714 
8715  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8716  changes to any JSON value.
8717 
8718  @liveexample{The example below shows several ways to create JSON values by
8719  specifying a subrange with iterators.,basic_json__InputIt_InputIt}
8720 
8721  @since version 1.0.0
8722  */
8723  template<class InputIT, typename std::enable_if<
8724  std::is_same<InputIT, typename basic_json_t::iterator>::value or
8725  std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
8726  basic_json(InputIT first, InputIT last)
8727  {
8728  assert(first.m_object != nullptr);
8729  assert(last.m_object != nullptr);
8730 
8731  // make sure iterator fits the current value
8732  if (JSON_UNLIKELY(first.m_object != last.m_object))
8733  {
8734  JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
8735  }
8736 
8737  // copy type from first iterator
8738  m_type = first.m_object->m_type;
8739 
8740  // check if iterator range is complete for primitive values
8741  switch (m_type)
8742  {
8743  case value_t::boolean:
8744  case value_t::number_float:
8745  case value_t::number_integer:
8746  case value_t::number_unsigned:
8747  case value_t::string:
8748  {
8749  if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
8750  or not last.m_it.primitive_iterator.is_end()))
8751  {
8752  JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
8753  }
8754  break;
8755  }
8756 
8757  default:
8758  break;
8759  }
8760 
8761  switch (m_type)
8762  {
8763  case value_t::number_integer:
8764  {
8765  m_value.number_integer = first.m_object->m_value.number_integer;
8766  break;
8767  }
8768 
8769  case value_t::number_unsigned:
8770  {
8771  m_value.number_unsigned = first.m_object->m_value.number_unsigned;
8772  break;
8773  }
8774 
8775  case value_t::number_float:
8776  {
8777  m_value.number_float = first.m_object->m_value.number_float;
8778  break;
8779  }
8780 
8781  case value_t::boolean:
8782  {
8783  m_value.boolean = first.m_object->m_value.boolean;
8784  break;
8785  }
8786 
8787  case value_t::string:
8788  {
8789  m_value = *first.m_object->m_value.string;
8790  break;
8791  }
8792 
8793  case value_t::object:
8794  {
8795  m_value.object = create<object_t>(first.m_it.object_iterator,
8796  last.m_it.object_iterator);
8797  break;
8798  }
8799 
8800  case value_t::array:
8801  {
8802  m_value.array = create<array_t>(first.m_it.array_iterator,
8803  last.m_it.array_iterator);
8804  break;
8805  }
8806 
8807  default:
8808  JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
8809  std::string(first.m_object->type_name())));
8810  }
8811 
8812  assert_invariant();
8813  }
8814 
8815 
8816  ///////////////////////////////////////
8817  // other constructors and destructor //
8818  ///////////////////////////////////////
8819 
8820  /// @private
8821  basic_json(const detail::json_ref<basic_json>& ref)
8822  : basic_json(ref.moved_or_copied())
8823  {}
8824 
8825  /*!
8826  @brief copy constructor
8827 
8828  Creates a copy of a given JSON value.
8829 
8830  @param[in] other the JSON value to copy
8831 
8832  @post `*this == other`
8833 
8834  @complexity Linear in the size of @a other.
8835 
8836  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8837  changes to any JSON value.
8838 
8839  @requirement This function helps `basic_json` satisfying the
8840  [Container](http://en.cppreference.com/w/cpp/concept/Container)
8841  requirements:
8842  - The complexity is linear.
8843  - As postcondition, it holds: `other == basic_json(other)`.
8844 
8845  @liveexample{The following code shows an example for the copy
8846  constructor.,basic_json__basic_json}
8847 
8848  @since version 1.0.0
8849  */
8850  basic_json(const basic_json& other)
8851  : m_type(other.m_type)
8852  {
8853  // check of passed value is valid
8854  other.assert_invariant();
8856  switch (m_type)
8857  {
8858  case value_t::object:
8859  {
8860  m_value = *other.m_value.object;
8861  break;
8862  }
8863 
8864  case value_t::array:
8865  {
8866  m_value = *other.m_value.array;
8867  break;
8868  }
8869 
8870  case value_t::string:
8871  {
8872  m_value = *other.m_value.string;
8873  break;
8874  }
8875 
8876  case value_t::boolean:
8877  {
8878  m_value = other.m_value.boolean;
8879  break;
8880  }
8881 
8882  case value_t::number_integer:
8883  {
8884  m_value = other.m_value.number_integer;
8885  break;
8886  }
8887 
8888  case value_t::number_unsigned:
8889  {
8890  m_value = other.m_value.number_unsigned;
8891  break;
8892  }
8893 
8894  case value_t::number_float:
8895  {
8896  m_value = other.m_value.number_float;
8897  break;
8898  }
8899 
8900  default:
8901  break;
8902  }
8903 
8904  assert_invariant();
8905  }
8906 
8907  /*!
8908  @brief move constructor
8909 
8910  Move constructor. Constructs a JSON value with the contents of the given
8911  value @a other using move semantics. It "steals" the resources from @a
8912  other and leaves it as JSON null value.
8913 
8914  @param[in,out] other value to move to this object
8915 
8916  @post `*this` has the same value as @a other before the call.
8917  @post @a other is a JSON null value.
8918 
8919  @complexity Constant.
8920 
8921  @exceptionsafety No-throw guarantee: this constructor never throws
8922  exceptions.
8923 
8924  @requirement This function helps `basic_json` satisfying the
8925  [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible)
8926  requirements.
8927 
8928  @liveexample{The code below shows the move constructor explicitly called
8929  via std::move.,basic_json__moveconstructor}
8930 
8931  @since version 1.0.0
8932  */
8933  basic_json(basic_json&& other) noexcept
8934  : m_type(std::move(other.m_type)),
8935  m_value(std::move(other.m_value))
8936  {
8937  // check that passed value is valid
8938  other.assert_invariant();
8939 
8940  // invalidate payload
8941  other.m_type = value_t::null;
8942  other.m_value = {};
8943 
8944  assert_invariant();
8945  }
8946 
8947  /*!
8948  @brief copy assignment
8949 
8950  Copy assignment operator. Copies a JSON value via the "copy and swap"
8951  strategy: It is expressed in terms of the copy constructor, destructor,
8952  and the `swap()` member function.
8953 
8954  @param[in] other value to copy from
8955 
8956  @complexity Linear.
8957 
8958  @requirement This function helps `basic_json` satisfying the
8959  [Container](http://en.cppreference.com/w/cpp/concept/Container)
8960  requirements:
8961  - The complexity is linear.
8962 
8963  @liveexample{The code below shows and example for the copy assignment. It
8964  creates a copy of value `a` which is then swapped with `b`. Finally\, the
8965  copy of `a` (which is the null value after the swap) is
8966  destroyed.,basic_json__copyassignment}
8967 
8968  @since version 1.0.0
8969  */
8970  reference& operator=(basic_json other) noexcept (
8971  std::is_nothrow_move_constructible<value_t>::value and
8972  std::is_nothrow_move_assignable<value_t>::value and
8973  std::is_nothrow_move_constructible<json_value>::value and
8974  std::is_nothrow_move_assignable<json_value>::value
8975  )
8976  {
8977  // check that passed value is valid
8978  other.assert_invariant();
8979 
8980  using std::swap;
8981  swap(m_type, other.m_type);
8982  swap(m_value, other.m_value);
8983 
8984  assert_invariant();
8985  return *this;
8986  }
8987 
8988  /*!
8989  @brief destructor
8990 
8991  Destroys the JSON value and frees all allocated memory.
8992 
8993  @complexity Linear.
8994 
8995  @requirement This function helps `basic_json` satisfying the
8996  [Container](http://en.cppreference.com/w/cpp/concept/Container)
8997  requirements:
8998  - The complexity is linear.
8999  - All stored elements are destroyed and all memory is freed.
9000 
9001  @since version 1.0.0
9002  */
9003  ~basic_json()
9004  {
9005  assert_invariant();
9006  m_value.destroy(m_type);
9007  }
9009  /// @}
9010 
9011  public:
9012  ///////////////////////
9013  // object inspection //
9014  ///////////////////////
9015 
9016  /// @name object inspection
9017  /// Functions to inspect the type of a JSON value.
9018  /// @{
9019 
9020  /*!
9021  @brief serialization
9022 
9023  Serialization function for JSON values. The function tries to mimic
9024  Python's `json.dumps()` function, and currently supports its @a indent
9025  and @a ensure_ascii parameters.
9026 
9027  @param[in] indent If indent is nonnegative, then array elements and object
9028  members will be pretty-printed with that indent level. An indent level of
9029  `0` will only insert newlines. `-1` (the default) selects the most compact
9030  representation.
9031  @param[in] indent_char The character to use for indentation if @a indent is
9032  greater than `0`. The default is ` ` (space).
9033  @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
9034  in the output are escaped with `\uXXXX` sequences, and the result consists
9035  of ASCII characters only.
9036 
9037  @return string containing the serialization of the JSON value
9038 
9039  @throw type_error.316 if a string stored inside the JSON value is not
9040  UTF-8 encoded
9041 
9042  @complexity Linear.
9043 
9044  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
9045  changes in the JSON value.
9046 
9047  @liveexample{The following example shows the effect of different @a indent\,
9048  @a indent_char\, and @a ensure_ascii parameters to the result of the
9049  serialization.,dump}
9050 
9051  @see https://docs.python.org/2/library/json.html#json.dump
9052 
9053  @since version 1.0.0; indentation character @a indent_char, option
9054  @a ensure_ascii and exceptions added in version 3.0.0
9055  */
9056  string_t dump(const int indent = -1, const char indent_char = ' ',
9057  const bool ensure_ascii = false) const
9058  {
9059  string_t result;
9060  serializer s(detail::output_adapter<char>(result), indent_char);
9062  if (indent >= 0)
9063  {
9064  s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
9065  }
9066  else
9067  {
9068  s.dump(*this, false, ensure_ascii, 0);
9069  }
9070 
9071  return result;
9072  }
9073 
9074  /*!
9075  @brief return the type of the JSON value (explicit)
9076 
9077  Return the type of the JSON value as a value from the @ref value_t
9078  enumeration.
9079 
9080  @return the type of the JSON value
9081  Value type | return value
9082  ------------------------- | -------------------------
9083  null | value_t::null
9084  boolean | value_t::boolean
9085  string | value_t::string
9086  number (integer) | value_t::number_integer
9087  number (unsigned integer) | value_t::number_unsigned
9088  number (floating-point) | value_t::number_float
9089  object | value_t::object
9090  array | value_t::array
9091  discarded | value_t::discarded
9092 
9093  @complexity Constant.
9094 
9095  @exceptionsafety No-throw guarantee: this member function never throws
9096  exceptions.
9097 
9098  @liveexample{The following code exemplifies `type()` for all JSON
9099  types.,type}
9100 
9101  @sa @ref operator value_t() -- return the type of the JSON value (implicit)
9102  @sa @ref type_name() -- return the type as string
9103 
9104  @since version 1.0.0
9105  */
9106  constexpr value_t type() const noexcept
9107  {
9108  return m_type;
9109  }
9110 
9111  /*!
9112  @brief return whether type is primitive
9113 
9114  This function returns true if and only if the JSON type is primitive
9115  (string, number, boolean, or null).
9116 
9117  @return `true` if type is primitive (string, number, boolean, or null),
9118  `false` otherwise.
9119 
9120  @complexity Constant.
9121 
9122  @exceptionsafety No-throw guarantee: this member function never throws
9123  exceptions.
9124 
9125  @liveexample{The following code exemplifies `is_primitive()` for all JSON
9126  types.,is_primitive}
9127 
9128  @sa @ref is_structured() -- returns whether JSON value is structured
9129  @sa @ref is_null() -- returns whether JSON value is `null`
9130  @sa @ref is_string() -- returns whether JSON value is a string
9131  @sa @ref is_boolean() -- returns whether JSON value is a boolean
9132  @sa @ref is_number() -- returns whether JSON value is a number
9133 
9134  @since version 1.0.0
9135  */
9136  constexpr bool is_primitive() const noexcept
9137  {
9138  return is_null() or is_string() or is_boolean() or is_number();
9139  }
9140 
9141  /*!
9142  @brief return whether type is structured
9143 
9144  This function returns true if and only if the JSON type is structured
9145  (array or object).
9146 
9147  @return `true` if type is structured (array or object), `false` otherwise.
9148 
9149  @complexity Constant.
9150 
9151  @exceptionsafety No-throw guarantee: this member function never throws
9152  exceptions.
9153 
9154  @liveexample{The following code exemplifies `is_structured()` for all JSON
9155  types.,is_structured}
9156 
9157  @sa @ref is_primitive() -- returns whether value is primitive
9158  @sa @ref is_array() -- returns whether value is an array
9159  @sa @ref is_object() -- returns whether value is an object
9160 
9161  @since version 1.0.0
9162  */
9163  constexpr bool is_structured() const noexcept
9164  {
9165  return is_array() or is_object();
9166  }
9167 
9168  /*!
9169  @brief return whether value is null
9170 
9171  This function returns true if and only if the JSON value is null.
9172 
9173  @return `true` if type is null, `false` otherwise.
9174 
9175  @complexity Constant.
9176 
9177  @exceptionsafety No-throw guarantee: this member function never throws
9178  exceptions.
9179 
9180  @liveexample{The following code exemplifies `is_null()` for all JSON
9181  types.,is_null}
9182 
9183  @since version 1.0.0
9184  */
9185  constexpr bool is_null() const noexcept
9186  {
9187  return (m_type == value_t::null);
9188  }
9189 
9190  /*!
9191  @brief return whether value is a boolean
9192 
9193  This function returns true if and only if the JSON value is a boolean.
9194 
9195  @return `true` if type is boolean, `false` otherwise.
9196 
9197  @complexity Constant.
9198 
9199  @exceptionsafety No-throw guarantee: this member function never throws
9200  exceptions.
9201 
9202  @liveexample{The following code exemplifies `is_boolean()` for all JSON
9203  types.,is_boolean}
9204 
9205  @since version 1.0.0
9206  */
9207  constexpr bool is_boolean() const noexcept
9208  {
9209  return (m_type == value_t::boolean);
9210  }
9211 
9212  /*!
9213  @brief return whether value is a number
9214 
9215  This function returns true if and only if the JSON value is a number. This
9216  includes both integer (signed and unsigned) and floating-point values.
9217 
9218  @return `true` if type is number (regardless whether integer, unsigned
9219  integer or floating-type), `false` otherwise.
9220 
9221  @complexity Constant.
9222 
9223  @exceptionsafety No-throw guarantee: this member function never throws
9224  exceptions.
9225 
9226  @liveexample{The following code exemplifies `is_number()` for all JSON
9227  types.,is_number}
9228 
9229  @sa @ref is_number_integer() -- check if value is an integer or unsigned
9230  integer number
9231  @sa @ref is_number_unsigned() -- check if value is an unsigned integer
9232  number
9233  @sa @ref is_number_float() -- check if value is a floating-point number
9234 
9235  @since version 1.0.0
9236  */
9237  constexpr bool is_number() const noexcept
9238  {
9239  return is_number_integer() or is_number_float();
9240  }
9241 
9242  /*!
9243  @brief return whether value is an integer number
9244 
9245  This function returns true if and only if the JSON value is a signed or
9246  unsigned integer number. This excludes floating-point values.
9247 
9248  @return `true` if type is an integer or unsigned integer number, `false`
9249  otherwise.
9250 
9251  @complexity Constant.
9252 
9253  @exceptionsafety No-throw guarantee: this member function never throws
9254  exceptions.
9255 
9256  @liveexample{The following code exemplifies `is_number_integer()` for all
9257  JSON types.,is_number_integer}
9258 
9259  @sa @ref is_number() -- check if value is a number
9260  @sa @ref is_number_unsigned() -- check if value is an unsigned integer
9261  number
9262  @sa @ref is_number_float() -- check if value is a floating-point number
9263 
9264  @since version 1.0.0
9265  */
9266  constexpr bool is_number_integer() const noexcept
9267  {
9268  return (m_type == value_t::number_integer or m_type == value_t::number_unsigned);
9269  }
9270 
9271  /*!
9272  @brief return whether value is an unsigned integer number
9273 
9274  This function returns true if and only if the JSON value is an unsigned
9275  integer number. This excludes floating-point and signed integer values.
9276 
9277  @return `true` if type is an unsigned integer number, `false` otherwise.
9278 
9279  @complexity Constant.
9280 
9281  @exceptionsafety No-throw guarantee: this member function never throws
9282  exceptions.
9283 
9284  @liveexample{The following code exemplifies `is_number_unsigned()` for all
9285  JSON types.,is_number_unsigned}
9286 
9287  @sa @ref is_number() -- check if value is a number
9288  @sa @ref is_number_integer() -- check if value is an integer or unsigned
9289  integer number
9290  @sa @ref is_number_float() -- check if value is a floating-point number
9291 
9292  @since version 2.0.0
9293  */
9294  constexpr bool is_number_unsigned() const noexcept
9295  {
9296  return (m_type == value_t::number_unsigned);
9297  }
9298 
9299  /*!
9300  @brief return whether value is a floating-point number
9301 
9302  This function returns true if and only if the JSON value is a
9303  floating-point number. This excludes signed and unsigned integer values.
9304 
9305  @return `true` if type is a floating-point number, `false` otherwise.
9306 
9307  @complexity Constant.
9308 
9309  @exceptionsafety No-throw guarantee: this member function never throws
9310  exceptions.
9311 
9312  @liveexample{The following code exemplifies `is_number_float()` for all
9313  JSON types.,is_number_float}
9314 
9315  @sa @ref is_number() -- check if value is number
9316  @sa @ref is_number_integer() -- check if value is an integer number
9317  @sa @ref is_number_unsigned() -- check if value is an unsigned integer
9318  number
9319 
9320  @since version 1.0.0
9321  */
9322  constexpr bool is_number_float() const noexcept
9323  {
9324  return (m_type == value_t::number_float);
9325  }
9326 
9327  /*!
9328  @brief return whether value is an object
9329 
9330  This function returns true if and only if the JSON value is an object.
9331 
9332  @return `true` if type is object, `false` otherwise.
9333 
9334  @complexity Constant.
9335 
9336  @exceptionsafety No-throw guarantee: this member function never throws
9337  exceptions.
9338 
9339  @liveexample{The following code exemplifies `is_object()` for all JSON
9340  types.,is_object}
9341 
9342  @since version 1.0.0
9343  */
9344  constexpr bool is_object() const noexcept
9345  {
9346  return (m_type == value_t::object);
9347  }
9348 
9349  /*!
9350  @brief return whether value is an array
9351 
9352  This function returns true if and only if the JSON value is an array.
9353 
9354  @return `true` if type is array, `false` otherwise.
9355 
9356  @complexity Constant.
9357 
9358  @exceptionsafety No-throw guarantee: this member function never throws
9359  exceptions.
9360 
9361  @liveexample{The following code exemplifies `is_array()` for all JSON
9362  types.,is_array}
9363 
9364  @since version 1.0.0
9365  */
9366  constexpr bool is_array() const noexcept
9367  {
9368  return (m_type == value_t::array);
9369  }
9370 
9371  /*!
9372  @brief return whether value is a string
9373 
9374  This function returns true if and only if the JSON value is a string.
9375 
9376  @return `true` if type is string, `false` otherwise.
9377 
9378  @complexity Constant.
9379 
9380  @exceptionsafety No-throw guarantee: this member function never throws
9381  exceptions.
9382 
9383  @liveexample{The following code exemplifies `is_string()` for all JSON
9384  types.,is_string}
9385 
9386  @since version 1.0.0
9387  */
9388  constexpr bool is_string() const noexcept
9389  {
9390  return (m_type == value_t::string);
9391  }
9392 
9393  /*!
9394  @brief return whether value is discarded
9395 
9396  This function returns true if and only if the JSON value was discarded
9397  during parsing with a callback function (see @ref parser_callback_t).
9398 
9399  @note This function will always be `false` for JSON values after parsing.
9400  That is, discarded values can only occur during parsing, but will be
9401  removed when inside a structured value or replaced by null in other cases.
9402 
9403  @return `true` if type is discarded, `false` otherwise.
9404 
9405  @complexity Constant.
9406 
9407  @exceptionsafety No-throw guarantee: this member function never throws
9408  exceptions.
9409 
9410  @liveexample{The following code exemplifies `is_discarded()` for all JSON
9411  types.,is_discarded}
9412 
9413  @since version 1.0.0
9414  */
9415  constexpr bool is_discarded() const noexcept
9416  {
9417  return (m_type == value_t::discarded);
9418  }
9419 
9420  /*!
9421  @brief return the type of the JSON value (implicit)
9422 
9423  Implicitly return the type of the JSON value as a value from the @ref
9424  value_t enumeration.
9425 
9426  @return the type of the JSON value
9427 
9428  @complexity Constant.
9429 
9430  @exceptionsafety No-throw guarantee: this member function never throws
9431  exceptions.
9432 
9433  @liveexample{The following code exemplifies the @ref value_t operator for
9434  all JSON types.,operator__value_t}
9435 
9436  @sa @ref type() -- return the type of the JSON value (explicit)
9437  @sa @ref type_name() -- return the type as string
9438 
9439  @since version 1.0.0
9440  */
9441  constexpr operator value_t() const noexcept
9442  {
9443  return m_type;
9444  }
9445 
9446  /// @}
9447 
9448  private:
9449  //////////////////
9450  // value access //
9451  //////////////////
9452 
9453  /// get a boolean (explicit)
9454  boolean_t get_impl(boolean_t* /*unused*/) const
9455  {
9456  if (JSON_LIKELY(is_boolean()))
9457  {
9458  return m_value.boolean;
9459  }
9460 
9461  JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
9462  }
9463 
9464  /// get a pointer to the value (object)
9465  object_t* get_impl_ptr(object_t* /*unused*/) noexcept
9466  {
9467  return is_object() ? m_value.object : nullptr;
9468  }
9469 
9470  /// get a pointer to the value (object)
9471  constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
9472  {
9473  return is_object() ? m_value.object : nullptr;
9474  }
9475 
9476  /// get a pointer to the value (array)
9477  array_t* get_impl_ptr(array_t* /*unused*/) noexcept
9478  {
9479  return is_array() ? m_value.array : nullptr;
9480  }
9481 
9482  /// get a pointer to the value (array)
9483  constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
9484  {
9485  return is_array() ? m_value.array : nullptr;
9486  }
9487 
9488  /// get a pointer to the value (string)
9489  string_t* get_impl_ptr(string_t* /*unused*/) noexcept
9490  {
9491  return is_string() ? m_value.string : nullptr;
9492  }
9493 
9494  /// get a pointer to the value (string)
9495  constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
9496  {
9497  return is_string() ? m_value.string : nullptr;
9498  }
9499 
9500  /// get a pointer to the value (boolean)
9501  boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
9502  {
9503  return is_boolean() ? &m_value.boolean : nullptr;
9504  }
9505 
9506  /// get a pointer to the value (boolean)
9507  constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
9508  {
9509  return is_boolean() ? &m_value.boolean : nullptr;
9510  }
9511 
9512  /// get a pointer to the value (integer number)
9513  number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
9514  {
9515  return is_number_integer() ? &m_value.number_integer : nullptr;
9516  }
9517 
9518  /// get a pointer to the value (integer number)
9519  constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
9520  {
9521  return is_number_integer() ? &m_value.number_integer : nullptr;
9522  }
9523 
9524  /// get a pointer to the value (unsigned number)
9525  number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
9526  {
9527  return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
9528  }
9529 
9530  /// get a pointer to the value (unsigned number)
9531  constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
9532  {
9533  return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
9534  }
9535 
9536  /// get a pointer to the value (floating-point number)
9537  number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
9538  {
9539  return is_number_float() ? &m_value.number_float : nullptr;
9540  }
9541 
9542  /// get a pointer to the value (floating-point number)
9543  constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
9544  {
9545  return is_number_float() ? &m_value.number_float : nullptr;
9546  }
9547 
9548  /*!
9549  @brief helper function to implement get_ref()
9550 
9551  This function helps to implement get_ref() without code duplication for
9552  const and non-const overloads
9553 
9554  @tparam ThisType will be deduced as `basic_json` or `const basic_json`
9555 
9556  @throw type_error.303 if ReferenceType does not match underlying value
9557  type of the current JSON
9558  */
9559  template<typename ReferenceType, typename ThisType>
9560  static ReferenceType get_ref_impl(ThisType& obj)
9561  {
9562  // delegate the call to get_ptr<>()
9563  auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
9564 
9565  if (JSON_LIKELY(ptr != nullptr))
9566  {
9567  return *ptr;
9568  }
9569 
9570  JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
9571  }
9572 
9573  public:
9574  /// @name value access
9575  /// Direct access to the stored value of a JSON value.
9576  /// @{
9577 
9578  /*!
9579  @brief get special-case overload
9580 
9581  This overloads avoids a lot of template boilerplate, it can be seen as the
9582  identity method
9583 
9584  @tparam BasicJsonType == @ref basic_json
9585 
9586  @return a copy of *this
9587 
9588  @complexity Constant.
9589 
9590  @since version 2.1.0
9591  */
9592  template<typename BasicJsonType, detail::enable_if_t<
9593  std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
9594  int> = 0>
9595  basic_json get() const
9596  {
9597  return *this;
9598  }
9599 
9600  /*!
9601  @brief get a value (explicit)
9602 
9603  Explicit type conversion between the JSON value and a compatible value
9604  which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
9605  and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
9606  The value is converted by calling the @ref json_serializer<ValueType>
9607  `from_json()` method.
9608 
9609  The function is equivalent to executing
9610  @code {.cpp}
9611  ValueType ret;
9612  JSONSerializer<ValueType>::from_json(*this, ret);
9613  return ret;
9614  @endcode
9615 
9616  This overloads is chosen if:
9617  - @a ValueType is not @ref basic_json,
9618  - @ref json_serializer<ValueType> has a `from_json()` method of the form
9619  `void from_json(const basic_json&, ValueType&)`, and
9620  - @ref json_serializer<ValueType> does not have a `from_json()` method of
9621  the form `ValueType from_json(const basic_json&)`
9622 
9623  @tparam ValueTypeCV the provided value type
9624  @tparam ValueType the returned value type
9625 
9626  @return copy of the JSON value, converted to @a ValueType
9627 
9628  @throw what @ref json_serializer<ValueType> `from_json()` method throws
9629 
9630  @liveexample{The example below shows several conversions from JSON values
9631  to other types. There a few things to note: (1) Floating-point numbers can
9632  be converted to integers\, (2) A JSON array can be converted to a standard
9633  `std::vector<short>`\, (3) A JSON object can be converted to C++
9634  associative containers such as `std::unordered_map<std::string\,
9635  json>`.,get__ValueType_const}
9636 
9637  @since version 2.1.0
9638  */
9639  template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
9640  detail::enable_if_t <
9641  not std::is_same<basic_json_t, ValueType>::value and
9642  detail::has_from_json<basic_json_t, ValueType>::value and
9643  not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
9644  int> = 0>
9645  ValueType get() const noexcept(noexcept(
9646  JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
9647  {
9648  // we cannot static_assert on ValueTypeCV being non-const, because
9649  // there is support for get<const basic_json_t>(), which is why we
9650  // still need the uncvref
9651  static_assert(not std::is_reference<ValueTypeCV>::value,
9652  "get() cannot be used with reference types, you might want to use get_ref()");
9653  static_assert(std::is_default_constructible<ValueType>::value,
9654  "types must be DefaultConstructible when used with get()");
9655 
9656  ValueType ret;
9657  JSONSerializer<ValueType>::from_json(*this, ret);
9658  return ret;
9659  }
9660 
9661  /*!
9662  @brief get a value (explicit); special case
9663 
9664  Explicit type conversion between the JSON value and a compatible value
9665  which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
9666  and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
9667  The value is converted by calling the @ref json_serializer<ValueType>
9668  `from_json()` method.
9669 
9670  The function is equivalent to executing
9671  @code {.cpp}
9672  return JSONSerializer<ValueTypeCV>::from_json(*this);
9673  @endcode
9674 
9675  This overloads is chosen if:
9676  - @a ValueType is not @ref basic_json and
9677  - @ref json_serializer<ValueType> has a `from_json()` method of the form
9678  `ValueType from_json(const basic_json&)`
9679 
9680  @note If @ref json_serializer<ValueType> has both overloads of
9681  `from_json()`, this one is chosen.
9682 
9683  @tparam ValueTypeCV the provided value type
9684  @tparam ValueType the returned value type
9685 
9686  @return copy of the JSON value, converted to @a ValueType
9687 
9688  @throw what @ref json_serializer<ValueType> `from_json()` method throws
9689 
9690  @since version 2.1.0
9691  */
9692  template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
9693  detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
9694  detail::has_non_default_from_json<basic_json_t, ValueType>::value,
9695  int> = 0>
9696  ValueType get() const noexcept(noexcept(
9697  JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
9698  {
9699  static_assert(not std::is_reference<ValueTypeCV>::value,
9700  "get() cannot be used with reference types, you might want to use get_ref()");
9701  return JSONSerializer<ValueTypeCV>::from_json(*this);
9702  }
9703 
9704  /*!
9705  @brief get a pointer value (explicit)
9706 
9707  Explicit pointer access to the internally stored JSON value. No copies are
9708  made.
9709 
9710  @warning The pointer becomes invalid if the underlying JSON object
9711  changes.
9712 
9713  @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
9714  object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
9715  @ref number_unsigned_t, or @ref number_float_t.
9716 
9717  @return pointer to the internally stored JSON value if the requested
9718  pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
9719 
9720  @complexity Constant.
9721 
9722  @liveexample{The example below shows how pointers to internal values of a
9723  JSON value can be requested. Note that no type conversions are made and a
9724  `nullptr` is returned if the value and the requested pointer type does not
9725  match.,get__PointerType}
9726 
9727  @sa @ref get_ptr() for explicit pointer-member access
9728 
9729  @since version 1.0.0
9730  */
9731  template<typename PointerType, typename std::enable_if<
9732  std::is_pointer<PointerType>::value, int>::type = 0>
9733  PointerType get() noexcept
9734  {
9735  // delegate the call to get_ptr
9736  return get_ptr<PointerType>();
9737  }
9739  /*!
9740  @brief get a pointer value (explicit)
9741  @copydoc get()
9742  */
9743  template<typename PointerType, typename std::enable_if<
9744  std::is_pointer<PointerType>::value, int>::type = 0>
9745  constexpr const PointerType get() const noexcept
9746  {
9747  // delegate the call to get_ptr
9748  return get_ptr<PointerType>();
9749  }
9751  /*!
9752  @brief get a pointer value (implicit)
9753 
9754  Implicit pointer access to the internally stored JSON value. No copies are
9755  made.
9756 
9757  @warning Writing data to the pointee of the result yields an undefined
9758  state.
9759 
9760  @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
9761  object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
9762  @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
9763  assertion.
9764 
9765  @return pointer to the internally stored JSON value if the requested
9766  pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
9767 
9768  @complexity Constant.
9769 
9770  @liveexample{The example below shows how pointers to internal values of a
9771  JSON value can be requested. Note that no type conversions are made and a
9772  `nullptr` is returned if the value and the requested pointer type does not
9773  match.,get_ptr}
9774 
9775  @since version 1.0.0
9776  */
9777  template<typename PointerType, typename std::enable_if<
9778  std::is_pointer<PointerType>::value, int>::type = 0>
9779  PointerType get_ptr() noexcept
9780  {
9781  // get the type of the PointerType (remove pointer and const)
9782  using pointee_t = typename std::remove_const<typename
9783  std::remove_pointer<typename
9784  std::remove_const<PointerType>::type>::type>::type;
9785  // make sure the type matches the allowed types
9786  static_assert(
9787  std::is_same<object_t, pointee_t>::value
9788  or std::is_same<array_t, pointee_t>::value
9789  or std::is_same<string_t, pointee_t>::value
9790  or std::is_same<boolean_t, pointee_t>::value
9791  or std::is_same<number_integer_t, pointee_t>::value
9792  or std::is_same<number_unsigned_t, pointee_t>::value
9793  or std::is_same<number_float_t, pointee_t>::value
9794  , "incompatible pointer type");
9795 
9796  // delegate the call to get_impl_ptr<>()
9797  return get_impl_ptr(static_cast<PointerType>(nullptr));
9798  }
9799 
9800  /*!
9801  @brief get a pointer value (implicit)
9802  @copydoc get_ptr()
9803  */
9804  template<typename PointerType, typename std::enable_if<
9805  std::is_pointer<PointerType>::value and
9806  std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
9807  constexpr const PointerType get_ptr() const noexcept
9808  {
9809  // get the type of the PointerType (remove pointer and const)
9810  using pointee_t = typename std::remove_const<typename
9811  std::remove_pointer<typename
9812  std::remove_const<PointerType>::type>::type>::type;
9813  // make sure the type matches the allowed types
9814  static_assert(
9815  std::is_same<object_t, pointee_t>::value
9816  or std::is_same<array_t, pointee_t>::value
9817  or std::is_same<string_t, pointee_t>::value
9818  or std::is_same<boolean_t, pointee_t>::value
9819  or std::is_same<number_integer_t, pointee_t>::value
9820  or std::is_same<number_unsigned_t, pointee_t>::value
9821  or std::is_same<number_float_t, pointee_t>::value
9822  , "incompatible pointer type");
9823 
9824  // delegate the call to get_impl_ptr<>() const
9825  return get_impl_ptr(static_cast<PointerType>(nullptr));
9826  }
9827 
9828  /*!
9829  @brief get a reference value (implicit)
9830 
9831  Implicit reference access to the internally stored JSON value. No copies
9832  are made.
9833 
9834  @warning Writing data to the referee of the result yields an undefined
9835  state.
9836 
9837  @tparam ReferenceType reference type; must be a reference to @ref array_t,
9838  @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
9839  @ref number_float_t. Enforced by static assertion.
9840 
9841  @return reference to the internally stored JSON value if the requested
9842  reference type @a ReferenceType fits to the JSON value; throws
9843  type_error.303 otherwise
9844 
9845  @throw type_error.303 in case passed type @a ReferenceType is incompatible
9846  with the stored JSON value; see example below
9847 
9848  @complexity Constant.
9849 
9850  @liveexample{The example shows several calls to `get_ref()`.,get_ref}
9851 
9852  @since version 1.1.0
9853  */
9854  template<typename ReferenceType, typename std::enable_if<
9855  std::is_reference<ReferenceType>::value, int>::type = 0>
9856  ReferenceType get_ref()
9857  {
9858  // delegate call to get_ref_impl
9859  return get_ref_impl<ReferenceType>(*this);
9860  }
9862  /*!
9863  @brief get a reference value (implicit)
9864  @copydoc get_ref()
9865  */
9866  template<typename ReferenceType, typename std::enable_if<
9867  std::is_reference<ReferenceType>::value and
9868  std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
9869  ReferenceType get_ref() const
9870  {
9871  // delegate call to get_ref_impl
9872  return get_ref_impl<ReferenceType>(*this);
9873  }
9875  /*!
9876  @brief get a value (implicit)
9877 
9878  Implicit type conversion between the JSON value and a compatible value.
9879  The call is realized by calling @ref get() const.
9880 
9881  @tparam ValueType non-pointer type compatible to the JSON value, for
9882  instance `int` for JSON integer numbers, `bool` for JSON booleans, or
9883  `std::vector` types for JSON arrays. The character type of @ref string_t
9884  as well as an initializer list of this type is excluded to avoid
9885  ambiguities as these types implicitly convert to `std::string`.
9886 
9887  @return copy of the JSON value, converted to type @a ValueType
9888 
9889  @throw type_error.302 in case passed type @a ValueType is incompatible
9890  to the JSON value type (e.g., the JSON value is of type boolean, but a
9891  string is requested); see example below
9892 
9893  @complexity Linear in the size of the JSON value.
9894 
9895  @liveexample{The example below shows several conversions from JSON values
9896  to other types. There a few things to note: (1) Floating-point numbers can
9897  be converted to integers\, (2) A JSON array can be converted to a standard
9898  `std::vector<short>`\, (3) A JSON object can be converted to C++
9899  associative containers such as `std::unordered_map<std::string\,
9900  json>`.,operator__ValueType}
9901 
9902  @since version 1.0.0
9903  */
9904  template < typename ValueType, typename std::enable_if <
9905  not std::is_pointer<ValueType>::value and
9906  not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
9907  not std::is_same<ValueType, typename string_t::value_type>::value
9908 #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
9909  and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
9910 #endif
9911 #if defined(JSON_HAS_CPP_17)
9912  and not std::is_same<ValueType, typename std::string_view>::value
9913 #endif
9914  , int >::type = 0 >
9915  operator ValueType() const
9916  {
9917  // delegate the call to get<>() const
9918  return get<ValueType>();
9919  }
9921  /// @}
9922 
9923 
9924  ////////////////////
9925  // element access //
9926  ////////////////////
9927 
9928  /// @name element access
9929  /// Access to the JSON value.
9930  /// @{
9931 
9932  /*!
9933  @brief access specified array element with bounds checking
9934 
9935  Returns a reference to the element at specified location @a idx, with
9936  bounds checking.
9937 
9938  @param[in] idx index of the element to access
9939 
9940  @return reference to the element at index @a idx
9941 
9942  @throw type_error.304 if the JSON value is not an array; in this case,
9943  calling `at` with an index makes no sense. See example below.
9944  @throw out_of_range.401 if the index @a idx is out of range of the array;
9945  that is, `idx >= size()`. See example below.
9946 
9947  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
9948  changes in the JSON value.
9949 
9950  @complexity Constant.
9951 
9952  @since version 1.0.0
9953 
9954  @liveexample{The example below shows how array elements can be read and
9955  written using `at()`. It also demonstrates the different exceptions that
9956  can be thrown.,at__size_type}
9957  */
9958  reference at(size_type idx)
9959  {
9960  // at only works for arrays
9961  if (JSON_LIKELY(is_array()))
9962  {
9964  {
9965  return m_value.array->at(idx);
9966  }
9967  JSON_CATCH (std::out_of_range&)
9968  {
9969  // create better exception explanation
9970  JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
9971  }
9972  }
9973  else
9974  {
9975  JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
9976  }
9977  }
9978 
9979  /*!
9980  @brief access specified array element with bounds checking
9981 
9982  Returns a const reference to the element at specified location @a idx,
9983  with bounds checking.
9984 
9985  @param[in] idx index of the element to access
9986 
9987  @return const reference to the element at index @a idx
9988 
9989  @throw type_error.304 if the JSON value is not an array; in this case,
9990  calling `at` with an index makes no sense. See example below.
9991  @throw out_of_range.401 if the index @a idx is out of range of the array;
9992  that is, `idx >= size()`. See example below.
9993 
9994  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
9995  changes in the JSON value.
9996 
9997  @complexity Constant.
9998 
9999  @since version 1.0.0
10000 
10001  @liveexample{The example below shows how array elements can be read using
10002  `at()`. It also demonstrates the different exceptions that can be thrown.,
10003  at__size_type_const}
10004  */
10005  const_reference at(size_type idx) const
10006  {
10007  // at only works for arrays
10008  if (JSON_LIKELY(is_array()))
10009  {
10010  JSON_TRY
10011  {
10012  return m_value.array->at(idx);
10013  }
10014  JSON_CATCH (std::out_of_range&)
10015  {
10016  // create better exception explanation
10017  JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
10018  }
10019  }
10020  else
10021  {
10022  JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
10023  }
10024  }
10025 
10026  /*!
10027  @brief access specified object element with bounds checking
10028 
10029  Returns a reference to the element at with specified key @a key, with
10030  bounds checking.
10031 
10032  @param[in] key key of the element to access
10033 
10034  @return reference to the element at key @a key
10035 
10036  @throw type_error.304 if the JSON value is not an object; in this case,
10037  calling `at` with a key makes no sense. See example below.
10038  @throw out_of_range.403 if the key @a key is is not stored in the object;
10039  that is, `find(key) == end()`. See example below.
10040 
10041  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
10042  changes in the JSON value.
10043 
10044  @complexity Logarithmic in the size of the container.
10045 
10046  @sa @ref operator[](const typename object_t::key_type&) for unchecked
10047  access by reference
10048  @sa @ref value() for access by value with a default value
10049 
10050  @since version 1.0.0
10051 
10052  @liveexample{The example below shows how object elements can be read and
10053  written using `at()`. It also demonstrates the different exceptions that
10054  can be thrown.,at__object_t_key_type}
10055  */
10056  reference at(const typename object_t::key_type& key)
10057  {
10058  // at only works for objects
10059  if (JSON_LIKELY(is_object()))
10060  {
10061  JSON_TRY
10062  {
10063  return m_value.object->at(key);
10064  }
10065  JSON_CATCH (std::out_of_range&)
10066  {
10067  // create better exception explanation
10068  JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
10069  }
10070  }
10071  else
10072  {
10073  JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
10074  }
10075  }
10076 
10077  /*!
10078  @brief access specified object element with bounds checking
10079 
10080  Returns a const reference to the element at with specified key @a key,
10081  with bounds checking.
10082 
10083  @param[in] key key of the element to access
10084 
10085  @return const reference to the element at key @a key
10086 
10087  @throw type_error.304 if the JSON value is not an object; in this case,
10088  calling `at` with a key makes no sense. See example below.
10089  @throw out_of_range.403 if the key @a key is is not stored in the object;
10090  that is, `find(key) == end()`. See example below.
10091 
10092  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
10093  changes in the JSON value.
10094 
10095  @complexity Logarithmic in the size of the container.
10096 
10097  @sa @ref operator[](const typename object_t::key_type&) for unchecked
10098  access by reference
10099  @sa @ref value() for access by value with a default value
10100 
10101  @since version 1.0.0
10102 
10103  @liveexample{The example below shows how object elements can be read using
10104  `at()`. It also demonstrates the different exceptions that can be thrown.,
10105  at__object_t_key_type_const}
10106  */
10107  const_reference at(const typename object_t::key_type& key) const
10108  {
10109  // at only works for objects
10110  if (JSON_LIKELY(is_object()))
10111  {
10112  JSON_TRY
10113  {
10114  return m_value.object->at(key);
10115  }
10116  JSON_CATCH (std::out_of_range&)
10117  {
10118  // create better exception explanation
10119  JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
10120  }
10121  }
10122  else
10123  {
10124  JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
10125  }
10126  }
10127 
10128  /*!
10129  @brief access specified array element
10130 
10131  Returns a reference to the element at specified location @a idx.
10132 
10133  @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
10134  then the array is silently filled up with `null` values to make `idx` a
10135  valid reference to the last stored element.
10136 
10137  @param[in] idx index of the element to access
10138 
10139  @return reference to the element at index @a idx
10140 
10141  @throw type_error.305 if the JSON value is not an array or null; in that
10142  cases, using the [] operator with an index makes no sense.
10143 
10144  @complexity Constant if @a idx is in the range of the array. Otherwise
10145  linear in `idx - size()`.
10146 
10147  @liveexample{The example below shows how array elements can be read and
10148  written using `[]` operator. Note the addition of `null`
10149  values.,operatorarray__size_type}
10150 
10151  @since version 1.0.0
10152  */
10153  reference operator[](size_type idx)
10154  {
10155  // implicitly convert null value to an empty array
10156  if (is_null())
10157  {
10158  m_type = value_t::array;
10159  m_value.array = create<array_t>();
10160  assert_invariant();
10161  }
10162 
10163  // operator[] only works for arrays
10164  if (JSON_LIKELY(is_array()))
10165  {
10166  // fill up array with null values if given idx is outside range
10167  if (idx >= m_value.array->size())
10168  {
10169  m_value.array->insert(m_value.array->end(),
10170  idx - m_value.array->size() + 1,
10171  basic_json());
10172  }
10173 
10174  return m_value.array->operator[](idx);
10175  }
10176 
10177  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10178  }
10179 
10180  /*!
10181  @brief access specified array element
10182 
10183  Returns a const reference to the element at specified location @a idx.
10184 
10185  @param[in] idx index of the element to access
10186 
10187  @return const reference to the element at index @a idx
10188 
10189  @throw type_error.305 if the JSON value is not an array; in that case,
10190  using the [] operator with an index makes no sense.
10191 
10192  @complexity Constant.
10193 
10194  @liveexample{The example below shows how array elements can be read using
10195  the `[]` operator.,operatorarray__size_type_const}
10196 
10197  @since version 1.0.0
10198  */
10199  const_reference operator[](size_type idx) const
10200  {
10201  // const operator[] only works for arrays
10202  if (JSON_LIKELY(is_array()))
10203  {
10204  return m_value.array->operator[](idx);
10205  }
10206 
10207  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10208  }
10209 
10210  /*!
10211  @brief access specified object element
10212 
10213  Returns a reference to the element at with specified key @a key.
10215  @note If @a key is not found in the object, then it is silently added to
10216  the object and filled with a `null` value to make `key` a valid reference.
10217  In case the value was `null` before, it is converted to an object.
10218 
10219  @param[in] key key of the element to access
10220 
10221  @return reference to the element at key @a key
10222 
10223  @throw type_error.305 if the JSON value is not an object or null; in that
10224  cases, using the [] operator with a key makes no sense.
10225 
10226  @complexity Logarithmic in the size of the container.
10227 
10228  @liveexample{The example below shows how object elements can be read and
10229  written using the `[]` operator.,operatorarray__key_type}
10230 
10231  @sa @ref at(const typename object_t::key_type&) for access by reference
10232  with range checking
10233  @sa @ref value() for access by value with a default value
10234 
10235  @since version 1.0.0
10236  */
10237  reference operator[](const typename object_t::key_type& key)
10238  {
10239  // implicitly convert null value to an empty object
10240  if (is_null())
10241  {
10242  m_type = value_t::object;
10243  m_value.object = create<object_t>();
10244  assert_invariant();
10245  }
10246 
10247  // operator[] only works for objects
10248  if (JSON_LIKELY(is_object()))
10249  {
10250  return m_value.object->operator[](key);
10251  }
10253  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10254  }
10255 
10256  /*!
10257  @brief read-only access specified object element
10258 
10259  Returns a const reference to the element at with specified key @a key. No
10260  bounds checking is performed.
10261 
10262  @warning If the element with key @a key does not exist, the behavior is
10263  undefined.
10264 
10265  @param[in] key key of the element to access
10266 
10267  @return const reference to the element at key @a key
10268 
10269  @pre The element with key @a key must exist. **This precondition is
10270  enforced with an assertion.**
10271 
10272  @throw type_error.305 if the JSON value is not an object; in that case,
10273  using the [] operator with a key makes no sense.
10274 
10275  @complexity Logarithmic in the size of the container.
10276 
10277  @liveexample{The example below shows how object elements can be read using
10278  the `[]` operator.,operatorarray__key_type_const}
10279 
10280  @sa @ref at(const typename object_t::key_type&) for access by reference
10281  with range checking
10282  @sa @ref value() for access by value with a default value
10283 
10284  @since version 1.0.0
10285  */
10286  const_reference operator[](const typename object_t::key_type& key) const
10287  {
10288  // const operator[] only works for objects
10289  if (JSON_LIKELY(is_object()))
10290  {
10291  assert(m_value.object->find(key) != m_value.object->end());
10292  return m_value.object->find(key)->second;
10293  }
10294 
10295  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10296  }
10297 
10298  /*!
10299  @brief access specified object element
10300 
10301  Returns a reference to the element at with specified key @a key.
10302 
10303  @note If @a key is not found in the object, then it is silently added to
10304  the object and filled with a `null` value to make `key` a valid reference.
10305  In case the value was `null` before, it is converted to an object.
10306 
10307  @param[in] key key of the element to access
10308 
10309  @return reference to the element at key @a key
10310 
10311  @throw type_error.305 if the JSON value is not an object or null; in that
10312  cases, using the [] operator with a key makes no sense.
10313 
10314  @complexity Logarithmic in the size of the container.
10315 
10316  @liveexample{The example below shows how object elements can be read and
10317  written using the `[]` operator.,operatorarray__key_type}
10318 
10319  @sa @ref at(const typename object_t::key_type&) for access by reference
10320  with range checking
10321  @sa @ref value() for access by value with a default value
10322 
10323  @since version 1.1.0
10324  */
10325  template<typename T>
10326  reference operator[](T* key)
10327  {
10328  // implicitly convert null to object
10329  if (is_null())
10330  {
10331  m_type = value_t::object;
10332  m_value = value_t::object;
10333  assert_invariant();
10334  }
10335 
10336  // at only works for objects
10337  if (JSON_LIKELY(is_object()))
10338  {
10339  return m_value.object->operator[](key);
10340  }
10342  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10343  }
10344 
10345  /*!
10346  @brief read-only access specified object element
10347 
10348  Returns a const reference to the element at with specified key @a key. No
10349  bounds checking is performed.
10350 
10351  @warning If the element with key @a key does not exist, the behavior is
10352  undefined.
10353 
10354  @param[in] key key of the element to access
10355 
10356  @return const reference to the element at key @a key
10357 
10358  @pre The element with key @a key must exist. **This precondition is
10359  enforced with an assertion.**
10360 
10361  @throw type_error.305 if the JSON value is not an object; in that case,
10362  using the [] operator with a key makes no sense.
10363 
10364  @complexity Logarithmic in the size of the container.
10365 
10366  @liveexample{The example below shows how object elements can be read using
10367  the `[]` operator.,operatorarray__key_type_const}
10368 
10369  @sa @ref at(const typename object_t::key_type&) for access by reference
10370  with range checking
10371  @sa @ref value() for access by value with a default value
10372 
10373  @since version 1.1.0
10374  */
10375  template<typename T>
10376  const_reference operator[](T* key) const
10377  {
10378  // at only works for objects
10379  if (JSON_LIKELY(is_object()))
10380  {
10381  assert(m_value.object->find(key) != m_value.object->end());
10382  return m_value.object->find(key)->second;
10383  }
10384 
10385  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10386  }
10387 
10388  /*!
10389  @brief access specified object element with default value
10390 
10391  Returns either a copy of an object's element at the specified key @a key
10392  or a given default value if no element with key @a key exists.
10393 
10394  The function is basically equivalent to executing
10395  @code {.cpp}
10396  try {
10397  return at(key);
10398  } catch(out_of_range) {
10399  return default_value;
10400  }
10401  @endcode
10402 
10403  @note Unlike @ref at(const typename object_t::key_type&), this function
10404  does not throw if the given key @a key was not found.
10405 
10406  @note Unlike @ref operator[](const typename object_t::key_type& key), this
10407  function does not implicitly add an element to the position defined by @a
10408  key. This function is furthermore also applicable to const objects.
10409 
10410  @param[in] key key of the element to access
10411  @param[in] default_value the value to return if @a key is not found
10412 
10413  @tparam ValueType type compatible to JSON values, for instance `int` for
10414  JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
10415  JSON arrays. Note the type of the expected value at @a key and the default
10416  value @a default_value must be compatible.
10417 
10418  @return copy of the element at key @a key or @a default_value if @a key
10419  is not found
10420 
10421  @throw type_error.306 if the JSON value is not an object; in that case,
10422  using `value()` with a key makes no sense.
10423 
10424  @complexity Logarithmic in the size of the container.
10425 
10426  @liveexample{The example below shows how object elements can be queried
10427  with a default value.,basic_json__value}
10428 
10429  @sa @ref at(const typename object_t::key_type&) for access by reference
10430  with range checking
10431  @sa @ref operator[](const typename object_t::key_type&) for unchecked
10432  access by reference
10433 
10434  @since version 1.0.0
10435  */
10436  template<class ValueType, typename std::enable_if<
10437  std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
10438  ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
10439  {
10440  // at only works for objects
10441  if (JSON_LIKELY(is_object()))
10442  {
10443  // if key is found, return value and given default value otherwise
10444  const auto it = find(key);
10445  if (it != end())
10446  {
10447  return *it;
10448  }
10449 
10450  return default_value;
10451  }
10452 
10453  JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
10454  }
10455 
10456  /*!
10457  @brief overload for a default value of type const char*
10458  @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
10459  */
10460  string_t value(const typename object_t::key_type& key, const char* default_value) const
10461  {
10462  return value(key, string_t(default_value));
10463  }
10464 
10465  /*!
10466  @brief access specified object element via JSON Pointer with default value
10467 
10468  Returns either a copy of an object's element at the specified key @a key
10469  or a given default value if no element with key @a key exists.
10470 
10471  The function is basically equivalent to executing
10472  @code {.cpp}
10473  try {
10474  return at(ptr);
10475  } catch(out_of_range) {
10476  return default_value;
10477  }
10478  @endcode
10479 
10480  @note Unlike @ref at(const json_pointer&), this function does not throw
10481  if the given key @a key was not found.
10482 
10483  @param[in] ptr a JSON pointer to the element to access
10484  @param[in] default_value the value to return if @a ptr found no value
10485 
10486  @tparam ValueType type compatible to JSON values, for instance `int` for
10487  JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
10488  JSON arrays. Note the type of the expected value at @a key and the default
10489  value @a default_value must be compatible.
10490 
10491  @return copy of the element at key @a key or @a default_value if @a key
10492  is not found
10493 
10494  @throw type_error.306 if the JSON value is not an objec; in that case,
10495  using `value()` with a key makes no sense.
10496 
10497  @complexity Logarithmic in the size of the container.
10498 
10499  @liveexample{The example below shows how object elements can be queried
10500  with a default value.,basic_json__value_ptr}
10501 
10502  @sa @ref operator[](const json_pointer&) for unchecked access by reference
10503 
10504  @since version 2.0.2
10505  */
10506  template<class ValueType, typename std::enable_if<
10507  std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
10508  ValueType value(const json_pointer& ptr, const ValueType& default_value) const
10509  {
10510  // at only works for objects
10511  if (JSON_LIKELY(is_object()))
10512  {
10513  // if pointer resolves a value, return it or use default value
10514  JSON_TRY
10515  {
10516  return ptr.get_checked(this);
10517  }
10518  JSON_CATCH (out_of_range&)
10519  {
10520  return default_value;
10521  }
10522  }
10524  JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
10525  }
10526 
10527  /*!
10528  @brief overload for a default value of type const char*
10529  @copydoc basic_json::value(const json_pointer&, ValueType) const
10530  */
10531  string_t value(const json_pointer& ptr, const char* default_value) const
10532  {
10533  return value(ptr, string_t(default_value));
10534  }
10535 
10536  /*!
10537  @brief access the first element
10538 
10539  Returns a reference to the first element in the container. For a JSON
10540  container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
10541 
10542  @return In case of a structured type (array or object), a reference to the
10543  first element is returned. In case of number, string, or boolean values, a
10544  reference to the value is returned.
10545 
10546  @complexity Constant.
10547 
10548  @pre The JSON value must not be `null` (would throw `std::out_of_range`)
10549  or an empty array or object (undefined behavior, **guarded by
10550  assertions**).
10551  @post The JSON value remains unchanged.
10552 
10553  @throw invalid_iterator.214 when called on `null` value
10554 
10555  @liveexample{The following code shows an example for `front()`.,front}
10556 
10557  @sa @ref back() -- access the last element
10558 
10559  @since version 1.0.0
10560  */
10561  reference front()
10562  {
10563  return *begin();
10564  }
10565 
10566  /*!
10567  @copydoc basic_json::front()
10568  */
10569  const_reference front() const
10570  {
10571  return *cbegin();
10572  }
10573 
10574  /*!
10575  @brief access the last element
10577  Returns a reference to the last element in the container. For a JSON
10578  container `c`, the expression `c.back()` is equivalent to
10579  @code {.cpp}
10580  auto tmp = c.end();
10581  --tmp;
10582  return *tmp;
10583  @endcode
10585  @return In case of a structured type (array or object), a reference to the
10586  last element is returned. In case of number, string, or boolean values, a
10587  reference to the value is returned.
10588 
10589  @complexity Constant.
10590 
10591  @pre The JSON value must not be `null` (would throw `std::out_of_range`)
10592  or an empty array or object (undefined behavior, **guarded by
10593  assertions**).
10594  @post The JSON value remains unchanged.
10595 
10596  @throw invalid_iterator.214 when called on a `null` value. See example
10597  below.
10598 
10599  @liveexample{The following code shows an example for `back()`.,back}
10600 
10601  @sa @ref front() -- access the first element
10602 
10603  @since version 1.0.0
10604  */
10605  reference back()
10606  {
10607  auto tmp = end();
10608  --tmp;
10609  return *tmp;
10610  }
10611 
10612  /*!
10613  @copydoc basic_json::back()
10614  */
10615  const_reference back() const
10616  {
10617  auto tmp = cend();
10618  --tmp;
10619  return *tmp;
10620  }
10621 
10622  /*!
10623  @brief remove element given an iterator
10624 
10625  Removes the element specified by iterator @a pos. The iterator @a pos must
10626  be valid and dereferenceable. Thus the `end()` iterator (which is valid,
10627  but is not dereferenceable) cannot be used as a value for @a pos.
10628 
10629  If called on a primitive type other than `null`, the resulting JSON value
10630  will be `null`.
10631 
10632  @param[in] pos iterator to the element to remove
10633  @return Iterator following the last removed element. If the iterator @a
10634  pos refers to the last element, the `end()` iterator is returned.
10635 
10636  @tparam IteratorType an @ref iterator or @ref const_iterator
10637 
10638  @post Invalidates iterators and references at or after the point of the
10639  erase, including the `end()` iterator.
10640 
10641  @throw type_error.307 if called on a `null` value; example: `"cannot use
10642  erase() with null"`
10643  @throw invalid_iterator.202 if called on an iterator which does not belong
10644  to the current JSON value; example: `"iterator does not fit current
10645  value"`
10646  @throw invalid_iterator.205 if called on a primitive type with invalid
10647  iterator (i.e., any iterator which is not `begin()`); example: `"iterator
10648  out of range"`
10649 
10650  @complexity The complexity depends on the type:
10651  - objects: amortized constant
10652  - arrays: linear in distance between @a pos and the end of the container
10653  - strings: linear in the length of the string
10654  - other types: constant
10655 
10656  @liveexample{The example shows the result of `erase()` for different JSON
10657  types.,erase__IteratorType}
10658 
10659  @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
10660  the given range
10661  @sa @ref erase(const typename object_t::key_type&) -- removes the element
10662  from an object at the given key
10663  @sa @ref erase(const size_type) -- removes the element from an array at
10664  the given index
10665 
10666  @since version 1.0.0
10667  */
10668  template<class IteratorType, typename std::enable_if<
10669  std::is_same<IteratorType, typename basic_json_t::iterator>::value or
10670  std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
10671  = 0>
10672  IteratorType erase(IteratorType pos)
10673  {
10674  // make sure iterator fits the current value
10675  if (JSON_UNLIKELY(this != pos.m_object))
10676  {
10677  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
10678  }
10679 
10680  IteratorType result = end();
10681 
10682  switch (m_type)
10683  {
10684  case value_t::boolean:
10685  case value_t::number_float:
10686  case value_t::number_integer:
10687  case value_t::number_unsigned:
10688  case value_t::string:
10689  {
10690  if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
10691  {
10692  JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
10693  }
10694 
10695  if (is_string())
10696  {
10697  AllocatorType<string_t> alloc;
10698  std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
10699  std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
10700  m_value.string = nullptr;
10701  }
10702 
10703  m_type = value_t::null;
10704  assert_invariant();
10705  break;
10706  }
10707 
10708  case value_t::object:
10709  {
10710  result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
10711  break;
10712  }
10713 
10714  case value_t::array:
10715  {
10716  result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
10717  break;
10718  }
10719 
10720  default:
10721  JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
10722  }
10723 
10724  return result;
10725  }
10726 
10727  /*!
10728  @brief remove elements given an iterator range
10729 
10730  Removes the element specified by the range `[first; last)`. The iterator
10731  @a first does not need to be dereferenceable if `first == last`: erasing
10732  an empty range is a no-op.
10733 
10734  If called on a primitive type other than `null`, the resulting JSON value
10735  will be `null`.
10736 
10737  @param[in] first iterator to the beginning of the range to remove
10738  @param[in] last iterator past the end of the range to remove
10739  @return Iterator following the last removed element. If the iterator @a
10740  second refers to the last element, the `end()` iterator is returned.
10741 
10742  @tparam IteratorType an @ref iterator or @ref const_iterator
10743 
10744  @post Invalidates iterators and references at or after the point of the
10745  erase, including the `end()` iterator.
10746 
10747  @throw type_error.307 if called on a `null` value; example: `"cannot use
10748  erase() with null"`
10749  @throw invalid_iterator.203 if called on iterators which does not belong
10750  to the current JSON value; example: `"iterators do not fit current value"`
10751  @throw invalid_iterator.204 if called on a primitive type with invalid
10752  iterators (i.e., if `first != begin()` and `last != end()`); example:
10753  `"iterators out of range"`
10754 
10755  @complexity The complexity depends on the type:
10756  - objects: `log(size()) + std::distance(first, last)`
10757  - arrays: linear in the distance between @a first and @a last, plus linear
10758  in the distance between @a last and end of the container
10759  - strings: linear in the length of the string
10760  - other types: constant
10761 
10762  @liveexample{The example shows the result of `erase()` for different JSON
10763  types.,erase__IteratorType_IteratorType}
10764 
10765  @sa @ref erase(IteratorType) -- removes the element at a given position
10766  @sa @ref erase(const typename object_t::key_type&) -- removes the element
10767  from an object at the given key
10768  @sa @ref erase(const size_type) -- removes the element from an array at
10769  the given index
10770 
10771  @since version 1.0.0
10772  */
10773  template<class IteratorType, typename std::enable_if<
10774  std::is_same<IteratorType, typename basic_json_t::iterator>::value or
10775  std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
10776  = 0>
10777  IteratorType erase(IteratorType first, IteratorType last)
10778  {
10779  // make sure iterator fits the current value
10780  if (JSON_UNLIKELY(this != first.m_object or this != last.m_object))
10781  {
10782  JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
10783  }
10784 
10785  IteratorType result = end();
10786 
10787  switch (m_type)
10788  {
10789  case value_t::boolean:
10790  case value_t::number_float:
10791  case value_t::number_integer:
10792  case value_t::number_unsigned:
10793  case value_t::string:
10794  {
10795  if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin()
10796  or not last.m_it.primitive_iterator.is_end()))
10797  {
10798  JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
10799  }
10800 
10801  if (is_string())
10802  {
10803  AllocatorType<string_t> alloc;
10804  std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
10805  std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
10806  m_value.string = nullptr;
10807  }
10808 
10809  m_type = value_t::null;
10810  assert_invariant();
10811  break;
10812  }
10813 
10814  case value_t::object:
10815  {
10816  result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
10817  last.m_it.object_iterator);
10818  break;
10819  }
10820 
10821  case value_t::array:
10822  {
10823  result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
10824  last.m_it.array_iterator);
10825  break;
10826  }
10827 
10828  default:
10829  JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
10830  }
10831 
10832  return result;
10833  }
10834 
10835  /*!
10836  @brief remove element from a JSON object given a key
10837 
10838  Removes elements from a JSON object with the key value @a key.
10839 
10840  @param[in] key value of the elements to remove
10841 
10842  @return Number of elements removed. If @a ObjectType is the default
10843  `std::map` type, the return value will always be `0` (@a key was not
10844  found) or `1` (@a key was found).
10845 
10846  @post References and iterators to the erased elements are invalidated.
10847  Other references and iterators are not affected.
10848 
10849  @throw type_error.307 when called on a type other than JSON object;
10850  example: `"cannot use erase() with null"`
10851 
10852  @complexity `log(size()) + count(key)`
10853 
10854  @liveexample{The example shows the effect of `erase()`.,erase__key_type}
10855 
10856  @sa @ref erase(IteratorType) -- removes the element at a given position
10857  @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
10858  the given range
10859  @sa @ref erase(const size_type) -- removes the element from an array at
10860  the given index
10861 
10862  @since version 1.0.0
10863  */
10864  size_type erase(const typename object_t::key_type& key)
10865  {
10866  // this erase only works for objects
10867  if (JSON_LIKELY(is_object()))
10868  {
10869  return m_value.object->erase(key);
10870  }
10871 
10872  JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
10873  }
10874 
10875  /*!
10876  @brief remove element from a JSON array given an index
10877 
10878  Removes element from a JSON array at the index @a idx.
10880  @param[in] idx index of the element to remove
10881 
10882  @throw type_error.307 when called on a type other than JSON object;
10883  example: `"cannot use erase() with null"`
10884  @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
10885  is out of range"`
10886 
10887  @complexity Linear in distance between @a idx and the end of the container.
10888 
10889  @liveexample{The example shows the effect of `erase()`.,erase__size_type}
10890 
10891  @sa @ref erase(IteratorType) -- removes the element at a given position
10892  @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
10893  the given range
10894  @sa @ref erase(const typename object_t::key_type&) -- removes the element
10895  from an object at the given key
10896 
10897  @since version 1.0.0
10898  */
10899  void erase(const size_type idx)
10900  {
10901  // this erase only works for arrays
10902  if (JSON_LIKELY(is_array()))
10903  {
10904  if (JSON_UNLIKELY(idx >= size()))
10905  {
10906  JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
10907  }
10908 
10909  m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
10910  }
10911  else
10912  {
10913  JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
10914  }
10915  }
10916 
10917  /// @}
10918 
10919 
10920  ////////////
10921  // lookup //
10922  ////////////
10923 
10924  /// @name lookup
10925  /// @{
10926 
10927  /*!
10928  @brief find an element in a JSON object
10929 
10930  Finds an element in a JSON object with key equivalent to @a key. If the
10931  element is not found or the JSON value is not an object, end() is
10932  returned.
10933 
10934  @note This method always returns @ref end() when executed on a JSON type
10935  that is not an object.
10936 
10937  @param[in] key key value of the element to search for.
10938 
10939  @return Iterator to an element with key equivalent to @a key. If no such
10940  element is found or the JSON value is not an object, past-the-end (see
10941  @ref end()) iterator is returned.
10942 
10943  @complexity Logarithmic in the size of the JSON object.
10944 
10945  @liveexample{The example shows how `find()` is used.,find__key_type}
10946 
10947  @since version 1.0.0
10948  */
10949  template<typename KeyT>
10950  iterator find(KeyT&& key)
10951  {
10952  auto result = end();
10953 
10954  if (is_object())
10955  {
10956  result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
10957  }
10958 
10959  return result;
10960  }
10961 
10962  /*!
10963  @brief find an element in a JSON object
10964  @copydoc find(KeyT&&)
10965  */
10966  template<typename KeyT>
10967  const_iterator find(KeyT&& key) const
10968  {
10969  auto result = cend();
10970 
10971  if (is_object())
10972  {
10973  result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
10974  }
10975 
10976  return result;
10977  }
10978 
10979  /*!
10980  @brief returns the number of occurrences of a key in a JSON object
10981 
10982  Returns the number of elements with key @a key. If ObjectType is the
10983  default `std::map` type, the return value will always be `0` (@a key was
10984  not found) or `1` (@a key was found).
10985 
10986  @note This method always returns `0` when executed on a JSON type that is
10987  not an object.
10988 
10989  @param[in] key key value of the element to count
10990 
10991  @return Number of elements with key @a key. If the JSON value is not an
10992  object, the return value will be `0`.
10993 
10994  @complexity Logarithmic in the size of the JSON object.
10995 
10996  @liveexample{The example shows how `count()` is used.,count}
10997 
10998  @since version 1.0.0
10999  */
11000  template<typename KeyT>
11001  size_type count(KeyT&& key) const
11002  {
11003  // return 0 for all nonobject types
11004  return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
11005  }
11006 
11007  /// @}
11008 
11009 
11010  ///////////////
11011  // iterators //
11012  ///////////////
11013 
11014  /// @name iterators
11015  /// @{
11017  /*!
11018  @brief returns an iterator to the first element
11019 
11020  Returns an iterator to the first element.
11021 
11022  @image html range-begin-end.svg "Illustration from cppreference.com"
11023 
11024  @return iterator to the first element
11025 
11026  @complexity Constant.
11027 
11028  @requirement This function helps `basic_json` satisfying the
11029  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11030  requirements:
11031  - The complexity is constant.
11032 
11033  @liveexample{The following code shows an example for `begin()`.,begin}
11034 
11035  @sa @ref cbegin() -- returns a const iterator to the beginning
11036  @sa @ref end() -- returns an iterator to the end
11037  @sa @ref cend() -- returns a const iterator to the end
11038 
11039  @since version 1.0.0
11040  */
11041  iterator begin() noexcept
11042  {
11043  iterator result(this);
11044  result.set_begin();
11045  return result;
11046  }
11047 
11048  /*!
11049  @copydoc basic_json::cbegin()
11050  */
11051  const_iterator begin() const noexcept
11052  {
11053  return cbegin();
11054  }
11055 
11056  /*!
11057  @brief returns a const iterator to the first element
11058 
11059  Returns a const iterator to the first element.
11060 
11061  @image html range-begin-end.svg "Illustration from cppreference.com"
11062 
11063  @return const iterator to the first element
11064 
11065  @complexity Constant.
11067  @requirement This function helps `basic_json` satisfying the
11068  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11069  requirements:
11070  - The complexity is constant.
11071  - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
11072 
11073  @liveexample{The following code shows an example for `cbegin()`.,cbegin}
11074 
11075  @sa @ref begin() -- returns an iterator to the beginning
11076  @sa @ref end() -- returns an iterator to the end
11077  @sa @ref cend() -- returns a const iterator to the end
11078 
11079  @since version 1.0.0
11080  */
11081  const_iterator cbegin() const noexcept
11082  {
11083  const_iterator result(this);
11084  result.set_begin();
11085  return result;
11086  }
11087 
11088  /*!
11089  @brief returns an iterator to one past the last element
11090 
11091  Returns an iterator to one past the last element.
11092 
11093  @image html range-begin-end.svg "Illustration from cppreference.com"
11094 
11095  @return iterator one past the last element
11097  @complexity Constant.
11098 
11099  @requirement This function helps `basic_json` satisfying the
11100  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11101  requirements:
11102  - The complexity is constant.
11103 
11104  @liveexample{The following code shows an example for `end()`.,end}
11105 
11106  @sa @ref cend() -- returns a const iterator to the end
11107  @sa @ref begin() -- returns an iterator to the beginning
11108  @sa @ref cbegin() -- returns a const iterator to the beginning
11109 
11110  @since version 1.0.0
11111  */
11112  iterator end() noexcept
11113  {
11114  iterator result(this);
11115  result.set_end();
11116  return result;
11117  }
11118 
11119  /*!
11120  @copydoc basic_json::cend()
11121  */
11122  const_iterator end() const noexcept
11123  {
11124  return cend();
11125  }
11126 
11127  /*!
11128  @brief returns a const iterator to one past the last element
11129 
11130  Returns a const iterator to one past the last element.
11131 
11132  @image html range-begin-end.svg "Illustration from cppreference.com"
11133 
11134  @return const iterator one past the last element
11135 
11136  @complexity Constant.
11138  @requirement This function helps `basic_json` satisfying the
11139  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11140  requirements:
11141  - The complexity is constant.
11142  - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
11143 
11144  @liveexample{The following code shows an example for `cend()`.,cend}
11145 
11146  @sa @ref end() -- returns an iterator to the end
11147  @sa @ref begin() -- returns an iterator to the beginning
11148  @sa @ref cbegin() -- returns a const iterator to the beginning
11149 
11150  @since version 1.0.0
11151  */
11152  const_iterator cend() const noexcept
11153  {
11154  const_iterator result(this);
11155  result.set_end();
11156  return result;
11157  }
11158 
11159  /*!
11160  @brief returns an iterator to the reverse-beginning
11161 
11162  Returns an iterator to the reverse-beginning; that is, the last element.
11163 
11164  @image html range-rbegin-rend.svg "Illustration from cppreference.com"
11165 
11166  @complexity Constant.
11168  @requirement This function helps `basic_json` satisfying the
11169  [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
11170  requirements:
11171  - The complexity is constant.
11172  - Has the semantics of `reverse_iterator(end())`.
11173 
11174  @liveexample{The following code shows an example for `rbegin()`.,rbegin}
11175 
11176  @sa @ref crbegin() -- returns a const reverse iterator to the beginning
11177  @sa @ref rend() -- returns a reverse iterator to the end
11178  @sa @ref crend() -- returns a const reverse iterator to the end
11179 
11180  @since version 1.0.0
11181  */
11182  reverse_iterator rbegin() noexcept
11183  {
11184  return reverse_iterator(end());
11185  }
11186 
11187  /*!
11188  @copydoc basic_json::crbegin()
11189  */
11190  const_reverse_iterator rbegin() const noexcept
11191  {
11192  return crbegin();
11193  }
11194 
11195  /*!
11196  @brief returns an iterator to the reverse-end
11198  Returns an iterator to the reverse-end; that is, one before the first
11199  element.
11200 
11201  @image html range-rbegin-rend.svg "Illustration from cppreference.com"
11202 
11203  @complexity Constant.
11204 
11205  @requirement This function helps `basic_json` satisfying the
11206  [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
11207  requirements:
11208  - The complexity is constant.
11209  - Has the semantics of `reverse_iterator(begin())`.
11210 
11211  @liveexample{The following code shows an example for `rend()`.,rend}
11212 
11213  @sa @ref crend() -- returns a const reverse iterator to the end
11214  @sa @ref rbegin() -- returns a reverse iterator to the beginning
11215  @sa @ref crbegin() -- returns a const reverse iterator to the beginning
11216 
11217  @since version 1.0.0
11218  */
11219  reverse_iterator rend() noexcept
11220  {
11221  return reverse_iterator(begin());
11222  }
11223 
11224  /*!
11225  @copydoc basic_json::crend()
11226  */
11227  const_reverse_iterator rend() const noexcept
11228  {
11229  return crend();
11230  }
11231 
11232  /*!
11233  @brief returns a const reverse iterator to the last element
11235  Returns a const iterator to the reverse-beginning; that is, the last
11236  element.
11237 
11238  @image html range-rbegin-rend.svg "Illustration from cppreference.com"
11239 
11240  @complexity Constant.
11241 
11242  @requirement This function helps `basic_json` satisfying the
11243  [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
11244  requirements:
11245  - The complexity is constant.
11246  - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
11247 
11248  @liveexample{The following code shows an example for `crbegin()`.,crbegin}
11249 
11250  @sa @ref rbegin() -- returns a reverse iterator to the beginning
11251  @sa @ref rend() -- returns a reverse iterator to the end
11252  @sa @ref crend() -- returns a const reverse iterator to the end
11253 
11254  @since version 1.0.0
11255  */
11256  const_reverse_iterator crbegin() const noexcept
11257  {
11258  return const_reverse_iterator(cend());
11259  }
11260 
11261  /*!
11262  @brief returns a const reverse iterator to one before the first
11263 
11264  Returns a const reverse iterator to the reverse-end; that is, one before
11265  the first element.
11266 
11267  @image html range-rbegin-rend.svg "Illustration from cppreference.com"
11268 
11269  @complexity Constant.
11270 
11271  @requirement This function helps `basic_json` satisfying the
11272  [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
11273  requirements:
11274  - The complexity is constant.
11275  - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
11276 
11277  @liveexample{The following code shows an example for `crend()`.,crend}
11278 
11279  @sa @ref rend() -- returns a reverse iterator to the end
11280  @sa @ref rbegin() -- returns a reverse iterator to the beginning
11281  @sa @ref crbegin() -- returns a const reverse iterator to the beginning
11282 
11283  @since version 1.0.0
11284  */
11285  const_reverse_iterator crend() const noexcept
11286  {
11287  return const_reverse_iterator(cbegin());
11288  }
11289 
11290  public:
11291  /*!
11292  @brief wrapper to access iterator member functions in range-based for
11293 
11294  This function allows to access @ref iterator::key() and @ref
11295  iterator::value() during range-based for loops. In these loops, a
11296  reference to the JSON values is returned, so there is no access to the
11297  underlying iterator.
11298 
11299  For loop without iterator_wrapper:
11301  @code{cpp}
11302  for (auto it = j_object.begin(); it != j_object.end(); ++it)
11303  {
11304  std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
11305  }
11306  @endcode
11307 
11308  Range-based for loop without iterator proxy:
11309 
11310  @code{cpp}
11311  for (auto it : j_object)
11312  {
11313  // "it" is of type json::reference and has no key() member
11314  std::cout << "value: " << it << '\n';
11315  }
11316  @endcode
11317 
11318  Range-based for loop with iterator proxy:
11319 
11320  @code{cpp}
11321  for (auto it : json::iterator_wrapper(j_object))
11322  {
11323  std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
11324  }
11325  @endcode
11326 
11327  @note When iterating over an array, `key()` will return the index of the
11328  element as string (see example).
11329 
11330  @param[in] ref reference to a JSON value
11331  @return iteration proxy object wrapping @a ref with an interface to use in
11332  range-based for loops
11333 
11334  @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
11335 
11336  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
11337  changes in the JSON value.
11338 
11339  @complexity Constant.
11340 
11341  @note The name of this function is not yet final and may change in the
11342  future.
11343  */
11344  static iteration_proxy<iterator> iterator_wrapper(reference ref)
11345  {
11346  return iteration_proxy<iterator>(ref);
11347  }
11348 
11349  /*!
11350  @copydoc iterator_wrapper(reference)
11351  */
11352  static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref)
11353  {
11354  return iteration_proxy<const_iterator>(ref);
11355  }
11356 
11357  /// @}
11358 
11360  //////////////
11361  // capacity //
11362  //////////////
11363 
11364  /// @name capacity
11365  /// @{
11366 
11367  /*!
11368  @brief checks whether the container is empty.
11369 
11370  Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
11371 
11372  @return The return value depends on the different types and is
11373  defined as follows:
11374  Value type | return value
11375  ----------- | -------------
11376  null | `true`
11377  boolean | `false`
11378  string | `false`
11379  number | `false`
11380  object | result of function `object_t::empty()`
11381  array | result of function `array_t::empty()`
11382 
11383  @liveexample{The following code uses `empty()` to check if a JSON
11384  object contains any elements.,empty}
11385 
11386  @complexity Constant, as long as @ref array_t and @ref object_t satisfy
11387  the Container concept; that is, their `empty()` functions have constant
11388  complexity.
11389 
11390  @iterators No changes.
11391 
11392  @exceptionsafety No-throw guarantee: this function never throws exceptions.
11393 
11394  @note This function does not return whether a string stored as JSON value
11395  is empty - it returns whether the JSON container itself is empty which is
11396  false in the case of a string.
11397 
11398  @requirement This function helps `basic_json` satisfying the
11399  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11400  requirements:
11401  - The complexity is constant.
11402  - Has the semantics of `begin() == end()`.
11403 
11404  @sa @ref size() -- returns the number of elements
11405 
11406  @since version 1.0.0
11407  */
11408  bool empty() const noexcept
11409  {
11410  switch (m_type)
11411  {
11412  case value_t::null:
11413  {
11414  // null values are empty
11415  return true;
11416  }
11417 
11418  case value_t::array:
11419  {
11420  // delegate call to array_t::empty()
11421  return m_value.array->empty();
11422  }
11424  case value_t::object:
11425  {
11426  // delegate call to object_t::empty()
11427  return m_value.object->empty();
11428  }
11429 
11430  default:
11431  {
11432  // all other types are nonempty
11433  return false;
11434  }
11435  }
11436  }
11437 
11438  /*!
11439  @brief returns the number of elements
11440 
11441  Returns the number of elements in a JSON value.
11442 
11443  @return The return value depends on the different types and is
11444  defined as follows:
11445  Value type | return value
11446  ----------- | -------------
11447  null | `0`
11448  boolean | `1`
11449  string | `1`
11450  number | `1`
11451  object | result of function object_t::size()
11452  array | result of function array_t::size()
11453 
11454  @liveexample{The following code calls `size()` on the different value
11455  types.,size}
11456 
11457  @complexity Constant, as long as @ref array_t and @ref object_t satisfy
11458  the Container concept; that is, their size() functions have constant
11459  complexity.
11460 
11461  @iterators No changes.
11462 
11463  @exceptionsafety No-throw guarantee: this function never throws exceptions.
11464 
11465  @note This function does not return the length of a string stored as JSON
11466  value - it returns the number of elements in the JSON value which is 1 in
11467  the case of a string.
11468 
11469  @requirement This function helps `basic_json` satisfying the
11470  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11471  requirements:
11472  - The complexity is constant.
11473  - Has the semantics of `std::distance(begin(), end())`.
11474 
11475  @sa @ref empty() -- checks whether the container is empty
11476  @sa @ref max_size() -- returns the maximal number of elements
11477 
11478  @since version 1.0.0
11479  */
11480  size_type size() const noexcept
11481  {
11482  switch (m_type)
11483  {
11484  case value_t::null:
11485  {
11486  // null values are empty
11487  return 0;
11488  }
11489 
11490  case value_t::array:
11491  {
11492  // delegate call to array_t::size()
11493  return m_value.array->size();
11494  }
11496  case value_t::object:
11497  {
11498  // delegate call to object_t::size()
11499  return m_value.object->size();
11500  }
11501 
11502  default:
11503  {
11504  // all other types have size 1
11505  return 1;
11506  }
11507  }
11508  }
11509 
11510  /*!
11511  @brief returns the maximum possible number of elements
11512 
11513  Returns the maximum number of elements a JSON value is able to hold due to
11514  system or library implementation limitations, i.e. `std::distance(begin(),
11515  end())` for the JSON value.
11516 
11517  @return The return value depends on the different types and is
11518  defined as follows:
11519  Value type | return value
11520  ----------- | -------------
11521  null | `0` (same as `size()`)
11522  boolean | `1` (same as `size()`)
11523  string | `1` (same as `size()`)
11524  number | `1` (same as `size()`)
11525  object | result of function `object_t::max_size()`
11526  array | result of function `array_t::max_size()`
11527 
11528  @liveexample{The following code calls `max_size()` on the different value
11529  types. Note the output is implementation specific.,max_size}
11530 
11531  @complexity Constant, as long as @ref array_t and @ref object_t satisfy
11532  the Container concept; that is, their `max_size()` functions have constant
11533  complexity.
11534 
11535  @iterators No changes.
11536 
11537  @exceptionsafety No-throw guarantee: this function never throws exceptions.
11538 
11539  @requirement This function helps `basic_json` satisfying the
11540  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11541  requirements:
11542  - The complexity is constant.
11543  - Has the semantics of returning `b.size()` where `b` is the largest
11544  possible JSON value.
11545 
11546  @sa @ref size() -- returns the number of elements
11547 
11548  @since version 1.0.0
11549  */
11550  size_type max_size() const noexcept
11551  {
11552  switch (m_type)
11553  {
11554  case value_t::array:
11555  {
11556  // delegate call to array_t::max_size()
11557  return m_value.array->max_size();
11558  }
11559 
11560  case value_t::object:
11561  {
11562  // delegate call to object_t::max_size()
11563  return m_value.object->max_size();
11564  }
11566  default:
11567  {
11568  // all other types have max_size() == size()
11569  return size();
11570  }
11571  }
11572  }
11573 
11574  /// @}
11575 
11576 
11577  ///////////////
11578  // modifiers //
11579  ///////////////
11580 
11581  /// @name modifiers
11582  /// @{
11583 
11584  /*!
11585  @brief clears the contents
11586 
11587  Clears the content of a JSON value and resets it to the default value as
11588  if @ref basic_json(value_t) would have been called with the current value
11589  type from @ref type():
11590 
11591  Value type | initial value
11592  ----------- | -------------
11593  null | `null`
11594  boolean | `false`
11595  string | `""`
11596  number | `0`
11597  object | `{}`
11598  array | `[]`
11599 
11600  @post Has the same effect as calling
11601  @code {.cpp}
11602  *this = basic_json(type());
11603  @endcode
11604 
11605  @liveexample{The example below shows the effect of `clear()` to different
11606  JSON types.,clear}
11607 
11608  @complexity Linear in the size of the JSON value.
11609 
11610  @iterators All iterators, pointers and references related to this container
11611  are invalidated.
11612 
11613  @exceptionsafety No-throw guarantee: this function never throws exceptions.
11614 
11615  @sa @ref basic_json(value_t) -- constructor that creates an object with the
11616  same value than calling `clear()`
11617 
11618  @since version 1.0.0
11619  */
11620  void clear() noexcept
11621  {
11622  switch (m_type)
11623  {
11624  case value_t::number_integer:
11625  {
11626  m_value.number_integer = 0;
11627  break;
11628  }
11629 
11630  case value_t::number_unsigned:
11631  {
11632  m_value.number_unsigned = 0;
11633  break;
11634  }
11636  case value_t::number_float:
11637  {
11638  m_value.number_float = 0.0;
11639  break;
11640  }
11641 
11642  case value_t::boolean:
11643  {
11644  m_value.boolean = false;
11645  break;
11646  }
11647 
11648  case value_t::string:
11649  {
11650  m_value.string->clear();
11651  break;
11652  }
11653 
11654  case value_t::array:
11655  {
11656  m_value.array->clear();
11657  break;
11658  }
11659 
11660  case value_t::object:
11661  {
11662  m_value.object->clear();
11663  break;
11664  }
11665 
11666  default:
11667  break;
11668  }
11669  }
11670 
11671  /*!
11672  @brief add an object to an array
11673 
11674  Appends the given element @a val to the end of the JSON value. If the
11675  function is called on a JSON null value, an empty array is created before
11676  appending @a val.
11677 
11678  @param[in] val the value to add to the JSON array
11679 
11680  @throw type_error.308 when called on a type other than JSON array or
11681  null; example: `"cannot use push_back() with number"`
11682 
11683  @complexity Amortized constant.
11684 
11685  @liveexample{The example shows how `push_back()` and `+=` can be used to
11686  add elements to a JSON array. Note how the `null` value was silently
11687  converted to a JSON array.,push_back}
11688 
11689  @since version 1.0.0
11690  */
11691  void push_back(basic_json&& val)
11692  {
11693  // push_back only works for null objects or arrays
11694  if (JSON_UNLIKELY(not(is_null() or is_array())))
11695  {
11696  JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
11697  }
11698 
11699  // transform null object into an array
11700  if (is_null())
11701  {
11702  m_type = value_t::array;
11703  m_value = value_t::array;
11704  assert_invariant();
11705  }
11707  // add element to array (move semantics)
11708  m_value.array->push_back(std::move(val));
11709  // invalidate object
11710  val.m_type = value_t::null;
11711  }
11712 
11713  /*!
11714  @brief add an object to an array
11715  @copydoc push_back(basic_json&&)
11716  */
11717  reference operator+=(basic_json&& val)
11718  {
11719  push_back(std::move(val));
11720  return *this;
11721  }
11722 
11723  /*!
11724  @brief add an object to an array
11725  @copydoc push_back(basic_json&&)
11726  */
11727  void push_back(const basic_json& val)
11728  {
11729  // push_back only works for null objects or arrays
11730  if (JSON_UNLIKELY(not(is_null() or is_array())))
11731  {
11732  JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
11733  }
11734 
11735  // transform null object into an array
11736  if (is_null())
11737  {
11738  m_type = value_t::array;
11739  m_value = value_t::array;
11740  assert_invariant();
11741  }
11743  // add element to array
11744  m_value.array->push_back(val);
11745  }
11746 
11747  /*!
11748  @brief add an object to an array
11749  @copydoc push_back(basic_json&&)
11750  */
11751  reference operator+=(const basic_json& val)
11752  {
11753  push_back(val);
11754  return *this;
11755  }
11756 
11757  /*!
11758  @brief add an object to an object
11759 
11760  Inserts the given element @a val to the JSON object. If the function is
11761  called on a JSON null value, an empty object is created before inserting
11762  @a val.
11763 
11764  @param[in] val the value to add to the JSON object
11765 
11766  @throw type_error.308 when called on a type other than JSON object or
11767  null; example: `"cannot use push_back() with number"`
11768 
11769  @complexity Logarithmic in the size of the container, O(log(`size()`)).
11770 
11771  @liveexample{The example shows how `push_back()` and `+=` can be used to
11772  add elements to a JSON object. Note how the `null` value was silently
11773  converted to a JSON object.,push_back__object_t__value}
11774 
11775  @since version 1.0.0
11776  */
11777  void push_back(const typename object_t::value_type& val)
11778  {
11779  // push_back only works for null objects or objects
11780  if (JSON_UNLIKELY(not(is_null() or is_object())))
11781  {
11782  JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
11783  }
11784 
11785  // transform null object into an object
11786  if (is_null())
11787  {
11788  m_type = value_t::object;
11789  m_value = value_t::object;
11790  assert_invariant();
11791  }
11793  // add element to array
11794  m_value.object->insert(val);
11795  }
11796 
11797  /*!
11798  @brief add an object to an object
11799  @copydoc push_back(const typename object_t::value_type&)
11800  */
11801  reference operator+=(const typename object_t::value_type& val)
11802  {
11803  push_back(val);
11804  return *this;
11805  }
11806 
11807  /*!
11808  @brief add an object to an object
11809 
11810  This function allows to use `push_back` with an initializer list. In case
11811 
11812  1. the current value is an object,
11813  2. the initializer list @a init contains only two elements, and
11814  3. the first element of @a init is a string,
11815 
11816  @a init is converted into an object element and added using
11817  @ref push_back(const typename object_t::value_type&). Otherwise, @a init
11818  is converted to a JSON value and added using @ref push_back(basic_json&&).
11819 
11820  @param[in] init an initializer list
11821 
11822  @complexity Linear in the size of the initializer list @a init.
11823 
11824  @note This function is required to resolve an ambiguous overload error,
11825  because pairs like `{"key", "value"}` can be both interpreted as
11826  `object_t::value_type` or `std::initializer_list<basic_json>`, see
11827  https://github.com/nlohmann/json/issues/235 for more information.
11828 
11829  @liveexample{The example shows how initializer lists are treated as
11830  objects when possible.,push_back__initializer_list}
11831  */
11832  void push_back(initializer_list_t init)
11833  {
11834  if (is_object() and init.size() == 2 and (*init.begin())->is_string())
11835  {
11836  basic_json&& key = init.begin()->moved_or_copied();
11837  push_back(typename object_t::value_type(
11838  std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
11839  }
11840  else
11841  {
11842  push_back(basic_json(init));
11843  }
11844  }
11845 
11846  /*!
11847  @brief add an object to an object
11848  @copydoc push_back(initializer_list_t)
11849  */
11850  reference operator+=(initializer_list_t init)
11851  {
11852  push_back(init);
11853  return *this;
11854  }
11855 
11856  /*!
11857  @brief add an object to an array
11858 
11859  Creates a JSON value from the passed parameters @a args to the end of the
11860  JSON value. If the function is called on a JSON null value, an empty array
11861  is created before appending the value created from @a args.
11862 
11863  @param[in] args arguments to forward to a constructor of @ref basic_json
11864  @tparam Args compatible types to create a @ref basic_json object
11866  @throw type_error.311 when called on a type other than JSON array or
11867  null; example: `"cannot use emplace_back() with number"`
11868 
11869  @complexity Amortized constant.
11870 
11871  @liveexample{The example shows how `push_back()` can be used to add
11872  elements to a JSON array. Note how the `null` value was silently converted
11873  to a JSON array.,emplace_back}
11874 
11875  @since version 2.0.8
11876  */
11877  template<class... Args>
11878  void emplace_back(Args&& ... args)
11879  {
11880  // emplace_back only works for null objects or arrays
11881  if (JSON_UNLIKELY(not(is_null() or is_array())))
11882  {
11883  JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
11884  }
11885 
11886  // transform null object into an array
11887  if (is_null())
11888  {
11889  m_type = value_t::array;
11890  m_value = value_t::array;
11891  assert_invariant();
11892  }
11894  // add element to array (perfect forwarding)
11895  m_value.array->emplace_back(std::forward<Args>(args)...);
11896  }
11897 
11898  /*!
11899  @brief add an object to an object if key does not exist
11900 
11901  Inserts a new element into a JSON object constructed in-place with the
11902  given @a args if there is no element with the key in the container. If the
11903  function is called on a JSON null value, an empty object is created before
11904  appending the value created from @a args.
11905 
11906  @param[in] args arguments to forward to a constructor of @ref basic_json
11907  @tparam Args compatible types to create a @ref basic_json object
11908 
11909  @return a pair consisting of an iterator to the inserted element, or the
11910  already-existing element if no insertion happened, and a bool
11911  denoting whether the insertion took place.
11912 
11913  @throw type_error.311 when called on a type other than JSON object or
11914  null; example: `"cannot use emplace() with number"`
11915 
11916  @complexity Logarithmic in the size of the container, O(log(`size()`)).
11917 
11918  @liveexample{The example shows how `emplace()` can be used to add elements
11919  to a JSON object. Note how the `null` value was silently converted to a
11920  JSON object. Further note how no value is added if there was already one
11921  value stored with the same key.,emplace}
11922 
11923  @since version 2.0.8
11924  */
11925  template<class... Args>
11926  std::pair<iterator, bool> emplace(Args&& ... args)
11927  {
11928  // emplace only works for null objects or arrays
11929  if (JSON_UNLIKELY(not(is_null() or is_object())))
11930  {
11931  JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
11932  }
11933 
11934  // transform null object into an object
11935  if (is_null())
11936  {
11937  m_type = value_t::object;
11938  m_value = value_t::object;
11939  assert_invariant();
11940  }
11942  // add element to array (perfect forwarding)
11943  auto res = m_value.object->emplace(std::forward<Args>(args)...);
11944  // create result iterator and set iterator to the result of emplace
11945  auto it = begin();
11946  it.m_it.object_iterator = res.first;
11947 
11948  // return pair of iterator and boolean
11949  return {it, res.second};
11950  }
11951 
11952  /*!
11953  @brief inserts element
11954 
11955  Inserts element @a val before iterator @a pos.
11956 
11957  @param[in] pos iterator before which the content will be inserted; may be
11958  the end() iterator
11959  @param[in] val element to insert
11960  @return iterator pointing to the inserted @a val.
11961 
11962  @throw type_error.309 if called on JSON values other than arrays;
11963  example: `"cannot use insert() with string"`
11964  @throw invalid_iterator.202 if @a pos is not an iterator of *this;
11965  example: `"iterator does not fit current value"`
11966 
11967  @complexity Constant plus linear in the distance between @a pos and end of
11968  the container.
11969 
11970  @liveexample{The example shows how `insert()` is used.,insert}
11971 
11972  @since version 1.0.0
11973  */
11974  iterator insert(const_iterator pos, const basic_json& val)
11975  {
11976  // insert only works for arrays
11977  if (JSON_LIKELY(is_array()))
11978  {
11979  // check if iterator pos fits to this JSON value
11980  if (JSON_UNLIKELY(pos.m_object != this))
11981  {
11982  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
11983  }
11984 
11985  // insert to array and return iterator
11986  iterator result(this);
11987  result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
11988  return result;
11989  }
11990 
11991  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
11992  }
11993 
11994  /*!
11995  @brief inserts element
11996  @copydoc insert(const_iterator, const basic_json&)
11997  */
11998  iterator insert(const_iterator pos, basic_json&& val)
11999  {
12000  return insert(pos, val);
12001  }
12002 
12003  /*!
12004  @brief inserts elements
12005 
12006  Inserts @a cnt copies of @a val before iterator @a pos.
12007 
12008  @param[in] pos iterator before which the content will be inserted; may be
12009  the end() iterator
12010  @param[in] cnt number of copies of @a val to insert
12011  @param[in] val element to insert
12012  @return iterator pointing to the first element inserted, or @a pos if
12013  `cnt==0`
12014 
12015  @throw type_error.309 if called on JSON values other than arrays; example:
12016  `"cannot use insert() with string"`
12017  @throw invalid_iterator.202 if @a pos is not an iterator of *this;
12018  example: `"iterator does not fit current value"`
12019 
12020  @complexity Linear in @a cnt plus linear in the distance between @a pos
12021  and end of the container.
12022 
12023  @liveexample{The example shows how `insert()` is used.,insert__count}
12024 
12025  @since version 1.0.0
12026  */
12027  iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
12028  {
12029  // insert only works for arrays
12030  if (JSON_LIKELY(is_array()))
12031  {
12032  // check if iterator pos fits to this JSON value
12033  if (JSON_UNLIKELY(pos.m_object != this))
12034  {
12035  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
12036  }
12037 
12038  // insert to array and return iterator
12039  iterator result(this);
12040  result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
12041  return result;
12042  }
12043 
12044  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12045  }
12046 
12047  /*!
12048  @brief inserts elements
12049 
12050  Inserts elements from range `[first, last)` before iterator @a pos.
12051 
12052  @param[in] pos iterator before which the content will be inserted; may be
12053  the end() iterator
12054  @param[in] first begin of the range of elements to insert
12055  @param[in] last end of the range of elements to insert
12056 
12057  @throw type_error.309 if called on JSON values other than arrays; example:
12058  `"cannot use insert() with string"`
12059  @throw invalid_iterator.202 if @a pos is not an iterator of *this;
12060  example: `"iterator does not fit current value"`
12061  @throw invalid_iterator.210 if @a first and @a last do not belong to the
12062  same JSON value; example: `"iterators do not fit"`
12063  @throw invalid_iterator.211 if @a first or @a last are iterators into
12064  container for which insert is called; example: `"passed iterators may not
12065  belong to container"`
12066 
12067  @return iterator pointing to the first element inserted, or @a pos if
12068  `first==last`
12069 
12070  @complexity Linear in `std::distance(first, last)` plus linear in the
12071  distance between @a pos and end of the container.
12072 
12073  @liveexample{The example shows how `insert()` is used.,insert__range}
12074 
12075  @since version 1.0.0
12076  */
12077  iterator insert(const_iterator pos, const_iterator first, const_iterator last)
12078  {
12079  // insert only works for arrays
12080  if (JSON_UNLIKELY(not is_array()))
12081  {
12082  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12083  }
12084 
12085  // check if iterator pos fits to this JSON value
12086  if (JSON_UNLIKELY(pos.m_object != this))
12087  {
12088  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
12089  }
12090 
12091  // check if range iterators belong to the same JSON object
12092  if (JSON_UNLIKELY(first.m_object != last.m_object))
12093  {
12094  JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
12095  }
12096 
12097  if (JSON_UNLIKELY(first.m_object == this))
12098  {
12099  JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
12100  }
12101 
12102  // insert to array and return iterator
12103  iterator result(this);
12104  result.m_it.array_iterator = m_value.array->insert(
12105  pos.m_it.array_iterator,
12106  first.m_it.array_iterator,
12107  last.m_it.array_iterator);
12108  return result;
12109  }
12110 
12111  /*!
12112  @brief inserts elements
12113 
12114  Inserts elements from initializer list @a ilist before iterator @a pos.
12115 
12116  @param[in] pos iterator before which the content will be inserted; may be
12117  the end() iterator
12118  @param[in] ilist initializer list to insert the values from
12119 
12120  @throw type_error.309 if called on JSON values other than arrays; example:
12121  `"cannot use insert() with string"`
12122  @throw invalid_iterator.202 if @a pos is not an iterator of *this;
12123  example: `"iterator does not fit current value"`
12124 
12125  @return iterator pointing to the first element inserted, or @a pos if
12126  `ilist` is empty
12127 
12128  @complexity Linear in `ilist.size()` plus linear in the distance between
12129  @a pos and end of the container.
12130 
12131  @liveexample{The example shows how `insert()` is used.,insert__ilist}
12132 
12133  @since version 1.0.0
12134  */
12135  iterator insert(const_iterator pos, initializer_list_t ilist)
12136  {
12137  // insert only works for arrays
12138  if (JSON_UNLIKELY(not is_array()))
12139  {
12140  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12141  }
12142 
12143  // check if iterator pos fits to this JSON value
12144  if (JSON_UNLIKELY(pos.m_object != this))
12145  {
12146  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
12147  }
12148 
12149  // insert to array and return iterator
12150  iterator result(this);
12151  result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end());
12152  return result;
12153  }
12154 
12155  /*!
12156  @brief inserts elements
12157 
12158  Inserts elements from range `[first, last)`.
12159 
12160  @param[in] first begin of the range of elements to insert
12161  @param[in] last end of the range of elements to insert
12162 
12163  @throw type_error.309 if called on JSON values other than objects; example:
12164  `"cannot use insert() with string"`
12165  @throw invalid_iterator.202 if iterator @a first or @a last does does not
12166  point to an object; example: `"iterators first and last must point to
12167  objects"`
12168  @throw invalid_iterator.210 if @a first and @a last do not belong to the
12169  same JSON value; example: `"iterators do not fit"`
12170 
12171  @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
12172  of elements to insert.
12173 
12174  @liveexample{The example shows how `insert()` is used.,insert__range_object}
12175 
12176  @since version 3.0.0
12177  */
12178  void insert(const_iterator first, const_iterator last)
12179  {
12180  // insert only works for objects
12181  if (JSON_UNLIKELY(not is_object()))
12182  {
12183  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12184  }
12185 
12186  // check if range iterators belong to the same JSON object
12187  if (JSON_UNLIKELY(first.m_object != last.m_object))
12188  {
12189  JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
12190  }
12191 
12192  // passed iterators must belong to objects
12193  if (JSON_UNLIKELY(not first.m_object->is_object()))
12194  {
12195  JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
12196  }
12197 
12198  m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
12199  }
12200 
12201  /*!
12202  @brief updates a JSON object from another object, overwriting existing keys
12203 
12204  Inserts all values from JSON object @a j and overwrites existing keys.
12205 
12206  @param[in] j JSON object to read values from
12207 
12208  @throw type_error.312 if called on JSON values other than objects; example:
12209  `"cannot use update() with string"`
12210 
12211  @complexity O(N*log(size() + N)), where N is the number of elements to
12212  insert.
12213 
12214  @liveexample{The example shows how `update()` is used.,update}
12215 
12216  @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
12217 
12218  @since version 3.0.0
12219  */
12220  void update(const_reference j)
12221  {
12222  // implicitly convert null value to an empty object
12223  if (is_null())
12224  {
12225  m_type = value_t::object;
12226  m_value.object = create<object_t>();
12227  assert_invariant();
12228  }
12229 
12230  if (JSON_UNLIKELY(not is_object()))
12231  {
12232  JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
12233  }
12234  if (JSON_UNLIKELY(not j.is_object()))
12235  {
12236  JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
12237  }
12238 
12239  for (auto it = j.begin(); it != j.end(); ++it)
12240  {
12241  m_value.object->operator[](it.key()) = it.value();
12242  }
12243  }
12244 
12245  /*!
12246  @brief updates a JSON object from another object, overwriting existing keys
12247 
12248  Inserts all values from from range `[first, last)` and overwrites existing
12249  keys.
12250 
12251  @param[in] first begin of the range of elements to insert
12252  @param[in] last end of the range of elements to insert
12253 
12254  @throw type_error.312 if called on JSON values other than objects; example:
12255  `"cannot use update() with string"`
12256  @throw invalid_iterator.202 if iterator @a first or @a last does does not
12257  point to an object; example: `"iterators first and last must point to
12258  objects"`
12259  @throw invalid_iterator.210 if @a first and @a last do not belong to the
12260  same JSON value; example: `"iterators do not fit"`
12261 
12262  @complexity O(N*log(size() + N)), where N is the number of elements to
12263  insert.
12264 
12265  @liveexample{The example shows how `update()` is used__range.,update}
12266 
12267  @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
12268 
12269  @since version 3.0.0
12270  */
12271  void update(const_iterator first, const_iterator last)
12272  {
12273  // implicitly convert null value to an empty object
12274  if (is_null())
12275  {
12276  m_type = value_t::object;
12277  m_value.object = create<object_t>();
12278  assert_invariant();
12279  }
12280 
12281  if (JSON_UNLIKELY(not is_object()))
12282  {
12283  JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
12284  }
12285 
12286  // check if range iterators belong to the same JSON object
12287  if (JSON_UNLIKELY(first.m_object != last.m_object))
12288  {
12289  JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
12290  }
12291 
12292  // passed iterators must belong to objects
12293  if (JSON_UNLIKELY(not first.m_object->is_object()
12294  or not first.m_object->is_object()))
12295  {
12296  JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
12297  }
12298 
12299  for (auto it = first; it != last; ++it)
12300  {
12301  m_value.object->operator[](it.key()) = it.value();
12302  }
12303  }
12304 
12305  /*!
12306  @brief exchanges the values
12307 
12308  Exchanges the contents of the JSON value with those of @a other. Does not
12309  invoke any move, copy, or swap operations on individual elements. All
12310  iterators and references remain valid. The past-the-end iterator is
12311  invalidated.
12312 
12313  @param[in,out] other JSON value to exchange the contents with
12314 
12315  @complexity Constant.
12316 
12317  @liveexample{The example below shows how JSON values can be swapped with
12318  `swap()`.,swap__reference}
12319 
12320  @since version 1.0.0
12321  */
12322  void swap(reference other) noexcept (
12323  std::is_nothrow_move_constructible<value_t>::value and
12324  std::is_nothrow_move_assignable<value_t>::value and
12325  std::is_nothrow_move_constructible<json_value>::value and
12326  std::is_nothrow_move_assignable<json_value>::value
12327  )
12328  {
12329  std::swap(m_type, other.m_type);
12330  std::swap(m_value, other.m_value);
12331  assert_invariant();
12332  }
12333 
12334  /*!
12335  @brief exchanges the values
12336 
12337  Exchanges the contents of a JSON array with those of @a other. Does not
12338  invoke any move, copy, or swap operations on individual elements. All
12339  iterators and references remain valid. The past-the-end iterator is
12340  invalidated.
12341 
12342  @param[in,out] other array to exchange the contents with
12343 
12344  @throw type_error.310 when JSON value is not an array; example: `"cannot
12345  use swap() with string"`
12346 
12347  @complexity Constant.
12348 
12349  @liveexample{The example below shows how arrays can be swapped with
12350  `swap()`.,swap__array_t}
12351 
12352  @since version 1.0.0
12353  */
12354  void swap(array_t& other)
12355  {
12356  // swap only works for arrays
12357  if (JSON_LIKELY(is_array()))
12358  {
12359  std::swap(*(m_value.array), other);
12360  }
12361  else
12362  {
12363  JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
12364  }
12365  }
12366 
12367  /*!
12368  @brief exchanges the values
12370  Exchanges the contents of a JSON object with those of @a other. Does not
12371  invoke any move, copy, or swap operations on individual elements. All
12372  iterators and references remain valid. The past-the-end iterator is
12373  invalidated.
12374 
12375  @param[in,out] other object to exchange the contents with
12376 
12377  @throw type_error.310 when JSON value is not an object; example:
12378  `"cannot use swap() with string"`
12379 
12380  @complexity Constant.
12381 
12382  @liveexample{The example below shows how objects can be swapped with
12383  `swap()`.,swap__object_t}
12384 
12385  @since version 1.0.0
12386  */
12387  void swap(object_t& other)
12388  {
12389  // swap only works for objects
12390  if (JSON_LIKELY(is_object()))
12391  {
12392  std::swap(*(m_value.object), other);
12393  }
12394  else
12395  {
12396  JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
12397  }
12398  }
12399 
12400  /*!
12401  @brief exchanges the values
12403  Exchanges the contents of a JSON string with those of @a other. Does not
12404  invoke any move, copy, or swap operations on individual elements. All
12405  iterators and references remain valid. The past-the-end iterator is
12406  invalidated.
12407 
12408  @param[in,out] other string to exchange the contents with
12409 
12410  @throw type_error.310 when JSON value is not a string; example: `"cannot
12411  use swap() with boolean"`
12412 
12413  @complexity Constant.
12414 
12415  @liveexample{The example below shows how strings can be swapped with
12416  `swap()`.,swap__string_t}
12417 
12418  @since version 1.0.0
12419  */
12420  void swap(string_t& other)
12421  {
12422  // swap only works for strings
12423  if (JSON_LIKELY(is_string()))
12424  {
12425  std::swap(*(m_value.string), other);
12426  }
12427  else
12428  {
12429  JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
12430  }
12431  }
12432 
12433  /// @}
12434 
12435  public:
12436  //////////////////////////////////////////
12437  // lexicographical comparison operators //
12438  //////////////////////////////////////////
12439 
12440  /// @name lexicographical comparison operators
12441  /// @{
12442 
12443  /*!
12444  @brief comparison: equal
12445 
12446  Compares two JSON values for equality according to the following rules:
12447  - Two JSON values are equal if (1) they are from the same type and (2)
12448  their stored values are the same according to their respective
12449  `operator==`.
12450  - Integer and floating-point numbers are automatically converted before
12451  comparison. Note than two NaN values are always treated as unequal.
12452  - Two JSON null values are equal.
12453 
12454  @note Floating-point inside JSON values numbers are compared with
12455  `json::number_float_t::operator==` which is `double::operator==` by
12456  default. To compare floating-point while respecting an epsilon, an alternative
12457  [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
12458  could be used, for instance
12459  @code {.cpp}
12460  template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
12461  inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
12462  {
12463  return std::abs(a - b) <= epsilon;
12464  }
12465  @endcode
12466 
12467  @note NaN values never compare equal to themselves or to other NaN values.
12468 
12469  @param[in] lhs first JSON value to consider
12470  @param[in] rhs second JSON value to consider
12471  @return whether the values @a lhs and @a rhs are equal
12472 
12473  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12474 
12475  @complexity Linear.
12476 
12477  @liveexample{The example demonstrates comparing several JSON
12478  types.,operator__equal}
12479 
12480  @since version 1.0.0
12481  */
12482  friend bool operator==(const_reference lhs, const_reference rhs) noexcept
12483  {
12484  const auto lhs_type = lhs.type();
12485  const auto rhs_type = rhs.type();
12486 
12487  if (lhs_type == rhs_type)
12488  {
12489  switch (lhs_type)
12490  {
12491  case value_t::array:
12492  return (*lhs.m_value.array == *rhs.m_value.array);
12493 
12494  case value_t::object:
12495  return (*lhs.m_value.object == *rhs.m_value.object);
12496 
12497  case value_t::null:
12498  return true;
12499 
12500  case value_t::string:
12501  return (*lhs.m_value.string == *rhs.m_value.string);
12502 
12503  case value_t::boolean:
12504  return (lhs.m_value.boolean == rhs.m_value.boolean);
12505 
12506  case value_t::number_integer:
12507  return (lhs.m_value.number_integer == rhs.m_value.number_integer);
12508 
12509  case value_t::number_unsigned:
12510  return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned);
12511 
12512  case value_t::number_float:
12513  return (lhs.m_value.number_float == rhs.m_value.number_float);
12514 
12515  default:
12516  return false;
12517  }
12518  }
12519  else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
12520  {
12521  return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float);
12522  }
12523  else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
12524  {
12525  return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer));
12526  }
12527  else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
12528  {
12529  return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float);
12530  }
12531  else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
12532  {
12533  return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned));
12534  }
12535  else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
12536  {
12537  return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer);
12538  }
12539  else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
12540  {
12541  return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned));
12542  }
12543 
12544  return false;
12545  }
12546 
12547  /*!
12548  @brief comparison: equal
12549  @copydoc operator==(const_reference, const_reference)
12550  */
12551  template<typename ScalarType, typename std::enable_if<
12552  std::is_scalar<ScalarType>::value, int>::type = 0>
12553  friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
12554  {
12555  return (lhs == basic_json(rhs));
12556  }
12557 
12558  /*!
12559  @brief comparison: equal
12560  @copydoc operator==(const_reference, const_reference)
12561  */
12562  template<typename ScalarType, typename std::enable_if<
12563  std::is_scalar<ScalarType>::value, int>::type = 0>
12564  friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
12565  {
12566  return (basic_json(lhs) == rhs);
12567  }
12569  /*!
12570  @brief comparison: not equal
12571 
12572  Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
12573 
12574  @param[in] lhs first JSON value to consider
12575  @param[in] rhs second JSON value to consider
12576  @return whether the values @a lhs and @a rhs are not equal
12577 
12578  @complexity Linear.
12580  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12581 
12582  @liveexample{The example demonstrates comparing several JSON
12583  types.,operator__notequal}
12584 
12585  @since version 1.0.0
12586  */
12587  friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
12588  {
12589  return not (lhs == rhs);
12590  }
12591 
12592  /*!
12593  @brief comparison: not equal
12594  @copydoc operator!=(const_reference, const_reference)
12595  */
12596  template<typename ScalarType, typename std::enable_if<
12597  std::is_scalar<ScalarType>::value, int>::type = 0>
12598  friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
12599  {
12600  return (lhs != basic_json(rhs));
12601  }
12603  /*!
12604  @brief comparison: not equal
12605  @copydoc operator!=(const_reference, const_reference)
12606  */
12607  template<typename ScalarType, typename std::enable_if<
12608  std::is_scalar<ScalarType>::value, int>::type = 0>
12609  friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
12610  {
12611  return (basic_json(lhs) != rhs);
12612  }
12614  /*!
12615  @brief comparison: less than
12616 
12617  Compares whether one JSON value @a lhs is less than another JSON value @a
12618  rhs according to the following rules:
12619  - If @a lhs and @a rhs have the same type, the values are compared using
12620  the default `<` operator.
12621  - Integer and floating-point numbers are automatically converted before
12622  comparison
12623  - In case @a lhs and @a rhs have different types, the values are ignored
12624  and the order of the types is considered, see
12625  @ref operator<(const value_t, const value_t).
12626 
12627  @param[in] lhs first JSON value to consider
12628  @param[in] rhs second JSON value to consider
12629  @return whether @a lhs is less than @a rhs
12630 
12631  @complexity Linear.
12632 
12633  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12634 
12635  @liveexample{The example demonstrates comparing several JSON
12636  types.,operator__less}
12637 
12638  @since version 1.0.0
12639  */
12640  friend bool operator<(const_reference lhs, const_reference rhs) noexcept
12641  {
12642  const auto lhs_type = lhs.type();
12643  const auto rhs_type = rhs.type();
12644 
12645  if (lhs_type == rhs_type)
12646  {
12647  switch (lhs_type)
12648  {
12649  case value_t::array:
12650  return (*lhs.m_value.array) < (*rhs.m_value.array);
12651 
12652  case value_t::object:
12653  return *lhs.m_value.object < *rhs.m_value.object;
12654 
12655  case value_t::null:
12656  return false;
12657 
12658  case value_t::string:
12659  return *lhs.m_value.string < *rhs.m_value.string;
12660 
12661  case value_t::boolean:
12662  return lhs.m_value.boolean < rhs.m_value.boolean;
12663 
12664  case value_t::number_integer:
12665  return lhs.m_value.number_integer < rhs.m_value.number_integer;
12666 
12667  case value_t::number_unsigned:
12668  return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
12669 
12670  case value_t::number_float:
12671  return lhs.m_value.number_float < rhs.m_value.number_float;
12672 
12673  default:
12674  return false;
12675  }
12676  }
12677  else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
12678  {
12679  return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
12680  }
12681  else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
12682  {
12683  return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
12684  }
12685  else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
12686  {
12687  return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
12688  }
12689  else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
12690  {
12691  return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
12692  }
12693  else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
12694  {
12695  return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
12696  }
12697  else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
12698  {
12699  return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
12700  }
12701 
12702  // We only reach this line if we cannot compare values. In that case,
12703  // we compare types. Note we have to call the operator explicitly,
12704  // because MSVC has problems otherwise.
12705  return operator<(lhs_type, rhs_type);
12706  }
12707 
12708  /*!
12709  @brief comparison: less than
12710  @copydoc operator<(const_reference, const_reference)
12711  */
12712  template<typename ScalarType, typename std::enable_if<
12713  std::is_scalar<ScalarType>::value, int>::type = 0>
12714  friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
12715  {
12716  return (lhs < basic_json(rhs));
12717  }
12718 
12719  /*!
12720  @brief comparison: less than
12721  @copydoc operator<(const_reference, const_reference)
12722  */
12723  template<typename ScalarType, typename std::enable_if<
12724  std::is_scalar<ScalarType>::value, int>::type = 0>
12725  friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
12726  {
12727  return (basic_json(lhs) < rhs);
12728  }
12730  /*!
12731  @brief comparison: less than or equal
12732 
12733  Compares whether one JSON value @a lhs is less than or equal to another
12734  JSON value by calculating `not (rhs < lhs)`.
12735 
12736  @param[in] lhs first JSON value to consider
12737  @param[in] rhs second JSON value to consider
12738  @return whether @a lhs is less than or equal to @a rhs
12739 
12740  @complexity Linear.
12741 
12742  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12743 
12744  @liveexample{The example demonstrates comparing several JSON
12745  types.,operator__greater}
12746 
12747  @since version 1.0.0
12748  */
12749  friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
12750  {
12751  return not (rhs < lhs);
12752  }
12753 
12754  /*!
12755  @brief comparison: less than or equal
12756  @copydoc operator<=(const_reference, const_reference)
12757  */
12758  template<typename ScalarType, typename std::enable_if<
12759  std::is_scalar<ScalarType>::value, int>::type = 0>
12760  friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
12761  {
12762  return (lhs <= basic_json(rhs));
12763  }
12765  /*!
12766  @brief comparison: less than or equal
12767  @copydoc operator<=(const_reference, const_reference)
12768  */
12769  template<typename ScalarType, typename std::enable_if<
12770  std::is_scalar<ScalarType>::value, int>::type = 0>
12771  friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
12772  {
12773  return (basic_json(lhs) <= rhs);
12774  }
12776  /*!
12777  @brief comparison: greater than
12778 
12779  Compares whether one JSON value @a lhs is greater than another
12780  JSON value by calculating `not (lhs <= rhs)`.
12781 
12782  @param[in] lhs first JSON value to consider
12783  @param[in] rhs second JSON value to consider
12784  @return whether @a lhs is greater than to @a rhs
12785 
12786  @complexity Linear.
12787 
12788  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12789 
12790  @liveexample{The example demonstrates comparing several JSON
12791  types.,operator__lessequal}
12792 
12793  @since version 1.0.0
12794  */
12795  friend bool operator>(const_reference lhs, const_reference rhs) noexcept
12796  {
12797  return not (lhs <= rhs);
12798  }
12799 
12800  /*!
12801  @brief comparison: greater than
12802  @copydoc operator>(const_reference, const_reference)
12803  */
12804  template<typename ScalarType, typename std::enable_if<
12805  std::is_scalar<ScalarType>::value, int>::type = 0>
12806  friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
12807  {
12808  return (lhs > basic_json(rhs));
12809  }
12811  /*!
12812  @brief comparison: greater than
12813  @copydoc operator>(const_reference, const_reference)
12814  */
12815  template<typename ScalarType, typename std::enable_if<
12816  std::is_scalar<ScalarType>::value, int>::type = 0>
12817  friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
12818  {
12819  return (basic_json(lhs) > rhs);
12820  }
12822  /*!
12823  @brief comparison: greater than or equal
12824 
12825  Compares whether one JSON value @a lhs is greater than or equal to another
12826  JSON value by calculating `not (lhs < rhs)`.
12827 
12828  @param[in] lhs first JSON value to consider
12829  @param[in] rhs second JSON value to consider
12830  @return whether @a lhs is greater than or equal to @a rhs
12831 
12832  @complexity Linear.
12833 
12834  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12835 
12836  @liveexample{The example demonstrates comparing several JSON
12837  types.,operator__greaterequal}
12838 
12839  @since version 1.0.0
12840  */
12841  friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
12842  {
12843  return not (lhs < rhs);
12844  }
12845 
12846  /*!
12847  @brief comparison: greater than or equal
12848  @copydoc operator>=(const_reference, const_reference)
12849  */
12850  template<typename ScalarType, typename std::enable_if<
12851  std::is_scalar<ScalarType>::value, int>::type = 0>
12852  friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
12853  {
12854  return (lhs >= basic_json(rhs));
12855  }
12857  /*!
12858  @brief comparison: greater than or equal
12859  @copydoc operator>=(const_reference, const_reference)
12860  */
12861  template<typename ScalarType, typename std::enable_if<
12862  std::is_scalar<ScalarType>::value, int>::type = 0>
12863  friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
12864  {
12865  return (basic_json(lhs) >= rhs);
12866  }
12868  /// @}
12869 
12870  ///////////////////
12871  // serialization //
12872  ///////////////////
12873 
12874  /// @name serialization
12875  /// @{
12876 
12877  /*!
12878  @brief serialize to stream
12879 
12880  Serialize the given JSON value @a j to the output stream @a o. The JSON
12881  value will be serialized using the @ref dump member function.
12882 
12883  - The indentation of the output can be controlled with the member variable
12884  `width` of the output stream @a o. For instance, using the manipulator
12885  `std::setw(4)` on @a o sets the indentation level to `4` and the
12886  serialization result is the same as calling `dump(4)`.
12887 
12888  - The indentation character can be controlled with the member variable
12889  `fill` of the output stream @a o. For instance, the manipulator
12890  `std::setfill('\\t')` sets indentation to use a tab character rather than
12891  the default space character.
12892 
12893  @param[in,out] o stream to serialize to
12894  @param[in] j JSON value to serialize
12895 
12896  @return the stream @a o
12897 
12898  @throw type_error.316 if a string stored inside the JSON value is not
12899  UTF-8 encoded
12900 
12901  @complexity Linear.
12902 
12903  @liveexample{The example below shows the serialization with different
12904  parameters to `width` to adjust the indentation level.,operator_serialize}
12905 
12906  @since version 1.0.0; indentation character added in version 3.0.0
12907  */
12908  friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
12909  {
12910  // read width member and use it as indentation parameter if nonzero
12911  const bool pretty_print = (o.width() > 0);
12912  const auto indentation = (pretty_print ? o.width() : 0);
12913 
12914  // reset width to 0 for subsequent calls to this stream
12915  o.width(0);
12916 
12917  // do the actual serialization
12918  serializer s(detail::output_adapter<char>(o), o.fill());
12919  s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
12920  return o;
12921  }
12922 
12923  /*!
12924  @brief serialize to stream
12925  @deprecated This stream operator is deprecated and will be removed in a
12926  future version of the library. Please use
12927  @ref operator<<(std::ostream&, const basic_json&)
12928  instead; that is, replace calls like `j >> o;` with `o << j;`.
12929  @since version 1.0.0; deprecated since version 3.0.0
12930  */
12932  friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
12933  {
12934  return o << j;
12935  }
12936 
12937  /// @}
12938 
12939 
12940  /////////////////////
12941  // deserialization //
12942  /////////////////////
12943 
12944  /// @name deserialization
12945  /// @{
12946 
12947  /*!
12948  @brief deserialize from a compatible input
12949 
12950  This function reads from a compatible input. Examples are:
12951  - an array of 1-byte values
12952  - strings with character/literal type with size of 1 byte
12953  - input streams
12954  - container with contiguous storage of 1-byte values. Compatible container
12955  types include `std::vector`, `std::string`, `std::array`,
12956  `std::valarray`, and `std::initializer_list`. Furthermore, C-style
12957  arrays can be used with `std::begin()`/`std::end()`. User-defined
12958  containers can be used as long as they implement random-access iterators
12959  and a contiguous storage.
12960 
12961  @pre Each element of the container has a size of 1 byte. Violating this
12962  precondition yields undefined behavior. **This precondition is enforced
12963  with a static assertion.**
12964 
12965  @pre The container storage is contiguous. Violating this precondition
12966  yields undefined behavior. **This precondition is enforced with an
12967  assertion.**
12968  @pre Each element of the container has a size of 1 byte. Violating this
12969  precondition yields undefined behavior. **This precondition is enforced
12970  with a static assertion.**
12971 
12972  @warning There is no way to enforce all preconditions at compile-time. If
12973  the function is called with a noncompliant container and with
12974  assertions switched off, the behavior is undefined and will most
12975  likely yield segmentation violation.
12976 
12977  @param[in] i input to read from
12978  @param[in] cb a parser callback function of type @ref parser_callback_t
12979  which is used to control the deserialization by filtering unwanted values
12980  (optional)
12981 
12982  @return result of the deserialization
12983 
12984  @throw parse_error.101 if a parse error occurs; example: `""unexpected end
12985  of input; expected string literal""`
12986  @throw parse_error.102 if to_unicode fails or surrogate error
12987  @throw parse_error.103 if to_unicode fails
12988 
12989  @complexity Linear in the length of the input. The parser is a predictive
12990  LL(1) parser. The complexity can be higher if the parser callback function
12991  @a cb has a super-linear complexity.
12992 
12993  @note A UTF-8 byte order mark is silently ignored.
12994 
12995  @liveexample{The example below demonstrates the `parse()` function reading
12996  from an array.,parse__array__parser_callback_t}
12997 
12998  @liveexample{The example below demonstrates the `parse()` function with
12999  and without callback function.,parse__string__parser_callback_t}
13000 
13001  @liveexample{The example below demonstrates the `parse()` function with
13002  and without callback function.,parse__istream__parser_callback_t}
13003 
13004  @liveexample{The example below demonstrates the `parse()` function reading
13005  from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
13006 
13007  @since version 2.0.3 (contiguous containers)
13008  */
13009  static basic_json parse(detail::input_adapter i,
13010  const parser_callback_t cb = nullptr,
13011  const bool allow_exceptions = true)
13012  {
13013  basic_json result;
13014  parser(i, cb, allow_exceptions).parse(true, result);
13015  return result;
13016  }
13017 
13018  /*!
13019  @copydoc basic_json parse(detail::input_adapter, const parser_callback_t)
13020  */
13021  static basic_json parse(detail::input_adapter& i,
13022  const parser_callback_t cb = nullptr,
13023  const bool allow_exceptions = true)
13024  {
13025  basic_json result;
13026  parser(i, cb, allow_exceptions).parse(true, result);
13027  return result;
13028  }
13029 
13030  static bool accept(detail::input_adapter i)
13031  {
13032  return parser(i).accept(true);
13033  }
13034 
13035  static bool accept(detail::input_adapter& i)
13036  {
13037  return parser(i).accept(true);
13038  }
13039 
13040  /*!
13041  @brief deserialize from an iterator range with contiguous storage
13042 
13043  This function reads from an iterator range of a container with contiguous
13044  storage of 1-byte values. Compatible container types include
13045  `std::vector`, `std::string`, `std::array`, `std::valarray`, and
13046  `std::initializer_list`. Furthermore, C-style arrays can be used with
13047  `std::begin()`/`std::end()`. User-defined containers can be used as long
13048  as they implement random-access iterators and a contiguous storage.
13049 
13050  @pre The iterator range is contiguous. Violating this precondition yields
13051  undefined behavior. **This precondition is enforced with an assertion.**
13052  @pre Each element in the range has a size of 1 byte. Violating this
13053  precondition yields undefined behavior. **This precondition is enforced
13054  with a static assertion.**
13055 
13056  @warning There is no way to enforce all preconditions at compile-time. If
13057  the function is called with noncompliant iterators and with
13058  assertions switched off, the behavior is undefined and will most
13059  likely yield segmentation violation.
13060 
13061  @tparam IteratorType iterator of container with contiguous storage
13062  @param[in] first begin of the range to parse (included)
13063  @param[in] last end of the range to parse (excluded)
13064  @param[in] cb a parser callback function of type @ref parser_callback_t
13065  which is used to control the deserialization by filtering unwanted values
13066  (optional)
13067  @param[in] allow_exceptions whether to throw exceptions in case of a
13068  parse error (optional, true by default)
13069 
13070  @return result of the deserialization
13071 
13072  @throw parse_error.101 in case of an unexpected token
13073  @throw parse_error.102 if to_unicode fails or surrogate error
13074  @throw parse_error.103 if to_unicode fails
13075 
13076  @complexity Linear in the length of the input. The parser is a predictive
13077  LL(1) parser. The complexity can be higher if the parser callback function
13078  @a cb has a super-linear complexity.
13079 
13080  @note A UTF-8 byte order mark is silently ignored.
13081 
13082  @liveexample{The example below demonstrates the `parse()` function reading
13083  from an iterator range.,parse__iteratortype__parser_callback_t}
13084 
13085  @since version 2.0.3
13086  */
13087  template<class IteratorType, typename std::enable_if<
13088  std::is_base_of<
13089  std::random_access_iterator_tag,
13090  typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
13091  static basic_json parse(IteratorType first, IteratorType last,
13092  const parser_callback_t cb = nullptr,
13093  const bool allow_exceptions = true)
13094  {
13095  basic_json result;
13096  parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
13097  return result;
13098  }
13099 
13100  template<class IteratorType, typename std::enable_if<
13101  std::is_base_of<
13102  std::random_access_iterator_tag,
13103  typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
13104  static bool accept(IteratorType first, IteratorType last)
13105  {
13106  return parser(detail::input_adapter(first, last)).accept(true);
13107  }
13108 
13109  /*!
13110  @brief deserialize from stream
13111  @deprecated This stream operator is deprecated and will be removed in a
13112  future version of the library. Please use
13113  @ref operator>>(std::istream&, basic_json&)
13114  instead; that is, replace calls like `j << i;` with `i >> j;`.
13115  @since version 1.0.0; deprecated since version 3.0.0
13116  */
13118  friend std::istream& operator<<(basic_json& j, std::istream& i)
13119  {
13120  return operator>>(i, j);
13121  }
13122 
13123  /*!
13124  @brief deserialize from stream
13125 
13126  Deserializes an input stream to a JSON value.
13127 
13128  @param[in,out] i input stream to read a serialized JSON value from
13129  @param[in,out] j JSON value to write the deserialized input to
13130 
13131  @throw parse_error.101 in case of an unexpected token
13132  @throw parse_error.102 if to_unicode fails or surrogate error
13133  @throw parse_error.103 if to_unicode fails
13134 
13135  @complexity Linear in the length of the input. The parser is a predictive
13136  LL(1) parser.
13137 
13138  @note A UTF-8 byte order mark is silently ignored.
13139 
13140  @liveexample{The example below shows how a JSON value is constructed by
13141  reading a serialization from a stream.,operator_deserialize}
13142 
13143  @sa parse(std::istream&, const parser_callback_t) for a variant with a
13144  parser callback function to filter values while parsing
13145 
13146  @since version 1.0.0
13147  */
13148  friend std::istream& operator>>(std::istream& i, basic_json& j)
13149  {
13150  parser(detail::input_adapter(i)).parse(false, j);
13151  return i;
13152  }
13153 
13154  /// @}
13155 
13156  ///////////////////////////
13157  // convenience functions //
13158  ///////////////////////////
13159 
13160  /*!
13161  @brief return the type as string
13162 
13163  Returns the type name as string to be used in error messages - usually to
13164  indicate that a function was called on a wrong JSON type.
13165 
13166  @return a string representation of a the @a m_type member:
13167  Value type | return value
13168  ----------- | -------------
13169  null | `"null"`
13170  boolean | `"boolean"`
13171  string | `"string"`
13172  number | `"number"` (for all number types)
13173  object | `"object"`
13174  array | `"array"`
13175  discarded | `"discarded"`
13176 
13177  @exceptionsafety No-throw guarantee: this function never throws exceptions.
13178 
13179  @complexity Constant.
13180 
13181  @liveexample{The following code exemplifies `type_name()` for all JSON
13182  types.,type_name}
13183 
13184  @sa @ref type() -- return the type of the JSON value
13185  @sa @ref operator value_t() -- return the type of the JSON value (implicit)
13186 
13187  @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
13188  since 3.0.0
13189  */
13190  const char* type_name() const noexcept
13191  {
13192  {
13193  switch (m_type)
13194  {
13195  case value_t::null:
13196  return "null";
13197  case value_t::object:
13198  return "object";
13199  case value_t::array:
13200  return "array";
13201  case value_t::string:
13202  return "string";
13203  case value_t::boolean:
13204  return "boolean";
13205  case value_t::discarded:
13206  return "discarded";
13207  default:
13208  return "number";
13209  }
13210  }
13211  }
13212 
13213 
13214  private:
13215  //////////////////////
13216  // member variables //
13217  //////////////////////
13218 
13219  /// the type of the current element
13220  value_t m_type = value_t::null;
13221 
13222  /// the value of the current element
13223  json_value m_value = {};
13224 
13225  //////////////////////////////////////////
13226  // binary serialization/deserialization //
13227  //////////////////////////////////////////
13228 
13229  /// @name binary serialization/deserialization support
13230  /// @{
13231 
13232  public:
13233  /*!
13234  @brief create a CBOR serialization of a given JSON value
13235 
13236  Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
13237  Binary Object Representation) serialization format. CBOR is a binary
13238  serialization format which aims to be more compact than JSON itself, yet
13239  more efficient to parse.
13240 
13241  The library uses the following mapping from JSON values types to
13242  CBOR types according to the CBOR specification (RFC 7049):
13243 
13244  JSON value type | value/range | CBOR type | first byte
13245  --------------- | ------------------------------------------ | ---------------------------------- | ---------------
13246  null | `null` | Null | 0xF6
13247  boolean | `true` | True | 0xF5
13248  boolean | `false` | False | 0xF4
13249  number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
13250  number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
13251  number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
13252  number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
13253  number_integer | -24..-1 | Negative integer | 0x20..0x37
13254  number_integer | 0..23 | Integer | 0x00..0x17
13255  number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
13256  number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
13257  number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
13258  number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
13259  number_unsigned | 0..23 | Integer | 0x00..0x17
13260  number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
13261  number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
13262  number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
13263  number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
13264  number_float | *any value* | Double-Precision Float | 0xFB
13265  string | *length*: 0..23 | UTF-8 string | 0x60..0x77
13266  string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
13267  string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
13268  string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
13269  string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
13270  array | *size*: 0..23 | array | 0x80..0x97
13271  array | *size*: 23..255 | array (1 byte follow) | 0x98
13272  array | *size*: 256..65535 | array (2 bytes follow) | 0x99
13273  array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
13274  array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
13275  object | *size*: 0..23 | map | 0xA0..0xB7
13276  object | *size*: 23..255 | map (1 byte follow) | 0xB8
13277  object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
13278  object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
13279  object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
13280 
13281  @note The mapping is **complete** in the sense that any JSON value type
13282  can be converted to a CBOR value.
13283 
13284  @note If NaN or Infinity are stored inside a JSON number, they are
13285  serialized properly. This behavior differs from the @ref dump()
13286  function which serializes NaN or Infinity to `null`.
13287 
13288  @note The following CBOR types are not used in the conversion:
13289  - byte strings (0x40..0x5F)
13290  - UTF-8 strings terminated by "break" (0x7F)
13291  - arrays terminated by "break" (0x9F)
13292  - maps terminated by "break" (0xBF)
13293  - date/time (0xC0..0xC1)
13294  - bignum (0xC2..0xC3)
13295  - decimal fraction (0xC4)
13296  - bigfloat (0xC5)
13297  - tagged items (0xC6..0xD4, 0xD8..0xDB)
13298  - expected conversions (0xD5..0xD7)
13299  - simple values (0xE0..0xF3, 0xF8)
13300  - undefined (0xF7)
13301  - half and single-precision floats (0xF9-0xFA)
13302  - break (0xFF)
13303 
13304  @param[in] j JSON value to serialize
13305  @return MessagePack serialization as byte vector
13306 
13307  @complexity Linear in the size of the JSON value @a j.
13308 
13309  @liveexample{The example shows the serialization of a JSON value to a byte
13310  vector in CBOR format.,to_cbor}
13311 
13312  @sa http://cbor.io
13313  @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the
13314  analogous deserialization
13315  @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
13316 
13317  @since version 2.0.9
13318  */
13319  static std::vector<uint8_t> to_cbor(const basic_json& j)
13320  {
13321  std::vector<uint8_t> result;
13322  to_cbor(j, result);
13323  return result;
13324  }
13325 
13326  static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
13327  {
13328  binary_writer<uint8_t>(o).write_cbor(j);
13329  }
13330 
13331  static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
13332  {
13333  binary_writer<char>(o).write_cbor(j);
13334  }
13335 
13336  /*!
13337  @brief create a MessagePack serialization of a given JSON value
13338 
13339  Serializes a given JSON value @a j to a byte vector using the MessagePack
13340  serialization format. MessagePack is a binary serialization format which
13341  aims to be more compact than JSON itself, yet more efficient to parse.
13342 
13343  The library uses the following mapping from JSON values types to
13344  MessagePack types according to the MessagePack specification:
13345 
13346  JSON value type | value/range | MessagePack type | first byte
13347  --------------- | --------------------------------- | ---------------- | ----------
13348  null | `null` | nil | 0xC0
13349  boolean | `true` | true | 0xC3
13350  boolean | `false` | false | 0xC2
13351  number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
13352  number_integer | -2147483648..-32769 | int32 | 0xD2
13353  number_integer | -32768..-129 | int16 | 0xD1
13354  number_integer | -128..-33 | int8 | 0xD0
13355  number_integer | -32..-1 | negative fixint | 0xE0..0xFF
13356  number_integer | 0..127 | positive fixint | 0x00..0x7F
13357  number_integer | 128..255 | uint 8 | 0xCC
13358  number_integer | 256..65535 | uint 16 | 0xCD
13359  number_integer | 65536..4294967295 | uint 32 | 0xCE
13360  number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
13361  number_unsigned | 0..127 | positive fixint | 0x00..0x7F
13362  number_unsigned | 128..255 | uint 8 | 0xCC
13363  number_unsigned | 256..65535 | uint 16 | 0xCD
13364  number_unsigned | 65536..4294967295 | uint 32 | 0xCE
13365  number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
13366  number_float | *any value* | float 64 | 0xCB
13367  string | *length*: 0..31 | fixstr | 0xA0..0xBF
13368  string | *length*: 32..255 | str 8 | 0xD9
13369  string | *length*: 256..65535 | str 16 | 0xDA
13370  string | *length*: 65536..4294967295 | str 32 | 0xDB
13371  array | *size*: 0..15 | fixarray | 0x90..0x9F
13372  array | *size*: 16..65535 | array 16 | 0xDC
13373  array | *size*: 65536..4294967295 | array 32 | 0xDD
13374  object | *size*: 0..15 | fix map | 0x80..0x8F
13375  object | *size*: 16..65535 | map 16 | 0xDE
13376  object | *size*: 65536..4294967295 | map 32 | 0xDF
13377 
13378  @note The mapping is **complete** in the sense that any JSON value type
13379  can be converted to a MessagePack value.
13380 
13381  @note The following values can **not** be converted to a MessagePack value:
13382  - strings with more than 4294967295 bytes
13383  - arrays with more than 4294967295 elements
13384  - objects with more than 4294967295 elements
13385 
13386  @note The following MessagePack types are not used in the conversion:
13387  - bin 8 - bin 32 (0xC4..0xC6)
13388  - ext 8 - ext 32 (0xC7..0xC9)
13389  - float 32 (0xCA)
13390  - fixext 1 - fixext 16 (0xD4..0xD8)
13391 
13392  @note Any MessagePack output created @ref to_msgpack can be successfully
13393  parsed by @ref from_msgpack.
13394 
13395  @note If NaN or Infinity are stored inside a JSON number, they are
13396  serialized properly. This behavior differs from the @ref dump()
13397  function which serializes NaN or Infinity to `null`.
13398 
13399  @param[in] j JSON value to serialize
13400  @return MessagePack serialization as byte vector
13401 
13402  @complexity Linear in the size of the JSON value @a j.
13403 
13404  @liveexample{The example shows the serialization of a JSON value to a byte
13405  vector in MessagePack format.,to_msgpack}
13406 
13407  @sa http://msgpack.org
13408  @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
13409  analogous deserialization
13410  @sa @ref to_cbor(const basic_json& for the related CBOR format
13411 
13412  @since version 2.0.9
13413  */
13414  static std::vector<uint8_t> to_msgpack(const basic_json& j)
13415  {
13416  std::vector<uint8_t> result;
13417  to_msgpack(j, result);
13418  return result;
13419  }
13420 
13421  static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
13422  {
13423  binary_writer<uint8_t>(o).write_msgpack(j);
13424  }
13425 
13426  static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
13427  {
13428  binary_writer<char>(o).write_msgpack(j);
13429  }
13430 
13431  /*!
13432  @brief create a JSON value from an input in CBOR format
13433 
13434  Deserializes a given input @a i to a JSON value using the CBOR (Concise
13435  Binary Object Representation) serialization format.
13437  The library maps CBOR types to JSON value types as follows:
13438 
13439  CBOR type | JSON value type | first byte
13440  ---------------------- | --------------- | ----------
13441  Integer | number_unsigned | 0x00..0x17
13442  Unsigned integer | number_unsigned | 0x18
13443  Unsigned integer | number_unsigned | 0x19
13444  Unsigned integer | number_unsigned | 0x1A
13445  Unsigned integer | number_unsigned | 0x1B
13446  Negative integer | number_integer | 0x20..0x37
13447  Negative integer | number_integer | 0x38
13448  Negative integer | number_integer | 0x39
13449  Negative integer | number_integer | 0x3A
13450  Negative integer | number_integer | 0x3B
13451  Negative integer | number_integer | 0x40..0x57
13452  UTF-8 string | string | 0x60..0x77
13453  UTF-8 string | string | 0x78
13454  UTF-8 string | string | 0x79
13455  UTF-8 string | string | 0x7A
13456  UTF-8 string | string | 0x7B
13457  UTF-8 string | string | 0x7F
13458  array | array | 0x80..0x97
13459  array | array | 0x98
13460  array | array | 0x99
13461  array | array | 0x9A
13462  array | array | 0x9B
13463  array | array | 0x9F
13464  map | object | 0xA0..0xB7
13465  map | object | 0xB8
13466  map | object | 0xB9
13467  map | object | 0xBA
13468  map | object | 0xBB
13469  map | object | 0xBF
13470  False | `false` | 0xF4
13471  True | `true` | 0xF5
13472  Nill | `null` | 0xF6
13473  Half-Precision Float | number_float | 0xF9
13474  Single-Precision Float | number_float | 0xFA
13475  Double-Precision Float | number_float | 0xFB
13476 
13477  @warning The mapping is **incomplete** in the sense that not all CBOR
13478  types can be converted to a JSON value. The following CBOR types
13479  are not supported and will yield parse errors (parse_error.112):
13480  - byte strings (0x40..0x5F)
13481  - date/time (0xC0..0xC1)
13482  - bignum (0xC2..0xC3)
13483  - decimal fraction (0xC4)
13484  - bigfloat (0xC5)
13485  - tagged items (0xC6..0xD4, 0xD8..0xDB)
13486  - expected conversions (0xD5..0xD7)
13487  - simple values (0xE0..0xF3, 0xF8)
13488  - undefined (0xF7)
13489 
13490  @warning CBOR allows map keys of any type, whereas JSON only allows
13491  strings as keys in object values. Therefore, CBOR maps with keys
13492  other than UTF-8 strings are rejected (parse_error.113).
13493 
13494  @note Any CBOR output created @ref to_cbor can be successfully parsed by
13495  @ref from_cbor.
13496 
13497  @param[in] i an input in CBOR format convertible to an input adapter
13498  @param[in] strict whether to expect the input to be consumed until EOF
13499  (true by default)
13500  @return deserialized JSON value
13501 
13502  @throw parse_error.110 if the given input ends prematurely or the end of
13503  file was not reached when @a strict was set to true
13504  @throw parse_error.112 if unsupported features from CBOR were
13505  used in the given input @a v or if the input is not valid CBOR
13506  @throw parse_error.113 if a string was expected as map key, but not found
13507 
13508  @complexity Linear in the size of the input @a i.
13509 
13510  @liveexample{The example shows the deserialization of a byte vector in CBOR
13511  format to a JSON value.,from_cbor}
13512 
13513  @sa http://cbor.io
13514  @sa @ref to_cbor(const basic_json&) for the analogous serialization
13515  @sa @ref from_msgpack(detail::input_adapter, const bool) for the
13516  related MessagePack format
13517 
13518  @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
13519  consume input adapters, removed start_index parameter, and added
13520  @a strict parameter since 3.0.0
13521  */
13522  static basic_json from_cbor(detail::input_adapter i,
13523  const bool strict = true)
13524  {
13525  return binary_reader(i).parse_cbor(strict);
13526  }
13527 
13528  /*!
13529  @copydoc from_cbor(detail::input_adapter, const bool)
13530  */
13531  template<typename A1, typename A2,
13532  detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
13533  static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true)
13534  {
13535  return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_cbor(strict);
13536  }
13538  /*!
13539  @brief create a JSON value from an input in MessagePack format
13540 
13541  Deserializes a given input @a i to a JSON value using the MessagePack
13542  serialization format.
13543 
13544  The library maps MessagePack types to JSON value types as follows:
13545 
13546  MessagePack type | JSON value type | first byte
13547  ---------------- | --------------- | ----------
13548  positive fixint | number_unsigned | 0x00..0x7F
13549  fixmap | object | 0x80..0x8F
13550  fixarray | array | 0x90..0x9F
13551  fixstr | string | 0xA0..0xBF
13552  nil | `null` | 0xC0
13553  false | `false` | 0xC2
13554  true | `true` | 0xC3
13555  float 32 | number_float | 0xCA
13556  float 64 | number_float | 0xCB
13557  uint 8 | number_unsigned | 0xCC
13558  uint 16 | number_unsigned | 0xCD
13559  uint 32 | number_unsigned | 0xCE
13560  uint 64 | number_unsigned | 0xCF
13561  int 8 | number_integer | 0xD0
13562  int 16 | number_integer | 0xD1
13563  int 32 | number_integer | 0xD2
13564  int 64 | number_integer | 0xD3
13565  str 8 | string | 0xD9
13566  str 16 | string | 0xDA
13567  str 32 | string | 0xDB
13568  array 16 | array | 0xDC
13569  array 32 | array | 0xDD
13570  map 16 | object | 0xDE
13571  map 32 | object | 0xDF
13572  negative fixint | number_integer | 0xE0-0xFF
13573 
13574  @warning The mapping is **incomplete** in the sense that not all
13575  MessagePack types can be converted to a JSON value. The following
13576  MessagePack types are not supported and will yield parse errors:
13577  - bin 8 - bin 32 (0xC4..0xC6)
13578  - ext 8 - ext 32 (0xC7..0xC9)
13579  - fixext 1 - fixext 16 (0xD4..0xD8)
13580 
13581  @note Any MessagePack output created @ref to_msgpack can be successfully
13582  parsed by @ref from_msgpack.
13583 
13584  @param[in] i an input in MessagePack format convertible to an input
13585  adapter
13586  @param[in] strict whether to expect the input to be consumed until EOF
13587  (true by default)
13588 
13589  @throw parse_error.110 if the given input ends prematurely or the end of
13590  file was not reached when @a strict was set to true
13591  @throw parse_error.112 if unsupported features from MessagePack were
13592  used in the given input @a i or if the input is not valid MessagePack
13593  @throw parse_error.113 if a string was expected as map key, but not found
13594 
13595  @complexity Linear in the size of the input @a i.
13596 
13597  @liveexample{The example shows the deserialization of a byte vector in
13598  MessagePack format to a JSON value.,from_msgpack}
13599 
13600  @sa http://msgpack.org
13601  @sa @ref to_msgpack(const basic_json&) for the analogous serialization
13602  @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR
13603  format
13604 
13605  @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
13606  consume input adapters, removed start_index parameter, and added
13607  @a strict parameter since 3.0.0
13608  */
13609  static basic_json from_msgpack(detail::input_adapter i,
13610  const bool strict = true)
13611  {
13612  return binary_reader(i).parse_msgpack(strict);
13613  }
13614 
13615  /*!
13616  @copydoc from_msgpack(detail::input_adapter, const bool)
13617  */
13618  template<typename A1, typename A2,
13619  detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
13620  static basic_json from_msgpack(A1 && a1, A2 && a2, const bool strict = true)
13621  {
13622  return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_msgpack(strict);
13623  }
13625  /// @}
13626 
13627  //////////////////////////
13628  // JSON Pointer support //
13629  //////////////////////////
13630 
13631  /// @name JSON Pointer functions
13632  /// @{
13633 
13634  /*!
13635  @brief access specified element via JSON Pointer
13636 
13637  Uses a JSON pointer to retrieve a reference to the respective JSON value.
13638  No bound checking is performed. Similar to @ref operator[](const typename
13639  object_t::key_type&), `null` values are created in arrays and objects if
13640  necessary.
13641 
13642  In particular:
13643  - If the JSON pointer points to an object key that does not exist, it
13644  is created an filled with a `null` value before a reference to it
13645  is returned.
13646  - If the JSON pointer points to an array index that does not exist, it
13647  is created an filled with a `null` value before a reference to it
13648  is returned. All indices between the current maximum and the given
13649  index are also filled with `null`.
13650  - The special value `-` is treated as a synonym for the index past the
13651  end.
13652 
13653  @param[in] ptr a JSON pointer
13654 
13655  @return reference to the element pointed to by @a ptr
13656 
13657  @complexity Constant.
13658 
13659  @throw parse_error.106 if an array index begins with '0'
13660  @throw parse_error.109 if an array index was not a number
13661  @throw out_of_range.404 if the JSON pointer can not be resolved
13662 
13663  @liveexample{The behavior is shown in the example.,operatorjson_pointer}
13664 
13665  @since version 2.0.0
13666  */
13667  reference operator[](const json_pointer& ptr)
13668  {
13669  return ptr.get_unchecked(this);
13670  }
13671 
13672  /*!
13673  @brief access specified element via JSON Pointer
13674 
13675  Uses a JSON pointer to retrieve a reference to the respective JSON value.
13676  No bound checking is performed. The function does not change the JSON
13677  value; no `null` values are created. In particular, the the special value
13678  `-` yields an exception.
13679 
13680  @param[in] ptr JSON pointer to the desired element
13681 
13682  @return const reference to the element pointed to by @a ptr
13683 
13684  @complexity Constant.
13685 
13686  @throw parse_error.106 if an array index begins with '0'
13687  @throw parse_error.109 if an array index was not a number
13688  @throw out_of_range.402 if the array index '-' is used
13689  @throw out_of_range.404 if the JSON pointer can not be resolved
13690 
13691  @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
13692 
13693  @since version 2.0.0
13694  */
13695  const_reference operator[](const json_pointer& ptr) const
13696  {
13697  return ptr.get_unchecked(this);
13698  }
13699 
13700  /*!
13701  @brief access specified element via JSON Pointer
13702 
13703  Returns a reference to the element at with specified JSON pointer @a ptr,
13704  with bounds checking.
13705 
13706  @param[in] ptr JSON pointer to the desired element
13707 
13708  @return reference to the element pointed to by @a ptr
13709 
13710  @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
13711  begins with '0'. See example below.
13712 
13713  @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
13714  is not a number. See example below.
13715 
13716  @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
13717  is out of range. See example below.
13718 
13719  @throw out_of_range.402 if the array index '-' is used in the passed JSON
13720  pointer @a ptr. As `at` provides checked access (and no elements are
13721  implicitly inserted), the index '-' is always invalid. See example below.
13722 
13723  @throw out_of_range.403 if the JSON pointer describes a key of an object
13724  which cannot be found. See example below.
13725 
13726  @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
13727  See example below.
13728 
13729  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
13730  changes in the JSON value.
13731 
13732  @complexity Constant.
13733 
13734  @since version 2.0.0
13735 
13736  @liveexample{The behavior is shown in the example.,at_json_pointer}
13737  */
13738  reference at(const json_pointer& ptr)
13739  {
13740  return ptr.get_checked(this);
13741  }
13742 
13743  /*!
13744  @brief access specified element via JSON Pointer
13745 
13746  Returns a const reference to the element at with specified JSON pointer @a
13747  ptr, with bounds checking.
13748 
13749  @param[in] ptr JSON pointer to the desired element
13750 
13751  @return reference to the element pointed to by @a ptr
13752 
13753  @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
13754  begins with '0'. See example below.
13755 
13756  @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
13757  is not a number. See example below.
13758 
13759  @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
13760  is out of range. See example below.
13761 
13762  @throw out_of_range.402 if the array index '-' is used in the passed JSON
13763  pointer @a ptr. As `at` provides checked access (and no elements are
13764  implicitly inserted), the index '-' is always invalid. See example below.
13765 
13766  @throw out_of_range.403 if the JSON pointer describes a key of an object
13767  which cannot be found. See example below.
13768 
13769  @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
13770  See example below.
13771 
13772  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
13773  changes in the JSON value.
13774 
13775  @complexity Constant.
13776 
13777  @since version 2.0.0
13778 
13779  @liveexample{The behavior is shown in the example.,at_json_pointer_const}
13780  */
13781  const_reference at(const json_pointer& ptr) const
13782  {
13783  return ptr.get_checked(this);
13784  }
13785 
13786  /*!
13787  @brief return flattened JSON value
13788 
13789  The function creates a JSON object whose keys are JSON pointers (see [RFC
13790  6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
13791  primitive. The original JSON value can be restored using the @ref
13792  unflatten() function.
13793 
13794  @return an object that maps JSON pointers to primitive values
13795 
13796  @note Empty objects and arrays are flattened to `null` and will not be
13797  reconstructed correctly by the @ref unflatten() function.
13798 
13799  @complexity Linear in the size the JSON value.
13800 
13801  @liveexample{The following code shows how a JSON object is flattened to an
13802  object whose keys consist of JSON pointers.,flatten}
13803 
13804  @sa @ref unflatten() for the reverse function
13805 
13806  @since version 2.0.0
13807  */
13808  basic_json flatten() const
13809  {
13810  basic_json result(value_t::object);
13811  json_pointer::flatten("", *this, result);
13812  return result;
13813  }
13814 
13815  /*!
13816  @brief unflatten a previously flattened JSON value
13817 
13818  The function restores the arbitrary nesting of a JSON value that has been
13819  flattened before using the @ref flatten() function. The JSON value must
13820  meet certain constraints:
13821  1. The value must be an object.
13822  2. The keys must be JSON pointers (see
13823  [RFC 6901](https://tools.ietf.org/html/rfc6901))
13824  3. The mapped values must be primitive JSON types.
13825 
13826  @return the original JSON from a flattened version
13827 
13828  @note Empty objects and arrays are flattened by @ref flatten() to `null`
13829  values and can not unflattened to their original type. Apart from
13830  this example, for a JSON value `j`, the following is always true:
13831  `j == j.flatten().unflatten()`.
13832 
13833  @complexity Linear in the size the JSON value.
13834 
13835  @throw type_error.314 if value is not an object
13836  @throw type_error.315 if object values are not primitive
13837 
13838  @liveexample{The following code shows how a flattened JSON object is
13839  unflattened into the original nested JSON object.,unflatten}
13840 
13841  @sa @ref flatten() for the reverse function
13842 
13843  @since version 2.0.0
13844  */
13845  basic_json unflatten() const
13846  {
13847  return json_pointer::unflatten(*this);
13848  }
13849 
13850  /// @}
13851 
13852  //////////////////////////
13853  // JSON Patch functions //
13854  //////////////////////////
13855 
13856  /// @name JSON Patch functions
13857  /// @{
13858 
13859  /*!
13860  @brief applies a JSON patch
13861 
13862  [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
13863  expressing a sequence of operations to apply to a JSON) document. With
13864  this function, a JSON Patch is applied to the current JSON value by
13865  executing all operations from the patch.
13866 
13867  @param[in] json_patch JSON patch document
13868  @return patched document
13869 
13870  @note The application of a patch is atomic: Either all operations succeed
13871  and the patched document is returned or an exception is thrown. In
13872  any case, the original value is not changed: the patch is applied
13873  to a copy of the value.
13874 
13875  @throw parse_error.104 if the JSON patch does not consist of an array of
13876  objects
13877 
13878  @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
13879  attributes are missing); example: `"operation add must have member path"`
13880 
13881  @throw out_of_range.401 if an array index is out of range.
13882 
13883  @throw out_of_range.403 if a JSON pointer inside the patch could not be
13884  resolved successfully in the current JSON value; example: `"key baz not
13885  found"`
13886 
13887  @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
13888  "move")
13889 
13890  @throw other_error.501 if "test" operation was unsuccessful
13891 
13892  @complexity Linear in the size of the JSON value and the length of the
13893  JSON patch. As usually only a fraction of the JSON value is affected by
13894  the patch, the complexity can usually be neglected.
13895 
13896  @liveexample{The following code shows how a JSON patch is applied to a
13897  value.,patch}
13898 
13899  @sa @ref diff -- create a JSON patch by comparing two JSON values
13900 
13901  @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
13902  @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
13903 
13904  @since version 2.0.0
13905  */
13906  basic_json patch(const basic_json& json_patch) const
13907  {
13908  // make a working copy to apply the patch to
13909  basic_json result = *this;
13910 
13911  // the valid JSON Patch operations
13912  enum class patch_operations {add, remove, replace, move, copy, test, invalid};
13913 
13914  const auto get_op = [](const std::string & op)
13915  {
13916  if (op == "add")
13917  {
13918  return patch_operations::add;
13919  }
13920  if (op == "remove")
13921  {
13922  return patch_operations::remove;
13923  }
13924  if (op == "replace")
13925  {
13926  return patch_operations::replace;
13927  }
13928  if (op == "move")
13929  {
13930  return patch_operations::move;
13931  }
13932  if (op == "copy")
13933  {
13934  return patch_operations::copy;
13935  }
13936  if (op == "test")
13937  {
13938  return patch_operations::test;
13939  }
13940 
13941  return patch_operations::invalid;
13942  };
13943 
13944  // wrapper for "add" operation; add value at ptr
13945  const auto operation_add = [&result](json_pointer & ptr, basic_json val)
13946  {
13947  // adding to the root of the target document means replacing it
13948  if (ptr.is_root())
13949  {
13950  result = val;
13951  }
13952  else
13953  {
13954  // make sure the top element of the pointer exists
13955  json_pointer top_pointer = ptr.top();
13956  if (top_pointer != ptr)
13957  {
13958  result.at(top_pointer);
13959  }
13960 
13961  // get reference to parent of JSON pointer ptr
13962  const auto last_path = ptr.pop_back();
13963  basic_json& parent = result[ptr];
13964 
13965  switch (parent.m_type)
13966  {
13967  case value_t::null:
13968  case value_t::object:
13969  {
13970  // use operator[] to add value
13971  parent[last_path] = val;
13972  break;
13973  }
13974 
13975  case value_t::array:
13976  {
13977  if (last_path == "-")
13978  {
13979  // special case: append to back
13980  parent.push_back(val);
13981  }
13982  else
13983  {
13984  const auto idx = std::stoi(last_path);
13985  if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
13986  {
13987  // avoid undefined behavior
13988  JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
13989  }
13990  else
13991  {
13992  // default case: insert add offset
13993  parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
13994  }
13995  }
13996  break;
13997  }
13998 
13999  default:
14000  {
14001  // if there exists a parent it cannot be primitive
14002  assert(false); // LCOV_EXCL_LINE
14003  }
14004  }
14005  }
14006  };
14007 
14008  // wrapper for "remove" operation; remove value at ptr
14009  const auto operation_remove = [&result](json_pointer & ptr)
14010  {
14011  // get reference to parent of JSON pointer ptr
14012  const auto last_path = ptr.pop_back();
14013  basic_json& parent = result.at(ptr);
14014 
14015  // remove child
14016  if (parent.is_object())
14017  {
14018  // perform range check
14019  auto it = parent.find(last_path);
14020  if (JSON_LIKELY(it != parent.end()))
14021  {
14022  parent.erase(it);
14023  }
14024  else
14025  {
14026  JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
14027  }
14028  }
14029  else if (parent.is_array())
14030  {
14031  // note erase performs range check
14032  parent.erase(static_cast<size_type>(std::stoi(last_path)));
14033  }
14034  };
14035 
14036  // type check: top level value must be an array
14037  if (JSON_UNLIKELY(not json_patch.is_array()))
14038  {
14039  JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
14040  }
14041 
14042  // iterate and apply the operations
14043  for (const auto& val : json_patch)
14044  {
14045  // wrapper to get a value for an operation
14046  const auto get_value = [&val](const std::string & op,
14047  const std::string & member,
14048  bool string_type) -> basic_json&
14049  {
14050  // find value
14051  auto it = val.m_value.object->find(member);
14052 
14053  // context-sensitive error message
14054  const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
14055 
14056  // check if desired value is present
14057  if (JSON_UNLIKELY(it == val.m_value.object->end()))
14058  {
14059  JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
14060  }
14061 
14062  // check if result is of type string
14063  if (JSON_UNLIKELY(string_type and not it->second.is_string()))
14064  {
14065  JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
14066  }
14067 
14068  // no error: return value
14069  return it->second;
14070  };
14071 
14072  // type check: every element of the array must be an object
14073  if (JSON_UNLIKELY(not val.is_object()))
14074  {
14075  JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
14076  }
14077 
14078  // collect mandatory members
14079  const std::string op = get_value("op", "op", true);
14080  const std::string path = get_value(op, "path", true);
14081  json_pointer ptr(path);
14082 
14083  switch (get_op(op))
14084  {
14085  case patch_operations::add:
14086  {
14087  operation_add(ptr, get_value("add", "value", false));
14088  break;
14089  }
14090 
14091  case patch_operations::remove:
14092  {
14093  operation_remove(ptr);
14094  break;
14095  }
14096 
14097  case patch_operations::replace:
14098  {
14099  // the "path" location must exist - use at()
14100  result.at(ptr) = get_value("replace", "value", false);
14101  break;
14102  }
14103 
14104  case patch_operations::move:
14105  {
14106  const std::string from_path = get_value("move", "from", true);
14107  json_pointer from_ptr(from_path);
14108 
14109  // the "from" location must exist - use at()
14110  basic_json v = result.at(from_ptr);
14111 
14112  // The move operation is functionally identical to a
14113  // "remove" operation on the "from" location, followed
14114  // immediately by an "add" operation at the target
14115  // location with the value that was just removed.
14116  operation_remove(from_ptr);
14117  operation_add(ptr, v);
14118  break;
14119  }
14120 
14121  case patch_operations::copy:
14122  {
14123  const std::string from_path = get_value("copy", "from", true);
14124  const json_pointer from_ptr(from_path);
14125 
14126  // the "from" location must exist - use at()
14127  result[ptr] = result.at(from_ptr);
14128  break;
14129  }
14130 
14131  case patch_operations::test:
14132  {
14133  bool success = false;
14134  JSON_TRY
14135  {
14136  // check if "value" matches the one at "path"
14137  // the "path" location must exist - use at()
14138  success = (result.at(ptr) == get_value("test", "value", false));
14139  }
14140  JSON_CATCH (out_of_range&)
14141  {
14142  // ignore out of range errors: success remains false
14143  }
14144 
14145  // throw an exception if test fails
14146  if (JSON_UNLIKELY(not success))
14147  {
14148  JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
14149  }
14150 
14151  break;
14152  }
14153 
14154  case patch_operations::invalid:
14155  {
14156  // op must be "add", "remove", "replace", "move", "copy", or
14157  // "test"
14158  JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
14159  }
14160  }
14161  }
14162 
14163  return result;
14164  }
14165 
14166  /*!
14167  @brief creates a diff as a JSON patch
14168 
14169  Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
14170  be changed into the value @a target by calling @ref patch function.
14171 
14172  @invariant For two JSON values @a source and @a target, the following code
14173  yields always `true`:
14174  @code {.cpp}
14175  source.patch(diff(source, target)) == target;
14176  @endcode
14177 
14178  @note Currently, only `remove`, `add`, and `replace` operations are
14179  generated.
14180 
14181  @param[in] source JSON value to compare from
14182  @param[in] target JSON value to compare against
14183  @param[in] path helper value to create JSON pointers
14184 
14185  @return a JSON patch to convert the @a source to @a target
14186 
14187  @complexity Linear in the lengths of @a source and @a target.
14188 
14189  @liveexample{The following code shows how a JSON patch is created as a
14190  diff for two JSON values.,diff}
14191 
14192  @sa @ref patch -- apply a JSON patch
14193 
14194  @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
14195 
14196  @since version 2.0.0
14197  */
14198  static basic_json diff(const basic_json& source, const basic_json& target,
14199  const std::string& path = "")
14200  {
14201  // the patch
14202  basic_json result(value_t::array);
14203 
14204  // if the values are the same, return empty patch
14205  if (source == target)
14206  {
14207  return result;
14208  }
14209 
14210  if (source.type() != target.type())
14211  {
14212  // different types: replace value
14213  result.push_back(
14214  {
14215  {"op", "replace"}, {"path", path}, {"value", target}
14216  });
14217  }
14218  else
14219  {
14220  switch (source.type())
14221  {
14222  case value_t::array:
14223  {
14224  // first pass: traverse common elements
14225  std::size_t i = 0;
14226  while (i < source.size() and i < target.size())
14227  {
14228  // recursive call to compare array values at index i
14229  auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
14230  result.insert(result.end(), temp_diff.begin(), temp_diff.end());
14231  ++i;
14232  }
14233 
14234  // i now reached the end of at least one array
14235  // in a second pass, traverse the remaining elements
14236 
14237  // remove my remaining elements
14238  const auto end_index = static_cast<difference_type>(result.size());
14239  while (i < source.size())
14240  {
14241  // add operations in reverse order to avoid invalid
14242  // indices
14243  result.insert(result.begin() + end_index, object(
14244  {
14245  {"op", "remove"},
14246  {"path", path + "/" + std::to_string(i)}
14247  }));
14248  ++i;
14249  }
14250 
14251  // add other remaining elements
14252  while (i < target.size())
14253  {
14254  result.push_back(
14255  {
14256  {"op", "add"},
14257  {"path", path + "/" + std::to_string(i)},
14258  {"value", target[i]}
14259  });
14260  ++i;
14261  }
14262 
14263  break;
14264  }
14265 
14266  case value_t::object:
14267  {
14268  // first pass: traverse this object's elements
14269  for (auto it = source.begin(); it != source.end(); ++it)
14270  {
14271  // escape the key name to be used in a JSON patch
14272  const auto key = json_pointer::escape(it.key());
14273 
14274  if (target.find(it.key()) != target.end())
14275  {
14276  // recursive call to compare object values at key it
14277  auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
14278  result.insert(result.end(), temp_diff.begin(), temp_diff.end());
14279  }
14280  else
14281  {
14282  // found a key that is not in o -> remove it
14283  result.push_back(object(
14284  {
14285  {"op", "remove"}, {"path", path + "/" + key}
14286  }));
14287  }
14288  }
14289 
14290  // second pass: traverse other object's elements
14291  for (auto it = target.begin(); it != target.end(); ++it)
14292  {
14293  if (source.find(it.key()) == source.end())
14294  {
14295  // found a key that is not in this -> add it
14296  const auto key = json_pointer::escape(it.key());
14297  result.push_back(
14298  {
14299  {"op", "add"}, {"path", path + "/" + key},
14300  {"value", it.value()}
14301  });
14302  }
14303  }
14304 
14305  break;
14306  }
14307 
14308  default:
14309  {
14310  // both primitive type: replace value
14311  result.push_back(
14312  {
14313  {"op", "replace"}, {"path", path}, {"value", target}
14314  });
14315  break;
14316  }
14317  }
14318  }
14319 
14320  return result;
14321  }
14322 
14323  /// @}
14324 };
14325 
14326 /////////////
14327 // presets //
14328 /////////////
14329 
14330 /*!
14331 @brief default JSON class
14332 
14333 This type is the default specialization of the @ref basic_json class which
14334 uses the standard template types.
14335 
14336 @since version 1.0.0
14337 */
14338 using json = basic_json<>;
14339 
14340 //////////////////
14341 // json_pointer //
14342 //////////////////
14343 
14346 json_pointer::get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const
14347 {
14348  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14349  auto result = &j;
14350 
14351  // in case no reference tokens exist, return a reference to the JSON value
14352  // j which will be overwritten by a primitive value
14353  for (const auto& reference_token : reference_tokens)
14354  {
14355  switch (result->m_type)
14356  {
14357  case detail::value_t::null:
14358  {
14359  if (reference_token == "0")
14360  {
14361  // start a new array if reference token is 0
14362  result = &result->operator[](0);
14363  }
14364  else
14365  {
14366  // start a new object otherwise
14367  result = &result->operator[](reference_token);
14368  }
14369  break;
14370  }
14371 
14372  case detail::value_t::object:
14373  {
14374  // create an entry in the object
14375  result = &result->operator[](reference_token);
14376  break;
14377  }
14378 
14379  case detail::value_t::array:
14380  {
14381  // create an entry in the array
14382  JSON_TRY
14383  {
14384  result = &result->operator[](static_cast<size_type>(std::stoi(reference_token)));
14385  }
14386  JSON_CATCH(std::invalid_argument&)
14387  {
14388  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14389  }
14390  break;
14391  }
14392 
14393  /*
14394  The following code is only reached if there exists a reference
14395  token _and_ the current value is primitive. In this case, we have
14396  an error situation, because primitive values may only occur as
14397  single value; that is, with an empty list of reference tokens.
14398  */
14399  default:
14400  JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
14401  }
14402  }
14403 
14404  return *result;
14405 }
14406 
14409 json_pointer::get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const
14410 {
14411  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14412  for (const auto& reference_token : reference_tokens)
14413  {
14414  // convert null values to arrays or objects before continuing
14415  if (ptr->m_type == detail::value_t::null)
14416  {
14417  // check if reference token is a number
14418  const bool nums =
14419  std::all_of(reference_token.begin(), reference_token.end(),
14420  [](const char x)
14421  {
14422  return (x >= '0' and x <= '9');
14423  });
14424 
14425  // change value to array for numbers or "-" or to object otherwise
14426  *ptr = (nums or reference_token == "-")
14427  ? detail::value_t::array
14428  : detail::value_t::object;
14429  }
14430 
14431  switch (ptr->m_type)
14432  {
14433  case detail::value_t::object:
14434  {
14435  // use unchecked object access
14436  ptr = &ptr->operator[](reference_token);
14437  break;
14438  }
14439 
14440  case detail::value_t::array:
14441  {
14442  // error condition (cf. RFC 6901, Sect. 4)
14443  if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
14444  {
14445  JSON_THROW(detail::parse_error::create(106, 0,
14446  "array index '" + reference_token +
14447  "' must not begin with '0'"));
14448  }
14449 
14450  if (reference_token == "-")
14451  {
14452  // explicitly treat "-" as index beyond the end
14453  ptr = &ptr->operator[](ptr->m_value.array->size());
14454  }
14455  else
14456  {
14457  // convert array index to number; unchecked access
14458  JSON_TRY
14459  {
14460  ptr = &ptr->operator[](
14461  static_cast<size_type>(std::stoi(reference_token)));
14462  }
14463  JSON_CATCH(std::invalid_argument&)
14464  {
14465  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14466  }
14467  }
14468  break;
14469  }
14470 
14471  default:
14472  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
14473  }
14474  }
14475 
14476  return *ptr;
14477 }
14478 
14481 json_pointer::get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const
14482 {
14483  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14484  for (const auto& reference_token : reference_tokens)
14485  {
14486  switch (ptr->m_type)
14487  {
14488  case detail::value_t::object:
14489  {
14490  // note: at performs range check
14491  ptr = &ptr->at(reference_token);
14492  break;
14493  }
14494 
14495  case detail::value_t::array:
14496  {
14497  if (JSON_UNLIKELY(reference_token == "-"))
14498  {
14499  // "-" always fails the range check
14500  JSON_THROW(detail::out_of_range::create(402,
14501  "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
14502  ") is out of range"));
14503  }
14504 
14505  // error condition (cf. RFC 6901, Sect. 4)
14506  if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
14507  {
14508  JSON_THROW(detail::parse_error::create(106, 0,
14509  "array index '" + reference_token +
14510  "' must not begin with '0'"));
14511  }
14512 
14513  // note: at performs range check
14514  JSON_TRY
14515  {
14516  ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
14517  }
14518  JSON_CATCH(std::invalid_argument&)
14519  {
14520  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14521  }
14522  break;
14523  }
14524 
14525  default:
14526  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
14527  }
14528  }
14529 
14530  return *ptr;
14531 }
14532 
14535 json_pointer::get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const
14536 {
14537  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14538  for (const auto& reference_token : reference_tokens)
14539  {
14540  switch (ptr->m_type)
14541  {
14542  case detail::value_t::object:
14543  {
14544  // use unchecked object access
14545  ptr = &ptr->operator[](reference_token);
14546  break;
14547  }
14548 
14549  case detail::value_t::array:
14550  {
14551  if (JSON_UNLIKELY(reference_token == "-"))
14552  {
14553  // "-" cannot be used for const access
14554  JSON_THROW(detail::out_of_range::create(402,
14555  "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
14556  ") is out of range"));
14557  }
14558 
14559  // error condition (cf. RFC 6901, Sect. 4)
14560  if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
14561  {
14562  JSON_THROW(detail::parse_error::create(106, 0,
14563  "array index '" + reference_token +
14564  "' must not begin with '0'"));
14565  }
14566 
14567  // use unchecked array access
14568  JSON_TRY
14569  {
14570  ptr = &ptr->operator[](
14571  static_cast<size_type>(std::stoi(reference_token)));
14572  }
14573  JSON_CATCH(std::invalid_argument&)
14574  {
14575  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14576  }
14577  break;
14578  }
14579 
14580  default:
14581  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
14582  }
14583  }
14584 
14585  return *ptr;
14586 }
14587 
14590 json_pointer::get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const
14591 {
14592  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14593  for (const auto& reference_token : reference_tokens)
14594  {
14595  switch (ptr->m_type)
14596  {
14597  case detail::value_t::object:
14598  {
14599  // note: at performs range check
14600  ptr = &ptr->at(reference_token);
14601  break;
14602  }
14603 
14604  case detail::value_t::array:
14605  {
14606  if (JSON_UNLIKELY(reference_token == "-"))
14607  {
14608  // "-" always fails the range check
14609  JSON_THROW(detail::out_of_range::create(402,
14610  "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
14611  ") is out of range"));
14612  }
14613 
14614  // error condition (cf. RFC 6901, Sect. 4)
14615  if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
14616  {
14617  JSON_THROW(detail::parse_error::create(106, 0,
14618  "array index '" + reference_token +
14619  "' must not begin with '0'"));
14620  }
14621 
14622  // note: at performs range check
14623  JSON_TRY
14624  {
14625  ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
14626  }
14627  JSON_CATCH(std::invalid_argument&)
14628  {
14629  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14630  }
14631  break;
14632  }
14633 
14634  default:
14635  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
14636  }
14637  }
14638 
14639  return *ptr;
14640 }
14641 
14643 void json_pointer::flatten(const std::string& reference_string,
14644  const NLOHMANN_BASIC_JSON_TPL& value,
14645  NLOHMANN_BASIC_JSON_TPL& result)
14646 {
14647  switch (value.m_type)
14648  {
14649  case detail::value_t::array:
14650  {
14651  if (value.m_value.array->empty())
14652  {
14653  // flatten empty array as null
14654  result[reference_string] = nullptr;
14655  }
14656  else
14657  {
14658  // iterate array and use index as reference string
14659  for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
14660  {
14661  flatten(reference_string + "/" + std::to_string(i),
14662  value.m_value.array->operator[](i), result);
14663  }
14664  }
14665  break;
14666  }
14667 
14668  case detail::value_t::object:
14669  {
14670  if (value.m_value.object->empty())
14671  {
14672  // flatten empty object as null
14673  result[reference_string] = nullptr;
14674  }
14675  else
14676  {
14677  // iterate object and use keys as reference string
14678  for (const auto& element : *value.m_value.object)
14679  {
14680  flatten(reference_string + "/" + escape(element.first), element.second, result);
14681  }
14682  }
14683  break;
14684  }
14685 
14686  default:
14687  {
14688  // add primitive value with its reference string
14689  result[reference_string] = value;
14690  break;
14691  }
14692  }
14693 }
14694 
14697 json_pointer::unflatten(const NLOHMANN_BASIC_JSON_TPL& value)
14698 {
14699  if (JSON_UNLIKELY(not value.is_object()))
14700  {
14701  JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
14702  }
14703 
14704  NLOHMANN_BASIC_JSON_TPL result;
14705 
14706  // iterate the JSON object values
14707  for (const auto& element : *value.m_value.object)
14708  {
14709  if (JSON_UNLIKELY(not element.second.is_primitive()))
14710  {
14711  JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
14712  }
14713 
14714  // assign value to reference pointed to by JSON pointer; Note that if
14715  // the JSON pointer is "" (i.e., points to the whole value), function
14716  // get_and_create returns a reference to result itself. An assignment
14717  // will then create a primitive value.
14718  json_pointer(element.first).get_and_create(result) = element.second;
14719  }
14720 
14721  return result;
14722 }
14723 
14724 inline bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept
14725 {
14726  return (lhs.reference_tokens == rhs.reference_tokens);
14727 }
14728 
14729 inline bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept
14730 {
14731  return not (lhs == rhs);
14732 }
14733 } // namespace nlohmann
14734 
14735 
14736 ///////////////////////
14737 // nonmember support //
14738 ///////////////////////
14740 // specialization of std::swap, and std::hash
14741 namespace std
14742 {
14743 /*!
14744 @brief exchanges the values of two JSON objects
14745 
14746 @since version 1.0.0
14747 */
14748 template<>
14749 inline void swap(nlohmann::json& j1,
14750  nlohmann::json& j2) noexcept(
14751  is_nothrow_move_constructible<nlohmann::json>::value and
14752  is_nothrow_move_assignable<nlohmann::json>::value
14753  )
14754 {
14755  j1.swap(j2);
14756 }
14757 
14758 /// hash value for JSON objects
14759 template<>
14760 struct hash<nlohmann::json>
14761 {
14762  /*!
14763  @brief return a hash value for a JSON object
14764 
14765  @since version 1.0.0
14766  */
14767  std::size_t operator()(const nlohmann::json& j) const
14768  {
14769  // a naive hashing via the string representation
14770  const auto& h = hash<nlohmann::json::string_t>();
14771  return h(j.dump());
14772  }
14773 };
14774 
14775 /// specialization for std::less<value_t>
14776 /// @note: do not remove the space after '<',
14777 /// see https://github.com/nlohmann/json/pull/679
14778 template<>
14779 struct less< ::nlohmann::detail::value_t>
14780 {
14781  /*!
14782  @brief compare two value_t enum values
14783  @since version 3.0.0
14784  */
14785  bool operator()(nlohmann::detail::value_t lhs,
14786  nlohmann::detail::value_t rhs) const noexcept
14787  {
14788  return nlohmann::detail::operator<(lhs, rhs);
14789  }
14790 };
14791 
14792 } // namespace std
14793 
14794 /*!
14795 @brief user-defined string literal for JSON values
14796 
14797 This operator implements a user-defined string literal for JSON objects. It
14798 can be used by adding `"_json"` to a string literal and returns a JSON object
14799 if no parse error occurred.
14800 
14801 @param[in] s a string representation of a JSON object
14802 @param[in] n the length of string @a s
14803 @return a JSON object
14804 
14805 @since version 1.0.0
14806 */
14807 inline nlohmann::json operator "" _json(const char* s, std::size_t n)
14808 {
14809  return nlohmann::json::parse(s, s + n);
14810 }
14811 
14812 /*!
14813 @brief user-defined string literal for JSON pointer
14814 
14815 This operator implements a user-defined string literal for JSON Pointers. It
14816 can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
14817 object if no parse error occurred.
14818 
14819 @param[in] s a string representation of a JSON Pointer
14820 @param[in] n the length of string @a s
14821 @return a JSON pointer object
14822 
14823 @since version 2.0.0
14824 */
14825 inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
14826 {
14827  return nlohmann::json::json_pointer(std::string(s, n));
14828 }
14829 
14830 // restore GCC/clang diagnostic settings
14831 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
14832  #pragma GCC diagnostic pop
14833 #endif
14834 #if defined(__clang__)
14835  #pragma GCC diagnostic pop
14836 #endif
14837 
14838 // clean up
14839 #undef JSON_CATCH
14840 #undef JSON_THROW
14841 #undef JSON_TRY
14842 #undef JSON_LIKELY
14843 #undef JSON_UNLIKELY
14844 #undef JSON_DEPRECATED
14845 #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
14846 #undef NLOHMANN_BASIC_JSON_TPL
14847 
14848 #endif
#define NLOHMANN_BASIC_JSON_TPL_DECLARATION
Definition: json.hpp:144
#define JSON_DEPRECATED
Definition: json.hpp:89
#define JSON_LIKELY(x)
Definition: json.hpp:108
#define NLOHMANN_JSON_HAS_HELPER(type)
Helper to determine whether there&#39;s a key_type for T.
Definition: json.hpp:801
#define JSON_UNLIKELY(x)
Definition: json.hpp:109
friend class basic_json
allow basic_json to access private members
Definition: json.hpp:6957
static void from_json(BasicJsonType &&j, ValueType &val) noexcept(noexcept(::nlohmann::from_json(std::forward< BasicJsonType >(j), val)))
convert a JSON value to any value type
Definition: json.hpp:6919
constexpr const auto & from_json
Definition: json.hpp:6895
#define JSON_CATCH(exception)
Definition: json.hpp:100
namespace for Niels Lohmann
Definition: json.hpp:125
#define NLOHMANN_BASIC_JSON_TPL
Definition: json.hpp:152
static void to_json(BasicJsonType &j, ValueType &&val) noexcept(noexcept(::nlohmann::to_json(j, std::forward< ValueType >(val))))
convert any value type to a JSON value
Definition: json.hpp:6935
#define JSON_TRY
Definition: json.hpp:99
#define JSON_THROW(exception)
Definition: json.hpp:98
constexpr const auto & to_json
Definition: json.hpp:6894
json_pointer(const std::string &s="")
create JSON pointer
Definition: json.hpp:6981
JSON Pointer.
Definition: json.hpp:6953