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 json.exception.other_error.502 | invalid object size for conversion | Some conversions to user-defined types impose constraints on the object size (e.g. std::pair)
460 
461 @sa @ref exception for the base class of the library exceptions
462 @sa @ref parse_error for exceptions indicating a parse error
463 @sa @ref invalid_iterator for exceptions indicating errors with iterators
464 @sa @ref type_error for exceptions indicating executing a member function with
465  a wrong type
466 @sa @ref out_of_range for exceptions indicating access out of the defined range
467 
468 @liveexample{The following code shows how an `other_error` exception can be
469 caught.,other_error}
470 
471 @since version 3.0.0
472 */
473 class other_error : public exception
474 {
475  public:
476  static other_error create(int id_, const std::string& what_arg)
477  {
478  std::string w = exception::name("other_error", id_) + what_arg;
479  return other_error(id_, w.c_str());
480  }
481 
482  private:
483  other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
484 };
485 
486 
487 
488 ///////////////////////////
489 // JSON type enumeration //
490 ///////////////////////////
491 
492 /*!
493 @brief the JSON type enumeration
494 
495 This enumeration collects the different JSON types. It is internally used to
496 distinguish the stored values, and the functions @ref basic_json::is_null(),
497 @ref basic_json::is_object(), @ref basic_json::is_array(),
498 @ref basic_json::is_string(), @ref basic_json::is_boolean(),
499 @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
500 @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
501 @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
502 @ref basic_json::is_structured() rely on it.
503 
504 @note There are three enumeration entries (number_integer, number_unsigned, and
505 number_float), because the library distinguishes these three types for numbers:
506 @ref basic_json::number_unsigned_t is used for unsigned integers,
507 @ref basic_json::number_integer_t is used for signed integers, and
508 @ref basic_json::number_float_t is used for floating-point numbers or to
509 approximate integers which do not fit in the limits of their respective type.
510 
511 @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
512 value with the default value for a given type
513 
514 @since version 1.0.0
515 */
516 enum class value_t : uint8_t
517 {
518  null, ///< null value
519  object, ///< object (unordered set of name/value pairs)
520  array, ///< array (ordered collection of values)
521  string, ///< string value
522  boolean, ///< boolean value
523  number_integer, ///< number value (signed integer)
524  number_unsigned, ///< number value (unsigned integer)
525  number_float, ///< number value (floating-point)
526  discarded ///< discarded by the the parser callback function
527 };
528 
529 /*!
530 @brief comparison operator for JSON types
531 
532 Returns an ordering that is similar to Python:
533 - order: null < boolean < number < object < array < string
534 - furthermore, each type is not smaller than itself
535 - discarded values are not comparable
536 
537 @since version 1.0.0
538 */
539 inline bool operator<(const value_t lhs, const value_t rhs) noexcept
540 {
541  static constexpr std::array<uint8_t, 8> order = {{
542  0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
543  1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
544  }
545  };
546 
547  const auto l_index = static_cast<std::size_t>(lhs);
548  const auto r_index = static_cast<std::size_t>(rhs);
549  return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
550 }
551 
552 
553 /////////////
554 // helpers //
555 /////////////
556 
557 template<typename> struct is_basic_json : std::false_type {};
558 
560 struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
561 
562 // alias templates to reduce boilerplate
563 template<bool B, typename T = void>
564 using enable_if_t = typename std::enable_if<B, T>::type;
565 
566 template<typename T>
567 using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
568 
569 // implementation of C++14 index_sequence and affiliates
570 // source: https://stackoverflow.com/a/32223343
571 template<std::size_t... Ints>
572 struct index_sequence
573 {
574  using type = index_sequence;
575  using value_type = std::size_t;
576  static constexpr std::size_t size() noexcept
577  {
578  return sizeof...(Ints);
579  }
580 };
581 
582 template<class Sequence1, class Sequence2>
583 struct merge_and_renumber;
584 
585 template<std::size_t... I1, std::size_t... I2>
586 struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
587  : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
588 
589 template<std::size_t N>
590 struct make_index_sequence
591  : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
592  typename make_index_sequence < N - N / 2 >::type > {};
593 
594 template<> struct make_index_sequence<0> : index_sequence<> {};
595 template<> struct make_index_sequence<1> : index_sequence<0> {};
596 
597 template<typename... Ts>
598 using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
599 
600 /*
601 Implementation of two C++17 constructs: conjunction, negation. This is needed
602 to avoid evaluating all the traits in a condition
603 
604 For example: not std::is_same<void, T>::value and has_value_type<T>::value
605 will not compile when T = void (on MSVC at least). Whereas
606 conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
607 stop evaluating if negation<...>::value == false
608 
609 Please note that those constructs must be used with caution, since symbols can
610 become very long quickly (which can slow down compilation and cause MSVC
611 internal compiler errors). Only use it when you have to (see example ahead).
612 */
613 template<class...> struct conjunction : std::true_type {};
614 template<class B1> struct conjunction<B1> : B1 {};
615 template<class B1, class... Bn>
616 struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
617 
618 template<class B> struct negation : std::integral_constant<bool, not B::value> {};
619 
620 // dispatch utility (taken from ranges-v3)
621 template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
622 template<> struct priority_tag<0> {};
623 
624 
625 //////////////////
626 // constructors //
627 //////////////////
628 
629 template<value_t> struct external_constructor;
630 
631 template<>
632 struct external_constructor<value_t::boolean>
633 {
634  template<typename BasicJsonType>
635  static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
636  {
637  j.m_type = value_t::boolean;
638  j.m_value = b;
639  j.assert_invariant();
640  }
641 };
642 
643 template<>
644 struct external_constructor<value_t::string>
645 {
646  template<typename BasicJsonType>
647  static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
648  {
649  j.m_type = value_t::string;
650  j.m_value = s;
651  j.assert_invariant();
652  }
653 
654  template<typename BasicJsonType>
655  static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
656  {
657  j.m_type = value_t::string;
658  j.m_value = std::move(s);
659  j.assert_invariant();
660  }
661 };
662 
663 template<>
664 struct external_constructor<value_t::number_float>
665 {
666  template<typename BasicJsonType>
667  static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
668  {
669  j.m_type = value_t::number_float;
670  j.m_value = val;
671  j.assert_invariant();
672  }
673 };
674 
675 template<>
676 struct external_constructor<value_t::number_unsigned>
677 {
678  template<typename BasicJsonType>
679  static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
680  {
681  j.m_type = value_t::number_unsigned;
682  j.m_value = val;
683  j.assert_invariant();
684  }
685 };
686 
687 template<>
688 struct external_constructor<value_t::number_integer>
689 {
690  template<typename BasicJsonType>
691  static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
692  {
693  j.m_type = value_t::number_integer;
694  j.m_value = val;
695  j.assert_invariant();
696  }
697 };
698 
699 template<>
700 struct external_constructor<value_t::array>
701 {
702  template<typename BasicJsonType>
703  static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
704  {
705  j.m_type = value_t::array;
706  j.m_value = arr;
707  j.assert_invariant();
708  }
709 
710  template<typename BasicJsonType>
711  static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
712  {
713  j.m_type = value_t::array;
714  j.m_value = std::move(arr);
715  j.assert_invariant();
716  }
717 
718  template<typename BasicJsonType, typename CompatibleArrayType,
719  enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
720  int> = 0>
721  static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
722  {
723  using std::begin;
724  using std::end;
725  j.m_type = value_t::array;
726  j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
727  j.assert_invariant();
728  }
729 
730  template<typename BasicJsonType>
731  static void construct(BasicJsonType& j, const std::vector<bool>& arr)
732  {
733  j.m_type = value_t::array;
734  j.m_value = value_t::array;
735  j.m_value.array->reserve(arr.size());
736  for (bool x : arr)
737  {
738  j.m_value.array->push_back(x);
739  }
740  j.assert_invariant();
741  }
742 
743  template<typename BasicJsonType, typename T,
744  enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
745  static void construct(BasicJsonType& j, const std::valarray<T>& arr)
746  {
747  j.m_type = value_t::array;
748  j.m_value = value_t::array;
749  j.m_value.array->resize(arr.size());
750  std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
751  j.assert_invariant();
752  }
753 };
754 
755 template<>
756 struct external_constructor<value_t::object>
757 {
758  template<typename BasicJsonType>
759  static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
760  {
761  j.m_type = value_t::object;
762  j.m_value = obj;
763  j.assert_invariant();
764  }
765 
766  template<typename BasicJsonType>
767  static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
768  {
769  j.m_type = value_t::object;
770  j.m_value = std::move(obj);
771  j.assert_invariant();
772  }
773 
774  template<typename BasicJsonType, typename CompatibleObjectType,
775  enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
776  static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
777  {
778  using std::begin;
779  using std::end;
780 
781  j.m_type = value_t::object;
782  j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
783  j.assert_invariant();
784  }
785 };
786 
787 
788 ////////////////////////
789 // has_/is_ functions //
790 ////////////////////////
791 
792 /*!
793 @brief Helper to determine whether there's a key_type for T.
794 
795 This helper is used to tell associative containers apart from other containers
796 such as sequence containers. For instance, `std::map` passes the test as it
797 contains a `mapped_type`, whereas `std::vector` fails the test.
798 
799 @sa http://stackoverflow.com/a/7728728/266378
800 @since version 1.0.0, overworked in version 2.0.6
801 */
802 #define NLOHMANN_JSON_HAS_HELPER(type)
803  template<typename T> struct has_##type {
804  private:
805  template<typename U, typename = typename U::type>
806  static int detect(U &&);
807  static void detect(...);
808  public:
809  static constexpr bool value =
810  std::is_integral<decltype(detect(std::declval<T>()))>::value;
811  }
812 
813 NLOHMANN_JSON_HAS_HELPER(mapped_type);
814 NLOHMANN_JSON_HAS_HELPER(key_type);
815 NLOHMANN_JSON_HAS_HELPER(value_type);
816 NLOHMANN_JSON_HAS_HELPER(iterator);
817 
818 #undef NLOHMANN_JSON_HAS_HELPER
819 
820 
821 template<bool B, class RealType, class CompatibleObjectType>
822 struct is_compatible_object_type_impl : std::false_type {};
823 
824 template<class RealType, class CompatibleObjectType>
825 struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
826 {
827  static constexpr auto value =
828  std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and
829  std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value;
830 };
831 
832 template<class BasicJsonType, class CompatibleObjectType>
833 struct is_compatible_object_type
834 {
835  static auto constexpr value = is_compatible_object_type_impl <
836  conjunction<negation<std::is_same<void, CompatibleObjectType>>,
837  has_mapped_type<CompatibleObjectType>,
838  has_key_type<CompatibleObjectType>>::value,
839  typename BasicJsonType::object_t, CompatibleObjectType >::value;
840 };
841 
842 template<typename BasicJsonType, typename T>
843 struct is_basic_json_nested_type
844 {
845  static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
846  std::is_same<T, typename BasicJsonType::const_iterator>::value or
847  std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
848  std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value;
849 };
850 
851 template<class BasicJsonType, class CompatibleArrayType>
852 struct is_compatible_array_type
853 {
854  static auto constexpr value =
855  conjunction<negation<std::is_same<void, CompatibleArrayType>>,
856  negation<is_compatible_object_type<
857  BasicJsonType, CompatibleArrayType>>,
858  negation<std::is_constructible<typename BasicJsonType::string_t,
859  CompatibleArrayType>>,
860  negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
861  has_value_type<CompatibleArrayType>,
862  has_iterator<CompatibleArrayType>>::value;
863 };
864 
865 template<bool, typename, typename>
866 struct is_compatible_integer_type_impl : std::false_type {};
867 
868 template<typename RealIntegerType, typename CompatibleNumberIntegerType>
869 struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
870 {
871  // is there an assert somewhere on overflows?
872  using RealLimits = std::numeric_limits<RealIntegerType>;
873  using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
874 
875  static constexpr auto value =
876  std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and
877  CompatibleLimits::is_integer and
878  RealLimits::is_signed == CompatibleLimits::is_signed;
879 };
880 
881 template<typename RealIntegerType, typename CompatibleNumberIntegerType>
882 struct is_compatible_integer_type
883 {
884  static constexpr auto value =
885  is_compatible_integer_type_impl <
886  std::is_integral<CompatibleNumberIntegerType>::value and
887  not std::is_same<bool, CompatibleNumberIntegerType>::value,
888  RealIntegerType, CompatibleNumberIntegerType >::value;
889 };
890 
891 
892 // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
893 template<typename BasicJsonType, typename T>
894 struct has_from_json
895 {
896  private:
897  // also check the return type of from_json
898  template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
899  std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
900  static int detect(U&&);
901  static void detect(...);
902 
903  public:
904  static constexpr bool value = std::is_integral<decltype(
905  detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
906 };
907 
908 // This trait checks if JSONSerializer<T>::from_json(json const&) exists
909 // this overload is used for non-default-constructible user-defined-types
910 template<typename BasicJsonType, typename T>
911 struct has_non_default_from_json
912 {
913  private:
914  template<typename U, typename =
915  enable_if_t<std::is_same<T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value>>
916  static int detect(U&&);
917  static void detect(...);
918 
919  public:
920  static constexpr bool value = std::is_integral<decltype(detect(
921  std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
922 };
923 
924 // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
925 template<typename BasicJsonType, typename T>
926 struct has_to_json
927 {
928  private:
929  template<typename U, typename = decltype(uncvref_t<U>::to_json(
930  std::declval<BasicJsonType&>(), std::declval<T>()))>
931  static int detect(U&&);
932  static void detect(...);
933 
934  public:
935  static constexpr bool value = std::is_integral<decltype(detect(
936  std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
937 };
938 
939 
940 /////////////
941 // to_json //
942 /////////////
943 
944 template<typename BasicJsonType, typename T,
945  enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
946 void to_json(BasicJsonType& j, T b) noexcept
947 {
948  external_constructor<value_t::boolean>::construct(j, b);
949 }
950 
951 template<typename BasicJsonType, typename CompatibleString,
952  enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
953 void to_json(BasicJsonType& j, const CompatibleString& s)
954 {
955  external_constructor<value_t::string>::construct(j, s);
956 }
957 
958 template<typename BasicJsonType>
959 void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
960 {
961  external_constructor<value_t::string>::construct(j, std::move(s));
962 }
963 
964 template<typename BasicJsonType, typename FloatType,
965  enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
966 void to_json(BasicJsonType& j, FloatType val) noexcept
967 {
968  external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
969 }
970 
971 template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
972  enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
973 void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
974 {
975  external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
976 }
977 
978 template<typename BasicJsonType, typename CompatibleNumberIntegerType,
979  enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
980 void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
981 {
982  external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
983 }
984 
985 template<typename BasicJsonType, typename EnumType,
986  enable_if_t<std::is_enum<EnumType>::value, int> = 0>
987 void to_json(BasicJsonType& j, EnumType e) noexcept
988 {
989  using underlying_type = typename std::underlying_type<EnumType>::type;
990  external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
991 }
992 
993 template<typename BasicJsonType>
994 void to_json(BasicJsonType& j, const std::vector<bool>& e)
995 {
996  external_constructor<value_t::array>::construct(j, e);
997 }
998 
999 template<typename BasicJsonType, typename CompatibleArrayType,
1000  enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
1001  std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
1002  int> = 0>
1003 void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
1004 {
1005  external_constructor<value_t::array>::construct(j, arr);
1006 }
1007 
1008 template<typename BasicJsonType, typename T,
1009  enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
1010 void to_json(BasicJsonType& j, std::valarray<T> arr)
1011 {
1012  external_constructor<value_t::array>::construct(j, std::move(arr));
1013 }
1014 
1015 template<typename BasicJsonType>
1016 void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
1017 {
1018  external_constructor<value_t::array>::construct(j, std::move(arr));
1019 }
1020 
1021 template<typename BasicJsonType, typename CompatibleObjectType,
1022  enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
1023 void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
1024 {
1025  external_constructor<value_t::object>::construct(j, obj);
1026 }
1027 
1028 template<typename BasicJsonType>
1029 void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
1030 {
1031  external_constructor<value_t::object>::construct(j, std::move(obj));
1032 }
1033 
1034 template<typename BasicJsonType, typename T, std::size_t N,
1035  enable_if_t<not std::is_constructible<typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0>
1036 void to_json(BasicJsonType& j, T (&arr)[N])
1037 {
1038  external_constructor<value_t::array>::construct(j, arr);
1039 }
1040 
1041 template<typename BasicJsonType, typename... Args>
1042 void to_json(BasicJsonType& j, const std::pair<Args...>& p)
1043 {
1044  j = {p.first, p.second};
1045 }
1046 
1047 template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
1048 void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>)
1049 {
1050  j = {std::get<Idx>(t)...};
1051 }
1052 
1053 template<typename BasicJsonType, typename... Args>
1054 void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
1055 {
1056  to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
1057 }
1058 
1059 ///////////////
1060 // from_json //
1061 ///////////////
1062 
1063 // overloads for basic_json template parameters
1064 template<typename BasicJsonType, typename ArithmeticType,
1065  enable_if_t<std::is_arithmetic<ArithmeticType>::value and
1066  not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
1067  int> = 0>
1068 void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
1069 {
1070  switch (static_cast<value_t>(j))
1071  {
1072  case value_t::number_unsigned:
1073  {
1074  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
1075  break;
1076  }
1077  case value_t::number_integer:
1078  {
1079  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
1080  break;
1081  }
1082  case value_t::number_float:
1083  {
1084  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
1085  break;
1086  }
1087 
1088  default:
1089  JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
1090  }
1091 }
1092 
1093 template<typename BasicJsonType>
1094 void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
1095 {
1096  if (JSON_UNLIKELY(not j.is_boolean()))
1097  {
1098  JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
1099  }
1100  b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
1101 }
1102 
1103 template<typename BasicJsonType>
1104 void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
1105 {
1106  if (JSON_UNLIKELY(not j.is_string()))
1107  {
1108  JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
1109  }
1110  s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
1111 }
1112 
1113 template<typename BasicJsonType>
1114 void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
1115 {
1116  get_arithmetic_value(j, val);
1117 }
1118 
1119 template<typename BasicJsonType>
1120 void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
1121 {
1122  get_arithmetic_value(j, val);
1123 }
1124 
1125 template<typename BasicJsonType>
1126 void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
1127 {
1128  get_arithmetic_value(j, val);
1129 }
1130 
1131 template<typename BasicJsonType, typename EnumType,
1132  enable_if_t<std::is_enum<EnumType>::value, int> = 0>
1133 void from_json(const BasicJsonType& j, EnumType& e)
1134 {
1135  typename std::underlying_type<EnumType>::type val;
1136  get_arithmetic_value(j, val);
1137  e = static_cast<EnumType>(val);
1138 }
1139 
1140 template<typename BasicJsonType>
1141 void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
1142 {
1143  if (JSON_UNLIKELY(not j.is_array()))
1144  {
1145  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1146  }
1147  arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
1148 }
1149 
1150 // forward_list doesn't have an insert method
1151 template<typename BasicJsonType, typename T, typename Allocator,
1152  enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
1153 void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
1154 {
1155  if (JSON_UNLIKELY(not j.is_array()))
1156  {
1157  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1158  }
1159  std::transform(j.rbegin(), j.rend(),
1160  std::front_inserter(l), [](const BasicJsonType & i)
1161  {
1162  return i.template get<T>();
1163  });
1164 }
1165 
1166 // valarray doesn't have an insert method
1167 template<typename BasicJsonType, typename T,
1168  enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
1169 void from_json(const BasicJsonType& j, std::valarray<T>& l)
1170 {
1171  if (JSON_UNLIKELY(not j.is_array()))
1172  {
1173  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1174  }
1175  l.resize(j.size());
1176  std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
1177 }
1178 
1179 template<typename BasicJsonType, typename CompatibleArrayType>
1180 void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/)
1181 {
1182  using std::end;
1183 
1184  std::transform(j.begin(), j.end(),
1185  std::inserter(arr, end(arr)), [](const BasicJsonType & i)
1186  {
1187  // get<BasicJsonType>() returns *this, this won't call a from_json
1188  // method when value_type is BasicJsonType
1189  return i.template get<typename CompatibleArrayType::value_type>();
1190  });
1191 }
1192 
1193 template<typename BasicJsonType, typename CompatibleArrayType>
1194 auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/)
1195 -> decltype(
1196  arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
1197  void())
1198 {
1199  using std::end;
1200 
1201  arr.reserve(j.size());
1202  std::transform(j.begin(), j.end(),
1203  std::inserter(arr, end(arr)), [](const BasicJsonType & i)
1204  {
1205  // get<BasicJsonType>() returns *this, this won't call a from_json
1206  // method when value_type is BasicJsonType
1207  return i.template get<typename CompatibleArrayType::value_type>();
1208  });
1209 }
1210 
1211 template<typename BasicJsonType, typename T, std::size_t N>
1212 void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/)
1213 {
1214  for (std::size_t i = 0; i < N; ++i)
1215  {
1216  arr[i] = j.at(i).template get<T>();
1217  }
1218 }
1219 
1220 template<typename BasicJsonType, typename CompatibleArrayType,
1221  enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
1222  std::is_convertible<BasicJsonType, typename CompatibleArrayType::value_type>::value and
1223  not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0>
1224 void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
1225 {
1226  if (JSON_UNLIKELY(not j.is_array()))
1227  {
1228  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1229  }
1230 
1231  from_json_array_impl(j, arr, priority_tag<2> {});
1232 }
1233 
1234 template<typename BasicJsonType, typename CompatibleObjectType,
1235  enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
1236 void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
1237 {
1238  if (JSON_UNLIKELY(not j.is_object()))
1239  {
1240  JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
1241  }
1242 
1243  auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
1244  using value_type = typename CompatibleObjectType::value_type;
1245  std::transform(
1246  inner_object->begin(), inner_object->end(),
1247  std::inserter(obj, obj.begin()),
1248  [](typename BasicJsonType::object_t::value_type const & p)
1249  {
1250  return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>());
1251  });
1252 }
1253 
1254 // overload for arithmetic types, not chosen for basic_json template arguments
1255 // (BooleanType, etc..); note: Is it really necessary to provide explicit
1256 // overloads for boolean_t etc. in case of a custom BooleanType which is not
1257 // an arithmetic type?
1258 template<typename BasicJsonType, typename ArithmeticType,
1259  enable_if_t <
1260  std::is_arithmetic<ArithmeticType>::value and
1261  not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
1262  not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
1263  not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
1264  not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
1265  int> = 0>
1266 void from_json(const BasicJsonType& j, ArithmeticType& val)
1267 {
1268  switch (static_cast<value_t>(j))
1269  {
1270  case value_t::number_unsigned:
1271  {
1272  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
1273  break;
1274  }
1275  case value_t::number_integer:
1276  {
1277  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
1278  break;
1279  }
1280  case value_t::number_float:
1281  {
1282  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
1283  break;
1284  }
1285  case value_t::boolean:
1286  {
1287  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
1288  break;
1289  }
1290 
1291  default:
1292  JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
1293  }
1294 }
1295 
1296 template<typename BasicJsonType, typename A1, typename A2>
1297 void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
1298 {
1299  p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
1300 }
1301 
1302 template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
1303 void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>)
1304 {
1305  t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
1306 }
1307 
1308 template<typename BasicJsonType, typename... Args>
1309 void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
1310 {
1311  from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
1312 }
1313 
1314 struct to_json_fn
1315 {
1316  private:
1317  template<typename BasicJsonType, typename T>
1318  auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
1319  -> decltype(to_json(j, std::forward<T>(val)), void())
1320  {
1321  return to_json(j, std::forward<T>(val));
1322  }
1323 
1324  template<typename BasicJsonType, typename T>
1325  void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept
1326  {
1327  static_assert(sizeof(BasicJsonType) == 0,
1328  "could not find to_json() method in T's namespace");
1329 
1330 #ifdef _MSC_VER
1331  // MSVC does not show a stacktrace for the above assert
1332  using decayed = uncvref_t<T>;
1333  static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
1334  "forcing MSVC stacktrace to show which T we're talking about.");
1335 #endif
1336  }
1337 
1338  public:
1339  template<typename BasicJsonType, typename T>
1340  void operator()(BasicJsonType& j, T&& val) const
1341  noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
1342  {
1343  return call(j, std::forward<T>(val), priority_tag<1> {});
1344  }
1345 };
1346 
1347 struct from_json_fn
1348 {
1349  private:
1350  template<typename BasicJsonType, typename T>
1351  auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const
1352  noexcept(noexcept(from_json(j, val)))
1353  -> decltype(from_json(j, val), void())
1354  {
1355  return from_json(j, val);
1356  }
1357 
1358  template<typename BasicJsonType, typename T>
1359  void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept
1360  {
1361  static_assert(sizeof(BasicJsonType) == 0,
1362  "could not find from_json() method in T's namespace");
1363 #ifdef _MSC_VER
1364  // MSVC does not show a stacktrace for the above assert
1365  using decayed = uncvref_t<T>;
1366  static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
1367  "forcing MSVC stacktrace to show which T we're talking about.");
1368 #endif
1369  }
1370 
1371  public:
1372  template<typename BasicJsonType, typename T>
1373  void operator()(const BasicJsonType& j, T& val) const
1374  noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
1375  {
1376  return call(j, val, priority_tag<1> {});
1377  }
1378 };
1379 
1380 // taken from ranges-v3
1381 template<typename T>
1382 struct static_const
1383 {
1384  static constexpr T value{};
1385 };
1386 
1387 template<typename T>
1388 constexpr T static_const<T>::value;
1389 
1390 ////////////////////
1391 // input adapters //
1392 ////////////////////
1393 
1394 /*!
1395 @brief abstract input adapter interface
1396 
1397 Produces a stream of std::char_traits<char>::int_type characters from a
1398 std::istream, a buffer, or some other input type. Accepts the return of exactly
1399 one non-EOF character for future input. The int_type characters returned
1400 consist of all valid char values as positive values (typically unsigned char),
1401 plus an EOF value outside that range, specified by the value of the function
1402 std::char_traits<char>::eof(). This value is typically -1, but could be any
1403 arbitrary value which is not a valid char value.
1404 */
1405 struct input_adapter_protocol
1406 {
1407  /// get a character [0,255] or std::char_traits<char>::eof().
1408  virtual std::char_traits<char>::int_type get_character() = 0;
1409  /// restore the last non-eof() character to input
1410  virtual void unget_character() = 0;
1411  virtual ~input_adapter_protocol() = default;
1412 };
1413 
1414 /// a type to simplify interfaces
1415 using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
1416 
1417 /*!
1418 Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
1419 beginning of input. Does not support changing the underlying std::streambuf
1420 in mid-input. Maintains underlying std::istream and std::streambuf to support
1421 subsequent use of standard std::istream operations to process any input
1422 characters following those used in parsing the JSON input. Clears the
1423 std::istream flags; any input errors (e.g., EOF) will be detected by the first
1424 subsequent call for input from the std::istream.
1425 */
1426 class input_stream_adapter : public input_adapter_protocol
1427 {
1428  public:
1429  ~input_stream_adapter() override
1430  {
1431  // clear stream flags; we use underlying streambuf I/O, do not
1432  // maintain ifstream flags
1433  is.clear();
1434  }
1435 
1436  explicit input_stream_adapter(std::istream& i)
1437  : is(i), sb(*i.rdbuf())
1438  {
1439  // skip byte order mark
1440  std::char_traits<char>::int_type c;
1441  if ((c = get_character()) == 0xEF)
1442  {
1443  if ((c = get_character()) == 0xBB)
1444  {
1445  if ((c = get_character()) == 0xBF)
1446  {
1447  return; // Ignore BOM
1448  }
1449  else if (c != std::char_traits<char>::eof())
1450  {
1451  is.unget();
1452  }
1453  is.putback('\xBB');
1454  }
1455  else if (c != std::char_traits<char>::eof())
1456  {
1457  is.unget();
1458  }
1459  is.putback('\xEF');
1460  }
1461  else if (c != std::char_traits<char>::eof())
1462  {
1463  is.unget(); // no byte order mark; process as usual
1464  }
1465  }
1466 
1467  // delete because of pointer members
1468  input_stream_adapter(const input_stream_adapter&) = delete;
1469  input_stream_adapter& operator=(input_stream_adapter&) = delete;
1470 
1471  // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
1472  // ensure that std::char_traits<char>::eof() and the character 0xFF do not
1473  // end up as the same value, eg. 0xFFFFFFFF.
1474  std::char_traits<char>::int_type get_character() override
1475  {
1476  return sb.sbumpc();
1477  }
1478 
1479  void unget_character() override
1480  {
1481  sb.sungetc(); // is.unget() avoided for performance
1482  }
1483 
1484  private:
1485  /// the associated input stream
1486  std::istream& is;
1487  std::streambuf& sb;
1488 };
1489 
1490 /// input adapter for buffer input
1491 class input_buffer_adapter : public input_adapter_protocol
1492 {
1493  public:
1494  input_buffer_adapter(const char* b, const std::size_t l)
1495  : cursor(b), limit(b + l), start(b)
1496  {
1497  // skip byte order mark
1498  if (l >= 3 and b[0] == '\xEF' and b[1] == '\xBB' and b[2] == '\xBF')
1499  {
1500  cursor += 3;
1501  }
1502  }
1503 
1504  // delete because of pointer members
1505  input_buffer_adapter(const input_buffer_adapter&) = delete;
1506  input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
1507 
1508  std::char_traits<char>::int_type get_character() noexcept override
1509  {
1510  if (JSON_LIKELY(cursor < limit))
1511  {
1512  return std::char_traits<char>::to_int_type(*(cursor++));
1513  }
1514 
1515  return std::char_traits<char>::eof();
1516  }
1517 
1518  void unget_character() noexcept override
1519  {
1520  if (JSON_LIKELY(cursor > start))
1521  {
1522  --cursor;
1523  }
1524  }
1525 
1526  private:
1527  /// pointer to the current character
1528  const char* cursor;
1529  /// pointer past the last character
1530  const char* limit;
1531  /// pointer to the first character
1532  const char* start;
1533 };
1534 
1535 class input_adapter
1536 {
1537  public:
1538  // native support
1539 
1540  /// input adapter for input stream
1541  input_adapter(std::istream& i)
1542  : ia(std::make_shared<input_stream_adapter>(i)) {}
1543 
1544  /// input adapter for input stream
1545  input_adapter(std::istream&& i)
1546  : ia(std::make_shared<input_stream_adapter>(i)) {}
1547 
1548  /// input adapter for buffer
1549  template<typename CharT,
1550  typename std::enable_if<
1551  std::is_pointer<CharT>::value and
1552  std::is_integral<typename std::remove_pointer<CharT>::type>::value and
1553  sizeof(typename std::remove_pointer<CharT>::type) == 1,
1554  int>::type = 0>
1555  input_adapter(CharT b, std::size_t l)
1556  : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
1557 
1558  // derived support
1559 
1560  /// input adapter for string literal
1561  template<typename CharT,
1562  typename std::enable_if<
1563  std::is_pointer<CharT>::value and
1564  std::is_integral<typename std::remove_pointer<CharT>::type>::value and
1565  sizeof(typename std::remove_pointer<CharT>::type) == 1,
1566  int>::type = 0>
1567  input_adapter(CharT b)
1568  : input_adapter(reinterpret_cast<const char*>(b),
1569  std::strlen(reinterpret_cast<const char*>(b))) {}
1570 
1571  /// input adapter for iterator range with contiguous storage
1572  template<class IteratorType,
1573  typename std::enable_if<
1574  std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
1575  int>::type = 0>
1576  input_adapter(IteratorType first, IteratorType last)
1577  {
1578  // assertion to check that the iterator range is indeed contiguous,
1579  // see http://stackoverflow.com/a/35008842/266378 for more discussion
1580  assert(std::accumulate(
1581  first, last, std::pair<bool, int>(true, 0),
1582  [&first](std::pair<bool, int> res, decltype(*first) val)
1583  {
1584  res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
1585  return res;
1586  }).first);
1587 
1588  // assertion to check that each element is 1 byte long
1589  static_assert(
1590  sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
1591  "each element in the iterator range must have the size of 1 byte");
1592 
1593  const auto len = static_cast<size_t>(std::distance(first, last));
1594  if (JSON_LIKELY(len > 0))
1595  {
1596  // there is at least one element: use the address of first
1597  ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
1598  }
1599  else
1600  {
1601  // the address of first cannot be used: use nullptr
1602  ia = std::make_shared<input_buffer_adapter>(nullptr, len);
1603  }
1604  }
1605 
1606  /// input adapter for array
1607  template<class T, std::size_t N>
1608  input_adapter(T (&array)[N])
1609  : input_adapter(std::begin(array), std::end(array)) {}
1610 
1611  /// input adapter for contiguous container
1612  template<class ContiguousContainer, typename
1613  std::enable_if<not std::is_pointer<ContiguousContainer>::value and
1614  std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
1615  int>::type = 0>
1616  input_adapter(const ContiguousContainer& c)
1617  : input_adapter(std::begin(c), std::end(c)) {}
1618 
1619  operator input_adapter_t()
1620  {
1621  return ia;
1622  }
1623 
1624  private:
1625  /// the actual adapter
1626  input_adapter_t ia = nullptr;
1627 };
1628 
1629 //////////////////////
1630 // lexer and parser //
1631 //////////////////////
1632 
1633 /*!
1634 @brief lexical analysis
1635 
1636 This class organizes the lexical analysis during JSON deserialization.
1637 */
1638 template<typename BasicJsonType>
1639 class lexer
1640 {
1641  using number_integer_t = typename BasicJsonType::number_integer_t;
1642  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
1643  using number_float_t = typename BasicJsonType::number_float_t;
1644 
1645  public:
1646  /// token types for the parser
1647  enum class token_type
1648  {
1649  uninitialized, ///< indicating the scanner is uninitialized
1650  literal_true, ///< the `true` literal
1651  literal_false, ///< the `false` literal
1652  literal_null, ///< the `null` literal
1653  value_string, ///< a string -- use get_string() for actual value
1654  value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
1655  value_integer, ///< a signed integer -- use get_number_integer() for actual value
1656  value_float, ///< an floating point number -- use get_number_float() for actual value
1657  begin_array, ///< the character for array begin `[`
1658  begin_object, ///< the character for object begin `{`
1659  end_array, ///< the character for array end `]`
1660  end_object, ///< the character for object end `}`
1661  name_separator, ///< the name separator `:`
1662  value_separator, ///< the value separator `,`
1663  parse_error, ///< indicating a parse error
1664  end_of_input, ///< indicating the end of the input buffer
1665  literal_or_value ///< a literal or the begin of a value (only for diagnostics)
1666  };
1667 
1668  /// return name of values of type token_type (only used for errors)
1669  static const char* token_type_name(const token_type t) noexcept
1670  {
1671  switch (t)
1672  {
1673  case token_type::uninitialized:
1674  return "<uninitialized>";
1675  case token_type::literal_true:
1676  return "true literal";
1677  case token_type::literal_false:
1678  return "false literal";
1679  case token_type::literal_null:
1680  return "null literal";
1681  case token_type::value_string:
1682  return "string literal";
1683  case lexer::token_type::value_unsigned:
1684  case lexer::token_type::value_integer:
1685  case lexer::token_type::value_float:
1686  return "number literal";
1687  case token_type::begin_array:
1688  return "'['";
1689  case token_type::begin_object:
1690  return "'{'";
1691  case token_type::end_array:
1692  return "']'";
1693  case token_type::end_object:
1694  return "'}'";
1695  case token_type::name_separator:
1696  return "':'";
1697  case token_type::value_separator:
1698  return "','";
1699  case token_type::parse_error:
1700  return "<parse error>";
1701  case token_type::end_of_input:
1702  return "end of input";
1703  case token_type::literal_or_value:
1704  return "'[', '{', or a literal";
1705  default: // catch non-enum values
1706  return "unknown token"; // LCOV_EXCL_LINE
1707  }
1708  }
1709 
1710  explicit lexer(detail::input_adapter_t adapter)
1711  : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
1712 
1713  // delete because of pointer members
1714  lexer(const lexer&) = delete;
1715  lexer& operator=(lexer&) = delete;
1716 
1717  private:
1718  /////////////////////
1719  // locales
1720  /////////////////////
1721 
1722  /// return the locale-dependent decimal point
1723  static char get_decimal_point() noexcept
1724  {
1725  const auto loc = localeconv();
1726  assert(loc != nullptr);
1727  return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
1728  }
1729 
1730  /////////////////////
1731  // scan functions
1732  /////////////////////
1733 
1734  /*!
1735  @brief get codepoint from 4 hex characters following `\u`
1736 
1737  For input "\u c1 c2 c3 c4" the codepoint is:
1738  (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
1739  = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
1740 
1741  Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
1742  must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
1743  conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
1744  between the ASCII value of the character and the desired integer value.
1745 
1746  @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
1747  non-hex character)
1748  */
1749  int get_codepoint()
1750  {
1751  // this function only makes sense after reading `\u`
1752  assert(current == 'u');
1753  int codepoint = 0;
1754 
1755  const auto factors = { 12, 8, 4, 0 };
1756  for (const auto factor : factors)
1757  {
1758  get();
1759 
1760  if (current >= '0' and current <= '9')
1761  {
1762  codepoint += ((current - 0x30) << factor);
1763  }
1764  else if (current >= 'A' and current <= 'F')
1765  {
1766  codepoint += ((current - 0x37) << factor);
1767  }
1768  else if (current >= 'a' and current <= 'f')
1769  {
1770  codepoint += ((current - 0x57) << factor);
1771  }
1772  else
1773  {
1774  return -1;
1775  }
1776  }
1777 
1778  assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
1779  return codepoint;
1780  }
1781 
1782  /*!
1783  @brief check if the next byte(s) are inside a given range
1784 
1785  Adds the current byte and, for each passed range, reads a new byte and
1786  checks if it is inside the range. If a violation was detected, set up an
1787  error message and return false. Otherwise, return true.
1788 
1789  @param[in] ranges list of integers; interpreted as list of pairs of
1790  inclusive lower and upper bound, respectively
1791 
1792  @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
1793  1, 2, or 3 pairs. This precondition is enforced by an assertion.
1794 
1795  @return true if and only if no range violation was detected
1796  */
1797  bool next_byte_in_range(std::initializer_list<int> ranges)
1798  {
1799  assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
1800  add(current);
1801 
1802  for (auto range = ranges.begin(); range != ranges.end(); ++range)
1803  {
1804  get();
1805  if (JSON_LIKELY(*range <= current and current <= *(++range)))
1806  {
1807  add(current);
1808  }
1809  else
1810  {
1811  error_message = "invalid string: ill-formed UTF-8 byte";
1812  return false;
1813  }
1814  }
1815 
1816  return true;
1817  }
1818 
1819  /*!
1820  @brief scan a string literal
1821 
1822  This function scans a string according to Sect. 7 of RFC 7159. While
1823  scanning, bytes are escaped and copied into buffer yytext. Then the function
1824  returns successfully, yytext is *not* null-terminated (as it may contain \0
1825  bytes), and yytext.size() is the number of bytes in the string.
1826 
1827  @return token_type::value_string if string could be successfully scanned,
1828  token_type::parse_error otherwise
1829 
1830  @note In case of errors, variable error_message contains a textual
1831  description.
1832  */
1833  token_type scan_string()
1834  {
1835  // reset yytext (ignore opening quote)
1836  reset();
1837 
1838  // we entered the function by reading an open quote
1839  assert(current == '\"');
1840 
1841  while (true)
1842  {
1843  // get next character
1844  switch (get())
1845  {
1846  // end of file while parsing string
1847  case std::char_traits<char>::eof():
1848  {
1849  error_message = "invalid string: missing closing quote";
1850  return token_type::parse_error;
1851  }
1852 
1853  // closing quote
1854  case '\"':
1855  {
1856  return token_type::value_string;
1857  }
1858 
1859  // escapes
1860  case '\\':
1861  {
1862  switch (get())
1863  {
1864  // quotation mark
1865  case '\"':
1866  add('\"');
1867  break;
1868  // reverse solidus
1869  case '\\':
1870  add('\\');
1871  break;
1872  // solidus
1873  case '/':
1874  add('/');
1875  break;
1876  // backspace
1877  case 'b':
1878  add('\b');
1879  break;
1880  // form feed
1881  case 'f':
1882  add('\f');
1883  break;
1884  // line feed
1885  case 'n':
1886  add('\n');
1887  break;
1888  // carriage return
1889  case 'r':
1890  add('\r');
1891  break;
1892  // tab
1893  case 't':
1894  add('\t');
1895  break;
1896 
1897  // unicode escapes
1898  case 'u':
1899  {
1900  const int codepoint1 = get_codepoint();
1901  int codepoint = codepoint1; // start with codepoint1
1902 
1903  if (JSON_UNLIKELY(codepoint1 == -1))
1904  {
1905  error_message = "invalid string: '\\u' must be followed by 4 hex digits";
1906  return token_type::parse_error;
1907  }
1908 
1909  // check if code point is a high surrogate
1910  if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
1911  {
1912  // expect next \uxxxx entry
1913  if (JSON_LIKELY(get() == '\\' and get() == 'u'))
1914  {
1915  const int codepoint2 = get_codepoint();
1916 
1917  if (JSON_UNLIKELY(codepoint2 == -1))
1918  {
1919  error_message = "invalid string: '\\u' must be followed by 4 hex digits";
1920  return token_type::parse_error;
1921  }
1922 
1923  // check if codepoint2 is a low surrogate
1924  if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
1925  {
1926  // overwrite codepoint
1927  codepoint =
1928  // high surrogate occupies the most significant 22 bits
1929  (codepoint1 << 10)
1930  // low surrogate occupies the least significant 15 bits
1931  + codepoint2
1932  // there is still the 0xD800, 0xDC00 and 0x10000 noise
1933  // in the result so we have to subtract with:
1934  // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
1935  - 0x35FDC00;
1936  }
1937  else
1938  {
1939  error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
1940  return token_type::parse_error;
1941  }
1942  }
1943  else
1944  {
1945  error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
1946  return token_type::parse_error;
1947  }
1948  }
1949  else
1950  {
1951  if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
1952  {
1953  error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
1954  return token_type::parse_error;
1955  }
1956  }
1957 
1958  // result of the above calculation yields a proper codepoint
1959  assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
1960 
1961  // translate codepoint into bytes
1962  if (codepoint < 0x80)
1963  {
1964  // 1-byte characters: 0xxxxxxx (ASCII)
1965  add(codepoint);
1966  }
1967  else if (codepoint <= 0x7FF)
1968  {
1969  // 2-byte characters: 110xxxxx 10xxxxxx
1970  add(0xC0 | (codepoint >> 6));
1971  add(0x80 | (codepoint & 0x3F));
1972  }
1973  else if (codepoint <= 0xFFFF)
1974  {
1975  // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
1976  add(0xE0 | (codepoint >> 12));
1977  add(0x80 | ((codepoint >> 6) & 0x3F));
1978  add(0x80 | (codepoint & 0x3F));
1979  }
1980  else
1981  {
1982  // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1983  add(0xF0 | (codepoint >> 18));
1984  add(0x80 | ((codepoint >> 12) & 0x3F));
1985  add(0x80 | ((codepoint >> 6) & 0x3F));
1986  add(0x80 | (codepoint & 0x3F));
1987  }
1988 
1989  break;
1990  }
1991 
1992  // other characters after escape
1993  default:
1994  error_message = "invalid string: forbidden character after backslash";
1995  return token_type::parse_error;
1996  }
1997 
1998  break;
1999  }
2000 
2001  // invalid control characters
2002  case 0x00:
2003  case 0x01:
2004  case 0x02:
2005  case 0x03:
2006  case 0x04:
2007  case 0x05:
2008  case 0x06:
2009  case 0x07:
2010  case 0x08:
2011  case 0x09:
2012  case 0x0A:
2013  case 0x0B:
2014  case 0x0C:
2015  case 0x0D:
2016  case 0x0E:
2017  case 0x0F:
2018  case 0x10:
2019  case 0x11:
2020  case 0x12:
2021  case 0x13:
2022  case 0x14:
2023  case 0x15:
2024  case 0x16:
2025  case 0x17:
2026  case 0x18:
2027  case 0x19:
2028  case 0x1A:
2029  case 0x1B:
2030  case 0x1C:
2031  case 0x1D:
2032  case 0x1E:
2033  case 0x1F:
2034  {
2035  error_message = "invalid string: control character must be escaped";
2036  return token_type::parse_error;
2037  }
2038 
2039  // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
2040  case 0x20:
2041  case 0x21:
2042  case 0x23:
2043  case 0x24:
2044  case 0x25:
2045  case 0x26:
2046  case 0x27:
2047  case 0x28:
2048  case 0x29:
2049  case 0x2A:
2050  case 0x2B:
2051  case 0x2C:
2052  case 0x2D:
2053  case 0x2E:
2054  case 0x2F:
2055  case 0x30:
2056  case 0x31:
2057  case 0x32:
2058  case 0x33:
2059  case 0x34:
2060  case 0x35:
2061  case 0x36:
2062  case 0x37:
2063  case 0x38:
2064  case 0x39:
2065  case 0x3A:
2066  case 0x3B:
2067  case 0x3C:
2068  case 0x3D:
2069  case 0x3E:
2070  case 0x3F:
2071  case 0x40:
2072  case 0x41:
2073  case 0x42:
2074  case 0x43:
2075  case 0x44:
2076  case 0x45:
2077  case 0x46:
2078  case 0x47:
2079  case 0x48:
2080  case 0x49:
2081  case 0x4A:
2082  case 0x4B:
2083  case 0x4C:
2084  case 0x4D:
2085  case 0x4E:
2086  case 0x4F:
2087  case 0x50:
2088  case 0x51:
2089  case 0x52:
2090  case 0x53:
2091  case 0x54:
2092  case 0x55:
2093  case 0x56:
2094  case 0x57:
2095  case 0x58:
2096  case 0x59:
2097  case 0x5A:
2098  case 0x5B:
2099  case 0x5D:
2100  case 0x5E:
2101  case 0x5F:
2102  case 0x60:
2103  case 0x61:
2104  case 0x62:
2105  case 0x63:
2106  case 0x64:
2107  case 0x65:
2108  case 0x66:
2109  case 0x67:
2110  case 0x68:
2111  case 0x69:
2112  case 0x6A:
2113  case 0x6B:
2114  case 0x6C:
2115  case 0x6D:
2116  case 0x6E:
2117  case 0x6F:
2118  case 0x70:
2119  case 0x71:
2120  case 0x72:
2121  case 0x73:
2122  case 0x74:
2123  case 0x75:
2124  case 0x76:
2125  case 0x77:
2126  case 0x78:
2127  case 0x79:
2128  case 0x7A:
2129  case 0x7B:
2130  case 0x7C:
2131  case 0x7D:
2132  case 0x7E:
2133  case 0x7F:
2134  {
2135  add(current);
2136  break;
2137  }
2138 
2139  // U+0080..U+07FF: bytes C2..DF 80..BF
2140  case 0xC2:
2141  case 0xC3:
2142  case 0xC4:
2143  case 0xC5:
2144  case 0xC6:
2145  case 0xC7:
2146  case 0xC8:
2147  case 0xC9:
2148  case 0xCA:
2149  case 0xCB:
2150  case 0xCC:
2151  case 0xCD:
2152  case 0xCE:
2153  case 0xCF:
2154  case 0xD0:
2155  case 0xD1:
2156  case 0xD2:
2157  case 0xD3:
2158  case 0xD4:
2159  case 0xD5:
2160  case 0xD6:
2161  case 0xD7:
2162  case 0xD8:
2163  case 0xD9:
2164  case 0xDA:
2165  case 0xDB:
2166  case 0xDC:
2167  case 0xDD:
2168  case 0xDE:
2169  case 0xDF:
2170  {
2171  if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
2172  {
2173  return token_type::parse_error;
2174  }
2175  break;
2176  }
2177 
2178  // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
2179  case 0xE0:
2180  {
2181  if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
2182  {
2183  return token_type::parse_error;
2184  }
2185  break;
2186  }
2187 
2188  // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
2189  // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
2190  case 0xE1:
2191  case 0xE2:
2192  case 0xE3:
2193  case 0xE4:
2194  case 0xE5:
2195  case 0xE6:
2196  case 0xE7:
2197  case 0xE8:
2198  case 0xE9:
2199  case 0xEA:
2200  case 0xEB:
2201  case 0xEC:
2202  case 0xEE:
2203  case 0xEF:
2204  {
2205  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
2206  {
2207  return token_type::parse_error;
2208  }
2209  break;
2210  }
2211 
2212  // U+D000..U+D7FF: bytes ED 80..9F 80..BF
2213  case 0xED:
2214  {
2215  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
2216  {
2217  return token_type::parse_error;
2218  }
2219  break;
2220  }
2221 
2222  // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
2223  case 0xF0:
2224  {
2225  if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
2226  {
2227  return token_type::parse_error;
2228  }
2229  break;
2230  }
2231 
2232  // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
2233  case 0xF1:
2234  case 0xF2:
2235  case 0xF3:
2236  {
2237  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
2238  {
2239  return token_type::parse_error;
2240  }
2241  break;
2242  }
2243 
2244  // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
2245  case 0xF4:
2246  {
2247  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
2248  {
2249  return token_type::parse_error;
2250  }
2251  break;
2252  }
2253 
2254  // remaining bytes (80..C1 and F5..FF) are ill-formed
2255  default:
2256  {
2257  error_message = "invalid string: ill-formed UTF-8 byte";
2258  return token_type::parse_error;
2259  }
2260  }
2261  }
2262  }
2263 
2264  static void strtof(float& f, const char* str, char** endptr) noexcept
2265  {
2266  f = std::strtof(str, endptr);
2267  }
2268 
2269  static void strtof(double& f, const char* str, char** endptr) noexcept
2270  {
2271  f = std::strtod(str, endptr);
2272  }
2273 
2274  static void strtof(long double& f, const char* str, char** endptr) noexcept
2275  {
2276  f = std::strtold(str, endptr);
2277  }
2278 
2279  /*!
2280  @brief scan a number literal
2281 
2282  This function scans a string according to Sect. 6 of RFC 7159.
2283 
2284  The function is realized with a deterministic finite state machine derived
2285  from the grammar described in RFC 7159. Starting in state "init", the
2286  input is read and used to determined the next state. Only state "done"
2287  accepts the number. State "error" is a trap state to model errors. In the
2288  table below, "anything" means any character but the ones listed before.
2289 
2290  state | 0 | 1-9 | e E | + | - | . | anything
2291  ---------|----------|----------|----------|---------|---------|----------|-----------
2292  init | zero | any1 | [error] | [error] | minus | [error] | [error]
2293  minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
2294  zero | done | done | exponent | done | done | decimal1 | done
2295  any1 | any1 | any1 | exponent | done | done | decimal1 | done
2296  decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
2297  decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
2298  exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
2299  sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
2300  any2 | any2 | any2 | done | done | done | done | done
2301 
2302  The state machine is realized with one label per state (prefixed with
2303  "scan_number_") and `goto` statements between them. The state machine
2304  contains cycles, but any cycle can be left when EOF is read. Therefore,
2305  the function is guaranteed to terminate.
2306 
2307  During scanning, the read bytes are stored in yytext. This string is
2308  then converted to a signed integer, an unsigned integer, or a
2309  floating-point number.
2310 
2311  @return token_type::value_unsigned, token_type::value_integer, or
2312  token_type::value_float if number could be successfully scanned,
2313  token_type::parse_error otherwise
2314 
2315  @note The scanner is independent of the current locale. Internally, the
2316  locale's decimal point is used instead of `.` to work with the
2317  locale-dependent converters.
2318  */
2319  token_type scan_number()
2320  {
2321  // reset yytext to store the number's bytes
2322  reset();
2323 
2324  // the type of the parsed number; initially set to unsigned; will be
2325  // changed if minus sign, decimal point or exponent is read
2326  token_type number_type = token_type::value_unsigned;
2327 
2328  // state (init): we just found out we need to scan a number
2329  switch (current)
2330  {
2331  case '-':
2332  {
2333  add(current);
2334  goto scan_number_minus;
2335  }
2336 
2337  case '0':
2338  {
2339  add(current);
2340  goto scan_number_zero;
2341  }
2342 
2343  case '1':
2344  case '2':
2345  case '3':
2346  case '4':
2347  case '5':
2348  case '6':
2349  case '7':
2350  case '8':
2351  case '9':
2352  {
2353  add(current);
2354  goto scan_number_any1;
2355  }
2356 
2357  default:
2358  {
2359  // all other characters are rejected outside scan_number()
2360  assert(false); // LCOV_EXCL_LINE
2361  }
2362  }
2363 
2364 scan_number_minus:
2365  // state: we just parsed a leading minus sign
2366  number_type = token_type::value_integer;
2367  switch (get())
2368  {
2369  case '0':
2370  {
2371  add(current);
2372  goto scan_number_zero;
2373  }
2374 
2375  case '1':
2376  case '2':
2377  case '3':
2378  case '4':
2379  case '5':
2380  case '6':
2381  case '7':
2382  case '8':
2383  case '9':
2384  {
2385  add(current);
2386  goto scan_number_any1;
2387  }
2388 
2389  default:
2390  {
2391  error_message = "invalid number; expected digit after '-'";
2392  return token_type::parse_error;
2393  }
2394  }
2395 
2396 scan_number_zero:
2397  // state: we just parse a zero (maybe with a leading minus sign)
2398  switch (get())
2399  {
2400  case '.':
2401  {
2402  add(decimal_point_char);
2403  goto scan_number_decimal1;
2404  }
2405 
2406  case 'e':
2407  case 'E':
2408  {
2409  add(current);
2410  goto scan_number_exponent;
2411  }
2412 
2413  default:
2414  goto scan_number_done;
2415  }
2416 
2417 scan_number_any1:
2418  // state: we just parsed a number 0-9 (maybe with a leading minus sign)
2419  switch (get())
2420  {
2421  case '0':
2422  case '1':
2423  case '2':
2424  case '3':
2425  case '4':
2426  case '5':
2427  case '6':
2428  case '7':
2429  case '8':
2430  case '9':
2431  {
2432  add(current);
2433  goto scan_number_any1;
2434  }
2435 
2436  case '.':
2437  {
2438  add(decimal_point_char);
2439  goto scan_number_decimal1;
2440  }
2441 
2442  case 'e':
2443  case 'E':
2444  {
2445  add(current);
2446  goto scan_number_exponent;
2447  }
2448 
2449  default:
2450  goto scan_number_done;
2451  }
2452 
2453 scan_number_decimal1:
2454  // state: we just parsed a decimal point
2455  number_type = token_type::value_float;
2456  switch (get())
2457  {
2458  case '0':
2459  case '1':
2460  case '2':
2461  case '3':
2462  case '4':
2463  case '5':
2464  case '6':
2465  case '7':
2466  case '8':
2467  case '9':
2468  {
2469  add(current);
2470  goto scan_number_decimal2;
2471  }
2472 
2473  default:
2474  {
2475  error_message = "invalid number; expected digit after '.'";
2476  return token_type::parse_error;
2477  }
2478  }
2479 
2480 scan_number_decimal2:
2481  // we just parsed at least one number after a decimal point
2482  switch (get())
2483  {
2484  case '0':
2485  case '1':
2486  case '2':
2487  case '3':
2488  case '4':
2489  case '5':
2490  case '6':
2491  case '7':
2492  case '8':
2493  case '9':
2494  {
2495  add(current);
2496  goto scan_number_decimal2;
2497  }
2498 
2499  case 'e':
2500  case 'E':
2501  {
2502  add(current);
2503  goto scan_number_exponent;
2504  }
2505 
2506  default:
2507  goto scan_number_done;
2508  }
2509 
2510 scan_number_exponent:
2511  // we just parsed an exponent
2512  number_type = token_type::value_float;
2513  switch (get())
2514  {
2515  case '+':
2516  case '-':
2517  {
2518  add(current);
2519  goto scan_number_sign;
2520  }
2521 
2522  case '0':
2523  case '1':
2524  case '2':
2525  case '3':
2526  case '4':
2527  case '5':
2528  case '6':
2529  case '7':
2530  case '8':
2531  case '9':
2532  {
2533  add(current);
2534  goto scan_number_any2;
2535  }
2536 
2537  default:
2538  {
2539  error_message =
2540  "invalid number; expected '+', '-', or digit after exponent";
2541  return token_type::parse_error;
2542  }
2543  }
2544 
2545 scan_number_sign:
2546  // we just parsed an exponent sign
2547  switch (get())
2548  {
2549  case '0':
2550  case '1':
2551  case '2':
2552  case '3':
2553  case '4':
2554  case '5':
2555  case '6':
2556  case '7':
2557  case '8':
2558  case '9':
2559  {
2560  add(current);
2561  goto scan_number_any2;
2562  }
2563 
2564  default:
2565  {
2566  error_message = "invalid number; expected digit after exponent sign";
2567  return token_type::parse_error;
2568  }
2569  }
2570 
2571 scan_number_any2:
2572  // we just parsed a number after the exponent or exponent sign
2573  switch (get())
2574  {
2575  case '0':
2576  case '1':
2577  case '2':
2578  case '3':
2579  case '4':
2580  case '5':
2581  case '6':
2582  case '7':
2583  case '8':
2584  case '9':
2585  {
2586  add(current);
2587  goto scan_number_any2;
2588  }
2589 
2590  default:
2591  goto scan_number_done;
2592  }
2593 
2594 scan_number_done:
2595  // unget the character after the number (we only read it to know that
2596  // we are done scanning a number)
2597  unget();
2598 
2599  char* endptr = nullptr;
2600  errno = 0;
2601 
2602  // try to parse integers first and fall back to floats
2603  if (number_type == token_type::value_unsigned)
2604  {
2605  const auto x = std::strtoull(yytext.data(), &endptr, 10);
2606 
2607  // we checked the number format before
2608  assert(endptr == yytext.data() + yytext.size());
2609 
2610  if (errno == 0)
2611  {
2612  value_unsigned = static_cast<number_unsigned_t>(x);
2613  if (value_unsigned == x)
2614  {
2615  return token_type::value_unsigned;
2616  }
2617  }
2618  }
2619  else if (number_type == token_type::value_integer)
2620  {
2621  const auto x = std::strtoll(yytext.data(), &endptr, 10);
2622 
2623  // we checked the number format before
2624  assert(endptr == yytext.data() + yytext.size());
2625 
2626  if (errno == 0)
2627  {
2628  value_integer = static_cast<number_integer_t>(x);
2629  if (value_integer == x)
2630  {
2631  return token_type::value_integer;
2632  }
2633  }
2634  }
2635 
2636  // this code is reached if we parse a floating-point number or if an
2637  // integer conversion above failed
2638  strtof(value_float, yytext.data(), &endptr);
2639 
2640  // we checked the number format before
2641  assert(endptr == yytext.data() + yytext.size());
2642 
2643  return token_type::value_float;
2644  }
2645 
2646  /*!
2647  @param[in] literal_text the literal text to expect
2648  @param[in] length the length of the passed literal text
2649  @param[in] return_type the token type to return on success
2650  */
2651  token_type scan_literal(const char* literal_text, const std::size_t length,
2652  token_type return_type)
2653  {
2654  assert(current == literal_text[0]);
2655  for (std::size_t i = 1; i < length; ++i)
2656  {
2657  if (JSON_UNLIKELY(get() != literal_text[i]))
2658  {
2659  error_message = "invalid literal";
2660  return token_type::parse_error;
2661  }
2662  }
2663  return return_type;
2664  }
2665 
2666  /////////////////////
2667  // input management
2668  /////////////////////
2669 
2670  /// reset yytext; current character is beginning of token
2671  void reset() noexcept
2672  {
2673  yytext.clear();
2674  token_string.clear();
2675  token_string.push_back(std::char_traits<char>::to_char_type(current));
2676  }
2677 
2678  /*
2679  @brief get next character from the input
2680 
2681  This function provides the interface to the used input adapter. It does
2682  not throw in case the input reached EOF, but returns a
2683  `std::char_traits<char>::eof()` in that case. Stores the scanned characters
2684  for use in error messages.
2685 
2686  @return character read from the input
2687  */
2688  std::char_traits<char>::int_type get()
2689  {
2690  ++chars_read;
2691  current = ia->get_character();
2692  if (JSON_LIKELY(current != std::char_traits<char>::eof()))
2693  {
2694  token_string.push_back(std::char_traits<char>::to_char_type(current));
2695  }
2696  return current;
2697  }
2698 
2699  /// unget current character (return it again on next get)
2700  void unget()
2701  {
2702  --chars_read;
2703  if (JSON_LIKELY(current != std::char_traits<char>::eof()))
2704  {
2705  ia->unget_character();
2706  assert(token_string.size() != 0);
2707  token_string.pop_back();
2708  }
2709  }
2710 
2711  /// add a character to yytext
2712  void add(int c)
2713  {
2714  yytext.push_back(std::char_traits<char>::to_char_type(c));
2715  }
2716 
2717  public:
2718  /////////////////////
2719  // value getters
2720  /////////////////////
2721 
2722  /// return integer value
2723  constexpr number_integer_t get_number_integer() const noexcept
2724  {
2725  return value_integer;
2726  }
2727 
2728  /// return unsigned integer value
2729  constexpr number_unsigned_t get_number_unsigned() const noexcept
2730  {
2731  return value_unsigned;
2732  }
2733 
2734  /// return floating-point value
2735  constexpr number_float_t get_number_float() const noexcept
2736  {
2737  return value_float;
2738  }
2739 
2740  /// return current string value (implicitly resets the token; useful only once)
2741  std::string move_string()
2742  {
2743  return std::move(yytext);
2744  }
2745 
2746  /////////////////////
2747  // diagnostics
2748  /////////////////////
2749 
2750  /// return position of last read token
2751  constexpr std::size_t get_position() const noexcept
2752  {
2753  return chars_read;
2754  }
2755 
2756  /// return the last read token (for errors only). Will never contain EOF
2757  /// (an arbitrary value that is not a valid char value, often -1), because
2758  /// 255 may legitimately occur. May contain NUL, which should be escaped.
2759  std::string get_token_string() const
2760  {
2761  // escape control characters
2762  std::string result;
2763  for (auto c : token_string)
2764  {
2765  if ('\x00' <= c and c <= '\x1F')
2766  {
2767  // escape control characters
2768  std::stringstream ss;
2769  ss << "<U+" << std::setw(4) << std::uppercase << std::setfill('0')
2770  << std::hex << static_cast<int>(c) << ">";
2771  result += ss.str();
2772  }
2773  else
2774  {
2775  // add character as is
2776  result.push_back(c);
2777  }
2778  }
2779 
2780  return result;
2781  }
2782 
2783  /// return syntax error message
2784  constexpr const char* get_error_message() const noexcept
2785  {
2786  return error_message;
2787  }
2788 
2789  /////////////////////
2790  // actual scanner
2791  /////////////////////
2792 
2793  token_type scan()
2794  {
2795  // read next character and ignore whitespace
2796  do
2797  {
2798  get();
2799  }
2800  while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
2801 
2802  switch (current)
2803  {
2804  // structural characters
2805  case '[':
2806  return token_type::begin_array;
2807  case ']':
2808  return token_type::end_array;
2809  case '{':
2810  return token_type::begin_object;
2811  case '}':
2812  return token_type::end_object;
2813  case ':':
2814  return token_type::name_separator;
2815  case ',':
2816  return token_type::value_separator;
2817 
2818  // literals
2819  case 't':
2820  return scan_literal("true", 4, token_type::literal_true);
2821  case 'f':
2822  return scan_literal("false", 5, token_type::literal_false);
2823  case 'n':
2824  return scan_literal("null", 4, token_type::literal_null);
2825 
2826  // string
2827  case '\"':
2828  return scan_string();
2829 
2830  // number
2831  case '-':
2832  case '0':
2833  case '1':
2834  case '2':
2835  case '3':
2836  case '4':
2837  case '5':
2838  case '6':
2839  case '7':
2840  case '8':
2841  case '9':
2842  return scan_number();
2843 
2844  // end of input (the null byte is needed when parsing from
2845  // string literals)
2846  case '\0':
2847  case std::char_traits<char>::eof():
2848  return token_type::end_of_input;
2849 
2850  // error
2851  default:
2852  error_message = "invalid literal";
2853  return token_type::parse_error;
2854  }
2855  }
2856 
2857  private:
2858  /// input adapter
2859  detail::input_adapter_t ia = nullptr;
2860 
2861  /// the current character
2862  std::char_traits<char>::int_type current = std::char_traits<char>::eof();
2863 
2864  /// the number of characters read
2865  std::size_t chars_read = 0;
2866 
2867  /// raw input token string (for error messages)
2868  std::vector<char> token_string {};
2869 
2870  /// buffer for variable-length tokens (numbers, strings)
2871  std::string yytext {};
2872 
2873  /// a description of occurred lexer errors
2874  const char* error_message = "";
2875 
2876  // number values
2877  number_integer_t value_integer = 0;
2878  number_unsigned_t value_unsigned = 0;
2879  number_float_t value_float = 0;
2880 
2881  /// the decimal point
2882  const char decimal_point_char = '.';
2883 };
2884 
2885 /*!
2886 @brief syntax analysis
2887 
2888 This class implements a recursive decent parser.
2889 */
2890 template<typename BasicJsonType>
2891 class parser
2892 {
2893  using number_integer_t = typename BasicJsonType::number_integer_t;
2894  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
2895  using number_float_t = typename BasicJsonType::number_float_t;
2896  using lexer_t = lexer<BasicJsonType>;
2897  using token_type = typename lexer_t::token_type;
2898 
2899  public:
2900  enum class parse_event_t : uint8_t
2901  {
2902  /// the parser read `{` and started to process a JSON object
2903  object_start,
2904  /// the parser read `}` and finished processing a JSON object
2905  object_end,
2906  /// the parser read `[` and started to process a JSON array
2907  array_start,
2908  /// the parser read `]` and finished processing a JSON array
2909  array_end,
2910  /// the parser read a key of a value in an object
2911  key,
2912  /// the parser finished reading a JSON value
2913  value
2914  };
2915 
2916  using parser_callback_t =
2917  std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
2918 
2919  /// a parser reading from an input adapter
2920  explicit parser(detail::input_adapter_t adapter,
2921  const parser_callback_t cb = nullptr,
2922  const bool allow_exceptions_ = true)
2923  : callback(cb), m_lexer(adapter), allow_exceptions(allow_exceptions_)
2924  {}
2925 
2926  /*!
2927  @brief public parser interface
2928 
2929  @param[in] strict whether to expect the last token to be EOF
2930  @param[in,out] result parsed JSON value
2931 
2932  @throw parse_error.101 in case of an unexpected token
2933  @throw parse_error.102 if to_unicode fails or surrogate error
2934  @throw parse_error.103 if to_unicode fails
2935  */
2936  void parse(const bool strict, BasicJsonType& result)
2937  {
2938  // read first token
2939  get_token();
2940 
2941  parse_internal(true, result);
2942  result.assert_invariant();
2943 
2944  // in strict mode, input must be completely read
2945  if (strict)
2946  {
2947  get_token();
2948  expect(token_type::end_of_input);
2949  }
2950 
2951  // in case of an error, return discarded value
2952  if (errored)
2953  {
2954  result = value_t::discarded;
2955  return;
2956  }
2957 
2958  // set top-level value to null if it was discarded by the callback
2959  // function
2960  if (result.is_discarded())
2961  {
2962  result = nullptr;
2963  }
2964  }
2965 
2966  /*!
2967  @brief public accept interface
2968 
2969  @param[in] strict whether to expect the last token to be EOF
2970  @return whether the input is a proper JSON text
2971  */
2972  bool accept(const bool strict = true)
2973  {
2974  // read first token
2975  get_token();
2976 
2977  if (not accept_internal())
2978  {
2979  return false;
2980  }
2981 
2982  // strict => last token must be EOF
2983  return not strict or (get_token() == token_type::end_of_input);
2984  }
2985 
2986  private:
2987  /*!
2988  @brief the actual parser
2989  @throw parse_error.101 in case of an unexpected token
2990  @throw parse_error.102 if to_unicode fails or surrogate error
2991  @throw parse_error.103 if to_unicode fails
2992  */
2993  void parse_internal(bool keep, BasicJsonType& result)
2994  {
2995  // never parse after a parse error was detected
2996  assert(not errored);
2997 
2998  // start with a discarded value
2999  if (not result.is_discarded())
3000  {
3001  result.m_value.destroy(result.m_type);
3002  result.m_type = value_t::discarded;
3003  }
3004 
3005  switch (last_token)
3006  {
3007  case token_type::begin_object:
3008  {
3009  if (keep)
3010  {
3011  if (callback)
3012  {
3013  keep = callback(depth++, parse_event_t::object_start, result);
3014  }
3015 
3016  if (not callback or keep)
3017  {
3018  // explicitly set result to object to cope with {}
3019  result.m_type = value_t::object;
3020  result.m_value = value_t::object;
3021  }
3022  }
3023 
3024  // read next token
3025  get_token();
3026 
3027  // closing } -> we are done
3028  if (last_token == token_type::end_object)
3029  {
3030  if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
3031  {
3032  result.m_value.destroy(result.m_type);
3033  result.m_type = value_t::discarded;
3034  }
3035  break;
3036  }
3037 
3038  // parse values
3039  std::string key;
3040  BasicJsonType value;
3041  while (true)
3042  {
3043  // store key
3044  if (not expect(token_type::value_string))
3045  {
3046  return;
3047  }
3048  key = m_lexer.move_string();
3049 
3050  bool keep_tag = false;
3051  if (keep)
3052  {
3053  if (callback)
3054  {
3055  BasicJsonType k(key);
3056  keep_tag = callback(depth, parse_event_t::key, k);
3057  }
3058  else
3059  {
3060  keep_tag = true;
3061  }
3062  }
3063 
3064  // parse separator (:)
3065  get_token();
3066  if (not expect(token_type::name_separator))
3067  {
3068  return;
3069  }
3070 
3071  // parse and add value
3072  get_token();
3073  value.m_value.destroy(value.m_type);
3074  value.m_type = value_t::discarded;
3075  parse_internal(keep, value);
3076 
3077  if (JSON_UNLIKELY(errored))
3078  {
3079  return;
3080  }
3081 
3082  if (keep and keep_tag and not value.is_discarded())
3083  {
3084  result.m_value.object->emplace(std::move(key), std::move(value));
3085  }
3086 
3087  // comma -> next value
3088  get_token();
3089  if (last_token == token_type::value_separator)
3090  {
3091  get_token();
3092  continue;
3093  }
3094 
3095  // closing }
3096  if (not expect(token_type::end_object))
3097  {
3098  return;
3099  }
3100  break;
3101  }
3102 
3103  if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
3104  {
3105  result.m_value.destroy(result.m_type);
3106  result.m_type = value_t::discarded;
3107  }
3108  break;
3109  }
3110 
3111  case token_type::begin_array:
3112  {
3113  if (keep)
3114  {
3115  if (callback)
3116  {
3117  keep = callback(depth++, parse_event_t::array_start, result);
3118  }
3119 
3120  if (not callback or keep)
3121  {
3122  // explicitly set result to array to cope with []
3123  result.m_type = value_t::array;
3124  result.m_value = value_t::array;
3125  }
3126  }
3127 
3128  // read next token
3129  get_token();
3130 
3131  // closing ] -> we are done
3132  if (last_token == token_type::end_array)
3133  {
3134  if (callback and not callback(--depth, parse_event_t::array_end, result))
3135  {
3136  result.m_value.destroy(result.m_type);
3137  result.m_type = value_t::discarded;
3138  }
3139  break;
3140  }
3141 
3142  // parse values
3143  BasicJsonType value;
3144  while (true)
3145  {
3146  // parse value
3147  value.m_value.destroy(value.m_type);
3148  value.m_type = value_t::discarded;
3149  parse_internal(keep, value);
3150 
3151  if (JSON_UNLIKELY(errored))
3152  {
3153  return;
3154  }
3155 
3156  if (keep and not value.is_discarded())
3157  {
3158  result.m_value.array->push_back(std::move(value));
3159  }
3160 
3161  // comma -> next value
3162  get_token();
3163  if (last_token == token_type::value_separator)
3164  {
3165  get_token();
3166  continue;
3167  }
3168 
3169  // closing ]
3170  if (not expect(token_type::end_array))
3171  {
3172  return;
3173  }
3174  break;
3175  }
3176 
3177  if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
3178  {
3179  result.m_value.destroy(result.m_type);
3180  result.m_type = value_t::discarded;
3181  }
3182  break;
3183  }
3184 
3185  case token_type::literal_null:
3186  {
3187  result.m_type = value_t::null;
3188  break;
3189  }
3190 
3191  case token_type::value_string:
3192  {
3193  result.m_type = value_t::string;
3194  result.m_value = m_lexer.move_string();
3195  break;
3196  }
3197 
3198  case token_type::literal_true:
3199  {
3200  result.m_type = value_t::boolean;
3201  result.m_value = true;
3202  break;
3203  }
3204 
3205  case token_type::literal_false:
3206  {
3207  result.m_type = value_t::boolean;
3208  result.m_value = false;
3209  break;
3210  }
3211 
3212  case token_type::value_unsigned:
3213  {
3214  result.m_type = value_t::number_unsigned;
3215  result.m_value = m_lexer.get_number_unsigned();
3216  break;
3217  }
3218 
3219  case token_type::value_integer:
3220  {
3221  result.m_type = value_t::number_integer;
3222  result.m_value = m_lexer.get_number_integer();
3223  break;
3224  }
3225 
3226  case token_type::value_float:
3227  {
3228  result.m_type = value_t::number_float;
3229  result.m_value = m_lexer.get_number_float();
3230 
3231  // throw in case of infinity or NAN
3232  if (JSON_UNLIKELY(not std::isfinite(result.m_value.number_float)))
3233  {
3234  if (allow_exceptions)
3235  {
3236  JSON_THROW(out_of_range::create(406, "number overflow parsing '" +
3237  m_lexer.get_token_string() + "'"));
3238  }
3239  expect(token_type::uninitialized);
3240  }
3241  break;
3242  }
3243 
3244  case token_type::parse_error:
3245  {
3246  // using "uninitialized" to avoid "expected" message
3247  if (not expect(token_type::uninitialized))
3248  {
3249  return;
3250  }
3251  break; // LCOV_EXCL_LINE
3252  }
3253 
3254  default:
3255  {
3256  // the last token was unexpected; we expected a value
3257  if (not expect(token_type::literal_or_value))
3258  {
3259  return;
3260  }
3261  break; // LCOV_EXCL_LINE
3262  }
3263  }
3264 
3265  if (keep and callback and not callback(depth, parse_event_t::value, result))
3266  {
3267  result.m_type = value_t::discarded;
3268  }
3269  }
3270 
3271  /*!
3272  @brief the actual acceptor
3273 
3274  @invariant 1. The last token is not yet processed. Therefore, the caller
3275  of this function must make sure a token has been read.
3276  2. When this function returns, the last token is processed.
3277  That is, the last read character was already considered.
3278 
3279  This invariant makes sure that no token needs to be "unput".
3280  */
3281  bool accept_internal()
3282  {
3283  switch (last_token)
3284  {
3285  case token_type::begin_object:
3286  {
3287  // read next token
3288  get_token();
3289 
3290  // closing } -> we are done
3291  if (last_token == token_type::end_object)
3292  {
3293  return true;
3294  }
3295 
3296  // parse values
3297  while (true)
3298  {
3299  // parse key
3300  if (last_token != token_type::value_string)
3301  {
3302  return false;
3303  }
3304 
3305  // parse separator (:)
3306  get_token();
3307  if (last_token != token_type::name_separator)
3308  {
3309  return false;
3310  }
3311 
3312  // parse value
3313  get_token();
3314  if (not accept_internal())
3315  {
3316  return false;
3317  }
3318 
3319  // comma -> next value
3320  get_token();
3321  if (last_token == token_type::value_separator)
3322  {
3323  get_token();
3324  continue;
3325  }
3326 
3327  // closing }
3328  return (last_token == token_type::end_object);
3329  }
3330  }
3331 
3332  case token_type::begin_array:
3333  {
3334  // read next token
3335  get_token();
3336 
3337  // closing ] -> we are done
3338  if (last_token == token_type::end_array)
3339  {
3340  return true;
3341  }
3342 
3343  // parse values
3344  while (true)
3345  {
3346  // parse value
3347  if (not accept_internal())
3348  {
3349  return false;
3350  }
3351 
3352  // comma -> next value
3353  get_token();
3354  if (last_token == token_type::value_separator)
3355  {
3356  get_token();
3357  continue;
3358  }
3359 
3360  // closing ]
3361  return (last_token == token_type::end_array);
3362  }
3363  }
3364 
3365  case token_type::value_float:
3366  {
3367  // reject infinity or NAN
3368  return std::isfinite(m_lexer.get_number_float());
3369  }
3370 
3371  case token_type::literal_false:
3372  case token_type::literal_null:
3373  case token_type::literal_true:
3374  case token_type::value_integer:
3375  case token_type::value_string:
3376  case token_type::value_unsigned:
3377  return true;
3378 
3379  default: // the last token was unexpected
3380  return false;
3381  }
3382  }
3383 
3384  /// get next token from lexer
3385  token_type get_token()
3386  {
3387  return (last_token = m_lexer.scan());
3388  }
3389 
3390  /*!
3391  @throw parse_error.101 if expected token did not occur
3392  */
3393  bool expect(token_type t)
3394  {
3395  if (JSON_UNLIKELY(t != last_token))
3396  {
3397  errored = true;
3398  expected = t;
3399  if (allow_exceptions)
3400  {
3401  throw_exception();
3402  }
3403  else
3404  {
3405  return false;
3406  }
3407  }
3408 
3409  return true;
3410  }
3411 
3412  [[noreturn]] void throw_exception() const
3413  {
3414  std::string error_msg = "syntax error - ";
3415  if (last_token == token_type::parse_error)
3416  {
3417  error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
3418  m_lexer.get_token_string() + "'";
3419  }
3420  else
3421  {
3422  error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
3423  }
3424 
3425  if (expected != token_type::uninitialized)
3426  {
3427  error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
3428  }
3429 
3430  JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg));
3431  }
3432 
3433  private:
3434  /// current level of recursion
3435  int depth = 0;
3436  /// callback function
3437  const parser_callback_t callback = nullptr;
3438  /// the type of the last read token
3439  token_type last_token = token_type::uninitialized;
3440  /// the lexer
3441  lexer_t m_lexer;
3442  /// whether a syntax error occurred
3443  bool errored = false;
3444  /// possible reason for the syntax error
3445  token_type expected = token_type::uninitialized;
3446  /// whether to throw exceptions in case of errors
3447  const bool allow_exceptions = true;
3448 };
3449 
3450 ///////////////
3451 // iterators //
3452 ///////////////
3453 
3454 /*!
3455 @brief an iterator for primitive JSON types
3456 
3457 This class models an iterator for primitive JSON types (boolean, number,
3458 string). It's only purpose is to allow the iterator/const_iterator classes
3459 to "iterate" over primitive values. Internally, the iterator is modeled by
3460 a `difference_type` variable. Value begin_value (`0`) models the begin,
3461 end_value (`1`) models past the end.
3462 */
3463 class primitive_iterator_t
3464 {
3465  public:
3466  using difference_type = std::ptrdiff_t;
3467 
3468  constexpr difference_type get_value() const noexcept
3469  {
3470  return m_it;
3471  }
3472 
3473  /// set iterator to a defined beginning
3474  void set_begin() noexcept
3475  {
3476  m_it = begin_value;
3477  }
3478 
3479  /// set iterator to a defined past the end
3480  void set_end() noexcept
3481  {
3482  m_it = end_value;
3483  }
3484 
3485  /// return whether the iterator can be dereferenced
3486  constexpr bool is_begin() const noexcept
3487  {
3488  return m_it == begin_value;
3489  }
3490 
3491  /// return whether the iterator is at end
3492  constexpr bool is_end() const noexcept
3493  {
3494  return m_it == end_value;
3495  }
3496 
3497  friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3498  {
3499  return lhs.m_it == rhs.m_it;
3500  }
3501 
3502  friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3503  {
3504  return lhs.m_it < rhs.m_it;
3505  }
3506 
3507  primitive_iterator_t operator+(difference_type i)
3508  {
3509  auto result = *this;
3510  result += i;
3511  return result;
3512  }
3513 
3514  friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3515  {
3516  return lhs.m_it - rhs.m_it;
3517  }
3518 
3519  friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it)
3520  {
3521  return os << it.m_it;
3522  }
3523 
3524  primitive_iterator_t& operator++()
3525  {
3526  ++m_it;
3527  return *this;
3528  }
3529 
3530  primitive_iterator_t operator++(int)
3531  {
3532  auto result = *this;
3533  m_it++;
3534  return result;
3535  }
3536 
3537  primitive_iterator_t& operator--()
3538  {
3539  --m_it;
3540  return *this;
3541  }
3542 
3543  primitive_iterator_t operator--(int)
3544  {
3545  auto result = *this;
3546  m_it--;
3547  return result;
3548  }
3549 
3550  primitive_iterator_t& operator+=(difference_type n)
3551  {
3552  m_it += n;
3553  return *this;
3554  }
3555 
3556  primitive_iterator_t& operator-=(difference_type n)
3557  {
3558  m_it -= n;
3559  return *this;
3560  }
3561 
3562  private:
3563  static constexpr difference_type begin_value = 0;
3564  static constexpr difference_type end_value = begin_value + 1;
3565 
3566  /// iterator as signed integer type
3567  difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
3568 };
3569 
3570 /*!
3571 @brief an iterator value
3572 
3573 @note This structure could easily be a union, but MSVC currently does not allow
3574 unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
3575 */
3576 template<typename BasicJsonType> struct internal_iterator
3577 {
3578  /// iterator for JSON objects
3579  typename BasicJsonType::object_t::iterator object_iterator {};
3580  /// iterator for JSON arrays
3581  typename BasicJsonType::array_t::iterator array_iterator {};
3582  /// generic iterator for all other types
3583  primitive_iterator_t primitive_iterator {};
3584 };
3585 
3586 template<typename IteratorType> class iteration_proxy;
3587 
3588 /*!
3589 @brief a template for a bidirectional iterator for the @ref basic_json class
3590 
3591 This class implements a both iterators (iterator and const_iterator) for the
3592 @ref basic_json class.
3593 
3594 @note An iterator is called *initialized* when a pointer to a JSON value has
3595  been set (e.g., by a constructor or a copy assignment). If the iterator is
3596  default-constructed, it is *uninitialized* and most methods are undefined.
3597  **The library uses assertions to detect calls on uninitialized iterators.**
3598 
3599 @requirement The class satisfies the following concept requirements:
3600 -
3601 [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):
3602  The iterator that can be moved can be moved in both directions (i.e.
3603  incremented and decremented).
3604 
3605 @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
3606  iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
3607 */
3608 template<typename BasicJsonType>
3609 class iter_impl
3610 {
3611  /// allow basic_json to access private members
3612  friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
3613  friend BasicJsonType;
3614  friend iteration_proxy<iter_impl>;
3615 
3616  using object_t = typename BasicJsonType::object_t;
3617  using array_t = typename BasicJsonType::array_t;
3618  // make sure BasicJsonType is basic_json or const basic_json
3619  static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
3620  "iter_impl only accepts (const) basic_json");
3621 
3622  public:
3623 
3624  /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
3625  /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
3626  /// A user-defined iterator should provide publicly accessible typedefs named
3627  /// iterator_category, value_type, difference_type, pointer, and reference.
3628  /// Note that value_type is required to be non-const, even for constant iterators.
3629  using iterator_category = std::bidirectional_iterator_tag;
3630 
3631  /// the type of the values when the iterator is dereferenced
3632  using value_type = typename BasicJsonType::value_type;
3633  /// a type to represent differences between iterators
3634  using difference_type = typename BasicJsonType::difference_type;
3635  /// defines a pointer to the type iterated over (value_type)
3636  using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
3637  typename BasicJsonType::const_pointer,
3638  typename BasicJsonType::pointer>::type;
3639  /// defines a reference to the type iterated over (value_type)
3640  using reference =
3641  typename std::conditional<std::is_const<BasicJsonType>::value,
3642  typename BasicJsonType::const_reference,
3643  typename BasicJsonType::reference>::type;
3644 
3645  /// default constructor
3646  iter_impl() = default;
3647 
3648  /*!
3649  @brief constructor for a given JSON instance
3650  @param[in] object pointer to a JSON object for this iterator
3651  @pre object != nullptr
3652  @post The iterator is initialized; i.e. `m_object != nullptr`.
3653  */
3654  explicit iter_impl(pointer object) noexcept : m_object(object)
3655  {
3656  assert(m_object != nullptr);
3657 
3658  switch (m_object->m_type)
3659  {
3660  case value_t::object:
3661  {
3662  m_it.object_iterator = typename object_t::iterator();
3663  break;
3664  }
3665 
3666  case value_t::array:
3667  {
3668  m_it.array_iterator = typename array_t::iterator();
3669  break;
3670  }
3671 
3672  default:
3673  {
3674  m_it.primitive_iterator = primitive_iterator_t();
3675  break;
3676  }
3677  }
3678  }
3679 
3680  /*!
3681  @note The conventional copy constructor and copy assignment are implicitly
3682  defined. Combined with the following converting constructor and
3683  assignment, they support: (1) copy from iterator to iterator, (2)
3684  copy from const iterator to const iterator, and (3) conversion from
3685  iterator to const iterator. However conversion from const iterator
3686  to iterator is not defined.
3687  */
3688 
3689  /*!
3690  @brief converting constructor
3691  @param[in] other non-const iterator to copy from
3692  @note It is not checked whether @a other is initialized.
3693  */
3694  iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
3695  : m_object(other.m_object), m_it(other.m_it) {}
3696 
3697  /*!
3698  @brief converting assignment
3699  @param[in,out] other non-const iterator to copy from
3700  @return const/non-const iterator
3701  @note It is not checked whether @a other is initialized.
3702  */
3703  iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
3704  {
3705  m_object = other.m_object;
3706  m_it = other.m_it;
3707  return *this;
3708  }
3709 
3710  private:
3711  /*!
3712  @brief set the iterator to the first value
3713  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3714  */
3715  void set_begin() noexcept
3716  {
3717  assert(m_object != nullptr);
3718 
3719  switch (m_object->m_type)
3720  {
3721  case value_t::object:
3722  {
3723  m_it.object_iterator = m_object->m_value.object->begin();
3724  break;
3725  }
3726 
3727  case value_t::array:
3728  {
3729  m_it.array_iterator = m_object->m_value.array->begin();
3730  break;
3731  }
3732 
3733  case value_t::null:
3734  {
3735  // set to end so begin()==end() is true: null is empty
3736  m_it.primitive_iterator.set_end();
3737  break;
3738  }
3739 
3740  default:
3741  {
3742  m_it.primitive_iterator.set_begin();
3743  break;
3744  }
3745  }
3746  }
3747 
3748  /*!
3749  @brief set the iterator past the last value
3750  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3751  */
3752  void set_end() noexcept
3753  {
3754  assert(m_object != nullptr);
3755 
3756  switch (m_object->m_type)
3757  {
3758  case value_t::object:
3759  {
3760  m_it.object_iterator = m_object->m_value.object->end();
3761  break;
3762  }
3763 
3764  case value_t::array:
3765  {
3766  m_it.array_iterator = m_object->m_value.array->end();
3767  break;
3768  }
3769 
3770  default:
3771  {
3772  m_it.primitive_iterator.set_end();
3773  break;
3774  }
3775  }
3776  }
3777 
3778  public:
3779  /*!
3780  @brief return a reference to the value pointed to by the iterator
3781  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3782  */
3783  reference operator*() const
3784  {
3785  assert(m_object != nullptr);
3786 
3787  switch (m_object->m_type)
3788  {
3789  case value_t::object:
3790  {
3791  assert(m_it.object_iterator != m_object->m_value.object->end());
3792  return m_it.object_iterator->second;
3793  }
3794 
3795  case value_t::array:
3796  {
3797  assert(m_it.array_iterator != m_object->m_value.array->end());
3798  return *m_it.array_iterator;
3799  }
3800 
3801  case value_t::null:
3802  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
3803 
3804  default:
3805  {
3806  if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
3807  {
3808  return *m_object;
3809  }
3810 
3811  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
3812  }
3813  }
3814  }
3815 
3816  /*!
3817  @brief dereference the iterator
3818  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3819  */
3820  pointer operator->() const
3821  {
3822  assert(m_object != nullptr);
3823 
3824  switch (m_object->m_type)
3825  {
3826  case value_t::object:
3827  {
3828  assert(m_it.object_iterator != m_object->m_value.object->end());
3829  return &(m_it.object_iterator->second);
3830  }
3831 
3832  case value_t::array:
3833  {
3834  assert(m_it.array_iterator != m_object->m_value.array->end());
3835  return &*m_it.array_iterator;
3836  }
3837 
3838  default:
3839  {
3840  if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
3841  {
3842  return m_object;
3843  }
3844 
3845  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
3846  }
3847  }
3848  }
3849 
3850  /*!
3851  @brief post-increment (it++)
3852  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3853  */
3854  iter_impl operator++(int)
3855  {
3856  auto result = *this;
3857  ++(*this);
3858  return result;
3859  }
3860 
3861  /*!
3862  @brief pre-increment (++it)
3863  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3864  */
3865  iter_impl& operator++()
3866  {
3867  assert(m_object != nullptr);
3868 
3869  switch (m_object->m_type)
3870  {
3871  case value_t::object:
3872  {
3873  std::advance(m_it.object_iterator, 1);
3874  break;
3875  }
3876 
3877  case value_t::array:
3878  {
3879  std::advance(m_it.array_iterator, 1);
3880  break;
3881  }
3882 
3883  default:
3884  {
3885  ++m_it.primitive_iterator;
3886  break;
3887  }
3888  }
3889 
3890  return *this;
3891  }
3892 
3893  /*!
3894  @brief post-decrement (it--)
3895  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3896  */
3897  iter_impl operator--(int)
3898  {
3899  auto result = *this;
3900  --(*this);
3901  return result;
3902  }
3903 
3904  /*!
3905  @brief pre-decrement (--it)
3906  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3907  */
3908  iter_impl& operator--()
3909  {
3910  assert(m_object != nullptr);
3911 
3912  switch (m_object->m_type)
3913  {
3914  case value_t::object:
3915  {
3916  std::advance(m_it.object_iterator, -1);
3917  break;
3918  }
3919 
3920  case value_t::array:
3921  {
3922  std::advance(m_it.array_iterator, -1);
3923  break;
3924  }
3925 
3926  default:
3927  {
3928  --m_it.primitive_iterator;
3929  break;
3930  }
3931  }
3932 
3933  return *this;
3934  }
3935 
3936  /*!
3937  @brief comparison: equal
3938  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3939  */
3940  bool operator==(const iter_impl& other) const
3941  {
3942  // if objects are not the same, the comparison is undefined
3943  if (JSON_UNLIKELY(m_object != other.m_object))
3944  {
3945  JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
3946  }
3947 
3948  assert(m_object != nullptr);
3949 
3950  switch (m_object->m_type)
3951  {
3952  case value_t::object:
3953  return (m_it.object_iterator == other.m_it.object_iterator);
3954 
3955  case value_t::array:
3956  return (m_it.array_iterator == other.m_it.array_iterator);
3957 
3958  default:
3959  return (m_it.primitive_iterator == other.m_it.primitive_iterator);
3960  }
3961  }
3962 
3963  /*!
3964  @brief comparison: not equal
3965  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3966  */
3967  bool operator!=(const iter_impl& other) const
3968  {
3969  return not operator==(other);
3970  }
3971 
3972  /*!
3973  @brief comparison: smaller
3974  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3975  */
3976  bool operator<(const iter_impl& other) const
3977  {
3978  // if objects are not the same, the comparison is undefined
3979  if (JSON_UNLIKELY(m_object != other.m_object))
3980  {
3981  JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
3982  }
3983 
3984  assert(m_object != nullptr);
3985 
3986  switch (m_object->m_type)
3987  {
3988  case value_t::object:
3989  JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
3990 
3991  case value_t::array:
3992  return (m_it.array_iterator < other.m_it.array_iterator);
3993 
3994  default:
3995  return (m_it.primitive_iterator < other.m_it.primitive_iterator);
3996  }
3997  }
3998 
3999  /*!
4000  @brief comparison: less than or equal
4001  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4002  */
4003  bool operator<=(const iter_impl& other) const
4004  {
4005  return not other.operator < (*this);
4006  }
4007 
4008  /*!
4009  @brief comparison: greater than
4010  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4011  */
4012  bool operator>(const iter_impl& other) const
4013  {
4014  return not operator<=(other);
4015  }
4016 
4017  /*!
4018  @brief comparison: greater than or equal
4019  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4020  */
4021  bool operator>=(const iter_impl& other) const
4022  {
4023  return not operator<(other);
4024  }
4025 
4026  /*!
4027  @brief add to iterator
4028  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4029  */
4030  iter_impl& operator+=(difference_type i)
4031  {
4032  assert(m_object != nullptr);
4033 
4034  switch (m_object->m_type)
4035  {
4036  case value_t::object:
4037  JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
4038 
4039  case value_t::array:
4040  {
4041  std::advance(m_it.array_iterator, i);
4042  break;
4043  }
4044 
4045  default:
4046  {
4047  m_it.primitive_iterator += i;
4048  break;
4049  }
4050  }
4051 
4052  return *this;
4053  }
4054 
4055  /*!
4056  @brief subtract from iterator
4057  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4058  */
4059  iter_impl& operator-=(difference_type i)
4060  {
4061  return operator+=(-i);
4062  }
4063 
4064  /*!
4065  @brief add to iterator
4066  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4067  */
4068  iter_impl operator+(difference_type i) const
4069  {
4070  auto result = *this;
4071  result += i;
4072  return result;
4073  }
4074 
4075  /*!
4076  @brief addition of distance and iterator
4077  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4078  */
4079  friend iter_impl operator+(difference_type i, const iter_impl& it)
4080  {
4081  auto result = it;
4082  result += i;
4083  return result;
4084  }
4085 
4086  /*!
4087  @brief subtract from iterator
4088  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4089  */
4090  iter_impl operator-(difference_type i) const
4091  {
4092  auto result = *this;
4093  result -= i;
4094  return result;
4095  }
4096 
4097  /*!
4098  @brief return difference
4099  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4100  */
4101  difference_type operator-(const iter_impl& other) const
4102  {
4103  assert(m_object != nullptr);
4104 
4105  switch (m_object->m_type)
4106  {
4107  case value_t::object:
4108  JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
4109 
4110  case value_t::array:
4111  return m_it.array_iterator - other.m_it.array_iterator;
4112 
4113  default:
4114  return m_it.primitive_iterator - other.m_it.primitive_iterator;
4115  }
4116  }
4117 
4118  /*!
4119  @brief access to successor
4120  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4121  */
4122  reference operator[](difference_type n) const
4123  {
4124  assert(m_object != nullptr);
4125 
4126  switch (m_object->m_type)
4127  {
4128  case value_t::object:
4129  JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
4130 
4131  case value_t::array:
4132  return *std::next(m_it.array_iterator, n);
4133 
4134  case value_t::null:
4135  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4136 
4137  default:
4138  {
4139  if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
4140  {
4141  return *m_object;
4142  }
4143 
4144  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4145  }
4146  }
4147  }
4148 
4149  /*!
4150  @brief return the key of an object iterator
4151  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4152  */
4153  typename object_t::key_type key() const
4154  {
4155  assert(m_object != nullptr);
4156 
4157  if (JSON_LIKELY(m_object->is_object()))
4158  {
4159  return m_it.object_iterator->first;
4160  }
4161 
4162  JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
4163  }
4164 
4165  /*!
4166  @brief return the value of an iterator
4167  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4168  */
4169  reference value() const
4170  {
4171  return operator*();
4172  }
4173 
4174  private:
4175  /// associated JSON instance
4176  pointer m_object = nullptr;
4177  /// the actual iterator of the associated instance
4178  internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it = {};
4179 };
4180 
4181 /// proxy class for the iterator_wrapper functions
4182 template<typename IteratorType> class iteration_proxy
4183 {
4184  private:
4185  /// helper class for iteration
4186  class iteration_proxy_internal
4187  {
4188  private:
4189  /// the iterator
4190  IteratorType anchor;
4191  /// an index for arrays (used to create key names)
4192  std::size_t array_index = 0;
4193 
4194  public:
4195  explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {}
4196 
4197  /// dereference operator (needed for range-based for)
4198  iteration_proxy_internal& operator*()
4199  {
4200  return *this;
4201  }
4202 
4203  /// increment operator (needed for range-based for)
4204  iteration_proxy_internal& operator++()
4205  {
4206  ++anchor;
4207  ++array_index;
4208 
4209  return *this;
4210  }
4211 
4212  /// inequality operator (needed for range-based for)
4213  bool operator!=(const iteration_proxy_internal& o) const noexcept
4214  {
4215  return anchor != o.anchor;
4216  }
4217 
4218  /// return key of the iterator
4219  std::string key() const
4220  {
4221  assert(anchor.m_object != nullptr);
4222 
4223  switch (anchor.m_object->type())
4224  {
4225  // use integer array index as key
4226  case value_t::array:
4227  return std::to_string(array_index);
4228 
4229  // use key from the object
4230  case value_t::object:
4231  return anchor.key();
4232 
4233  // use an empty key for all primitive types
4234  default:
4235  return "";
4236  }
4237  }
4238 
4239  /// return value of the iterator
4240  typename IteratorType::reference value() const
4241  {
4242  return anchor.value();
4243  }
4244  };
4245 
4246  /// the container to iterate
4247  typename IteratorType::reference container;
4248 
4249  public:
4250  /// construct iteration proxy from a container
4251  explicit iteration_proxy(typename IteratorType::reference cont)
4252  : container(cont) {}
4253 
4254  /// return iterator begin (needed for range-based for)
4255  iteration_proxy_internal begin() noexcept
4256  {
4257  return iteration_proxy_internal(container.begin());
4258  }
4259 
4260  /// return iterator end (needed for range-based for)
4261  iteration_proxy_internal end() noexcept
4262  {
4263  return iteration_proxy_internal(container.end());
4264  }
4265 };
4266 
4267 /*!
4268 @brief a template for a reverse iterator class
4269 
4270 @tparam Base the base iterator type to reverse. Valid types are @ref
4271 iterator (to create @ref reverse_iterator) and @ref const_iterator (to
4272 create @ref const_reverse_iterator).
4273 
4274 @requirement The class satisfies the following concept requirements:
4275 -
4276 [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):
4277  The iterator that can be moved can be moved in both directions (i.e.
4278  incremented and decremented).
4279 - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
4280  It is possible to write to the pointed-to element (only if @a Base is
4281  @ref iterator).
4282 
4283 @since version 1.0.0
4284 */
4285 template<typename Base>
4286 class json_reverse_iterator : public std::reverse_iterator<Base>
4287 {
4288  public:
4289  using difference_type = std::ptrdiff_t;
4290  /// shortcut to the reverse iterator adapter
4291  using base_iterator = std::reverse_iterator<Base>;
4292  /// the reference type for the pointed-to element
4293  using reference = typename Base::reference;
4294 
4295  /// create reverse iterator from iterator
4296  json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
4297  : base_iterator(it) {}
4298 
4299  /// create reverse iterator from base class
4300  json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
4301 
4302  /// post-increment (it++)
4303  json_reverse_iterator operator++(int)
4304  {
4305  return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
4306  }
4307 
4308  /// pre-increment (++it)
4309  json_reverse_iterator& operator++()
4310  {
4311  return static_cast<json_reverse_iterator&>(base_iterator::operator++());
4312  }
4313 
4314  /// post-decrement (it--)
4315  json_reverse_iterator operator--(int)
4316  {
4317  return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
4318  }
4319 
4320  /// pre-decrement (--it)
4321  json_reverse_iterator& operator--()
4322  {
4323  return static_cast<json_reverse_iterator&>(base_iterator::operator--());
4324  }
4325 
4326  /// add to iterator
4327  json_reverse_iterator& operator+=(difference_type i)
4328  {
4329  return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
4330  }
4331 
4332  /// add to iterator
4333  json_reverse_iterator operator+(difference_type i) const
4334  {
4335  return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
4336  }
4337 
4338  /// subtract from iterator
4339  json_reverse_iterator operator-(difference_type i) const
4340  {
4341  return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
4342  }
4343 
4344  /// return difference
4345  difference_type operator-(const json_reverse_iterator& other) const
4346  {
4347  return base_iterator(*this) - base_iterator(other);
4348  }
4349 
4350  /// access to successor
4351  reference operator[](difference_type n) const
4352  {
4353  return *(this->operator+(n));
4354  }
4355 
4356  /// return the key of an object iterator
4357  auto key() const -> decltype(std::declval<Base>().key())
4358  {
4359  auto it = --this->base();
4360  return it.key();
4361  }
4362 
4363  /// return the value of an iterator
4364  reference value() const
4365  {
4366  auto it = --this->base();
4367  return it.operator * ();
4368  }
4369 };
4370 
4371 /////////////////////
4372 // output adapters //
4373 /////////////////////
4374 
4375 /// abstract output adapter interface
4376 template<typename CharType> struct output_adapter_protocol
4377 {
4378  virtual void write_character(CharType c) = 0;
4379  virtual void write_characters(const CharType* s, std::size_t length) = 0;
4380  virtual ~output_adapter_protocol() = default;
4381 };
4382 
4383 /// a type to simplify interfaces
4384 template<typename CharType>
4385 using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
4386 
4387 /// output adapter for byte vectors
4388 template<typename CharType>
4389 class output_vector_adapter : public output_adapter_protocol<CharType>
4390 {
4391  public:
4392  explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {}
4393 
4394  void write_character(CharType c) override
4395  {
4396  v.push_back(c);
4397  }
4398 
4399  void write_characters(const CharType* s, std::size_t length) override
4400  {
4401  std::copy(s, s + length, std::back_inserter(v));
4402  }
4403 
4404  private:
4405  std::vector<CharType>& v;
4406 };
4407 
4408 /// output adapter for output streams
4409 template<typename CharType>
4410 class output_stream_adapter : public output_adapter_protocol<CharType>
4411 {
4412  public:
4413  explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {}
4414 
4415  void write_character(CharType c) override
4416  {
4417  stream.put(c);
4418  }
4419 
4420  void write_characters(const CharType* s, std::size_t length) override
4421  {
4422  stream.write(s, static_cast<std::streamsize>(length));
4423  }
4424 
4425  private:
4426  std::basic_ostream<CharType>& stream;
4427 };
4428 
4429 /// output adapter for basic_string
4430 template<typename CharType>
4431 class output_string_adapter : public output_adapter_protocol<CharType>
4432 {
4433  public:
4434  explicit output_string_adapter(std::basic_string<CharType>& s) : str(s) {}
4435 
4436  void write_character(CharType c) override
4437  {
4438  str.push_back(c);
4439  }
4440 
4441  void write_characters(const CharType* s, std::size_t length) override
4442  {
4443  str.append(s, length);
4444  }
4445 
4446  private:
4447  std::basic_string<CharType>& str;
4448 };
4449 
4450 template<typename CharType>
4451 class output_adapter
4452 {
4453  public:
4454  output_adapter(std::vector<CharType>& vec)
4455  : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
4456 
4457  output_adapter(std::basic_ostream<CharType>& s)
4458  : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
4459 
4460  output_adapter(std::basic_string<CharType>& s)
4461  : oa(std::make_shared<output_string_adapter<CharType>>(s)) {}
4462 
4463  operator output_adapter_t<CharType>()
4464  {
4465  return oa;
4466  }
4467 
4468  private:
4469  output_adapter_t<CharType> oa = nullptr;
4470 };
4471 
4472 //////////////////////////////
4473 // binary reader and writer //
4474 //////////////////////////////
4475 
4476 /*!
4477 @brief deserialization of CBOR and MessagePack values
4478 */
4479 template<typename BasicJsonType>
4480 class binary_reader
4481 {
4482  using number_integer_t = typename BasicJsonType::number_integer_t;
4483  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
4484 
4485  public:
4486  /*!
4487  @brief create a binary reader
4488 
4489  @param[in] adapter input adapter to read from
4490  */
4491  explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
4492  {
4493  assert(ia);
4494  }
4495 
4496  /*!
4497  @brief create a JSON value from CBOR input
4498 
4499  @param[in] strict whether to expect the input to be consumed completed
4500  @return JSON value created from CBOR input
4501 
4502  @throw parse_error.110 if input ended unexpectedly or the end of file was
4503  not reached when @a strict was set to true
4504  @throw parse_error.112 if unsupported byte was read
4505  */
4506  BasicJsonType parse_cbor(const bool strict)
4507  {
4508  const auto res = parse_cbor_internal();
4509  if (strict)
4510  {
4511  get();
4512  check_eof(true);
4513  }
4514  return res;
4515  }
4516 
4517  /*!
4518  @brief create a JSON value from MessagePack input
4519 
4520  @param[in] strict whether to expect the input to be consumed completed
4521  @return JSON value created from MessagePack input
4522 
4523  @throw parse_error.110 if input ended unexpectedly or the end of file was
4524  not reached when @a strict was set to true
4525  @throw parse_error.112 if unsupported byte was read
4526  */
4527  BasicJsonType parse_msgpack(const bool strict)
4528  {
4529  const auto res = parse_msgpack_internal();
4530  if (strict)
4531  {
4532  get();
4533  check_eof(true);
4534  }
4535  return res;
4536  }
4537 
4538  /*!
4539  @brief determine system byte order
4540 
4541  @return true if and only if system's byte order is little endian
4542 
4543  @note from http://stackoverflow.com/a/1001328/266378
4544  */
4545  static constexpr bool little_endianess(int num = 1) noexcept
4546  {
4547  return (*reinterpret_cast<char*>(&num) == 1);
4548  }
4549 
4550  private:
4551  /*!
4552  @param[in] get_char whether a new character should be retrieved from the
4553  input (true, default) or whether the last read
4554  character should be considered instead
4555  */
4556  BasicJsonType parse_cbor_internal(const bool get_char = true)
4557  {
4558  switch (get_char ? get() : current)
4559  {
4560  // EOF
4561  case std::char_traits<char>::eof():
4562  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
4563 
4564  // Integer 0x00..0x17 (0..23)
4565  case 0x00:
4566  case 0x01:
4567  case 0x02:
4568  case 0x03:
4569  case 0x04:
4570  case 0x05:
4571  case 0x06:
4572  case 0x07:
4573  case 0x08:
4574  case 0x09:
4575  case 0x0A:
4576  case 0x0B:
4577  case 0x0C:
4578  case 0x0D:
4579  case 0x0E:
4580  case 0x0F:
4581  case 0x10:
4582  case 0x11:
4583  case 0x12:
4584  case 0x13:
4585  case 0x14:
4586  case 0x15:
4587  case 0x16:
4588  case 0x17:
4589  return static_cast<number_unsigned_t>(current);
4590 
4591  case 0x18: // Unsigned integer (one-byte uint8_t follows)
4592  return get_number<uint8_t>();
4593 
4594  case 0x19: // Unsigned integer (two-byte uint16_t follows)
4595  return get_number<uint16_t>();
4596 
4597  case 0x1A: // Unsigned integer (four-byte uint32_t follows)
4598  return get_number<uint32_t>();
4599 
4600  case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
4601  return get_number<uint64_t>();
4602 
4603  // Negative integer -1-0x00..-1-0x17 (-1..-24)
4604  case 0x20:
4605  case 0x21:
4606  case 0x22:
4607  case 0x23:
4608  case 0x24:
4609  case 0x25:
4610  case 0x26:
4611  case 0x27:
4612  case 0x28:
4613  case 0x29:
4614  case 0x2A:
4615  case 0x2B:
4616  case 0x2C:
4617  case 0x2D:
4618  case 0x2E:
4619  case 0x2F:
4620  case 0x30:
4621  case 0x31:
4622  case 0x32:
4623  case 0x33:
4624  case 0x34:
4625  case 0x35:
4626  case 0x36:
4627  case 0x37:
4628  return static_cast<int8_t>(0x20 - 1 - current);
4629 
4630  case 0x38: // Negative integer (one-byte uint8_t follows)
4631  {
4632  // must be uint8_t !
4633  return static_cast<number_integer_t>(-1) - get_number<uint8_t>();
4634  }
4635 
4636  case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
4637  {
4638  return static_cast<number_integer_t>(-1) - get_number<uint16_t>();
4639  }
4640 
4641  case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
4642  {
4643  return static_cast<number_integer_t>(-1) - get_number<uint32_t>();
4644  }
4645 
4646  case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
4647  {
4648  return static_cast<number_integer_t>(-1) -
4649  static_cast<number_integer_t>(get_number<uint64_t>());
4650  }
4651 
4652  // UTF-8 string (0x00..0x17 bytes follow)
4653  case 0x60:
4654  case 0x61:
4655  case 0x62:
4656  case 0x63:
4657  case 0x64:
4658  case 0x65:
4659  case 0x66:
4660  case 0x67:
4661  case 0x68:
4662  case 0x69:
4663  case 0x6A:
4664  case 0x6B:
4665  case 0x6C:
4666  case 0x6D:
4667  case 0x6E:
4668  case 0x6F:
4669  case 0x70:
4670  case 0x71:
4671  case 0x72:
4672  case 0x73:
4673  case 0x74:
4674  case 0x75:
4675  case 0x76:
4676  case 0x77:
4677  case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
4678  case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
4679  case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
4680  case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
4681  case 0x7F: // UTF-8 string (indefinite length)
4682  {
4683  return get_cbor_string();
4684  }
4685 
4686  // array (0x00..0x17 data items follow)
4687  case 0x80:
4688  case 0x81:
4689  case 0x82:
4690  case 0x83:
4691  case 0x84:
4692  case 0x85:
4693  case 0x86:
4694  case 0x87:
4695  case 0x88:
4696  case 0x89:
4697  case 0x8A:
4698  case 0x8B:
4699  case 0x8C:
4700  case 0x8D:
4701  case 0x8E:
4702  case 0x8F:
4703  case 0x90:
4704  case 0x91:
4705  case 0x92:
4706  case 0x93:
4707  case 0x94:
4708  case 0x95:
4709  case 0x96:
4710  case 0x97:
4711  {
4712  return get_cbor_array(current & 0x1F);
4713  }
4714 
4715  case 0x98: // array (one-byte uint8_t for n follows)
4716  {
4717  return get_cbor_array(get_number<uint8_t>());
4718  }
4719 
4720  case 0x99: // array (two-byte uint16_t for n follow)
4721  {
4722  return get_cbor_array(get_number<uint16_t>());
4723  }
4724 
4725  case 0x9A: // array (four-byte uint32_t for n follow)
4726  {
4727  return get_cbor_array(get_number<uint32_t>());
4728  }
4729 
4730  case 0x9B: // array (eight-byte uint64_t for n follow)
4731  {
4732  return get_cbor_array(get_number<uint64_t>());
4733  }
4734 
4735  case 0x9F: // array (indefinite length)
4736  {
4737  BasicJsonType result = value_t::array;
4738  while (get() != 0xFF)
4739  {
4740  result.push_back(parse_cbor_internal(false));
4741  }
4742  return result;
4743  }
4744 
4745  // map (0x00..0x17 pairs of data items follow)
4746  case 0xA0:
4747  case 0xA1:
4748  case 0xA2:
4749  case 0xA3:
4750  case 0xA4:
4751  case 0xA5:
4752  case 0xA6:
4753  case 0xA7:
4754  case 0xA8:
4755  case 0xA9:
4756  case 0xAA:
4757  case 0xAB:
4758  case 0xAC:
4759  case 0xAD:
4760  case 0xAE:
4761  case 0xAF:
4762  case 0xB0:
4763  case 0xB1:
4764  case 0xB2:
4765  case 0xB3:
4766  case 0xB4:
4767  case 0xB5:
4768  case 0xB6:
4769  case 0xB7:
4770  {
4771  return get_cbor_object(current & 0x1F);
4772  }
4773 
4774  case 0xB8: // map (one-byte uint8_t for n follows)
4775  {
4776  return get_cbor_object(get_number<uint8_t>());
4777  }
4778 
4779  case 0xB9: // map (two-byte uint16_t for n follow)
4780  {
4781  return get_cbor_object(get_number<uint16_t>());
4782  }
4783 
4784  case 0xBA: // map (four-byte uint32_t for n follow)
4785  {
4786  return get_cbor_object(get_number<uint32_t>());
4787  }
4788 
4789  case 0xBB: // map (eight-byte uint64_t for n follow)
4790  {
4791  return get_cbor_object(get_number<uint64_t>());
4792  }
4793 
4794  case 0xBF: // map (indefinite length)
4795  {
4796  BasicJsonType result = value_t::object;
4797  while (get() != 0xFF)
4798  {
4799  auto key = get_cbor_string();
4800  result[key] = parse_cbor_internal();
4801  }
4802  return result;
4803  }
4804 
4805  case 0xF4: // false
4806  {
4807  return false;
4808  }
4809 
4810  case 0xF5: // true
4811  {
4812  return true;
4813  }
4814 
4815  case 0xF6: // null
4816  {
4817  return value_t::null;
4818  }
4819 
4820  case 0xF9: // Half-Precision Float (two-byte IEEE 754)
4821  {
4822  const int byte1 = get();
4823  check_eof();
4824  const int byte2 = get();
4825  check_eof();
4826 
4827  // code from RFC 7049, Appendix D, Figure 3:
4828  // As half-precision floating-point numbers were only added
4829  // to IEEE 754 in 2008, today's programming platforms often
4830  // still only have limited support for them. It is very
4831  // easy to include at least decoding support for them even
4832  // without such support. An example of a small decoder for
4833  // half-precision floating-point numbers in the C language
4834  // is shown in Fig. 3.
4835  const int half = (byte1 << 8) + byte2;
4836  const int exp = (half >> 10) & 0x1F;
4837  const int mant = half & 0x3FF;
4838  double val;
4839  if (exp == 0)
4840  {
4841  val = std::ldexp(mant, -24);
4842  }
4843  else if (exp != 31)
4844  {
4845  val = std::ldexp(mant + 1024, exp - 25);
4846  }
4847  else
4848  {
4849  val = (mant == 0) ? std::numeric_limits<double>::infinity()
4850  : std::numeric_limits<double>::quiet_NaN();
4851  }
4852  return (half & 0x8000) != 0 ? -val : val;
4853  }
4854 
4855  case 0xFA: // Single-Precision Float (four-byte IEEE 754)
4856  {
4857  return get_number<float>();
4858  }
4859 
4860  case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
4861  {
4862  return get_number<double>();
4863  }
4864 
4865  default: // anything else (0xFF is handled inside the other types)
4866  {
4867  std::stringstream ss;
4868  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
4869  JSON_THROW(parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + ss.str()));
4870  }
4871  }
4872  }
4873 
4874  BasicJsonType parse_msgpack_internal()
4875  {
4876  switch (get())
4877  {
4878  // EOF
4879  case std::char_traits<char>::eof():
4880  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
4881 
4882  // positive fixint
4883  case 0x00:
4884  case 0x01:
4885  case 0x02:
4886  case 0x03:
4887  case 0x04:
4888  case 0x05:
4889  case 0x06:
4890  case 0x07:
4891  case 0x08:
4892  case 0x09:
4893  case 0x0A:
4894  case 0x0B:
4895  case 0x0C:
4896  case 0x0D:
4897  case 0x0E:
4898  case 0x0F:
4899  case 0x10:
4900  case 0x11:
4901  case 0x12:
4902  case 0x13:
4903  case 0x14:
4904  case 0x15:
4905  case 0x16:
4906  case 0x17:
4907  case 0x18:
4908  case 0x19:
4909  case 0x1A:
4910  case 0x1B:
4911  case 0x1C:
4912  case 0x1D:
4913  case 0x1E:
4914  case 0x1F:
4915  case 0x20:
4916  case 0x21:
4917  case 0x22:
4918  case 0x23:
4919  case 0x24:
4920  case 0x25:
4921  case 0x26:
4922  case 0x27:
4923  case 0x28:
4924  case 0x29:
4925  case 0x2A:
4926  case 0x2B:
4927  case 0x2C:
4928  case 0x2D:
4929  case 0x2E:
4930  case 0x2F:
4931  case 0x30:
4932  case 0x31:
4933  case 0x32:
4934  case 0x33:
4935  case 0x34:
4936  case 0x35:
4937  case 0x36:
4938  case 0x37:
4939  case 0x38:
4940  case 0x39:
4941  case 0x3A:
4942  case 0x3B:
4943  case 0x3C:
4944  case 0x3D:
4945  case 0x3E:
4946  case 0x3F:
4947  case 0x40:
4948  case 0x41:
4949  case 0x42:
4950  case 0x43:
4951  case 0x44:
4952  case 0x45:
4953  case 0x46:
4954  case 0x47:
4955  case 0x48:
4956  case 0x49:
4957  case 0x4A:
4958  case 0x4B:
4959  case 0x4C:
4960  case 0x4D:
4961  case 0x4E:
4962  case 0x4F:
4963  case 0x50:
4964  case 0x51:
4965  case 0x52:
4966  case 0x53:
4967  case 0x54:
4968  case 0x55:
4969  case 0x56:
4970  case 0x57:
4971  case 0x58:
4972  case 0x59:
4973  case 0x5A:
4974  case 0x5B:
4975  case 0x5C:
4976  case 0x5D:
4977  case 0x5E:
4978  case 0x5F:
4979  case 0x60:
4980  case 0x61:
4981  case 0x62:
4982  case 0x63:
4983  case 0x64:
4984  case 0x65:
4985  case 0x66:
4986  case 0x67:
4987  case 0x68:
4988  case 0x69:
4989  case 0x6A:
4990  case 0x6B:
4991  case 0x6C:
4992  case 0x6D:
4993  case 0x6E:
4994  case 0x6F:
4995  case 0x70:
4996  case 0x71:
4997  case 0x72:
4998  case 0x73:
4999  case 0x74:
5000  case 0x75:
5001  case 0x76:
5002  case 0x77:
5003  case 0x78:
5004  case 0x79:
5005  case 0x7A:
5006  case 0x7B:
5007  case 0x7C:
5008  case 0x7D:
5009  case 0x7E:
5010  case 0x7F:
5011  return static_cast<number_unsigned_t>(current);
5012 
5013  // fixmap
5014  case 0x80:
5015  case 0x81:
5016  case 0x82:
5017  case 0x83:
5018  case 0x84:
5019  case 0x85:
5020  case 0x86:
5021  case 0x87:
5022  case 0x88:
5023  case 0x89:
5024  case 0x8A:
5025  case 0x8B:
5026  case 0x8C:
5027  case 0x8D:
5028  case 0x8E:
5029  case 0x8F:
5030  {
5031  return get_msgpack_object(current & 0x0F);
5032  }
5033 
5034  // fixarray
5035  case 0x90:
5036  case 0x91:
5037  case 0x92:
5038  case 0x93:
5039  case 0x94:
5040  case 0x95:
5041  case 0x96:
5042  case 0x97:
5043  case 0x98:
5044  case 0x99:
5045  case 0x9A:
5046  case 0x9B:
5047  case 0x9C:
5048  case 0x9D:
5049  case 0x9E:
5050  case 0x9F:
5051  {
5052  return get_msgpack_array(current & 0x0F);
5053  }
5054 
5055  // fixstr
5056  case 0xA0:
5057  case 0xA1:
5058  case 0xA2:
5059  case 0xA3:
5060  case 0xA4:
5061  case 0xA5:
5062  case 0xA6:
5063  case 0xA7:
5064  case 0xA8:
5065  case 0xA9:
5066  case 0xAA:
5067  case 0xAB:
5068  case 0xAC:
5069  case 0xAD:
5070  case 0xAE:
5071  case 0xAF:
5072  case 0xB0:
5073  case 0xB1:
5074  case 0xB2:
5075  case 0xB3:
5076  case 0xB4:
5077  case 0xB5:
5078  case 0xB6:
5079  case 0xB7:
5080  case 0xB8:
5081  case 0xB9:
5082  case 0xBA:
5083  case 0xBB:
5084  case 0xBC:
5085  case 0xBD:
5086  case 0xBE:
5087  case 0xBF:
5088  return get_msgpack_string();
5089 
5090  case 0xC0: // nil
5091  return value_t::null;
5092 
5093  case 0xC2: // false
5094  return false;
5095 
5096  case 0xC3: // true
5097  return true;
5098 
5099  case 0xCA: // float 32
5100  return get_number<float>();
5101 
5102  case 0xCB: // float 64
5103  return get_number<double>();
5104 
5105  case 0xCC: // uint 8
5106  return get_number<uint8_t>();
5107 
5108  case 0xCD: // uint 16
5109  return get_number<uint16_t>();
5110 
5111  case 0xCE: // uint 32
5112  return get_number<uint32_t>();
5113 
5114  case 0xCF: // uint 64
5115  return get_number<uint64_t>();
5116 
5117  case 0xD0: // int 8
5118  return get_number<int8_t>();
5119 
5120  case 0xD1: // int 16
5121  return get_number<int16_t>();
5122 
5123  case 0xD2: // int 32
5124  return get_number<int32_t>();
5125 
5126  case 0xD3: // int 64
5127  return get_number<int64_t>();
5128 
5129  case 0xD9: // str 8
5130  case 0xDA: // str 16
5131  case 0xDB: // str 32
5132  return get_msgpack_string();
5133 
5134  case 0xDC: // array 16
5135  {
5136  return get_msgpack_array(get_number<uint16_t>());
5137  }
5138 
5139  case 0xDD: // array 32
5140  {
5141  return get_msgpack_array(get_number<uint32_t>());
5142  }
5143 
5144  case 0xDE: // map 16
5145  {
5146  return get_msgpack_object(get_number<uint16_t>());
5147  }
5148 
5149  case 0xDF: // map 32
5150  {
5151  return get_msgpack_object(get_number<uint32_t>());
5152  }
5153 
5154  // positive fixint
5155  case 0xE0:
5156  case 0xE1:
5157  case 0xE2:
5158  case 0xE3:
5159  case 0xE4:
5160  case 0xE5:
5161  case 0xE6:
5162  case 0xE7:
5163  case 0xE8:
5164  case 0xE9:
5165  case 0xEA:
5166  case 0xEB:
5167  case 0xEC:
5168  case 0xED:
5169  case 0xEE:
5170  case 0xEF:
5171  case 0xF0:
5172  case 0xF1:
5173  case 0xF2:
5174  case 0xF3:
5175  case 0xF4:
5176  case 0xF5:
5177  case 0xF6:
5178  case 0xF7:
5179  case 0xF8:
5180  case 0xF9:
5181  case 0xFA:
5182  case 0xFB:
5183  case 0xFC:
5184  case 0xFD:
5185  case 0xFE:
5186  case 0xFF:
5187  return static_cast<int8_t>(current);
5188 
5189  default: // anything else
5190  {
5191  std::stringstream ss;
5192  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5193  JSON_THROW(parse_error::create(112, chars_read,
5194  "error reading MessagePack; last byte: 0x" + ss.str()));
5195  }
5196  }
5197  }
5198 
5199  /*!
5200  @brief get next character from the input
5201 
5202  This function provides the interface to the used input adapter. It does
5203  not throw in case the input reached EOF, but returns a -'ve valued
5204  `std::char_traits<char>::eof()` in that case.
5205 
5206  @return character read from the input
5207  */
5208  int get()
5209  {
5210  ++chars_read;
5211  return (current = ia->get_character());
5212  }
5213 
5214  /*
5215  @brief read a number from the input
5216 
5217  @tparam NumberType the type of the number
5218 
5219  @return number of type @a NumberType
5220 
5221  @note This function needs to respect the system's endianess, because
5222  bytes in CBOR and MessagePack are stored in network order (big
5223  endian) and therefore need reordering on little endian systems.
5224 
5225  @throw parse_error.110 if input has less than `sizeof(NumberType)` bytes
5226  */
5227  template<typename NumberType> NumberType get_number()
5228  {
5229  // step 1: read input into array with system's byte order
5230  std::array<uint8_t, sizeof(NumberType)> vec;
5231  for (std::size_t i = 0; i < sizeof(NumberType); ++i)
5232  {
5233  get();
5234  check_eof();
5235 
5236  // reverse byte order prior to conversion if necessary
5237  if (is_little_endian)
5238  {
5239  vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);
5240  }
5241  else
5242  {
5243  vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE
5244  }
5245  }
5246 
5247  // step 2: convert array into number of type T and return
5248  NumberType result;
5249  std::memcpy(&result, vec.data(), sizeof(NumberType));
5250  return result;
5251  }
5252 
5253  /*!
5254  @brief create a string by reading characters from the input
5255 
5256  @param[in] len number of bytes to read
5257 
5258  @note We can not reserve @a len bytes for the result, because @a len
5259  may be too large. Usually, @ref check_eof() detects the end of
5260  the input before we run out of string memory.
5261 
5262  @return string created by reading @a len bytes
5263 
5264  @throw parse_error.110 if input has less than @a len bytes
5265  */
5266  template<typename NumberType>
5267  std::string get_string(const NumberType len)
5268  {
5269  std::string result;
5270  std::generate_n(std::back_inserter(result), len, [this]()
5271  {
5272  get();
5273  check_eof();
5274  return static_cast<char>(current);
5275  });
5276  return result;
5277  }
5278 
5279  /*!
5280  @brief reads a CBOR string
5281 
5282  This function first reads starting bytes to determine the expected
5283  string length and then copies this number of bytes into a string.
5284  Additionally, CBOR's strings with indefinite lengths are supported.
5285 
5286  @return string
5287 
5288  @throw parse_error.110 if input ended
5289  @throw parse_error.113 if an unexpected byte is read
5290  */
5291  std::string get_cbor_string()
5292  {
5293  check_eof();
5294 
5295  switch (current)
5296  {
5297  // UTF-8 string (0x00..0x17 bytes follow)
5298  case 0x60:
5299  case 0x61:
5300  case 0x62:
5301  case 0x63:
5302  case 0x64:
5303  case 0x65:
5304  case 0x66:
5305  case 0x67:
5306  case 0x68:
5307  case 0x69:
5308  case 0x6A:
5309  case 0x6B:
5310  case 0x6C:
5311  case 0x6D:
5312  case 0x6E:
5313  case 0x6F:
5314  case 0x70:
5315  case 0x71:
5316  case 0x72:
5317  case 0x73:
5318  case 0x74:
5319  case 0x75:
5320  case 0x76:
5321  case 0x77:
5322  {
5323  return get_string(current & 0x1F);
5324  }
5325 
5326  case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
5327  {
5328  return get_string(get_number<uint8_t>());
5329  }
5330 
5331  case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
5332  {
5333  return get_string(get_number<uint16_t>());
5334  }
5335 
5336  case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
5337  {
5338  return get_string(get_number<uint32_t>());
5339  }
5340 
5341  case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
5342  {
5343  return get_string(get_number<uint64_t>());
5344  }
5345 
5346  case 0x7F: // UTF-8 string (indefinite length)
5347  {
5348  std::string result;
5349  while (get() != 0xFF)
5350  {
5351  check_eof();
5352  result.push_back(static_cast<char>(current));
5353  }
5354  return result;
5355  }
5356 
5357  default:
5358  {
5359  std::stringstream ss;
5360  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5361  JSON_THROW(parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + ss.str()));
5362  }
5363  }
5364  }
5365 
5366  template<typename NumberType>
5367  BasicJsonType get_cbor_array(const NumberType len)
5368  {
5369  BasicJsonType result = value_t::array;
5370  std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
5371  {
5372  return parse_cbor_internal();
5373  });
5374  return result;
5375  }
5376 
5377  template<typename NumberType>
5378  BasicJsonType get_cbor_object(const NumberType len)
5379  {
5380  BasicJsonType result = value_t::object;
5381  std::generate_n(std::inserter(*result.m_value.object,
5382  result.m_value.object->end()),
5383  len, [this]()
5384  {
5385  get();
5386  auto key = get_cbor_string();
5387  auto val = parse_cbor_internal();
5388  return std::make_pair(std::move(key), std::move(val));
5389  });
5390  return result;
5391  }
5392 
5393  /*!
5394  @brief reads a MessagePack string
5395 
5396  This function first reads starting bytes to determine the expected
5397  string length and then copies this number of bytes into a string.
5398 
5399  @return string
5400 
5401  @throw parse_error.110 if input ended
5402  @throw parse_error.113 if an unexpected byte is read
5403  */
5404  std::string get_msgpack_string()
5405  {
5406  check_eof();
5407 
5408  switch (current)
5409  {
5410  // fixstr
5411  case 0xA0:
5412  case 0xA1:
5413  case 0xA2:
5414  case 0xA3:
5415  case 0xA4:
5416  case 0xA5:
5417  case 0xA6:
5418  case 0xA7:
5419  case 0xA8:
5420  case 0xA9:
5421  case 0xAA:
5422  case 0xAB:
5423  case 0xAC:
5424  case 0xAD:
5425  case 0xAE:
5426  case 0xAF:
5427  case 0xB0:
5428  case 0xB1:
5429  case 0xB2:
5430  case 0xB3:
5431  case 0xB4:
5432  case 0xB5:
5433  case 0xB6:
5434  case 0xB7:
5435  case 0xB8:
5436  case 0xB9:
5437  case 0xBA:
5438  case 0xBB:
5439  case 0xBC:
5440  case 0xBD:
5441  case 0xBE:
5442  case 0xBF:
5443  {
5444  return get_string(current & 0x1F);
5445  }
5446 
5447  case 0xD9: // str 8
5448  {
5449  return get_string(get_number<uint8_t>());
5450  }
5451 
5452  case 0xDA: // str 16
5453  {
5454  return get_string(get_number<uint16_t>());
5455  }
5456 
5457  case 0xDB: // str 32
5458  {
5459  return get_string(get_number<uint32_t>());
5460  }
5461 
5462  default:
5463  {
5464  std::stringstream ss;
5465  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5466  JSON_THROW(parse_error::create(113, chars_read,
5467  "expected a MessagePack string; last byte: 0x" + ss.str()));
5468  }
5469  }
5470  }
5471 
5472  template<typename NumberType>
5473  BasicJsonType get_msgpack_array(const NumberType len)
5474  {
5475  BasicJsonType result = value_t::array;
5476  std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
5477  {
5478  return parse_msgpack_internal();
5479  });
5480  return result;
5481  }
5482 
5483  template<typename NumberType>
5484  BasicJsonType get_msgpack_object(const NumberType len)
5485  {
5486  BasicJsonType result = value_t::object;
5487  std::generate_n(std::inserter(*result.m_value.object,
5488  result.m_value.object->end()),
5489  len, [this]()
5490  {
5491  get();
5492  auto key = get_msgpack_string();
5493  auto val = parse_msgpack_internal();
5494  return std::make_pair(std::move(key), std::move(val));
5495  });
5496  return result;
5497  }
5498 
5499  /*!
5500  @brief check if input ended
5501  @throw parse_error.110 if input ended
5502  */
5503  void check_eof(const bool expect_eof = false) const
5504  {
5505  if (expect_eof)
5506  {
5507  if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
5508  {
5509  JSON_THROW(parse_error::create(110, chars_read, "expected end of input"));
5510  }
5511  }
5512  else
5513  {
5514  if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
5515  {
5516  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
5517  }
5518  }
5519  }
5520 
5521  private:
5522  /// input adapter
5523  input_adapter_t ia = nullptr;
5524 
5525  /// the current character
5526  int current = std::char_traits<char>::eof();
5527 
5528  /// the number of characters read
5529  std::size_t chars_read = 0;
5530 
5531  /// whether we can assume little endianess
5532  const bool is_little_endian = little_endianess();
5533 };
5534 
5535 /*!
5536 @brief serialization to CBOR and MessagePack values
5537 */
5538 template<typename BasicJsonType, typename CharType>
5539 class binary_writer
5540 {
5541  public:
5542  /*!
5543  @brief create a binary writer
5544 
5545  @param[in] adapter output adapter to write to
5546  */
5547  explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
5548  {
5549  assert(oa);
5550  }
5551 
5552  /*!
5553  @brief[in] j JSON value to serialize
5554  */
5555  void write_cbor(const BasicJsonType& j)
5556  {
5557  switch (j.type())
5558  {
5559  case value_t::null:
5560  {
5561  oa->write_character(static_cast<CharType>(0xF6));
5562  break;
5563  }
5564 
5565  case value_t::boolean:
5566  {
5567  oa->write_character(j.m_value.boolean
5568  ? static_cast<CharType>(0xF5)
5569  : static_cast<CharType>(0xF4));
5570  break;
5571  }
5572 
5573  case value_t::number_integer:
5574  {
5575  if (j.m_value.number_integer >= 0)
5576  {
5577  // CBOR does not differentiate between positive signed
5578  // integers and unsigned integers. Therefore, we used the
5579  // code from the value_t::number_unsigned case here.
5580  if (j.m_value.number_integer <= 0x17)
5581  {
5582  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5583  }
5584  else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
5585  {
5586  oa->write_character(static_cast<CharType>(0x18));
5587  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5588  }
5589  else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
5590  {
5591  oa->write_character(static_cast<CharType>(0x19));
5592  write_number(static_cast<uint16_t>(j.m_value.number_integer));
5593  }
5594  else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
5595  {
5596  oa->write_character(static_cast<CharType>(0x1A));
5597  write_number(static_cast<uint32_t>(j.m_value.number_integer));
5598  }
5599  else
5600  {
5601  oa->write_character(static_cast<CharType>(0x1B));
5602  write_number(static_cast<uint64_t>(j.m_value.number_integer));
5603  }
5604  }
5605  else
5606  {
5607  // The conversions below encode the sign in the first
5608  // byte, and the value is converted to a positive number.
5609  const auto positive_number = -1 - j.m_value.number_integer;
5610  if (j.m_value.number_integer >= -24)
5611  {
5612  write_number(static_cast<uint8_t>(0x20 + positive_number));
5613  }
5614  else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
5615  {
5616  oa->write_character(static_cast<CharType>(0x38));
5617  write_number(static_cast<uint8_t>(positive_number));
5618  }
5619  else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
5620  {
5621  oa->write_character(static_cast<CharType>(0x39));
5622  write_number(static_cast<uint16_t>(positive_number));
5623  }
5624  else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
5625  {
5626  oa->write_character(static_cast<CharType>(0x3A));
5627  write_number(static_cast<uint32_t>(positive_number));
5628  }
5629  else
5630  {
5631  oa->write_character(static_cast<CharType>(0x3B));
5632  write_number(static_cast<uint64_t>(positive_number));
5633  }
5634  }
5635  break;
5636  }
5637 
5638  case value_t::number_unsigned:
5639  {
5640  if (j.m_value.number_unsigned <= 0x17)
5641  {
5642  write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
5643  }
5644  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
5645  {
5646  oa->write_character(static_cast<CharType>(0x18));
5647  write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
5648  }
5649  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
5650  {
5651  oa->write_character(static_cast<CharType>(0x19));
5652  write_number(static_cast<uint16_t>(j.m_value.number_unsigned));
5653  }
5654  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
5655  {
5656  oa->write_character(static_cast<CharType>(0x1A));
5657  write_number(static_cast<uint32_t>(j.m_value.number_unsigned));
5658  }
5659  else
5660  {
5661  oa->write_character(static_cast<CharType>(0x1B));
5662  write_number(static_cast<uint64_t>(j.m_value.number_unsigned));
5663  }
5664  break;
5665  }
5666 
5667  case value_t::number_float: // Double-Precision Float
5668  {
5669  oa->write_character(static_cast<CharType>(0xFB));
5670  write_number(j.m_value.number_float);
5671  break;
5672  }
5673 
5674  case value_t::string:
5675  {
5676  // step 1: write control byte and the string length
5677  const auto N = j.m_value.string->size();
5678  if (N <= 0x17)
5679  {
5680  write_number(static_cast<uint8_t>(0x60 + N));
5681  }
5682  else if (N <= 0xFF)
5683  {
5684  oa->write_character(static_cast<CharType>(0x78));
5685  write_number(static_cast<uint8_t>(N));
5686  }
5687  else if (N <= 0xFFFF)
5688  {
5689  oa->write_character(static_cast<CharType>(0x79));
5690  write_number(static_cast<uint16_t>(N));
5691  }
5692  else if (N <= 0xFFFFFFFF)
5693  {
5694  oa->write_character(static_cast<CharType>(0x7A));
5695  write_number(static_cast<uint32_t>(N));
5696  }
5697  // LCOV_EXCL_START
5698  else if (N <= 0xFFFFFFFFFFFFFFFF)
5699  {
5700  oa->write_character(static_cast<CharType>(0x7B));
5701  write_number(static_cast<uint64_t>(N));
5702  }
5703  // LCOV_EXCL_STOP
5704 
5705  // step 2: write the string
5706  oa->write_characters(
5707  reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
5708  j.m_value.string->size());
5709  break;
5710  }
5711 
5712  case value_t::array:
5713  {
5714  // step 1: write control byte and the array size
5715  const auto N = j.m_value.array->size();
5716  if (N <= 0x17)
5717  {
5718  write_number(static_cast<uint8_t>(0x80 + N));
5719  }
5720  else if (N <= 0xFF)
5721  {
5722  oa->write_character(static_cast<CharType>(0x98));
5723  write_number(static_cast<uint8_t>(N));
5724  }
5725  else if (N <= 0xFFFF)
5726  {
5727  oa->write_character(static_cast<CharType>(0x99));
5728  write_number(static_cast<uint16_t>(N));
5729  }
5730  else if (N <= 0xFFFFFFFF)
5731  {
5732  oa->write_character(static_cast<CharType>(0x9A));
5733  write_number(static_cast<uint32_t>(N));
5734  }
5735  // LCOV_EXCL_START
5736  else if (N <= 0xFFFFFFFFFFFFFFFF)
5737  {
5738  oa->write_character(static_cast<CharType>(0x9B));
5739  write_number(static_cast<uint64_t>(N));
5740  }
5741  // LCOV_EXCL_STOP
5742 
5743  // step 2: write each element
5744  for (const auto& el : *j.m_value.array)
5745  {
5746  write_cbor(el);
5747  }
5748  break;
5749  }
5750 
5751  case value_t::object:
5752  {
5753  // step 1: write control byte and the object size
5754  const auto N = j.m_value.object->size();
5755  if (N <= 0x17)
5756  {
5757  write_number(static_cast<uint8_t>(0xA0 + N));
5758  }
5759  else if (N <= 0xFF)
5760  {
5761  oa->write_character(static_cast<CharType>(0xB8));
5762  write_number(static_cast<uint8_t>(N));
5763  }
5764  else if (N <= 0xFFFF)
5765  {
5766  oa->write_character(static_cast<CharType>(0xB9));
5767  write_number(static_cast<uint16_t>(N));
5768  }
5769  else if (N <= 0xFFFFFFFF)
5770  {
5771  oa->write_character(static_cast<CharType>(0xBA));
5772  write_number(static_cast<uint32_t>(N));
5773  }
5774  // LCOV_EXCL_START
5775  else if (N <= 0xFFFFFFFFFFFFFFFF)
5776  {
5777  oa->write_character(static_cast<CharType>(0xBB));
5778  write_number(static_cast<uint64_t>(N));
5779  }
5780  // LCOV_EXCL_STOP
5781 
5782  // step 2: write each element
5783  for (const auto& el : *j.m_value.object)
5784  {
5785  write_cbor(el.first);
5786  write_cbor(el.second);
5787  }
5788  break;
5789  }
5790 
5791  default:
5792  break;
5793  }
5794  }
5795 
5796  /*!
5797  @brief[in] j JSON value to serialize
5798  */
5799  void write_msgpack(const BasicJsonType& j)
5800  {
5801  switch (j.type())
5802  {
5803  case value_t::null: // nil
5804  {
5805  oa->write_character(static_cast<CharType>(0xC0));
5806  break;
5807  }
5808 
5809  case value_t::boolean: // true and false
5810  {
5811  oa->write_character(j.m_value.boolean
5812  ? static_cast<CharType>(0xC3)
5813  : static_cast<CharType>(0xC2));
5814  break;
5815  }
5816 
5817  case value_t::number_integer:
5818  {
5819  if (j.m_value.number_integer >= 0)
5820  {
5821  // MessagePack does not differentiate between positive
5822  // signed integers and unsigned integers. Therefore, we used
5823  // the code from the value_t::number_unsigned case here.
5824  if (j.m_value.number_unsigned < 128)
5825  {
5826  // positive fixnum
5827  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5828  }
5829  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
5830  {
5831  // uint 8
5832  oa->write_character(static_cast<CharType>(0xCC));
5833  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5834  }
5835  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
5836  {
5837  // uint 16
5838  oa->write_character(static_cast<CharType>(0xCD));
5839  write_number(static_cast<uint16_t>(j.m_value.number_integer));
5840  }
5841  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
5842  {
5843  // uint 32
5844  oa->write_character(static_cast<CharType>(0xCE));
5845  write_number(static_cast<uint32_t>(j.m_value.number_integer));
5846  }
5847  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
5848  {
5849  // uint 64
5850  oa->write_character(static_cast<CharType>(0xCF));
5851  write_number(static_cast<uint64_t>(j.m_value.number_integer));
5852  }
5853  }
5854  else
5855  {
5856  if (j.m_value.number_integer >= -32)
5857  {
5858  // negative fixnum
5859  write_number(static_cast<int8_t>(j.m_value.number_integer));
5860  }
5861  else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and
5862  j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
5863  {
5864  // int 8
5865  oa->write_character(static_cast<CharType>(0xD0));
5866  write_number(static_cast<int8_t>(j.m_value.number_integer));
5867  }
5868  else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and
5869  j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
5870  {
5871  // int 16
5872  oa->write_character(static_cast<CharType>(0xD1));
5873  write_number(static_cast<int16_t>(j.m_value.number_integer));
5874  }
5875  else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and
5876  j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
5877  {
5878  // int 32
5879  oa->write_character(static_cast<CharType>(0xD2));
5880  write_number(static_cast<int32_t>(j.m_value.number_integer));
5881  }
5882  else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and
5883  j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
5884  {
5885  // int 64
5886  oa->write_character(static_cast<CharType>(0xD3));
5887  write_number(static_cast<int64_t>(j.m_value.number_integer));
5888  }
5889  }
5890  break;
5891  }
5892 
5893  case value_t::number_unsigned:
5894  {
5895  if (j.m_value.number_unsigned < 128)
5896  {
5897  // positive fixnum
5898  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5899  }
5900  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
5901  {
5902  // uint 8
5903  oa->write_character(static_cast<CharType>(0xCC));
5904  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5905  }
5906  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
5907  {
5908  // uint 16
5909  oa->write_character(static_cast<CharType>(0xCD));
5910  write_number(static_cast<uint16_t>(j.m_value.number_integer));
5911  }
5912  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
5913  {
5914  // uint 32
5915  oa->write_character(static_cast<CharType>(0xCE));
5916  write_number(static_cast<uint32_t>(j.m_value.number_integer));
5917  }
5918  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
5919  {
5920  // uint 64
5921  oa->write_character(static_cast<CharType>(0xCF));
5922  write_number(static_cast<uint64_t>(j.m_value.number_integer));
5923  }
5924  break;
5925  }
5926 
5927  case value_t::number_float: // float 64
5928  {
5929  oa->write_character(static_cast<CharType>(0xCB));
5930  write_number(j.m_value.number_float);
5931  break;
5932  }
5933 
5934  case value_t::string:
5935  {
5936  // step 1: write control byte and the string length
5937  const auto N = j.m_value.string->size();
5938  if (N <= 31)
5939  {
5940  // fixstr
5941  write_number(static_cast<uint8_t>(0xA0 | N));
5942  }
5943  else if (N <= 255)
5944  {
5945  // str 8
5946  oa->write_character(static_cast<CharType>(0xD9));
5947  write_number(static_cast<uint8_t>(N));
5948  }
5949  else if (N <= 65535)
5950  {
5951  // str 16
5952  oa->write_character(static_cast<CharType>(0xDA));
5953  write_number(static_cast<uint16_t>(N));
5954  }
5955  else if (N <= 4294967295)
5956  {
5957  // str 32
5958  oa->write_character(static_cast<CharType>(0xDB));
5959  write_number(static_cast<uint32_t>(N));
5960  }
5961 
5962  // step 2: write the string
5963  oa->write_characters(
5964  reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
5965  j.m_value.string->size());
5966  break;
5967  }
5968 
5969  case value_t::array:
5970  {
5971  // step 1: write control byte and the array size
5972  const auto N = j.m_value.array->size();
5973  if (N <= 15)
5974  {
5975  // fixarray
5976  write_number(static_cast<uint8_t>(0x90 | N));
5977  }
5978  else if (N <= 0xFFFF)
5979  {
5980  // array 16
5981  oa->write_character(static_cast<CharType>(0xDC));
5982  write_number(static_cast<uint16_t>(N));
5983  }
5984  else if (N <= 0xFFFFFFFF)
5985  {
5986  // array 32
5987  oa->write_character(static_cast<CharType>(0xDD));
5988  write_number(static_cast<uint32_t>(N));
5989  }
5990 
5991  // step 2: write each element
5992  for (const auto& el : *j.m_value.array)
5993  {
5994  write_msgpack(el);
5995  }
5996  break;
5997  }
5998 
5999  case value_t::object:
6000  {
6001  // step 1: write control byte and the object size
6002  const auto N = j.m_value.object->size();
6003  if (N <= 15)
6004  {
6005  // fixmap
6006  write_number(static_cast<uint8_t>(0x80 | (N & 0xF)));
6007  }
6008  else if (N <= 65535)
6009  {
6010  // map 16
6011  oa->write_character(static_cast<CharType>(0xDE));
6012  write_number(static_cast<uint16_t>(N));
6013  }
6014  else if (N <= 4294967295)
6015  {
6016  // map 32
6017  oa->write_character(static_cast<CharType>(0xDF));
6018  write_number(static_cast<uint32_t>(N));
6019  }
6020 
6021  // step 2: write each element
6022  for (const auto& el : *j.m_value.object)
6023  {
6024  write_msgpack(el.first);
6025  write_msgpack(el.second);
6026  }
6027  break;
6028  }
6029 
6030  default:
6031  break;
6032  }
6033  }
6034 
6035  private:
6036  /*
6037  @brief write a number to output input
6038 
6039  @param[in] n number of type @a NumberType
6040  @tparam NumberType the type of the number
6041 
6042  @note This function needs to respect the system's endianess, because bytes
6043  in CBOR and MessagePack are stored in network order (big endian) and
6044  therefore need reordering on little endian systems.
6045  */
6046  template<typename NumberType> void write_number(NumberType n)
6047  {
6048  // step 1: write number to array of length NumberType
6049  std::array<CharType, sizeof(NumberType)> vec;
6050  std::memcpy(vec.data(), &n, sizeof(NumberType));
6051 
6052  // step 2: write array to output (with possible reordering)
6053  if (is_little_endian)
6054  {
6055  // reverse byte order prior to conversion if necessary
6056  std::reverse(vec.begin(), vec.end());
6057  }
6058 
6059  oa->write_characters(vec.data(), sizeof(NumberType));
6060  }
6061 
6062  private:
6063  /// whether we can assume little endianess
6064  const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
6065 
6066  /// the output
6067  output_adapter_t<CharType> oa = nullptr;
6068 };
6069 
6070 ///////////////////
6071 // serialization //
6072 ///////////////////
6073 
6074 template<typename BasicJsonType>
6075 class serializer
6076 {
6077  using string_t = typename BasicJsonType::string_t;
6078  using number_float_t = typename BasicJsonType::number_float_t;
6079  using number_integer_t = typename BasicJsonType::number_integer_t;
6080  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
6081  public:
6082  /*!
6083  @param[in] s output stream to serialize to
6084  @param[in] ichar indentation character to use
6085  */
6086  serializer(output_adapter_t<char> s, const char ichar)
6087  : o(std::move(s)), loc(std::localeconv()),
6088  thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep)),
6089  decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point)),
6090  indent_char(ichar), indent_string(512, indent_char) {}
6091 
6092  // delete because of pointer members
6093  serializer(const serializer&) = delete;
6094  serializer& operator=(const serializer&) = delete;
6095 
6096  /*!
6097  @brief internal implementation of the serialization function
6098 
6099  This function is called by the public member function dump and organizes
6100  the serialization internally. The indentation level is propagated as
6101  additional parameter. In case of arrays and objects, the function is
6102  called recursively.
6103 
6104  - strings and object keys are escaped using `escape_string()`
6105  - integer numbers are converted implicitly via `operator<<`
6106  - floating-point numbers are converted to a string using `"%g"` format
6107 
6108  @param[in] val value to serialize
6109  @param[in] pretty_print whether the output shall be pretty-printed
6110  @param[in] indent_step the indent level
6111  @param[in] current_indent the current indent level (only used internally)
6112  */
6113  void dump(const BasicJsonType& val, const bool pretty_print,
6114  const bool ensure_ascii,
6115  const unsigned int indent_step,
6116  const unsigned int current_indent = 0)
6117  {
6118  switch (val.m_type)
6119  {
6120  case value_t::object:
6121  {
6122  if (val.m_value.object->empty())
6123  {
6124  o->write_characters("{}", 2);
6125  return;
6126  }
6127 
6128  if (pretty_print)
6129  {
6130  o->write_characters("{\n", 2);
6131 
6132  // variable to hold indentation for recursive calls
6133  const auto new_indent = current_indent + indent_step;
6134  if (JSON_UNLIKELY(indent_string.size() < new_indent))
6135  {
6136  indent_string.resize(indent_string.size() * 2, ' ');
6137  }
6138 
6139  // first n-1 elements
6140  auto i = val.m_value.object->cbegin();
6141  for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
6142  {
6143  o->write_characters(indent_string.c_str(), new_indent);
6144  o->write_character('\"');
6145  dump_escaped(i->first, ensure_ascii);
6146  o->write_characters("\": ", 3);
6147  dump(i->second, true, ensure_ascii, indent_step, new_indent);
6148  o->write_characters(",\n", 2);
6149  }
6150 
6151  // last element
6152  assert(i != val.m_value.object->cend());
6153  assert(std::next(i) == val.m_value.object->cend());
6154  o->write_characters(indent_string.c_str(), new_indent);
6155  o->write_character('\"');
6156  dump_escaped(i->first, ensure_ascii);
6157  o->write_characters("\": ", 3);
6158  dump(i->second, true, ensure_ascii, indent_step, new_indent);
6159 
6160  o->write_character('\n');
6161  o->write_characters(indent_string.c_str(), current_indent);
6162  o->write_character('}');
6163  }
6164  else
6165  {
6166  o->write_character('{');
6167 
6168  // first n-1 elements
6169  auto i = val.m_value.object->cbegin();
6170  for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
6171  {
6172  o->write_character('\"');
6173  dump_escaped(i->first, ensure_ascii);
6174  o->write_characters("\":", 2);
6175  dump(i->second, false, ensure_ascii, indent_step, current_indent);
6176  o->write_character(',');
6177  }
6178 
6179  // last element
6180  assert(i != val.m_value.object->cend());
6181  assert(std::next(i) == val.m_value.object->cend());
6182  o->write_character('\"');
6183  dump_escaped(i->first, ensure_ascii);
6184  o->write_characters("\":", 2);
6185  dump(i->second, false, ensure_ascii, indent_step, current_indent);
6186 
6187  o->write_character('}');
6188  }
6189 
6190  return;
6191  }
6192 
6193  case value_t::array:
6194  {
6195  if (val.m_value.array->empty())
6196  {
6197  o->write_characters("[]", 2);
6198  return;
6199  }
6200 
6201  if (pretty_print)
6202  {
6203  o->write_characters("[\n", 2);
6204 
6205  // variable to hold indentation for recursive calls
6206  const auto new_indent = current_indent + indent_step;
6207  if (JSON_UNLIKELY(indent_string.size() < new_indent))
6208  {
6209  indent_string.resize(indent_string.size() * 2, ' ');
6210  }
6211 
6212  // first n-1 elements
6213  for (auto i = val.m_value.array->cbegin();
6214  i != val.m_value.array->cend() - 1; ++i)
6215  {
6216  o->write_characters(indent_string.c_str(), new_indent);
6217  dump(*i, true, ensure_ascii, indent_step, new_indent);
6218  o->write_characters(",\n", 2);
6219  }
6220 
6221  // last element
6222  assert(not val.m_value.array->empty());
6223  o->write_characters(indent_string.c_str(), new_indent);
6224  dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
6225 
6226  o->write_character('\n');
6227  o->write_characters(indent_string.c_str(), current_indent);
6228  o->write_character(']');
6229  }
6230  else
6231  {
6232  o->write_character('[');
6233 
6234  // first n-1 elements
6235  for (auto i = val.m_value.array->cbegin();
6236  i != val.m_value.array->cend() - 1; ++i)
6237  {
6238  dump(*i, false, ensure_ascii, indent_step, current_indent);
6239  o->write_character(',');
6240  }
6241 
6242  // last element
6243  assert(not val.m_value.array->empty());
6244  dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
6245 
6246  o->write_character(']');
6247  }
6248 
6249  return;
6250  }
6251 
6252  case value_t::string:
6253  {
6254  o->write_character('\"');
6255  dump_escaped(*val.m_value.string, ensure_ascii);
6256  o->write_character('\"');
6257  return;
6258  }
6259 
6260  case value_t::boolean:
6261  {
6262  if (val.m_value.boolean)
6263  {
6264  o->write_characters("true", 4);
6265  }
6266  else
6267  {
6268  o->write_characters("false", 5);
6269  }
6270  return;
6271  }
6272 
6273  case value_t::number_integer:
6274  {
6275  dump_integer(val.m_value.number_integer);
6276  return;
6277  }
6278 
6279  case value_t::number_unsigned:
6280  {
6281  dump_integer(val.m_value.number_unsigned);
6282  return;
6283  }
6284 
6285  case value_t::number_float:
6286  {
6287  dump_float(val.m_value.number_float);
6288  return;
6289  }
6290 
6291  case value_t::discarded:
6292  {
6293  o->write_characters("<discarded>", 11);
6294  return;
6295  }
6296 
6297  case value_t::null:
6298  {
6299  o->write_characters("null", 4);
6300  return;
6301  }
6302  }
6303  }
6304 
6305  private:
6306  /*!
6307  @brief returns the number of expected bytes following in UTF-8 string
6308 
6309  @param[in] u the first byte of a UTF-8 string
6310  @return the number of expected bytes following
6311  */
6312  static constexpr std::size_t bytes_following(const uint8_t u)
6313  {
6314  return ((u <= 127) ? 0
6315  : ((192 <= u and u <= 223) ? 1
6316  : ((224 <= u and u <= 239) ? 2
6317  : ((240 <= u and u <= 247) ? 3 : std::string::npos))));
6318  }
6319 
6320  /*!
6321  @brief calculates the extra space to escape a JSON string
6322 
6323  @param[in] s the string to escape
6324  @param[in] ensure_ascii whether to escape non-ASCII characters with
6325  \uXXXX sequences
6326  @return the number of characters required to escape string @a s
6327 
6328  @complexity Linear in the length of string @a s.
6329  */
6330  static std::size_t extra_space(const string_t& s,
6331  const bool ensure_ascii) noexcept
6332  {
6333  std::size_t res = 0;
6334 
6335  for (std::size_t i = 0; i < s.size(); ++i)
6336  {
6337  switch (s[i])
6338  {
6339  // control characters that can be escaped with a backslash
6340  case '"':
6341  case '\\':
6342  case '\b':
6343  case '\f':
6344  case '\n':
6345  case '\r':
6346  case '\t':
6347  {
6348  // from c (1 byte) to \x (2 bytes)
6349  res += 1;
6350  break;
6351  }
6352 
6353  // control characters that need \uxxxx escaping
6354  case 0x00:
6355  case 0x01:
6356  case 0x02:
6357  case 0x03:
6358  case 0x04:
6359  case 0x05:
6360  case 0x06:
6361  case 0x07:
6362  case 0x0B:
6363  case 0x0E:
6364  case 0x0F:
6365  case 0x10:
6366  case 0x11:
6367  case 0x12:
6368  case 0x13:
6369  case 0x14:
6370  case 0x15:
6371  case 0x16:
6372  case 0x17:
6373  case 0x18:
6374  case 0x19:
6375  case 0x1A:
6376  case 0x1B:
6377  case 0x1C:
6378  case 0x1D:
6379  case 0x1E:
6380  case 0x1F:
6381  {
6382  // from c (1 byte) to \uxxxx (6 bytes)
6383  res += 5;
6384  break;
6385  }
6386 
6387  default:
6388  {
6389  if (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F))
6390  {
6391  const auto bytes = bytes_following(static_cast<uint8_t>(s[i]));
6392  // invalid characters will be detected by throw_if_invalid_utf8
6393  assert (bytes != std::string::npos);
6394 
6395  if (bytes == 3)
6396  {
6397  // codepoints that need 4 bytes (i.e., 3 additional
6398  // bytes) in UTF-8 need a surrogate pair when \u
6399  // escaping is used: from 4 bytes to \uxxxx\uxxxx
6400  // (12 bytes)
6401  res += (12 - bytes - 1);
6402  }
6403  else
6404  {
6405  // from x bytes to \uxxxx (6 bytes)
6406  res += (6 - bytes - 1);
6407  }
6408 
6409  // skip the additional bytes
6410  i += bytes;
6411  }
6412  break;
6413  }
6414  }
6415  }
6416 
6417  return res;
6418  }
6419 
6420  static void escape_codepoint(int codepoint, string_t& result, std::size_t& pos)
6421  {
6422  // expecting a proper codepoint
6423  assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
6424 
6425  // the last written character was the backslash before the 'u'
6426  assert(result[pos] == '\\');
6427 
6428  // write the 'u'
6429  result[++pos] = 'u';
6430 
6431  // convert a number 0..15 to its hex representation (0..f)
6432  static const std::array<char, 16> hexify =
6433  {
6434  {
6435  '0', '1', '2', '3', '4', '5', '6', '7',
6436  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
6437  }
6438  };
6439 
6440  if (codepoint < 0x10000)
6441  {
6442  // codepoints U+0000..U+FFFF can be represented as \uxxxx.
6443  result[++pos] = hexify[(codepoint >> 12) & 0x0F];
6444  result[++pos] = hexify[(codepoint >> 8) & 0x0F];
6445  result[++pos] = hexify[(codepoint >> 4) & 0x0F];
6446  result[++pos] = hexify[codepoint & 0x0F];
6447  }
6448  else
6449  {
6450  // codepoints U+10000..U+10FFFF need a surrogate pair to be
6451  // represented as \uxxxx\uxxxx.
6452  // http://www.unicode.org/faq/utf_bom.html#utf16-4
6453  codepoint -= 0x10000;
6454  const int high_surrogate = 0xD800 | ((codepoint >> 10) & 0x3FF);
6455  const int low_surrogate = 0xDC00 | (codepoint & 0x3FF);
6456  result[++pos] = hexify[(high_surrogate >> 12) & 0x0F];
6457  result[++pos] = hexify[(high_surrogate >> 8) & 0x0F];
6458  result[++pos] = hexify[(high_surrogate >> 4) & 0x0F];
6459  result[++pos] = hexify[high_surrogate & 0x0F];
6460  ++pos; // backslash is already in output
6461  result[++pos] = 'u';
6462  result[++pos] = hexify[(low_surrogate >> 12) & 0x0F];
6463  result[++pos] = hexify[(low_surrogate >> 8) & 0x0F];
6464  result[++pos] = hexify[(low_surrogate >> 4) & 0x0F];
6465  result[++pos] = hexify[low_surrogate & 0x0F];
6466  }
6467 
6468  ++pos;
6469  }
6470 
6471  /*!
6472  @brief dump escaped string
6473 
6474  Escape a string by replacing certain special characters by a sequence of an
6475  escape character (backslash) and another character and other control
6476  characters by a sequence of "\u" followed by a four-digit hex
6477  representation. The escaped string is written to output stream @a o.
6478 
6479  @param[in] s the string to escape
6480  @param[in] ensure_ascii whether to escape non-ASCII characters with
6481  \uXXXX sequences
6482 
6483  @complexity Linear in the length of string @a s.
6484  */
6485  void dump_escaped(const string_t& s, const bool ensure_ascii) const
6486  {
6487  throw_if_invalid_utf8(s);
6488 
6489  const auto space = extra_space(s, ensure_ascii);
6490  if (space == 0)
6491  {
6492  o->write_characters(s.c_str(), s.size());
6493  return;
6494  }
6495 
6496  // create a result string of necessary size
6497  string_t result(s.size() + space, '\\');
6498  std::size_t pos = 0;
6499 
6500  for (std::size_t i = 0; i < s.size(); ++i)
6501  {
6502  switch (s[i])
6503  {
6504  case '"': // quotation mark (0x22)
6505  {
6506  result[pos + 1] = '"';
6507  pos += 2;
6508  break;
6509  }
6510 
6511  case '\\': // reverse solidus (0x5C)
6512  {
6513  // nothing to change
6514  pos += 2;
6515  break;
6516  }
6517 
6518  case '\b': // backspace (0x08)
6519  {
6520  result[pos + 1] = 'b';
6521  pos += 2;
6522  break;
6523  }
6524 
6525  case '\f': // formfeed (0x0C)
6526  {
6527  result[pos + 1] = 'f';
6528  pos += 2;
6529  break;
6530  }
6531 
6532  case '\n': // newline (0x0A)
6533  {
6534  result[pos + 1] = 'n';
6535  pos += 2;
6536  break;
6537  }
6538 
6539  case '\r': // carriage return (0x0D)
6540  {
6541  result[pos + 1] = 'r';
6542  pos += 2;
6543  break;
6544  }
6545 
6546  case '\t': // horizontal tab (0x09)
6547  {
6548  result[pos + 1] = 't';
6549  pos += 2;
6550  break;
6551  }
6552 
6553  default:
6554  {
6555  // escape control characters (0x00..0x1F) or, if
6556  // ensure_ascii parameter is used, non-ASCII characters
6557  if ((0x00 <= s[i] and s[i] <= 0x1F) or
6558  (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F)))
6559  {
6560  const auto bytes = bytes_following(static_cast<uint8_t>(s[i]));
6561  // invalid characters will be detected by throw_if_invalid_utf8
6562  assert (bytes != std::string::npos);
6563 
6564  // check that the additional bytes are present
6565  assert(i + bytes < s.size());
6566 
6567  // to use \uxxxx escaping, we first need to caluclate
6568  // the codepoint from the UTF-8 bytes
6569  int codepoint = 0;
6570 
6571  assert(0 <= bytes and bytes <= 3);
6572  switch (bytes)
6573  {
6574  case 0:
6575  {
6576  codepoint = s[i] & 0xFF;
6577  break;
6578  }
6579 
6580  case 1:
6581  {
6582  codepoint = ((s[i] & 0x3F) << 6)
6583  + (s[i + 1] & 0x7F);
6584  break;
6585  }
6586 
6587  case 2:
6588  {
6589  codepoint = ((s[i] & 0x1F) << 12)
6590  + ((s[i + 1] & 0x7F) << 6)
6591  + (s[i + 2] & 0x7F);
6592  break;
6593  }
6594 
6595  case 3:
6596  {
6597  codepoint = ((s[i] & 0xF) << 18)
6598  + ((s[i + 1] & 0x7F) << 12)
6599  + ((s[i + 2] & 0x7F) << 6)
6600  + (s[i + 3] & 0x7F);
6601  break;
6602  }
6603 
6604  default:
6605  break; // LCOV_EXCL_LINE
6606  }
6607 
6608  escape_codepoint(codepoint, result, pos);
6609  i += bytes;
6610  }
6611  else
6612  {
6613  // all other characters are added as-is
6614  result[pos++] = s[i];
6615  }
6616  break;
6617  }
6618  }
6619  }
6620 
6621  assert(pos == result.size());
6622  o->write_characters(result.c_str(), result.size());
6623  }
6624 
6625  /*!
6626  @brief dump an integer
6627 
6628  Dump a given integer to output stream @a o. Works internally with
6629  @a number_buffer.
6630 
6631  @param[in] x integer number (signed or unsigned) to dump
6632  @tparam NumberType either @a number_integer_t or @a number_unsigned_t
6633  */
6634  template<typename NumberType, detail::enable_if_t<
6635  std::is_same<NumberType, number_unsigned_t>::value or
6636  std::is_same<NumberType, number_integer_t>::value,
6637  int> = 0>
6638  void dump_integer(NumberType x)
6639  {
6640  // special case for "0"
6641  if (x == 0)
6642  {
6643  o->write_character('0');
6644  return;
6645  }
6646 
6647  const bool is_negative = (x <= 0) and (x != 0); // see issue #755
6648  std::size_t i = 0;
6649 
6650  while (x != 0)
6651  {
6652  // spare 1 byte for '\0'
6653  assert(i < number_buffer.size() - 1);
6654 
6655  const auto digit = std::labs(static_cast<long>(x % 10));
6656  number_buffer[i++] = static_cast<char>('0' + digit);
6657  x /= 10;
6658  }
6659 
6660  if (is_negative)
6661  {
6662  // make sure there is capacity for the '-'
6663  assert(i < number_buffer.size() - 2);
6664  number_buffer[i++] = '-';
6665  }
6666 
6667  std::reverse(number_buffer.begin(), number_buffer.begin() + i);
6668  o->write_characters(number_buffer.data(), i);
6669  }
6670 
6671  /*!
6672  @brief dump a floating-point number
6673 
6674  Dump a given floating-point number to output stream @a o. Works internally
6675  with @a number_buffer.
6676 
6677  @param[in] x floating-point number to dump
6678  */
6679  void dump_float(number_float_t x)
6680  {
6681  // NaN / inf
6682  if (not std::isfinite(x) or std::isnan(x))
6683  {
6684  o->write_characters("null", 4);
6685  return;
6686  }
6687 
6688  // get number of digits for a text -> float -> text round-trip
6689  static constexpr auto d = std::numeric_limits<number_float_t>::digits10;
6690 
6691  // the actual conversion
6692  std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
6693 
6694  // negative value indicates an error
6695  assert(len > 0);
6696  // check if buffer was large enough
6697  assert(static_cast<std::size_t>(len) < number_buffer.size());
6698 
6699  // erase thousands separator
6700  if (thousands_sep != '\0')
6701  {
6702  const auto end = std::remove(number_buffer.begin(),
6703  number_buffer.begin() + len, thousands_sep);
6704  std::fill(end, number_buffer.end(), '\0');
6705  assert((end - number_buffer.begin()) <= len);
6706  len = (end - number_buffer.begin());
6707  }
6708 
6709  // convert decimal point to '.'
6710  if (decimal_point != '\0' and decimal_point != '.')
6711  {
6712  const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
6713  if (dec_pos != number_buffer.end())
6714  {
6715  *dec_pos = '.';
6716  }
6717  }
6718 
6719  o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
6720 
6721  // determine if need to append ".0"
6722  const bool value_is_int_like =
6723  std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
6724  [](char c)
6725  {
6726  return (c == '.' or c == 'e');
6727  });
6728 
6729  if (value_is_int_like)
6730  {
6731  o->write_characters(".0", 2);
6732  }
6733  }
6734 
6735  /*!
6736  @brief check whether a string is UTF-8 encoded
6737 
6738  The function checks each byte of a string whether it is UTF-8 encoded. The
6739  result of the check is stored in the @a state parameter. The function must
6740  be called initially with state 0 (accept). State 1 means the string must
6741  be rejected, because the current byte is not allowed. If the string is
6742  completely processed, but the state is non-zero, the string ended
6743  prematurely; that is, the last byte indicated more bytes should have
6744  followed.
6745 
6746  @param[in,out] state the state of the decoding
6747  @param[in] byte next byte to decode
6748 
6749  @note The function has been edited: a std::array is used and the code
6750  point is not calculated.
6751 
6752  @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
6753  @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
6754  */
6755  static void decode(uint8_t& state, const uint8_t byte)
6756  {
6757  static const std::array<uint8_t, 400> utf8d =
6758  {
6759  {
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, // 00..1F
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, // 20..3F
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, // 40..5F
6763  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
6764  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
6765  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
6766  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
6767  0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
6768  0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
6769  0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
6770  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
6771  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
6772  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
6773  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
6774  }
6775  };
6776 
6777  const uint8_t type = utf8d[byte];
6778  state = utf8d[256u + state * 16u + type];
6779  }
6780 
6781  /*!
6782  @brief throw an exception if a string is not UTF-8 encoded
6783 
6784  @param[in] str UTF-8 string to check
6785  @throw type_error.316 if passed string is not UTF-8 encoded
6786 
6787  @since version 3.0.0
6788  */
6789  static void throw_if_invalid_utf8(const std::string& str)
6790  {
6791  // start with state 0 (= accept)
6792  uint8_t state = 0;
6793 
6794  for (size_t i = 0; i < str.size(); ++i)
6795  {
6796  const auto byte = static_cast<uint8_t>(str[i]);
6797  decode(state, byte);
6798  if (state == 1)
6799  {
6800  // state 1 means reject
6801  std::stringstream ss;
6802  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(byte);
6803  JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str()));
6804  }
6805  }
6806 
6807  if (state != 0)
6808  {
6809  // we finish reading, but do not accept: string was incomplete
6810  std::stringstream ss;
6811  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(static_cast<uint8_t>(str.back()));
6812  JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str()));
6813  }
6814  }
6815 
6816  private:
6817  /// the output of the serializer
6818  output_adapter_t<char> o = nullptr;
6819 
6820  /// a (hopefully) large enough character buffer
6821  std::array<char, 64> number_buffer{{}};
6822 
6823  /// the locale
6824  const std::lconv* loc = nullptr;
6825  /// the locale's thousand separator character
6826  const char thousands_sep = '\0';
6827  /// the locale's decimal point character
6828  const char decimal_point = '\0';
6829 
6830  /// the indentation character
6831  const char indent_char;
6832 
6833  /// the indentation string
6834  string_t indent_string;
6835 };
6836 
6837 template<typename BasicJsonType>
6838 class json_ref
6839 {
6840  public:
6841  using value_type = BasicJsonType;
6842 
6843  json_ref(value_type&& value)
6844  : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
6845  {}
6846 
6847  json_ref(const value_type& value)
6848  : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
6849  {}
6850 
6851  json_ref(std::initializer_list<json_ref> init)
6852  : owned_value(init), value_ref(&owned_value), is_rvalue(true)
6853  {}
6854 
6855  template<class... Args>
6856  json_ref(Args&& ... args)
6857  : owned_value(std::forward<Args>(args)...), value_ref(&owned_value), is_rvalue(true)
6858  {}
6859 
6860  // class should be movable only
6861  json_ref(json_ref&&) = default;
6862  json_ref(const json_ref&) = delete;
6863  json_ref& operator=(const json_ref&) = delete;
6864 
6865  value_type moved_or_copied() const
6866  {
6867  if (is_rvalue)
6868  {
6869  return std::move(*value_ref);
6870  }
6871  return *value_ref;
6872  }
6873 
6874  value_type const& operator*() const
6875  {
6876  return *static_cast<value_type const*>(value_ref);
6877  }
6878 
6879  value_type const* operator->() const
6880  {
6881  return static_cast<value_type const*>(value_ref);
6882  }
6883 
6884  private:
6885  mutable value_type owned_value = nullptr;
6886  value_type* value_ref = nullptr;
6887  const bool is_rvalue;
6888 };
6889 
6890 } // namespace detail
6891 
6892 /// namespace to hold default `to_json` / `from_json` functions
6893 namespace
6894 {
6895 constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
6896 constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
6897 }
6898 
6899 
6900 /*!
6901 @brief default JSONSerializer template argument
6902 
6903 This serializer ignores the template arguments and uses ADL
6904 ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl))
6905 for serialization.
6906 */
6907 template<typename, typename>
6908 struct adl_serializer
6909 {
6910  /*!
6911  @brief convert a JSON value to any value type
6912 
6913  This function is usually called by the `get()` function of the
6914  @ref basic_json class (either explicit or via conversion operators).
6915 
6916  @param[in] j JSON value to read from
6917  @param[in,out] val value to write to
6918  */
6919  template<typename BasicJsonType, typename ValueType>
6920  static void from_json(BasicJsonType&& j, ValueType& val) noexcept(
6921  noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
6922  {
6923  ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
6924  }
6925 
6926  /*!
6927  @brief convert any value type to a JSON value
6928 
6929  This function is usually called by the constructors of the @ref basic_json
6930  class.
6931 
6932  @param[in,out] j JSON value to write to
6933  @param[in] val value to read from
6934  */
6935  template<typename BasicJsonType, typename ValueType>
6936  static void to_json(BasicJsonType& j, ValueType&& val) noexcept(
6937  noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
6938  {
6939  ::nlohmann::to_json(j, std::forward<ValueType>(val));
6940  }
6941 };
6942 
6943 /*!
6944 @brief JSON Pointer
6945 
6946 A JSON pointer defines a string syntax for identifying a specific value
6947 within a JSON document. It can be used with functions `at` and
6948 `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
6949 
6950 @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
6951 
6952 @since version 2.0.0
6953 */
6955 {
6956  /// allow basic_json to access private members
6958  friend class basic_json;
6959 
6960  public:
6961  /*!
6962  @brief create JSON pointer
6963 
6964  Create a JSON pointer according to the syntax described in
6965  [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
6966 
6967  @param[in] s string representing the JSON pointer; if omitted, the empty
6968  string is assumed which references the whole JSON value
6969 
6970  @throw parse_error.107 if the given JSON pointer @a s is nonempty and
6971  does not begin with a slash (`/`); see example below
6972 
6973  @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s
6974  is not followed by `0` (representing `~`) or `1` (representing `/`);
6975  see example below
6976 
6977  @liveexample{The example shows the construction several valid JSON
6978  pointers as well as the exceptional behavior.,json_pointer}
6979 
6980  @since version 2.0.0
6981  */
6982  explicit json_pointer(const std::string& s = "") : reference_tokens(split(s)) {}
6983 
6984  /*!
6985  @brief return a string representation of the JSON pointer
6986 
6987  @invariant For each JSON pointer `ptr`, it holds:
6988  @code {.cpp}
6989  ptr == json_pointer(ptr.to_string());
6990  @endcode
6991 
6992  @return a string representation of the JSON pointer
6993 
6994  @liveexample{The example shows the result of `to_string`.,
6995  json_pointer__to_string}
6996 
6997  @since version 2.0.0
6998  */
6999  std::string to_string() const noexcept
7000  {
7001  return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
7002  std::string{},
7003  [](const std::string & a, const std::string & b)
7004  {
7005  return a + "/" + escape(b);
7006  });
7007  }
7008 
7009  /// @copydoc to_string()
7010  operator std::string() const
7011  {
7012  return to_string();
7013  }
7014 
7015  private:
7016  /*!
7017  @brief remove and return last reference pointer
7018  @throw out_of_range.405 if JSON pointer has no parent
7019  */
7020  std::string pop_back()
7021  {
7022  if (JSON_UNLIKELY(is_root()))
7023  {
7024  JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
7025  }
7026 
7027  auto last = reference_tokens.back();
7028  reference_tokens.pop_back();
7029  return last;
7030  }
7031 
7032  /// return whether pointer points to the root document
7033  bool is_root() const
7034  {
7035  return reference_tokens.empty();
7036  }
7037 
7038  json_pointer top() const
7039  {
7040  if (JSON_UNLIKELY(is_root()))
7041  {
7042  JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
7043  }
7044 
7045  json_pointer result = *this;
7046  result.reference_tokens = {reference_tokens[0]};
7047  return result;
7048  }
7049 
7050 
7051  /*!
7052  @brief create and return a reference to the pointed to value
7053 
7054  @complexity Linear in the number of reference tokens.
7055 
7056  @throw parse_error.109 if array index is not a number
7057  @throw type_error.313 if value cannot be unflattened
7058  */
7060  NLOHMANN_BASIC_JSON_TPL& get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const;
7061 
7062  /*!
7063  @brief return a reference to the pointed to value
7064 
7065  @note This version does not throw if a value is not present, but tries to
7066  create nested values instead. For instance, calling this function
7067  with pointer `"/this/that"` on a null value is equivalent to calling
7068  `operator[]("this").operator[]("that")` on that value, effectively
7069  changing the null value to an object.
7070 
7071  @param[in] ptr a JSON value
7072 
7073  @return reference to the JSON value pointed to by the JSON pointer
7074 
7075  @complexity Linear in the length of the JSON pointer.
7076 
7077  @throw parse_error.106 if an array index begins with '0'
7078  @throw parse_error.109 if an array index was not a number
7079  @throw out_of_range.404 if the JSON pointer can not be resolved
7080  */
7082  NLOHMANN_BASIC_JSON_TPL& get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const;
7083 
7084  /*!
7085  @throw parse_error.106 if an array index begins with '0'
7086  @throw parse_error.109 if an array index was not a number
7087  @throw out_of_range.402 if the array index '-' is used
7088  @throw out_of_range.404 if the JSON pointer can not be resolved
7089  */
7091  NLOHMANN_BASIC_JSON_TPL& get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const;
7092 
7093  /*!
7094  @brief return a const reference to the pointed to value
7095 
7096  @param[in] ptr a JSON value
7097 
7098  @return const reference to the JSON value pointed to by the JSON
7099  pointer
7100 
7101  @throw parse_error.106 if an array index begins with '0'
7102  @throw parse_error.109 if an array index was not a number
7103  @throw out_of_range.402 if the array index '-' is used
7104  @throw out_of_range.404 if the JSON pointer can not be resolved
7105  */
7107  const NLOHMANN_BASIC_JSON_TPL& get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const;
7108 
7109  /*!
7110  @throw parse_error.106 if an array index begins with '0'
7111  @throw parse_error.109 if an array index was not a number
7112  @throw out_of_range.402 if the array index '-' is used
7113  @throw out_of_range.404 if the JSON pointer can not be resolved
7114  */
7116  const NLOHMANN_BASIC_JSON_TPL& get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const;
7117 
7118  /*!
7119  @brief split the string input to reference tokens
7120 
7121  @note This function is only called by the json_pointer constructor.
7122  All exceptions below are documented there.
7123 
7124  @throw parse_error.107 if the pointer is not empty or begins with '/'
7125  @throw parse_error.108 if character '~' is not followed by '0' or '1'
7126  */
7127  static std::vector<std::string> split(const std::string& reference_string)
7128  {
7129  std::vector<std::string> result;
7130 
7131  // special case: empty reference string -> no reference tokens
7132  if (reference_string.empty())
7133  {
7134  return result;
7135  }
7136 
7137  // check if nonempty reference string begins with slash
7138  if (JSON_UNLIKELY(reference_string[0] != '/'))
7139  {
7140  JSON_THROW(detail::parse_error::create(107, 1,
7141  "JSON pointer must be empty or begin with '/' - was: '" +
7142  reference_string + "'"));
7143  }
7144 
7145  // extract the reference tokens:
7146  // - slash: position of the last read slash (or end of string)
7147  // - start: position after the previous slash
7148  for (
7149  // search for the first slash after the first character
7150  std::size_t slash = reference_string.find_first_of('/', 1),
7151  // set the beginning of the first reference token
7152  start = 1;
7153  // we can stop if start == string::npos+1 = 0
7154  start != 0;
7155  // set the beginning of the next reference token
7156  // (will eventually be 0 if slash == std::string::npos)
7157  start = slash + 1,
7158  // find next slash
7159  slash = reference_string.find_first_of('/', start))
7160  {
7161  // use the text between the beginning of the reference token
7162  // (start) and the last slash (slash).
7163  auto reference_token = reference_string.substr(start, slash - start);
7164 
7165  // check reference tokens are properly escaped
7166  for (std::size_t pos = reference_token.find_first_of('~');
7167  pos != std::string::npos;
7168  pos = reference_token.find_first_of('~', pos + 1))
7169  {
7170  assert(reference_token[pos] == '~');
7171 
7172  // ~ must be followed by 0 or 1
7173  if (JSON_UNLIKELY(pos == reference_token.size() - 1 or
7174  (reference_token[pos + 1] != '0' and
7175  reference_token[pos + 1] != '1')))
7176  {
7177  JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
7178  }
7179  }
7180 
7181  // finally, store the reference token
7182  unescape(reference_token);
7183  result.push_back(reference_token);
7184  }
7185 
7186  return result;
7187  }
7188 
7189  /*!
7190  @brief replace all occurrences of a substring by another string
7191 
7192  @param[in,out] s the string to manipulate; changed so that all
7193  occurrences of @a f are replaced with @a t
7194  @param[in] f the substring to replace with @a t
7195  @param[in] t the string to replace @a f
7196 
7197  @pre The search string @a f must not be empty. **This precondition is
7198  enforced with an assertion.**
7199 
7200  @since version 2.0.0
7201  */
7202  static void replace_substring(std::string& s, const std::string& f,
7203  const std::string& t)
7204  {
7205  assert(not f.empty());
7206  for (auto pos = s.find(f); // find first occurrence of f
7207  pos != std::string::npos; // make sure f was found
7208  s.replace(pos, f.size(), t), // replace with t, and
7209  pos = s.find(f, pos + t.size())) // find next occurrence of f
7210  {}
7211  }
7212 
7213  /// escape "~"" to "~0" and "/" to "~1"
7214  static std::string escape(std::string s)
7215  {
7216  replace_substring(s, "~", "~0");
7217  replace_substring(s, "/", "~1");
7218  return s;
7219  }
7220 
7221  /// unescape "~1" to tilde and "~0" to slash (order is important!)
7222  static void unescape(std::string& s)
7223  {
7224  replace_substring(s, "~1", "/");
7225  replace_substring(s, "~0", "~");
7226  }
7227 
7228  /*!
7229  @param[in] reference_string the reference string to the current value
7230  @param[in] value the value to consider
7231  @param[in,out] result the result object to insert values to
7232 
7233  @note Empty objects or arrays are flattened to `null`.
7234  */
7236  static void flatten(const std::string& reference_string,
7237  const NLOHMANN_BASIC_JSON_TPL& value,
7238  NLOHMANN_BASIC_JSON_TPL& result);
7239 
7240  /*!
7241  @param[in] value flattened JSON
7242 
7243  @return unflattened JSON
7244 
7245  @throw parse_error.109 if array index is not a number
7246  @throw type_error.314 if value is not an object
7247  @throw type_error.315 if object values are not primitive
7248  @throw type_error.313 if value cannot be unflattened
7249  */
7252  unflatten(const NLOHMANN_BASIC_JSON_TPL& value);
7253 
7254  friend bool operator==(json_pointer const& lhs,
7255  json_pointer const& rhs) noexcept;
7256 
7257  friend bool operator!=(json_pointer const& lhs,
7258  json_pointer const& rhs) noexcept;
7259 
7260  /// the reference tokens
7261  std::vector<std::string> reference_tokens;
7262 };
7263 
7264 /*!
7265 @brief a class to store JSON values
7266 
7267 @tparam ObjectType type for JSON objects (`std::map` by default; will be used
7268 in @ref object_t)
7269 @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
7270 in @ref array_t)
7271 @tparam StringType type for JSON strings and object keys (`std::string` by
7272 default; will be used in @ref string_t)
7273 @tparam BooleanType type for JSON booleans (`bool` by default; will be used
7274 in @ref boolean_t)
7275 @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
7276 default; will be used in @ref number_integer_t)
7277 @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
7278 `uint64_t` by default; will be used in @ref number_unsigned_t)
7279 @tparam NumberFloatType type for JSON floating-point numbers (`double` by
7280 default; will be used in @ref number_float_t)
7281 @tparam AllocatorType type of the allocator to use (`std::allocator` by
7282 default)
7283 @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
7284 and `from_json()` (@ref adl_serializer by default)
7285 
7286 @requirement The class satisfies the following concept requirements:
7287 - Basic
7288  - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
7289  JSON values can be default constructed. The result will be a JSON null
7290  value.
7291  - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
7292  A JSON value can be constructed from an rvalue argument.
7293  - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
7294  A JSON value can be copy-constructed from an lvalue expression.
7295  - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
7296  A JSON value van be assigned from an rvalue argument.
7297  - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
7298  A JSON value can be copy-assigned from an lvalue expression.
7299  - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
7300  JSON values can be destructed.
7301 - Layout
7302  - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
7303  JSON values have
7304  [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
7305  All non-static data members are private and standard layout types, the
7306  class has no virtual functions or (virtual) base classes.
7307 - Library-wide
7308  - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
7309  JSON values can be compared with `==`, see @ref
7310  operator==(const_reference,const_reference).
7311  - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
7312  JSON values can be compared with `<`, see @ref
7313  operator<(const_reference,const_reference).
7314  - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
7315  Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
7316  other compatible types, using unqualified function call @ref swap().
7317  - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
7318  JSON values can be compared against `std::nullptr_t` objects which are used
7319  to model the `null` value.
7320 - Container
7321  - [Container](http://en.cppreference.com/w/cpp/concept/Container):
7322  JSON values can be used like STL containers and provide iterator access.
7323  - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
7324  JSON values can be used like STL containers and provide reverse iterator
7325  access.
7326 
7327 @invariant The member variables @a m_value and @a m_type have the following
7328 relationship:
7329 - If `m_type == value_t::object`, then `m_value.object != nullptr`.
7330 - If `m_type == value_t::array`, then `m_value.array != nullptr`.
7331 - If `m_type == value_t::string`, then `m_value.string != nullptr`.
7332 The invariants are checked by member function assert_invariant().
7333 
7334 @internal
7335 @note ObjectType trick from http://stackoverflow.com/a/9860911
7336 @endinternal
7337 
7338 @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
7339 Format](http://rfc7159.net/rfc7159)
7340 
7341 @since version 1.0.0
7342 
7343 @nosubgrouping
7344 */
7346 class basic_json
7347 {
7348  private:
7349  template<detail::value_t> friend struct detail::external_constructor;
7350  friend ::nlohmann::json_pointer;
7351  friend ::nlohmann::detail::parser<basic_json>;
7352  friend ::nlohmann::detail::serializer<basic_json>;
7353  template<typename BasicJsonType>
7354  friend class ::nlohmann::detail::iter_impl;
7355  template<typename BasicJsonType, typename CharType>
7356  friend class ::nlohmann::detail::binary_writer;
7357  template<typename BasicJsonType>
7358  friend class ::nlohmann::detail::binary_reader;
7359 
7360  /// workaround type for MSVC
7361  using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
7362 
7363  // convenience aliases for types residing in namespace detail;
7364  using lexer = ::nlohmann::detail::lexer<basic_json>;
7365  using parser = ::nlohmann::detail::parser<basic_json>;
7366 
7367  using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
7368  template<typename BasicJsonType>
7369  using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
7370  template<typename BasicJsonType>
7371  using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
7372  template<typename Iterator>
7373  using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
7374  template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
7375 
7376  template<typename CharType>
7377  using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
7378 
7379  using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
7380  template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
7381 
7382  using serializer = ::nlohmann::detail::serializer<basic_json>;
7383 
7384  public:
7385  using value_t = detail::value_t;
7386  /// @copydoc nlohmann::json_pointer
7387  using json_pointer = ::nlohmann::json_pointer;
7388  template<typename T, typename SFINAE>
7389  using json_serializer = JSONSerializer<T, SFINAE>;
7390  /// helper type for initializer lists of basic_json values
7391  using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
7393  ////////////////
7394  // exceptions //
7395  ////////////////
7397  /// @name exceptions
7398  /// Classes to implement user-defined exceptions.
7399  /// @{
7400 
7401  /// @copydoc detail::exception
7402  using exception = detail::exception;
7403  /// @copydoc detail::parse_error
7404  using parse_error = detail::parse_error;
7405  /// @copydoc detail::invalid_iterator
7406  using invalid_iterator = detail::invalid_iterator;
7407  /// @copydoc detail::type_error
7408  using type_error = detail::type_error;
7409  /// @copydoc detail::out_of_range
7410  using out_of_range = detail::out_of_range;
7411  /// @copydoc detail::other_error
7412  using other_error = detail::other_error;
7414  /// @}
7416 
7417  /////////////////////
7418  // container types //
7419  /////////////////////
7420 
7421  /// @name container types
7422  /// The canonic container types to use @ref basic_json like any other STL
7423  /// container.
7424  /// @{
7425 
7426  /// the type of elements in a basic_json container
7427  using value_type = basic_json;
7428 
7429  /// the type of an element reference
7430  using reference = value_type&;
7431  /// the type of an element const reference
7432  using const_reference = const value_type&;
7433 
7434  /// a type to represent differences between iterators
7435  using difference_type = std::ptrdiff_t;
7436  /// a type to represent container sizes
7437  using size_type = std::size_t;
7438 
7439  /// the allocator type
7440  using allocator_type = AllocatorType<basic_json>;
7441 
7442  /// the type of an element pointer
7443  using pointer = typename std::allocator_traits<allocator_type>::pointer;
7444  /// the type of an element const pointer
7445  using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
7446 
7447  /// an iterator for a basic_json container
7448  using iterator = iter_impl<basic_json>;
7449  /// a const iterator for a basic_json container
7450  using const_iterator = iter_impl<const basic_json>;
7451  /// a reverse iterator for a basic_json container
7452  using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
7453  /// a const reverse iterator for a basic_json container
7454  using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
7456  /// @}
7458 
7459  /*!
7460  @brief returns the allocator associated with the container
7461  */
7462  static allocator_type get_allocator()
7463  {
7464  return allocator_type();
7465  }
7466 
7467  /*!
7468  @brief returns version information on the library
7469 
7470  This function returns a JSON object with information about the library,
7471  including the version number and information on the platform and compiler.
7472 
7473  @return JSON object holding version information
7474  key | description
7475  ----------- | ---------------
7476  `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).
7477  `copyright` | The copyright line for the library as string.
7478  `name` | The name of the library as string.
7479  `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
7480  `url` | The URL of the project as string.
7481  `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).
7482 
7483  @liveexample{The following code shows an example output of the `meta()`
7484  function.,meta}
7485 
7486  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
7487  changes to any JSON value.
7488 
7489  @complexity Constant.
7490 
7491  @since 2.1.0
7492  */
7493  static basic_json meta()
7494  {
7495  basic_json result;
7496 
7497  result["copyright"] = "(C) 2013-2017 Niels Lohmann";
7498  result["name"] = "JSON for Modern C++";
7499  result["url"] = "https://github.com/nlohmann/json";
7500  result["version"] =
7501  {
7502  {"string", "3.0.0"}, {"major", 3}, {"minor", 0}, {"patch", 0}
7503  };
7504 
7505 #ifdef _WIN32
7506  result["platform"] = "win32";
7507 #elif defined __linux__
7508  result["platform"] = "linux";
7509 #elif defined __APPLE__
7510  result["platform"] = "apple";
7511 #elif defined __unix__
7512  result["platform"] = "unix";
7513 #else
7514  result["platform"] = "unknown";
7515 #endif
7516 
7517 #if defined(__ICC) || defined(__INTEL_COMPILER)
7518  result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
7519 #elif defined(__clang__)
7520  result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
7521 #elif defined(__GNUC__) || defined(__GNUG__)
7522  result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
7523 #elif defined(__HP_cc) || defined(__HP_aCC)
7524  result["compiler"] = "hp"
7525 #elif defined(__IBMCPP__)
7526  result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
7527 #elif defined(_MSC_VER)
7528  result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
7529 #elif defined(__PGI)
7530  result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
7531 #elif defined(__SUNPRO_CC)
7532  result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
7533 #else
7534  result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
7535 #endif
7536 
7537 #ifdef __cplusplus
7538  result["compiler"]["c++"] = std::to_string(__cplusplus);
7539 #else
7540  result["compiler"]["c++"] = "unknown";
7541 #endif
7542  return result;
7543  }
7544 
7545 
7546  ///////////////////////////
7547  // JSON value data types //
7548  ///////////////////////////
7549 
7550  /// @name JSON value data types
7551  /// The data types to store a JSON value. These types are derived from
7552  /// the template arguments passed to class @ref basic_json.
7553  /// @{
7554 
7555 #if defined(JSON_HAS_CPP_14)
7556  // Use transparent comparator if possible, combined with perfect forwarding
7557  // on find() and count() calls prevents unnecessary string construction.
7558  using object_comparator_t = std::less<>;
7559 #else
7560  using object_comparator_t = std::less<StringType>;
7561 #endif
7562 
7563  /*!
7564  @brief a type for an object
7566  [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
7567  > An object is an unordered collection of zero or more name/value pairs,
7568  > where a name is a string and a value is a string, number, boolean, null,
7569  > object, or array.
7570 
7571  To store objects in C++, a type is defined by the template parameters
7572  described below.
7573 
7574  @tparam ObjectType the container to store objects (e.g., `std::map` or
7575  `std::unordered_map`)
7576  @tparam StringType the type of the keys or names (e.g., `std::string`).
7577  The comparison function `std::less<StringType>` is used to order elements
7578  inside the container.
7579  @tparam AllocatorType the allocator to use for objects (e.g.,
7580  `std::allocator`)
7581 
7582  #### Default type
7583 
7584  With the default values for @a ObjectType (`std::map`), @a StringType
7585  (`std::string`), and @a AllocatorType (`std::allocator`), the default
7586  value for @a object_t is:
7587 
7588  @code {.cpp}
7589  std::map<
7590  std::string, // key_type
7591  basic_json, // value_type
7592  std::less<std::string>, // key_compare
7593  std::allocator<std::pair<const std::string, basic_json>> // allocator_type
7594  >
7595  @endcode
7596 
7597  #### Behavior
7598 
7599  The choice of @a object_t influences the behavior of the JSON class. With
7600  the default type, objects have the following behavior:
7601 
7602  - When all names are unique, objects will be interoperable in the sense
7603  that all software implementations receiving that object will agree on
7604  the name-value mappings.
7605  - When the names within an object are not unique, later stored name/value
7606  pairs overwrite previously stored name/value pairs, leaving the used
7607  names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will
7608  be treated as equal and both stored as `{"key": 1}`.
7609  - Internally, name/value pairs are stored in lexicographical order of the
7610  names. Objects will also be serialized (see @ref dump) in this order.
7611  For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
7612  and serialized as `{"a": 2, "b": 1}`.
7613  - When comparing objects, the order of the name/value pairs is irrelevant.
7614  This makes objects interoperable in the sense that they will not be
7615  affected by these differences. For instance, `{"b": 1, "a": 2}` and
7616  `{"a": 2, "b": 1}` will be treated as equal.
7617 
7618  #### Limits
7619 
7620  [RFC 7159](http://rfc7159.net/rfc7159) specifies:
7621  > An implementation may set limits on the maximum depth of nesting.
7622 
7623  In this class, the object's limit of nesting is not explicitly constrained.
7624  However, a maximum depth of nesting may be introduced by the compiler or
7625  runtime environment. A theoretical limit can be queried by calling the
7626  @ref max_size function of a JSON object.
7627 
7628  #### Storage
7629 
7630  Objects are stored as pointers in a @ref basic_json type. That is, for any
7631  access to object values, a pointer of type `object_t*` must be
7632  dereferenced.
7633 
7634  @sa @ref array_t -- type for an array value
7635 
7636  @since version 1.0.0
7637 
7638  @note The order name/value pairs are added to the object is *not*
7639  preserved by the library. Therefore, iterating an object may return
7640  name/value pairs in a different order than they were originally stored. In
7641  fact, keys will be traversed in alphabetical order as `std::map` with
7642  `std::less` is used by default. Please note this behavior conforms to [RFC
7643  7159](http://rfc7159.net/rfc7159), because any order implements the
7644  specified "unordered" nature of JSON objects.
7645  */
7646  using object_t = ObjectType<StringType,
7647  basic_json,
7648  object_comparator_t,
7649  AllocatorType<std::pair<const StringType,
7650  basic_json>>>;
7651 
7652  /*!
7653  @brief a type for an array
7654 
7655  [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
7656  > An array is an ordered sequence of zero or more values.
7657 
7658  To store objects in C++, a type is defined by the template parameters
7659  explained below.
7660 
7661  @tparam ArrayType container type to store arrays (e.g., `std::vector` or
7662  `std::list`)
7663  @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
7664 
7665  #### Default type
7666 
7667  With the default values for @a ArrayType (`std::vector`) and @a
7668  AllocatorType (`std::allocator`), the default value for @a array_t is:
7669 
7670  @code {.cpp}
7671  std::vector<
7672  basic_json, // value_type
7673  std::allocator<basic_json> // allocator_type
7674  >
7675  @endcode
7676 
7677  #### Limits
7678 
7679  [RFC 7159](http://rfc7159.net/rfc7159) specifies:
7680  > An implementation may set limits on the maximum depth of nesting.
7681 
7682  In this class, the array's limit of nesting is not explicitly constrained.
7683  However, a maximum depth of nesting may be introduced by the compiler or
7684  runtime environment. A theoretical limit can be queried by calling the
7685  @ref max_size function of a JSON array.
7686 
7687  #### Storage
7688 
7689  Arrays are stored as pointers in a @ref basic_json type. That is, for any
7690  access to array values, a pointer of type `array_t*` must be dereferenced.
7691 
7692  @sa @ref object_t -- type for an object value
7693 
7694  @since version 1.0.0
7695  */
7696  using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
7697 
7698  /*!
7699  @brief a type for a string
7700 
7701  [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
7702  > A string is a sequence of zero or more Unicode characters.
7703 
7704  To store objects in C++, a type is defined by the template parameter
7705  described below. Unicode values are split by the JSON class into
7706  byte-sized characters during deserialization.
7707 
7708  @tparam StringType the container to store strings (e.g., `std::string`).
7709  Note this container is used for keys/names in objects, see @ref object_t.
7710 
7711  #### Default type
7712 
7713  With the default values for @a StringType (`std::string`), the default
7714  value for @a string_t is:
7715 
7716  @code {.cpp}
7717  std::string
7718  @endcode
7719 
7720  #### Encoding
7721 
7722  Strings are stored in UTF-8 encoding. Therefore, functions like
7723  `std::string::size()` or `std::string::length()` return the number of
7724  bytes in the string rather than the number of characters or glyphs.
7725 
7726  #### String comparison
7727 
7728  [RFC 7159](http://rfc7159.net/rfc7159) states:
7729  > Software implementations are typically required to test names of object
7730  > members for equality. Implementations that transform the textual
7731  > representation into sequences of Unicode code units and then perform the
7732  > comparison numerically, code unit by code unit, are interoperable in the
7733  > sense that implementations will agree in all cases on equality or
7734  > inequality of two strings. For example, implementations that compare
7735  > strings with escaped characters unconverted may incorrectly find that
7736  > `"a\\b"` and `"a\u005Cb"` are not equal.
7737 
7738  This implementation is interoperable as it does compare strings code unit
7739  by code unit.
7740 
7741  #### Storage
7742 
7743  String values are stored as pointers in a @ref basic_json type. That is,
7744  for any access to string values, a pointer of type `string_t*` must be
7745  dereferenced.
7746 
7747  @since version 1.0.0
7748  */
7749  using string_t = StringType;
7750 
7751  /*!
7752  @brief a type for a boolean
7753 
7754  [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
7755  type which differentiates the two literals `true` and `false`.
7756 
7757  To store objects in C++, a type is defined by the template parameter @a
7758  BooleanType which chooses the type to use.
7759 
7760  #### Default type
7761 
7762  With the default values for @a BooleanType (`bool`), the default value for
7763  @a boolean_t is:
7764 
7765  @code {.cpp}
7766  bool
7767  @endcode
7768 
7769  #### Storage
7770 
7771  Boolean values are stored directly inside a @ref basic_json type.
7772 
7773  @since version 1.0.0
7774  */
7775  using boolean_t = BooleanType;
7776 
7777  /*!
7778  @brief a type for a number (integer)
7779 
7780  [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
7781  > The representation of numbers is similar to that used in most
7782  > programming languages. A number is represented in base 10 using decimal
7783  > digits. It contains an integer component that may be prefixed with an
7784  > optional minus sign, which may be followed by a fraction part and/or an
7785  > exponent part. Leading zeros are not allowed. (...) Numeric values that
7786  > cannot be represented in the grammar below (such as Infinity and NaN)
7787  > are not permitted.
7788 
7789  This description includes both integer and floating-point numbers.
7790  However, C++ allows more precise storage if it is known whether the number
7791  is a signed integer, an unsigned integer or a floating-point number.
7792  Therefore, three different types, @ref number_integer_t, @ref
7793  number_unsigned_t and @ref number_float_t are used.
7794 
7795  To store integer numbers in C++, a type is defined by the template
7796  parameter @a NumberIntegerType which chooses the type to use.
7797 
7798  #### Default type
7799 
7800  With the default values for @a NumberIntegerType (`int64_t`), the default
7801  value for @a number_integer_t is:
7802 
7803  @code {.cpp}
7804  int64_t
7805  @endcode
7806 
7807  #### Default behavior
7808 
7809  - The restrictions about leading zeros is not enforced in C++. Instead,
7810  leading zeros in integer literals lead to an interpretation as octal
7811  number. Internally, the value will be stored as decimal number. For
7812  instance, the C++ integer literal `010` will be serialized to `8`.
7813  During deserialization, leading zeros yield an error.
7814  - Not-a-number (NaN) values will be serialized to `null`.
7815 
7816  #### Limits
7817 
7818  [RFC 7159](http://rfc7159.net/rfc7159) specifies:
7819  > An implementation may set limits on the range and precision of numbers.
7820 
7821  When the default type is used, the maximal integer number that can be
7822  stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
7823  that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
7824  that are out of range will yield over/underflow when used in a
7825  constructor. During deserialization, too large or small integer numbers
7826  will be automatically be stored as @ref number_unsigned_t or @ref
7827  number_float_t.
7828 
7829  [RFC 7159](http://rfc7159.net/rfc7159) further states:
7830  > Note that when such software is used, numbers that are integers and are
7831  > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
7832  > that implementations will agree exactly on their numeric values.
7833 
7834  As this range is a subrange of the exactly supported range [INT64_MIN,
7835  INT64_MAX], this class's integer type is interoperable.
7836 
7837  #### Storage
7838 
7839  Integer number values are stored directly inside a @ref basic_json type.
7840 
7841  @sa @ref number_float_t -- type for number values (floating-point)
7842 
7843  @sa @ref number_unsigned_t -- type for number values (unsigned integer)
7844 
7845  @since version 1.0.0
7846  */
7847  using number_integer_t = NumberIntegerType;
7848 
7849  /*!
7850  @brief a type for a number (unsigned)
7851 
7852  [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
7853  > The representation of numbers is similar to that used in most
7854  > programming languages. A number is represented in base 10 using decimal
7855  > digits. It contains an integer component that may be prefixed with an
7856  > optional minus sign, which may be followed by a fraction part and/or an
7857  > exponent part. Leading zeros are not allowed. (...) Numeric values that
7858  > cannot be represented in the grammar below (such as Infinity and NaN)
7859  > are not permitted.
7860 
7861  This description includes both integer and floating-point numbers.
7862  However, C++ allows more precise storage if it is known whether the number
7863  is a signed integer, an unsigned integer or a floating-point number.
7864  Therefore, three different types, @ref number_integer_t, @ref
7865  number_unsigned_t and @ref number_float_t are used.
7866 
7867  To store unsigned integer numbers in C++, a type is defined by the
7868  template parameter @a NumberUnsignedType which chooses the type to use.
7869 
7870  #### Default type
7871 
7872  With the default values for @a NumberUnsignedType (`uint64_t`), the
7873  default value for @a number_unsigned_t is:
7874 
7875  @code {.cpp}
7876  uint64_t
7877  @endcode
7878 
7879  #### Default behavior
7880 
7881  - The restrictions about leading zeros is not enforced in C++. Instead,
7882  leading zeros in integer literals lead to an interpretation as octal
7883  number. Internally, the value will be stored as decimal number. For
7884  instance, the C++ integer literal `010` will be serialized to `8`.
7885  During deserialization, leading zeros yield an error.
7886  - Not-a-number (NaN) values will be serialized to `null`.
7887 
7888  #### Limits
7889 
7890  [RFC 7159](http://rfc7159.net/rfc7159) specifies:
7891  > An implementation may set limits on the range and precision of numbers.
7892 
7893  When the default type is used, the maximal integer number that can be
7894  stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
7895  number that can be stored is `0`. Integer numbers that are out of range
7896  will yield over/underflow when used in a constructor. During
7897  deserialization, too large or small integer numbers will be automatically
7898  be stored as @ref number_integer_t or @ref number_float_t.
7899 
7900  [RFC 7159](http://rfc7159.net/rfc7159) further states:
7901  > Note that when such software is used, numbers that are integers and are
7902  > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
7903  > that implementations will agree exactly on their numeric values.
7904 
7905  As this range is a subrange (when considered in conjunction with the
7906  number_integer_t type) of the exactly supported range [0, UINT64_MAX],
7907  this class's integer type is interoperable.
7908 
7909  #### Storage
7910 
7911  Integer number values are stored directly inside a @ref basic_json type.
7912 
7913  @sa @ref number_float_t -- type for number values (floating-point)
7914  @sa @ref number_integer_t -- type for number values (integer)
7915 
7916  @since version 2.0.0
7917  */
7918  using number_unsigned_t = NumberUnsignedType;
7919 
7920  /*!
7921  @brief a type for a number (floating-point)
7922 
7923  [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
7924  > The representation of numbers is similar to that used in most
7925  > programming languages. A number is represented in base 10 using decimal
7926  > digits. It contains an integer component that may be prefixed with an
7927  > optional minus sign, which may be followed by a fraction part and/or an
7928  > exponent part. Leading zeros are not allowed. (...) Numeric values that
7929  > cannot be represented in the grammar below (such as Infinity and NaN)
7930  > are not permitted.
7931 
7932  This description includes both integer and floating-point numbers.
7933  However, C++ allows more precise storage if it is known whether the number
7934  is a signed integer, an unsigned integer or a floating-point number.
7935  Therefore, three different types, @ref number_integer_t, @ref
7936  number_unsigned_t and @ref number_float_t are used.
7937 
7938  To store floating-point numbers in C++, a type is defined by the template
7939  parameter @a NumberFloatType which chooses the type to use.
7940 
7941  #### Default type
7942 
7943  With the default values for @a NumberFloatType (`double`), the default
7944  value for @a number_float_t is:
7945 
7946  @code {.cpp}
7947  double
7948  @endcode
7949 
7950  #### Default behavior
7951 
7952  - The restrictions about leading zeros is not enforced in C++. Instead,
7953  leading zeros in floating-point literals will be ignored. Internally,
7954  the value will be stored as decimal number. For instance, the C++
7955  floating-point literal `01.2` will be serialized to `1.2`. During
7956  deserialization, leading zeros yield an error.
7957  - Not-a-number (NaN) values will be serialized to `null`.
7958 
7959  #### Limits
7960 
7961  [RFC 7159](http://rfc7159.net/rfc7159) states:
7962  > This specification allows implementations to set limits on the range and
7963  > precision of numbers accepted. Since software that implements IEEE
7964  > 754-2008 binary64 (double precision) numbers is generally available and
7965  > widely used, good interoperability can be achieved by implementations
7966  > that expect no more precision or range than these provide, in the sense
7967  > that implementations will approximate JSON numbers within the expected
7968  > precision.
7969 
7970  This implementation does exactly follow this approach, as it uses double
7971  precision floating-point numbers. Note values smaller than
7972  `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
7973  will be stored as NaN internally and be serialized to `null`.
7974 
7975  #### Storage
7976 
7977  Floating-point number values are stored directly inside a @ref basic_json
7978  type.
7979 
7980  @sa @ref number_integer_t -- type for number values (integer)
7981 
7982  @sa @ref number_unsigned_t -- type for number values (unsigned integer)
7983 
7984  @since version 1.0.0
7985  */
7986  using number_float_t = NumberFloatType;
7987 
7988  /// @}
7989 
7990  private:
7992  /// helper for exception-safe object creation
7993  template<typename T, typename... Args>
7994  static T* create(Args&& ... args)
7995  {
7996  AllocatorType<T> alloc;
7997  using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
7998 
7999  auto deleter = [&](T * object)
8000  {
8001  AllocatorTraits::deallocate(alloc, object, 1);
8002  };
8003  std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
8004  AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
8005  assert(object != nullptr);
8006  return object.release();
8007  }
8008 
8009  ////////////////////////
8010  // JSON value storage //
8011  ////////////////////////
8012 
8013  /*!
8014  @brief a JSON value
8015 
8016  The actual storage for a JSON value of the @ref basic_json class. This
8017  union combines the different storage types for the JSON value types
8018  defined in @ref value_t.
8019 
8020  JSON type | value_t type | used type
8021  --------- | --------------- | ------------------------
8022  object | object | pointer to @ref object_t
8023  array | array | pointer to @ref array_t
8024  string | string | pointer to @ref string_t
8025  boolean | boolean | @ref boolean_t
8026  number | number_integer | @ref number_integer_t
8027  number | number_unsigned | @ref number_unsigned_t
8028  number | number_float | @ref number_float_t
8029  null | null | *no value is stored*
8030 
8031  @note Variable-length types (objects, arrays, and strings) are stored as
8032  pointers. The size of the union should not exceed 64 bits if the default
8033  value types are used.
8034 
8035  @since version 1.0.0
8036  */
8037  union json_value
8038  {
8039  /// object (stored with pointer to save storage)
8040  object_t* object;
8041  /// array (stored with pointer to save storage)
8042  array_t* array;
8043  /// string (stored with pointer to save storage)
8044  string_t* string;
8045  /// boolean
8046  boolean_t boolean;
8047  /// number (integer)
8048  number_integer_t number_integer;
8049  /// number (unsigned integer)
8050  number_unsigned_t number_unsigned;
8051  /// number (floating-point)
8052  number_float_t number_float;
8053 
8054  /// default constructor (for null values)
8055  json_value() = default;
8056  /// constructor for booleans
8057  json_value(boolean_t v) noexcept : boolean(v) {}
8058  /// constructor for numbers (integer)
8059  json_value(number_integer_t v) noexcept : number_integer(v) {}
8060  /// constructor for numbers (unsigned)
8061  json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
8062  /// constructor for numbers (floating-point)
8063  json_value(number_float_t v) noexcept : number_float(v) {}
8064  /// constructor for empty values of a given type
8065  json_value(value_t t)
8066  {
8067  switch (t)
8068  {
8069  case value_t::object:
8070  {
8071  object = create<object_t>();
8072  break;
8073  }
8074 
8075  case value_t::array:
8076  {
8077  array = create<array_t>();
8078  break;
8079  }
8080 
8081  case value_t::string:
8082  {
8083  string = create<string_t>("");
8084  break;
8085  }
8086 
8087  case value_t::boolean:
8088  {
8089  boolean = boolean_t(false);
8090  break;
8091  }
8092 
8093  case value_t::number_integer:
8094  {
8095  number_integer = number_integer_t(0);
8096  break;
8097  }
8098 
8099  case value_t::number_unsigned:
8100  {
8101  number_unsigned = number_unsigned_t(0);
8102  break;
8103  }
8104 
8105  case value_t::number_float:
8106  {
8107  number_float = number_float_t(0.0);
8108  break;
8109  }
8110 
8111  case value_t::null:
8112  {
8113  object = nullptr; // silence warning, see #821
8114  break;
8115  }
8116 
8117  default:
8118  {
8119  object = nullptr; // silence warning, see #821
8120  if (JSON_UNLIKELY(t == value_t::null))
8121  {
8122  JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.0.0")); // LCOV_EXCL_LINE
8123  }
8124  break;
8125  }
8126  }
8127  }
8128 
8129  /// constructor for strings
8130  json_value(const string_t& value)
8131  {
8132  string = create<string_t>(value);
8133  }
8134 
8135  /// constructor for rvalue strings
8136  json_value(string_t&& value)
8137  {
8138  string = create<string_t>(std::move(value));
8139  }
8140 
8141  /// constructor for objects
8142  json_value(const object_t& value)
8143  {
8144  object = create<object_t>(value);
8145  }
8146 
8147  /// constructor for rvalue objects
8148  json_value(object_t&& value)
8149  {
8150  object = create<object_t>(std::move(value));
8151  }
8152 
8153  /// constructor for arrays
8154  json_value(const array_t& value)
8155  {
8156  array = create<array_t>(value);
8157  }
8158 
8159  /// constructor for rvalue arrays
8160  json_value(array_t&& value)
8161  {
8162  array = create<array_t>(std::move(value));
8163  }
8164 
8165  void destroy(value_t t)
8166  {
8167  switch (t)
8168  {
8169  case value_t::object:
8170  {
8171  AllocatorType<object_t> alloc;
8172  std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
8173  std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
8174  break;
8175  }
8176 
8177  case value_t::array:
8178  {
8179  AllocatorType<array_t> alloc;
8180  std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
8181  std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
8182  break;
8183  }
8184 
8185  case value_t::string:
8186  {
8187  AllocatorType<string_t> alloc;
8188  std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
8189  std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
8190  break;
8191  }
8192 
8193  default:
8194  {
8195  break;
8196  }
8197  }
8198  }
8199  };
8200 
8201  /*!
8202  @brief checks the class invariants
8203 
8204  This function asserts the class invariants. It needs to be called at the
8205  end of every constructor to make sure that created objects respect the
8206  invariant. Furthermore, it has to be called each time the type of a JSON
8207  value is changed, because the invariant expresses a relationship between
8208  @a m_type and @a m_value.
8209  */
8210  void assert_invariant() const
8211  {
8212  assert(m_type != value_t::object or m_value.object != nullptr);
8213  assert(m_type != value_t::array or m_value.array != nullptr);
8214  assert(m_type != value_t::string or m_value.string != nullptr);
8215  }
8216 
8217  public:
8218  //////////////////////////
8219  // JSON parser callback //
8220  //////////////////////////
8221 
8222  /*!
8223  @brief parser event types
8224 
8225  The parser callback distinguishes the following events:
8226  - `object_start`: the parser read `{` and started to process a JSON object
8227  - `key`: the parser read a key of a value in an object
8228  - `object_end`: the parser read `}` and finished processing a JSON object
8229  - `array_start`: the parser read `[` and started to process a JSON array
8230  - `array_end`: the parser read `]` and finished processing a JSON array
8231  - `value`: the parser finished reading a JSON value
8232 
8233  @image html callback_events.png "Example when certain parse events are triggered"
8234 
8235  @sa @ref parser_callback_t for more information and examples
8236  */
8237  using parse_event_t = typename parser::parse_event_t;
8238 
8239  /*!
8240  @brief per-element parser callback type
8241 
8242  With a parser callback function, the result of parsing a JSON text can be
8243  influenced. When passed to @ref parse, it is called on certain events
8244  (passed as @ref parse_event_t via parameter @a event) with a set recursion
8245  depth @a depth and context JSON value @a parsed. The return value of the
8246  callback function is a boolean indicating whether the element that emitted
8247  the callback shall be kept or not.
8248 
8249  We distinguish six scenarios (determined by the event type) in which the
8250  callback function can be called. The following table describes the values
8251  of the parameters @a depth, @a event, and @a parsed.
8252 
8253  parameter @a event | description | parameter @a depth | parameter @a parsed
8254  ------------------ | ----------- | ------------------ | -------------------
8255  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
8256  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
8257  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
8258  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
8259  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
8260  parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
8261 
8262  @image html callback_events.png "Example when certain parse events are triggered"
8263 
8264  Discarding a value (i.e., returning `false`) has different effects
8265  depending on the context in which function was called:
8266 
8267  - Discarded values in structured types are skipped. That is, the parser
8268  will behave as if the discarded value was never read.
8269  - In case a value outside a structured type is skipped, it is replaced
8270  with `null`. This case happens if the top-level element is skipped.
8271 
8272  @param[in] depth the depth of the recursion during parsing
8273 
8274  @param[in] event an event of type parse_event_t indicating the context in
8275  the callback function has been called
8276 
8277  @param[in,out] parsed the current intermediate parse result; note that
8278  writing to this value has no effect for parse_event_t::key events
8279 
8280  @return Whether the JSON value which called the function during parsing
8281  should be kept (`true`) or not (`false`). In the latter case, it is either
8282  skipped completely or replaced by an empty discarded object.
8283 
8284  @sa @ref parse for examples
8285 
8286  @since version 1.0.0
8287  */
8288  using parser_callback_t = typename parser::parser_callback_t;
8289 
8290 
8291  //////////////////
8292  // constructors //
8293  //////////////////
8294 
8295  /// @name constructors and destructors
8296  /// Constructors of class @ref basic_json, copy/move constructor, copy
8297  /// assignment, static functions creating objects, and the destructor.
8298  /// @{
8299 
8300  /*!
8301  @brief create an empty value with a given type
8302 
8303  Create an empty JSON value with a given type. The value will be default
8304  initialized with an empty value which depends on the type:
8305 
8306  Value type | initial value
8307  ----------- | -------------
8308  null | `null`
8309  boolean | `false`
8310  string | `""`
8311  number | `0`
8312  object | `{}`
8313  array | `[]`
8314 
8315  @param[in] v the type of the value to create
8316 
8317  @complexity Constant.
8318 
8319  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8320  changes to any JSON value.
8321 
8322  @liveexample{The following code shows the constructor for different @ref
8323  value_t values,basic_json__value_t}
8324 
8325  @sa @ref clear() -- restores the postcondition of this constructor
8326 
8327  @since version 1.0.0
8328  */
8329  basic_json(const value_t v)
8330  : m_type(v), m_value(v)
8331  {
8332  assert_invariant();
8333  }
8335  /*!
8336  @brief create a null object
8337 
8338  Create a `null` JSON value. It either takes a null pointer as parameter
8339  (explicitly creating `null`) or no parameter (implicitly creating `null`).
8340  The passed null pointer itself is not read -- it is only used to choose
8341  the right constructor.
8342 
8343  @complexity Constant.
8344 
8345  @exceptionsafety No-throw guarantee: this constructor never throws
8346  exceptions.
8347 
8348  @liveexample{The following code shows the constructor with and without a
8349  null pointer parameter.,basic_json__nullptr_t}
8350 
8351  @since version 1.0.0
8352  */
8353  basic_json(std::nullptr_t = nullptr) noexcept
8354  : basic_json(value_t::null)
8355  {
8356  assert_invariant();
8357  }
8359  /*!
8360  @brief create a JSON value
8361 
8362  This is a "catch all" constructor for all compatible JSON types; that is,
8363  types for which a `to_json()` method exists. The constructor forwards the
8364  parameter @a val to that method (to `json_serializer<U>::to_json` method
8365  with `U = uncvref_t<CompatibleType>`, to be exact).
8366 
8367  Template type @a CompatibleType includes, but is not limited to, the
8368  following types:
8369  - **arrays**: @ref array_t and all kinds of compatible containers such as
8370  `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
8371  `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
8372  `std::multiset`, and `std::unordered_multiset` with a `value_type` from
8373  which a @ref basic_json value can be constructed.
8374  - **objects**: @ref object_t and all kinds of compatible associative
8375  containers such as `std::map`, `std::unordered_map`, `std::multimap`,
8376  and `std::unordered_multimap` with a `key_type` compatible to
8377  @ref string_t and a `value_type` from which a @ref basic_json value can
8378  be constructed.
8379  - **strings**: @ref string_t, string literals, and all compatible string
8380  containers can be used.
8381  - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
8382  @ref number_float_t, and all convertible number types such as `int`,
8383  `size_t`, `int64_t`, `float` or `double` can be used.
8384  - **boolean**: @ref boolean_t / `bool` can be used.
8385 
8386  See the examples below.
8387 
8388  @tparam CompatibleType a type such that:
8389  - @a CompatibleType is not derived from `std::istream`,
8390  - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
8391  constructors),
8392  - @a CompatibleType is not a @ref basic_json nested type (e.g.,
8393  @ref json_pointer, @ref iterator, etc ...)
8394  - @ref @ref json_serializer<U> has a
8395  `to_json(basic_json_t&, CompatibleType&&)` method
8396 
8397  @tparam U = `uncvref_t<CompatibleType>`
8398 
8399  @param[in] val the value to be forwarded to the respective constructor
8400 
8401  @complexity Usually linear in the size of the passed @a val, also
8402  depending on the implementation of the called `to_json()`
8403  method.
8404 
8405  @exceptionsafety Depends on the called constructor. For types directly
8406  supported by the library (i.e., all types for which no `to_json()` function
8407  was provided), strong guarantee holds: if an exception is thrown, there are
8408  no changes to any JSON value.
8409 
8410  @liveexample{The following code shows the constructor with several
8411  compatible types.,basic_json__CompatibleType}
8412 
8413  @since version 2.1.0
8414  */
8415  template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>,
8416  detail::enable_if_t<not std::is_base_of<std::istream, U>::value and
8417  not std::is_same<U, basic_json_t>::value and
8418  not detail::is_basic_json_nested_type<
8419  basic_json_t, U>::value and
8420  detail::has_to_json<basic_json, U>::value,
8421  int> = 0>
8422  basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json(
8423  std::declval<basic_json_t&>(), std::forward<CompatibleType>(val))))
8424  {
8425  JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
8426  assert_invariant();
8427  }
8428 
8429  /*!
8430  @brief create a container (array or object) from an initializer list
8431 
8432  Creates a JSON value of type array or object from the passed initializer
8433  list @a init. In case @a type_deduction is `true` (default), the type of
8434  the JSON value to be created is deducted from the initializer list @a init
8435  according to the following rules:
8436 
8437  1. If the list is empty, an empty JSON object value `{}` is created.
8438  2. If the list consists of pairs whose first element is a string, a JSON
8439  object value is created where the first elements of the pairs are
8440  treated as keys and the second elements are as values.
8441  3. In all other cases, an array is created.
8442 
8443  The rules aim to create the best fit between a C++ initializer list and
8444  JSON values. The rationale is as follows:
8445 
8446  1. The empty initializer list is written as `{}` which is exactly an empty
8447  JSON object.
8448  2. C++ has no way of describing mapped types other than to list a list of
8449  pairs. As JSON requires that keys must be of type string, rule 2 is the
8450  weakest constraint one can pose on initializer lists to interpret them
8451  as an object.
8452  3. In all other cases, the initializer list could not be interpreted as
8453  JSON object type, so interpreting it as JSON array type is safe.
8454 
8455  With the rules described above, the following JSON values cannot be
8456  expressed by an initializer list:
8457 
8458  - the empty array (`[]`): use @ref array(initializer_list_t)
8459  with an empty initializer list in this case
8460  - arrays whose elements satisfy rule 2: use @ref
8461  array(initializer_list_t) with the same initializer list
8462  in this case
8463 
8464  @note When used without parentheses around an empty initializer list, @ref
8465  basic_json() is called instead of this function, yielding the JSON null
8466  value.
8467 
8468  @param[in] init initializer list with JSON values
8469 
8470  @param[in] type_deduction internal parameter; when set to `true`, the type
8471  of the JSON value is deducted from the initializer list @a init; when set
8472  to `false`, the type provided via @a manual_type is forced. This mode is
8473  used by the functions @ref array(initializer_list_t) and
8474  @ref object(initializer_list_t).
8475 
8476  @param[in] manual_type internal parameter; when @a type_deduction is set
8477  to `false`, the created JSON value will use the provided type (only @ref
8478  value_t::array and @ref value_t::object are valid); when @a type_deduction
8479  is set to `true`, this parameter has no effect
8480 
8481  @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
8482  `value_t::object`, but @a init contains an element which is not a pair
8483  whose first element is a string. In this case, the constructor could not
8484  create an object. If @a type_deduction would have be `true`, an array
8485  would have been created. See @ref object(initializer_list_t)
8486  for an example.
8487 
8488  @complexity Linear in the size of the initializer list @a init.
8489 
8490  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8491  changes to any JSON value.
8492 
8493  @liveexample{The example below shows how JSON values are created from
8494  initializer lists.,basic_json__list_init_t}
8495 
8496  @sa @ref array(initializer_list_t) -- create a JSON array
8497  value from an initializer list
8498  @sa @ref object(initializer_list_t) -- create a JSON object
8499  value from an initializer list
8500 
8501  @since version 1.0.0
8502  */
8503  basic_json(initializer_list_t init,
8504  bool type_deduction = true,
8505  value_t manual_type = value_t::array)
8506  {
8507  // check if each element is an array with two elements whose first
8508  // element is a string
8509  bool is_an_object = std::all_of(init.begin(), init.end(),
8510  [](const detail::json_ref<basic_json>& element_ref)
8511  {
8512  return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string());
8513  });
8514 
8515  // adjust type if type deduction is not wanted
8516  if (not type_deduction)
8517  {
8518  // if array is wanted, do not create an object though possible
8519  if (manual_type == value_t::array)
8520  {
8521  is_an_object = false;
8522  }
8523 
8524  // if object is wanted but impossible, throw an exception
8525  if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object))
8526  {
8527  JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
8528  }
8529  }
8530 
8531  if (is_an_object)
8532  {
8533  // the initializer list is a list of pairs -> create object
8534  m_type = value_t::object;
8535  m_value = value_t::object;
8536 
8537  std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
8538  {
8539  auto element = element_ref.moved_or_copied();
8540  m_value.object->emplace(
8541  std::move(*((*element.m_value.array)[0].m_value.string)),
8542  std::move((*element.m_value.array)[1]));
8543  });
8544  }
8545  else
8546  {
8547  // the initializer list describes an array -> create array
8548  m_type = value_t::array;
8549  m_value.array = create<array_t>(init.begin(), init.end());
8550  }
8551 
8552  assert_invariant();
8553  }
8554 
8555  /*!
8556  @brief explicitly create an array from an initializer list
8557 
8558  Creates a JSON array value from a given initializer list. That is, given a
8559  list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
8560  initializer list is empty, the empty array `[]` is created.
8561 
8562  @note This function is only needed to express two edge cases that cannot
8563  be realized with the initializer list constructor (@ref
8564  basic_json(initializer_list_t, bool, value_t)). These cases
8565  are:
8566  1. creating an array whose elements are all pairs whose first element is a
8567  string -- in this case, the initializer list constructor would create an
8568  object, taking the first elements as keys
8569  2. creating an empty array -- passing the empty initializer list to the
8570  initializer list constructor yields an empty object
8571 
8572  @param[in] init initializer list with JSON values to create an array from
8573  (optional)
8574 
8575  @return JSON array value
8576 
8577  @complexity Linear in the size of @a init.
8578 
8579  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8580  changes to any JSON value.
8581 
8582  @liveexample{The following code shows an example for the `array`
8583  function.,array}
8584 
8585  @sa @ref basic_json(initializer_list_t, bool, value_t) --
8586  create a JSON value from an initializer list
8587  @sa @ref object(initializer_list_t) -- create a JSON object
8588  value from an initializer list
8589 
8590  @since version 1.0.0
8591  */
8592  static basic_json array(initializer_list_t init = {})
8593  {
8594  return basic_json(init, false, value_t::array);
8595  }
8596 
8597  /*!
8598  @brief explicitly create an object from an initializer list
8599 
8600  Creates a JSON object value from a given initializer list. The initializer
8601  lists elements must be pairs, and their first elements must be strings. If
8602  the initializer list is empty, the empty object `{}` is created.
8603 
8604  @note This function is only added for symmetry reasons. In contrast to the
8605  related function @ref array(initializer_list_t), there are
8606  no cases which can only be expressed by this function. That is, any
8607  initializer list @a init can also be passed to the initializer list
8608  constructor @ref basic_json(initializer_list_t, bool, value_t).
8609 
8610  @param[in] init initializer list to create an object from (optional)
8611 
8612  @return JSON object value
8613 
8614  @throw type_error.301 if @a init is not a list of pairs whose first
8615  elements are strings. In this case, no object can be created. When such a
8616  value is passed to @ref basic_json(initializer_list_t, bool, value_t),
8617  an array would have been created from the passed initializer list @a init.
8618  See example below.
8619 
8620  @complexity Linear in the size of @a init.
8621 
8622  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8623  changes to any JSON value.
8624 
8625  @liveexample{The following code shows an example for the `object`
8626  function.,object}
8627 
8628  @sa @ref basic_json(initializer_list_t, bool, value_t) --
8629  create a JSON value from an initializer list
8630  @sa @ref array(initializer_list_t) -- create a JSON array
8631  value from an initializer list
8632 
8633  @since version 1.0.0
8634  */
8635  static basic_json object(initializer_list_t init = {})
8636  {
8637  return basic_json(init, false, value_t::object);
8638  }
8639 
8640  /*!
8641  @brief construct an array with count copies of given value
8642 
8643  Constructs a JSON array value by creating @a cnt copies of a passed value.
8644  In case @a cnt is `0`, an empty array is created.
8645 
8646  @param[in] cnt the number of JSON copies of @a val to create
8647  @param[in] val the JSON value to copy
8648 
8649  @post `std::distance(begin(),end()) == cnt` holds.
8650 
8651  @complexity Linear in @a cnt.
8652 
8653  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8654  changes to any JSON value.
8655 
8656  @liveexample{The following code shows examples for the @ref
8657  basic_json(size_type\, const basic_json&)
8658  constructor.,basic_json__size_type_basic_json}
8659 
8660  @since version 1.0.0
8661  */
8662  basic_json(size_type cnt, const basic_json& val)
8663  : m_type(value_t::array)
8664  {
8665  m_value.array = create<array_t>(cnt, val);
8666  assert_invariant();
8667  }
8668 
8669  /*!
8670  @brief construct a JSON container given an iterator range
8671 
8672  Constructs the JSON value with the contents of the range `[first, last)`.
8673  The semantics depends on the different types a JSON value can have:
8674  - In case of a null type, invalid_iterator.206 is thrown.
8675  - In case of other primitive types (number, boolean, or string), @a first
8676  must be `begin()` and @a last must be `end()`. In this case, the value is
8677  copied. Otherwise, invalid_iterator.204 is thrown.
8678  - In case of structured types (array, object), the constructor behaves as
8679  similar versions for `std::vector` or `std::map`; that is, a JSON array
8680  or object is constructed from the values in the range.
8681 
8682  @tparam InputIT an input iterator type (@ref iterator or @ref
8683  const_iterator)
8684 
8685  @param[in] first begin of the range to copy from (included)
8686  @param[in] last end of the range to copy from (excluded)
8687 
8688  @pre Iterators @a first and @a last must be initialized. **This
8689  precondition is enforced with an assertion (see warning).** If
8690  assertions are switched off, a violation of this precondition yields
8691  undefined behavior.
8692 
8693  @pre Range `[first, last)` is valid. Usually, this precondition cannot be
8694  checked efficiently. Only certain edge cases are detected; see the
8695  description of the exceptions below. A violation of this precondition
8696  yields undefined behavior.
8697 
8698  @warning A precondition is enforced with a runtime assertion that will
8699  result in calling `std::abort` if this precondition is not met.
8700  Assertions can be disabled by defining `NDEBUG` at compile time.
8701  See http://en.cppreference.com/w/cpp/error/assert for more
8702  information.
8703 
8704  @throw invalid_iterator.201 if iterators @a first and @a last are not
8705  compatible (i.e., do not belong to the same JSON value). In this case,
8706  the range `[first, last)` is undefined.
8707  @throw invalid_iterator.204 if iterators @a first and @a last belong to a
8708  primitive type (number, boolean, or string), but @a first does not point
8709  to the first element any more. In this case, the range `[first, last)` is
8710  undefined. See example code below.
8711  @throw invalid_iterator.206 if iterators @a first and @a last belong to a
8712  null value. In this case, the range `[first, last)` is undefined.
8713 
8714  @complexity Linear in distance between @a first and @a last.
8715 
8716  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8717  changes to any JSON value.
8718 
8719  @liveexample{The example below shows several ways to create JSON values by
8720  specifying a subrange with iterators.,basic_json__InputIt_InputIt}
8721 
8722  @since version 1.0.0
8723  */
8724  template<class InputIT, typename std::enable_if<
8725  std::is_same<InputIT, typename basic_json_t::iterator>::value or
8726  std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
8727  basic_json(InputIT first, InputIT last)
8728  {
8729  assert(first.m_object != nullptr);
8730  assert(last.m_object != nullptr);
8731 
8732  // make sure iterator fits the current value
8733  if (JSON_UNLIKELY(first.m_object != last.m_object))
8734  {
8735  JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
8736  }
8737 
8738  // copy type from first iterator
8739  m_type = first.m_object->m_type;
8740 
8741  // check if iterator range is complete for primitive values
8742  switch (m_type)
8743  {
8744  case value_t::boolean:
8745  case value_t::number_float:
8746  case value_t::number_integer:
8747  case value_t::number_unsigned:
8748  case value_t::string:
8749  {
8750  if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
8751  or not last.m_it.primitive_iterator.is_end()))
8752  {
8753  JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
8754  }
8755  break;
8756  }
8757 
8758  default:
8759  break;
8760  }
8761 
8762  switch (m_type)
8763  {
8764  case value_t::number_integer:
8765  {
8766  m_value.number_integer = first.m_object->m_value.number_integer;
8767  break;
8768  }
8769 
8770  case value_t::number_unsigned:
8771  {
8772  m_value.number_unsigned = first.m_object->m_value.number_unsigned;
8773  break;
8774  }
8775 
8776  case value_t::number_float:
8777  {
8778  m_value.number_float = first.m_object->m_value.number_float;
8779  break;
8780  }
8781 
8782  case value_t::boolean:
8783  {
8784  m_value.boolean = first.m_object->m_value.boolean;
8785  break;
8786  }
8787 
8788  case value_t::string:
8789  {
8790  m_value = *first.m_object->m_value.string;
8791  break;
8792  }
8793 
8794  case value_t::object:
8795  {
8796  m_value.object = create<object_t>(first.m_it.object_iterator,
8797  last.m_it.object_iterator);
8798  break;
8799  }
8800 
8801  case value_t::array:
8802  {
8803  m_value.array = create<array_t>(first.m_it.array_iterator,
8804  last.m_it.array_iterator);
8805  break;
8806  }
8807 
8808  default:
8809  JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
8810  std::string(first.m_object->type_name())));
8811  }
8812 
8813  assert_invariant();
8814  }
8815 
8816 
8817  ///////////////////////////////////////
8818  // other constructors and destructor //
8819  ///////////////////////////////////////
8820 
8821  /// @private
8822  basic_json(const detail::json_ref<basic_json>& ref)
8823  : basic_json(ref.moved_or_copied())
8824  {}
8825 
8826  /*!
8827  @brief copy constructor
8828 
8829  Creates a copy of a given JSON value.
8830 
8831  @param[in] other the JSON value to copy
8832 
8833  @post `*this == other`
8834 
8835  @complexity Linear in the size of @a other.
8836 
8837  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8838  changes to any JSON value.
8839 
8840  @requirement This function helps `basic_json` satisfying the
8841  [Container](http://en.cppreference.com/w/cpp/concept/Container)
8842  requirements:
8843  - The complexity is linear.
8844  - As postcondition, it holds: `other == basic_json(other)`.
8845 
8846  @liveexample{The following code shows an example for the copy
8847  constructor.,basic_json__basic_json}
8848 
8849  @since version 1.0.0
8850  */
8851  basic_json(const basic_json& other)
8852  : m_type(other.m_type)
8853  {
8854  // check of passed value is valid
8855  other.assert_invariant();
8857  switch (m_type)
8858  {
8859  case value_t::object:
8860  {
8861  m_value = *other.m_value.object;
8862  break;
8863  }
8864 
8865  case value_t::array:
8866  {
8867  m_value = *other.m_value.array;
8868  break;
8869  }
8870 
8871  case value_t::string:
8872  {
8873  m_value = *other.m_value.string;
8874  break;
8875  }
8876 
8877  case value_t::boolean:
8878  {
8879  m_value = other.m_value.boolean;
8880  break;
8881  }
8882 
8883  case value_t::number_integer:
8884  {
8885  m_value = other.m_value.number_integer;
8886  break;
8887  }
8888 
8889  case value_t::number_unsigned:
8890  {
8891  m_value = other.m_value.number_unsigned;
8892  break;
8893  }
8894 
8895  case value_t::number_float:
8896  {
8897  m_value = other.m_value.number_float;
8898  break;
8899  }
8900 
8901  default:
8902  break;
8903  }
8904 
8905  assert_invariant();
8906  }
8907 
8908  /*!
8909  @brief move constructor
8910 
8911  Move constructor. Constructs a JSON value with the contents of the given
8912  value @a other using move semantics. It "steals" the resources from @a
8913  other and leaves it as JSON null value.
8914 
8915  @param[in,out] other value to move to this object
8916 
8917  @post `*this` has the same value as @a other before the call.
8918  @post @a other is a JSON null value.
8919 
8920  @complexity Constant.
8921 
8922  @exceptionsafety No-throw guarantee: this constructor never throws
8923  exceptions.
8924 
8925  @requirement This function helps `basic_json` satisfying the
8926  [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible)
8927  requirements.
8928 
8929  @liveexample{The code below shows the move constructor explicitly called
8930  via std::move.,basic_json__moveconstructor}
8931 
8932  @since version 1.0.0
8933  */
8934  basic_json(basic_json&& other) noexcept
8935  : m_type(std::move(other.m_type)),
8936  m_value(std::move(other.m_value))
8937  {
8938  // check that passed value is valid
8939  other.assert_invariant();
8940 
8941  // invalidate payload
8942  other.m_type = value_t::null;
8943  other.m_value = {};
8944 
8945  assert_invariant();
8946  }
8947 
8948  /*!
8949  @brief copy assignment
8950 
8951  Copy assignment operator. Copies a JSON value via the "copy and swap"
8952  strategy: It is expressed in terms of the copy constructor, destructor,
8953  and the `swap()` member function.
8954 
8955  @param[in] other value to copy from
8956 
8957  @complexity Linear.
8958 
8959  @requirement This function helps `basic_json` satisfying the
8960  [Container](http://en.cppreference.com/w/cpp/concept/Container)
8961  requirements:
8962  - The complexity is linear.
8963 
8964  @liveexample{The code below shows and example for the copy assignment. It
8965  creates a copy of value `a` which is then swapped with `b`. Finally\, the
8966  copy of `a` (which is the null value after the swap) is
8967  destroyed.,basic_json__copyassignment}
8968 
8969  @since version 1.0.0
8970  */
8971  reference& operator=(basic_json other) noexcept (
8972  std::is_nothrow_move_constructible<value_t>::value and
8973  std::is_nothrow_move_assignable<value_t>::value and
8974  std::is_nothrow_move_constructible<json_value>::value and
8975  std::is_nothrow_move_assignable<json_value>::value
8976  )
8977  {
8978  // check that passed value is valid
8979  other.assert_invariant();
8980 
8981  using std::swap;
8982  swap(m_type, other.m_type);
8983  swap(m_value, other.m_value);
8984 
8985  assert_invariant();
8986  return *this;
8987  }
8988 
8989  /*!
8990  @brief destructor
8991 
8992  Destroys the JSON value and frees all allocated memory.
8993 
8994  @complexity Linear.
8995 
8996  @requirement This function helps `basic_json` satisfying the
8997  [Container](http://en.cppreference.com/w/cpp/concept/Container)
8998  requirements:
8999  - The complexity is linear.
9000  - All stored elements are destroyed and all memory is freed.
9001 
9002  @since version 1.0.0
9003  */
9004  ~basic_json()
9005  {
9006  assert_invariant();
9007  m_value.destroy(m_type);
9008  }
9010  /// @}
9011 
9012  public:
9013  ///////////////////////
9014  // object inspection //
9015  ///////////////////////
9016 
9017  /// @name object inspection
9018  /// Functions to inspect the type of a JSON value.
9019  /// @{
9020 
9021  /*!
9022  @brief serialization
9023 
9024  Serialization function for JSON values. The function tries to mimic
9025  Python's `json.dumps()` function, and currently supports its @a indent
9026  and @a ensure_ascii parameters.
9027 
9028  @param[in] indent If indent is nonnegative, then array elements and object
9029  members will be pretty-printed with that indent level. An indent level of
9030  `0` will only insert newlines. `-1` (the default) selects the most compact
9031  representation.
9032  @param[in] indent_char The character to use for indentation if @a indent is
9033  greater than `0`. The default is ` ` (space).
9034  @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
9035  in the output are escaped with `\uXXXX` sequences, and the result consists
9036  of ASCII characters only.
9037 
9038  @return string containing the serialization of the JSON value
9039 
9040  @throw type_error.316 if a string stored inside the JSON value is not
9041  UTF-8 encoded
9042 
9043  @complexity Linear.
9044 
9045  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
9046  changes in the JSON value.
9047 
9048  @liveexample{The following example shows the effect of different @a indent\,
9049  @a indent_char\, and @a ensure_ascii parameters to the result of the
9050  serialization.,dump}
9051 
9052  @see https://docs.python.org/2/library/json.html#json.dump
9053 
9054  @since version 1.0.0; indentation character @a indent_char, option
9055  @a ensure_ascii and exceptions added in version 3.0.0
9056  */
9057  string_t dump(const int indent = -1, const char indent_char = ' ',
9058  const bool ensure_ascii = false) const
9059  {
9060  string_t result;
9061  serializer s(detail::output_adapter<char>(result), indent_char);
9063  if (indent >= 0)
9064  {
9065  s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
9066  }
9067  else
9068  {
9069  s.dump(*this, false, ensure_ascii, 0);
9070  }
9071 
9072  return result;
9073  }
9074 
9075  /*!
9076  @brief return the type of the JSON value (explicit)
9077 
9078  Return the type of the JSON value as a value from the @ref value_t
9079  enumeration.
9080 
9081  @return the type of the JSON value
9082  Value type | return value
9083  ------------------------- | -------------------------
9084  null | value_t::null
9085  boolean | value_t::boolean
9086  string | value_t::string
9087  number (integer) | value_t::number_integer
9088  number (unsigned integer) | value_t::number_unsigned
9089  number (floating-point) | value_t::number_float
9090  object | value_t::object
9091  array | value_t::array
9092  discarded | value_t::discarded
9093 
9094  @complexity Constant.
9095 
9096  @exceptionsafety No-throw guarantee: this member function never throws
9097  exceptions.
9098 
9099  @liveexample{The following code exemplifies `type()` for all JSON
9100  types.,type}
9101 
9102  @sa @ref operator value_t() -- return the type of the JSON value (implicit)
9103  @sa @ref type_name() -- return the type as string
9104 
9105  @since version 1.0.0
9106  */
9107  constexpr value_t type() const noexcept
9108  {
9109  return m_type;
9110  }
9111 
9112  /*!
9113  @brief return whether type is primitive
9114 
9115  This function returns true if and only if the JSON type is primitive
9116  (string, number, boolean, or null).
9117 
9118  @return `true` if type is primitive (string, number, boolean, or null),
9119  `false` otherwise.
9120 
9121  @complexity Constant.
9122 
9123  @exceptionsafety No-throw guarantee: this member function never throws
9124  exceptions.
9125 
9126  @liveexample{The following code exemplifies `is_primitive()` for all JSON
9127  types.,is_primitive}
9128 
9129  @sa @ref is_structured() -- returns whether JSON value is structured
9130  @sa @ref is_null() -- returns whether JSON value is `null`
9131  @sa @ref is_string() -- returns whether JSON value is a string
9132  @sa @ref is_boolean() -- returns whether JSON value is a boolean
9133  @sa @ref is_number() -- returns whether JSON value is a number
9134 
9135  @since version 1.0.0
9136  */
9137  constexpr bool is_primitive() const noexcept
9138  {
9139  return is_null() or is_string() or is_boolean() or is_number();
9140  }
9141 
9142  /*!
9143  @brief return whether type is structured
9144 
9145  This function returns true if and only if the JSON type is structured
9146  (array or object).
9147 
9148  @return `true` if type is structured (array or object), `false` otherwise.
9149 
9150  @complexity Constant.
9151 
9152  @exceptionsafety No-throw guarantee: this member function never throws
9153  exceptions.
9154 
9155  @liveexample{The following code exemplifies `is_structured()` for all JSON
9156  types.,is_structured}
9157 
9158  @sa @ref is_primitive() -- returns whether value is primitive
9159  @sa @ref is_array() -- returns whether value is an array
9160  @sa @ref is_object() -- returns whether value is an object
9161 
9162  @since version 1.0.0
9163  */
9164  constexpr bool is_structured() const noexcept
9165  {
9166  return is_array() or is_object();
9167  }
9168 
9169  /*!
9170  @brief return whether value is null
9171 
9172  This function returns true if and only if the JSON value is null.
9173 
9174  @return `true` if type is null, `false` otherwise.
9175 
9176  @complexity Constant.
9177 
9178  @exceptionsafety No-throw guarantee: this member function never throws
9179  exceptions.
9180 
9181  @liveexample{The following code exemplifies `is_null()` for all JSON
9182  types.,is_null}
9183 
9184  @since version 1.0.0
9185  */
9186  constexpr bool is_null() const noexcept
9187  {
9188  return (m_type == value_t::null);
9189  }
9190 
9191  /*!
9192  @brief return whether value is a boolean
9193 
9194  This function returns true if and only if the JSON value is a boolean.
9195 
9196  @return `true` if type is boolean, `false` otherwise.
9197 
9198  @complexity Constant.
9199 
9200  @exceptionsafety No-throw guarantee: this member function never throws
9201  exceptions.
9202 
9203  @liveexample{The following code exemplifies `is_boolean()` for all JSON
9204  types.,is_boolean}
9205 
9206  @since version 1.0.0
9207  */
9208  constexpr bool is_boolean() const noexcept
9209  {
9210  return (m_type == value_t::boolean);
9211  }
9212 
9213  /*!
9214  @brief return whether value is a number
9215 
9216  This function returns true if and only if the JSON value is a number. This
9217  includes both integer (signed and unsigned) and floating-point values.
9218 
9219  @return `true` if type is number (regardless whether integer, unsigned
9220  integer or floating-type), `false` otherwise.
9221 
9222  @complexity Constant.
9223 
9224  @exceptionsafety No-throw guarantee: this member function never throws
9225  exceptions.
9226 
9227  @liveexample{The following code exemplifies `is_number()` for all JSON
9228  types.,is_number}
9229 
9230  @sa @ref is_number_integer() -- check if value is an integer or unsigned
9231  integer number
9232  @sa @ref is_number_unsigned() -- check if value is an unsigned integer
9233  number
9234  @sa @ref is_number_float() -- check if value is a floating-point number
9235 
9236  @since version 1.0.0
9237  */
9238  constexpr bool is_number() const noexcept
9239  {
9240  return is_number_integer() or is_number_float();
9241  }
9242 
9243  /*!
9244  @brief return whether value is an integer number
9245 
9246  This function returns true if and only if the JSON value is a signed or
9247  unsigned integer number. This excludes floating-point values.
9248 
9249  @return `true` if type is an integer or unsigned integer number, `false`
9250  otherwise.
9251 
9252  @complexity Constant.
9253 
9254  @exceptionsafety No-throw guarantee: this member function never throws
9255  exceptions.
9256 
9257  @liveexample{The following code exemplifies `is_number_integer()` for all
9258  JSON types.,is_number_integer}
9259 
9260  @sa @ref is_number() -- check if value is a number
9261  @sa @ref is_number_unsigned() -- check if value is an unsigned integer
9262  number
9263  @sa @ref is_number_float() -- check if value is a floating-point number
9264 
9265  @since version 1.0.0
9266  */
9267  constexpr bool is_number_integer() const noexcept
9268  {
9269  return (m_type == value_t::number_integer or m_type == value_t::number_unsigned);
9270  }
9271 
9272  /*!
9273  @brief return whether value is an unsigned integer number
9274 
9275  This function returns true if and only if the JSON value is an unsigned
9276  integer number. This excludes floating-point and signed integer values.
9277 
9278  @return `true` if type is an unsigned integer number, `false` otherwise.
9279 
9280  @complexity Constant.
9281 
9282  @exceptionsafety No-throw guarantee: this member function never throws
9283  exceptions.
9284 
9285  @liveexample{The following code exemplifies `is_number_unsigned()` for all
9286  JSON types.,is_number_unsigned}
9287 
9288  @sa @ref is_number() -- check if value is a number
9289  @sa @ref is_number_integer() -- check if value is an integer or unsigned
9290  integer number
9291  @sa @ref is_number_float() -- check if value is a floating-point number
9292 
9293  @since version 2.0.0
9294  */
9295  constexpr bool is_number_unsigned() const noexcept
9296  {
9297  return (m_type == value_t::number_unsigned);
9298  }
9299 
9300  /*!
9301  @brief return whether value is a floating-point number
9302 
9303  This function returns true if and only if the JSON value is a
9304  floating-point number. This excludes signed and unsigned integer values.
9305 
9306  @return `true` if type is a floating-point number, `false` otherwise.
9307 
9308  @complexity Constant.
9309 
9310  @exceptionsafety No-throw guarantee: this member function never throws
9311  exceptions.
9312 
9313  @liveexample{The following code exemplifies `is_number_float()` for all
9314  JSON types.,is_number_float}
9315 
9316  @sa @ref is_number() -- check if value is number
9317  @sa @ref is_number_integer() -- check if value is an integer number
9318  @sa @ref is_number_unsigned() -- check if value is an unsigned integer
9319  number
9320 
9321  @since version 1.0.0
9322  */
9323  constexpr bool is_number_float() const noexcept
9324  {
9325  return (m_type == value_t::number_float);
9326  }
9327 
9328  /*!
9329  @brief return whether value is an object
9330 
9331  This function returns true if and only if the JSON value is an object.
9332 
9333  @return `true` if type is object, `false` otherwise.
9334 
9335  @complexity Constant.
9336 
9337  @exceptionsafety No-throw guarantee: this member function never throws
9338  exceptions.
9339 
9340  @liveexample{The following code exemplifies `is_object()` for all JSON
9341  types.,is_object}
9342 
9343  @since version 1.0.0
9344  */
9345  constexpr bool is_object() const noexcept
9346  {
9347  return (m_type == value_t::object);
9348  }
9349 
9350  /*!
9351  @brief return whether value is an array
9352 
9353  This function returns true if and only if the JSON value is an array.
9354 
9355  @return `true` if type is array, `false` otherwise.
9356 
9357  @complexity Constant.
9358 
9359  @exceptionsafety No-throw guarantee: this member function never throws
9360  exceptions.
9361 
9362  @liveexample{The following code exemplifies `is_array()` for all JSON
9363  types.,is_array}
9364 
9365  @since version 1.0.0
9366  */
9367  constexpr bool is_array() const noexcept
9368  {
9369  return (m_type == value_t::array);
9370  }
9371 
9372  /*!
9373  @brief return whether value is a string
9374 
9375  This function returns true if and only if the JSON value is a string.
9376 
9377  @return `true` if type is string, `false` otherwise.
9378 
9379  @complexity Constant.
9380 
9381  @exceptionsafety No-throw guarantee: this member function never throws
9382  exceptions.
9383 
9384  @liveexample{The following code exemplifies `is_string()` for all JSON
9385  types.,is_string}
9386 
9387  @since version 1.0.0
9388  */
9389  constexpr bool is_string() const noexcept
9390  {
9391  return (m_type == value_t::string);
9392  }
9393 
9394  /*!
9395  @brief return whether value is discarded
9396 
9397  This function returns true if and only if the JSON value was discarded
9398  during parsing with a callback function (see @ref parser_callback_t).
9399 
9400  @note This function will always be `false` for JSON values after parsing.
9401  That is, discarded values can only occur during parsing, but will be
9402  removed when inside a structured value or replaced by null in other cases.
9403 
9404  @return `true` if type is discarded, `false` otherwise.
9405 
9406  @complexity Constant.
9407 
9408  @exceptionsafety No-throw guarantee: this member function never throws
9409  exceptions.
9410 
9411  @liveexample{The following code exemplifies `is_discarded()` for all JSON
9412  types.,is_discarded}
9413 
9414  @since version 1.0.0
9415  */
9416  constexpr bool is_discarded() const noexcept
9417  {
9418  return (m_type == value_t::discarded);
9419  }
9420 
9421  /*!
9422  @brief return the type of the JSON value (implicit)
9423 
9424  Implicitly return the type of the JSON value as a value from the @ref
9425  value_t enumeration.
9426 
9427  @return the type of the JSON value
9428 
9429  @complexity Constant.
9430 
9431  @exceptionsafety No-throw guarantee: this member function never throws
9432  exceptions.
9433 
9434  @liveexample{The following code exemplifies the @ref value_t operator for
9435  all JSON types.,operator__value_t}
9436 
9437  @sa @ref type() -- return the type of the JSON value (explicit)
9438  @sa @ref type_name() -- return the type as string
9439 
9440  @since version 1.0.0
9441  */
9442  constexpr operator value_t() const noexcept
9443  {
9444  return m_type;
9445  }
9446 
9447  /// @}
9448 
9449  private:
9450  //////////////////
9451  // value access //
9452  //////////////////
9453 
9454  /// get a boolean (explicit)
9455  boolean_t get_impl(boolean_t* /*unused*/) const
9456  {
9457  if (JSON_LIKELY(is_boolean()))
9458  {
9459  return m_value.boolean;
9460  }
9461 
9462  JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
9463  }
9464 
9465  /// get a pointer to the value (object)
9466  object_t* get_impl_ptr(object_t* /*unused*/) noexcept
9467  {
9468  return is_object() ? m_value.object : nullptr;
9469  }
9470 
9471  /// get a pointer to the value (object)
9472  constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
9473  {
9474  return is_object() ? m_value.object : nullptr;
9475  }
9476 
9477  /// get a pointer to the value (array)
9478  array_t* get_impl_ptr(array_t* /*unused*/) noexcept
9479  {
9480  return is_array() ? m_value.array : nullptr;
9481  }
9482 
9483  /// get a pointer to the value (array)
9484  constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
9485  {
9486  return is_array() ? m_value.array : nullptr;
9487  }
9488 
9489  /// get a pointer to the value (string)
9490  string_t* get_impl_ptr(string_t* /*unused*/) noexcept
9491  {
9492  return is_string() ? m_value.string : nullptr;
9493  }
9494 
9495  /// get a pointer to the value (string)
9496  constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
9497  {
9498  return is_string() ? m_value.string : nullptr;
9499  }
9500 
9501  /// get a pointer to the value (boolean)
9502  boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
9503  {
9504  return is_boolean() ? &m_value.boolean : nullptr;
9505  }
9506 
9507  /// get a pointer to the value (boolean)
9508  constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
9509  {
9510  return is_boolean() ? &m_value.boolean : nullptr;
9511  }
9512 
9513  /// get a pointer to the value (integer number)
9514  number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
9515  {
9516  return is_number_integer() ? &m_value.number_integer : nullptr;
9517  }
9518 
9519  /// get a pointer to the value (integer number)
9520  constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
9521  {
9522  return is_number_integer() ? &m_value.number_integer : nullptr;
9523  }
9524 
9525  /// get a pointer to the value (unsigned number)
9526  number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
9527  {
9528  return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
9529  }
9530 
9531  /// get a pointer to the value (unsigned number)
9532  constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
9533  {
9534  return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
9535  }
9536 
9537  /// get a pointer to the value (floating-point number)
9538  number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
9539  {
9540  return is_number_float() ? &m_value.number_float : nullptr;
9541  }
9542 
9543  /// get a pointer to the value (floating-point number)
9544  constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
9545  {
9546  return is_number_float() ? &m_value.number_float : nullptr;
9547  }
9548 
9549  /*!
9550  @brief helper function to implement get_ref()
9551 
9552  This function helps to implement get_ref() without code duplication for
9553  const and non-const overloads
9554 
9555  @tparam ThisType will be deduced as `basic_json` or `const basic_json`
9556 
9557  @throw type_error.303 if ReferenceType does not match underlying value
9558  type of the current JSON
9559  */
9560  template<typename ReferenceType, typename ThisType>
9561  static ReferenceType get_ref_impl(ThisType& obj)
9562  {
9563  // delegate the call to get_ptr<>()
9564  auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
9565 
9566  if (JSON_LIKELY(ptr != nullptr))
9567  {
9568  return *ptr;
9569  }
9570 
9571  JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
9572  }
9573 
9574  public:
9575  /// @name value access
9576  /// Direct access to the stored value of a JSON value.
9577  /// @{
9578 
9579  /*!
9580  @brief get special-case overload
9581 
9582  This overloads avoids a lot of template boilerplate, it can be seen as the
9583  identity method
9584 
9585  @tparam BasicJsonType == @ref basic_json
9586 
9587  @return a copy of *this
9588 
9589  @complexity Constant.
9590 
9591  @since version 2.1.0
9592  */
9593  template<typename BasicJsonType, detail::enable_if_t<
9594  std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
9595  int> = 0>
9596  basic_json get() const
9597  {
9598  return *this;
9599  }
9600 
9601  /*!
9602  @brief get a value (explicit)
9603 
9604  Explicit type conversion between the JSON value and a compatible value
9605  which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
9606  and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
9607  The value is converted by calling the @ref json_serializer<ValueType>
9608  `from_json()` method.
9609 
9610  The function is equivalent to executing
9611  @code {.cpp}
9612  ValueType ret;
9613  JSONSerializer<ValueType>::from_json(*this, ret);
9614  return ret;
9615  @endcode
9616 
9617  This overloads is chosen if:
9618  - @a ValueType is not @ref basic_json,
9619  - @ref json_serializer<ValueType> has a `from_json()` method of the form
9620  `void from_json(const basic_json&, ValueType&)`, and
9621  - @ref json_serializer<ValueType> does not have a `from_json()` method of
9622  the form `ValueType from_json(const basic_json&)`
9623 
9624  @tparam ValueTypeCV the provided value type
9625  @tparam ValueType the returned value type
9626 
9627  @return copy of the JSON value, converted to @a ValueType
9628 
9629  @throw what @ref json_serializer<ValueType> `from_json()` method throws
9630 
9631  @liveexample{The example below shows several conversions from JSON values
9632  to other types. There a few things to note: (1) Floating-point numbers can
9633  be converted to integers\, (2) A JSON array can be converted to a standard
9634  `std::vector<short>`\, (3) A JSON object can be converted to C++
9635  associative containers such as `std::unordered_map<std::string\,
9636  json>`.,get__ValueType_const}
9637 
9638  @since version 2.1.0
9639  */
9640  template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
9641  detail::enable_if_t <
9642  not std::is_same<basic_json_t, ValueType>::value and
9643  detail::has_from_json<basic_json_t, ValueType>::value and
9644  not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
9645  int> = 0>
9646  ValueType get() const noexcept(noexcept(
9647  JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
9648  {
9649  // we cannot static_assert on ValueTypeCV being non-const, because
9650  // there is support for get<const basic_json_t>(), which is why we
9651  // still need the uncvref
9652  static_assert(not std::is_reference<ValueTypeCV>::value,
9653  "get() cannot be used with reference types, you might want to use get_ref()");
9654  static_assert(std::is_default_constructible<ValueType>::value,
9655  "types must be DefaultConstructible when used with get()");
9656 
9657  ValueType ret;
9658  JSONSerializer<ValueType>::from_json(*this, ret);
9659  return ret;
9660  }
9661 
9662  /*!
9663  @brief get a value (explicit); special case
9664 
9665  Explicit type conversion between the JSON value and a compatible value
9666  which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
9667  and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
9668  The value is converted by calling the @ref json_serializer<ValueType>
9669  `from_json()` method.
9670 
9671  The function is equivalent to executing
9672  @code {.cpp}
9673  return JSONSerializer<ValueTypeCV>::from_json(*this);
9674  @endcode
9675 
9676  This overloads is chosen if:
9677  - @a ValueType is not @ref basic_json and
9678  - @ref json_serializer<ValueType> has a `from_json()` method of the form
9679  `ValueType from_json(const basic_json&)`
9680 
9681  @note If @ref json_serializer<ValueType> has both overloads of
9682  `from_json()`, this one is chosen.
9683 
9684  @tparam ValueTypeCV the provided value type
9685  @tparam ValueType the returned value type
9686 
9687  @return copy of the JSON value, converted to @a ValueType
9688 
9689  @throw what @ref json_serializer<ValueType> `from_json()` method throws
9690 
9691  @since version 2.1.0
9692  */
9693  template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
9694  detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
9695  detail::has_non_default_from_json<basic_json_t, ValueType>::value,
9696  int> = 0>
9697  ValueType get() const noexcept(noexcept(
9698  JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
9699  {
9700  static_assert(not std::is_reference<ValueTypeCV>::value,
9701  "get() cannot be used with reference types, you might want to use get_ref()");
9702  return JSONSerializer<ValueTypeCV>::from_json(*this);
9703  }
9704 
9705  /*!
9706  @brief get a pointer value (explicit)
9707 
9708  Explicit pointer access to the internally stored JSON value. No copies are
9709  made.
9710 
9711  @warning The pointer becomes invalid if the underlying JSON object
9712  changes.
9713 
9714  @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
9715  object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
9716  @ref number_unsigned_t, or @ref number_float_t.
9717 
9718  @return pointer to the internally stored JSON value if the requested
9719  pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
9720 
9721  @complexity Constant.
9722 
9723  @liveexample{The example below shows how pointers to internal values of a
9724  JSON value can be requested. Note that no type conversions are made and a
9725  `nullptr` is returned if the value and the requested pointer type does not
9726  match.,get__PointerType}
9727 
9728  @sa @ref get_ptr() for explicit pointer-member access
9729 
9730  @since version 1.0.0
9731  */
9732  template<typename PointerType, typename std::enable_if<
9733  std::is_pointer<PointerType>::value, int>::type = 0>
9734  PointerType get() noexcept
9735  {
9736  // delegate the call to get_ptr
9737  return get_ptr<PointerType>();
9738  }
9740  /*!
9741  @brief get a pointer value (explicit)
9742  @copydoc get()
9743  */
9744  template<typename PointerType, typename std::enable_if<
9745  std::is_pointer<PointerType>::value, int>::type = 0>
9746  constexpr const PointerType get() const noexcept
9747  {
9748  // delegate the call to get_ptr
9749  return get_ptr<PointerType>();
9750  }
9752  /*!
9753  @brief get a pointer value (implicit)
9754 
9755  Implicit pointer access to the internally stored JSON value. No copies are
9756  made.
9757 
9758  @warning Writing data to the pointee of the result yields an undefined
9759  state.
9760 
9761  @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
9762  object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
9763  @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
9764  assertion.
9765 
9766  @return pointer to the internally stored JSON value if the requested
9767  pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
9768 
9769  @complexity Constant.
9770 
9771  @liveexample{The example below shows how pointers to internal values of a
9772  JSON value can be requested. Note that no type conversions are made and a
9773  `nullptr` is returned if the value and the requested pointer type does not
9774  match.,get_ptr}
9775 
9776  @since version 1.0.0
9777  */
9778  template<typename PointerType, typename std::enable_if<
9779  std::is_pointer<PointerType>::value, int>::type = 0>
9780  PointerType get_ptr() noexcept
9781  {
9782  // get the type of the PointerType (remove pointer and const)
9783  using pointee_t = typename std::remove_const<typename
9784  std::remove_pointer<typename
9785  std::remove_const<PointerType>::type>::type>::type;
9786  // make sure the type matches the allowed types
9787  static_assert(
9788  std::is_same<object_t, pointee_t>::value
9789  or std::is_same<array_t, pointee_t>::value
9790  or std::is_same<string_t, pointee_t>::value
9791  or std::is_same<boolean_t, pointee_t>::value
9792  or std::is_same<number_integer_t, pointee_t>::value
9793  or std::is_same<number_unsigned_t, pointee_t>::value
9794  or std::is_same<number_float_t, pointee_t>::value
9795  , "incompatible pointer type");
9796 
9797  // delegate the call to get_impl_ptr<>()
9798  return get_impl_ptr(static_cast<PointerType>(nullptr));
9799  }
9800 
9801  /*!
9802  @brief get a pointer value (implicit)
9803  @copydoc get_ptr()
9804  */
9805  template<typename PointerType, typename std::enable_if<
9806  std::is_pointer<PointerType>::value and
9807  std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
9808  constexpr const PointerType get_ptr() const noexcept
9809  {
9810  // get the type of the PointerType (remove pointer and const)
9811  using pointee_t = typename std::remove_const<typename
9812  std::remove_pointer<typename
9813  std::remove_const<PointerType>::type>::type>::type;
9814  // make sure the type matches the allowed types
9815  static_assert(
9816  std::is_same<object_t, pointee_t>::value
9817  or std::is_same<array_t, pointee_t>::value
9818  or std::is_same<string_t, pointee_t>::value
9819  or std::is_same<boolean_t, pointee_t>::value
9820  or std::is_same<number_integer_t, pointee_t>::value
9821  or std::is_same<number_unsigned_t, pointee_t>::value
9822  or std::is_same<number_float_t, pointee_t>::value
9823  , "incompatible pointer type");
9824 
9825  // delegate the call to get_impl_ptr<>() const
9826  return get_impl_ptr(static_cast<PointerType>(nullptr));
9827  }
9828 
9829  /*!
9830  @brief get a reference value (implicit)
9831 
9832  Implicit reference access to the internally stored JSON value. No copies
9833  are made.
9834 
9835  @warning Writing data to the referee of the result yields an undefined
9836  state.
9837 
9838  @tparam ReferenceType reference type; must be a reference to @ref array_t,
9839  @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
9840  @ref number_float_t. Enforced by static assertion.
9841 
9842  @return reference to the internally stored JSON value if the requested
9843  reference type @a ReferenceType fits to the JSON value; throws
9844  type_error.303 otherwise
9845 
9846  @throw type_error.303 in case passed type @a ReferenceType is incompatible
9847  with the stored JSON value; see example below
9848 
9849  @complexity Constant.
9850 
9851  @liveexample{The example shows several calls to `get_ref()`.,get_ref}
9852 
9853  @since version 1.1.0
9854  */
9855  template<typename ReferenceType, typename std::enable_if<
9856  std::is_reference<ReferenceType>::value, int>::type = 0>
9857  ReferenceType get_ref()
9858  {
9859  // delegate call to get_ref_impl
9860  return get_ref_impl<ReferenceType>(*this);
9861  }
9863  /*!
9864  @brief get a reference value (implicit)
9865  @copydoc get_ref()
9866  */
9867  template<typename ReferenceType, typename std::enable_if<
9868  std::is_reference<ReferenceType>::value and
9869  std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
9870  ReferenceType get_ref() const
9871  {
9872  // delegate call to get_ref_impl
9873  return get_ref_impl<ReferenceType>(*this);
9874  }
9876  /*!
9877  @brief get a value (implicit)
9878 
9879  Implicit type conversion between the JSON value and a compatible value.
9880  The call is realized by calling @ref get() const.
9881 
9882  @tparam ValueType non-pointer type compatible to the JSON value, for
9883  instance `int` for JSON integer numbers, `bool` for JSON booleans, or
9884  `std::vector` types for JSON arrays. The character type of @ref string_t
9885  as well as an initializer list of this type is excluded to avoid
9886  ambiguities as these types implicitly convert to `std::string`.
9887 
9888  @return copy of the JSON value, converted to type @a ValueType
9889 
9890  @throw type_error.302 in case passed type @a ValueType is incompatible
9891  to the JSON value type (e.g., the JSON value is of type boolean, but a
9892  string is requested); see example below
9893 
9894  @complexity Linear in the size of the JSON value.
9895 
9896  @liveexample{The example below shows several conversions from JSON values
9897  to other types. There a few things to note: (1) Floating-point numbers can
9898  be converted to integers\, (2) A JSON array can be converted to a standard
9899  `std::vector<short>`\, (3) A JSON object can be converted to C++
9900  associative containers such as `std::unordered_map<std::string\,
9901  json>`.,operator__ValueType}
9902 
9903  @since version 1.0.0
9904  */
9905  template < typename ValueType, typename std::enable_if <
9906  not std::is_pointer<ValueType>::value and
9907  not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
9908  not std::is_same<ValueType, typename string_t::value_type>::value
9909 #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
9910  and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
9911 #endif
9912 #if defined(JSON_HAS_CPP_17)
9913  and not std::is_same<ValueType, typename std::string_view>::value
9914 #endif
9915  , int >::type = 0 >
9916  operator ValueType() const
9917  {
9918  // delegate the call to get<>() const
9919  return get<ValueType>();
9920  }
9922  /// @}
9923 
9924 
9925  ////////////////////
9926  // element access //
9927  ////////////////////
9928 
9929  /// @name element access
9930  /// Access to the JSON value.
9931  /// @{
9932 
9933  /*!
9934  @brief access specified array element with bounds checking
9935 
9936  Returns a reference to the element at specified location @a idx, with
9937  bounds checking.
9938 
9939  @param[in] idx index of the element to access
9940 
9941  @return reference to the element at index @a idx
9942 
9943  @throw type_error.304 if the JSON value is not an array; in this case,
9944  calling `at` with an index makes no sense. See example below.
9945  @throw out_of_range.401 if the index @a idx is out of range of the array;
9946  that is, `idx >= size()`. See example below.
9947 
9948  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
9949  changes in the JSON value.
9950 
9951  @complexity Constant.
9952 
9953  @since version 1.0.0
9954 
9955  @liveexample{The example below shows how array elements can be read and
9956  written using `at()`. It also demonstrates the different exceptions that
9957  can be thrown.,at__size_type}
9958  */
9959  reference at(size_type idx)
9960  {
9961  // at only works for arrays
9962  if (JSON_LIKELY(is_array()))
9963  {
9965  {
9966  return m_value.array->at(idx);
9967  }
9968  JSON_CATCH (std::out_of_range&)
9969  {
9970  // create better exception explanation
9971  JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
9972  }
9973  }
9974  else
9975  {
9976  JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
9977  }
9978  }
9979 
9980  /*!
9981  @brief access specified array element with bounds checking
9982 
9983  Returns a const reference to the element at specified location @a idx,
9984  with bounds checking.
9985 
9986  @param[in] idx index of the element to access
9987 
9988  @return const reference to the element at index @a idx
9989 
9990  @throw type_error.304 if the JSON value is not an array; in this case,
9991  calling `at` with an index makes no sense. See example below.
9992  @throw out_of_range.401 if the index @a idx is out of range of the array;
9993  that is, `idx >= size()`. See example below.
9994 
9995  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
9996  changes in the JSON value.
9997 
9998  @complexity Constant.
9999 
10000  @since version 1.0.0
10001 
10002  @liveexample{The example below shows how array elements can be read using
10003  `at()`. It also demonstrates the different exceptions that can be thrown.,
10004  at__size_type_const}
10005  */
10006  const_reference at(size_type idx) const
10007  {
10008  // at only works for arrays
10009  if (JSON_LIKELY(is_array()))
10010  {
10011  JSON_TRY
10012  {
10013  return m_value.array->at(idx);
10014  }
10015  JSON_CATCH (std::out_of_range&)
10016  {
10017  // create better exception explanation
10018  JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
10019  }
10020  }
10021  else
10022  {
10023  JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
10024  }
10025  }
10026 
10027  /*!
10028  @brief access specified object element with bounds checking
10029 
10030  Returns a reference to the element at with specified key @a key, with
10031  bounds checking.
10032 
10033  @param[in] key key of the element to access
10034 
10035  @return reference to the element at key @a key
10036 
10037  @throw type_error.304 if the JSON value is not an object; in this case,
10038  calling `at` with a key makes no sense. See example below.
10039  @throw out_of_range.403 if the key @a key is is not stored in the object;
10040  that is, `find(key) == end()`. See example below.
10041 
10042  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
10043  changes in the JSON value.
10044 
10045  @complexity Logarithmic in the size of the container.
10046 
10047  @sa @ref operator[](const typename object_t::key_type&) for unchecked
10048  access by reference
10049  @sa @ref value() for access by value with a default value
10050 
10051  @since version 1.0.0
10052 
10053  @liveexample{The example below shows how object elements can be read and
10054  written using `at()`. It also demonstrates the different exceptions that
10055  can be thrown.,at__object_t_key_type}
10056  */
10057  reference at(const typename object_t::key_type& key)
10058  {
10059  // at only works for objects
10060  if (JSON_LIKELY(is_object()))
10061  {
10062  JSON_TRY
10063  {
10064  return m_value.object->at(key);
10065  }
10066  JSON_CATCH (std::out_of_range&)
10067  {
10068  // create better exception explanation
10069  JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
10070  }
10071  }
10072  else
10073  {
10074  JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
10075  }
10076  }
10077 
10078  /*!
10079  @brief access specified object element with bounds checking
10080 
10081  Returns a const reference to the element at with specified key @a key,
10082  with bounds checking.
10083 
10084  @param[in] key key of the element to access
10085 
10086  @return const reference to the element at key @a key
10087 
10088  @throw type_error.304 if the JSON value is not an object; in this case,
10089  calling `at` with a key makes no sense. See example below.
10090  @throw out_of_range.403 if the key @a key is is not stored in the object;
10091  that is, `find(key) == end()`. See example below.
10092 
10093  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
10094  changes in the JSON value.
10095 
10096  @complexity Logarithmic in the size of the container.
10097 
10098  @sa @ref operator[](const typename object_t::key_type&) for unchecked
10099  access by reference
10100  @sa @ref value() for access by value with a default value
10101 
10102  @since version 1.0.0
10103 
10104  @liveexample{The example below shows how object elements can be read using
10105  `at()`. It also demonstrates the different exceptions that can be thrown.,
10106  at__object_t_key_type_const}
10107  */
10108  const_reference at(const typename object_t::key_type& key) const
10109  {
10110  // at only works for objects
10111  if (JSON_LIKELY(is_object()))
10112  {
10113  JSON_TRY
10114  {
10115  return m_value.object->at(key);
10116  }
10117  JSON_CATCH (std::out_of_range&)
10118  {
10119  // create better exception explanation
10120  JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
10121  }
10122  }
10123  else
10124  {
10125  JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
10126  }
10127  }
10128 
10129  /*!
10130  @brief access specified array element
10131 
10132  Returns a reference to the element at specified location @a idx.
10133 
10134  @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
10135  then the array is silently filled up with `null` values to make `idx` a
10136  valid reference to the last stored element.
10137 
10138  @param[in] idx index of the element to access
10139 
10140  @return reference to the element at index @a idx
10141 
10142  @throw type_error.305 if the JSON value is not an array or null; in that
10143  cases, using the [] operator with an index makes no sense.
10144 
10145  @complexity Constant if @a idx is in the range of the array. Otherwise
10146  linear in `idx - size()`.
10147 
10148  @liveexample{The example below shows how array elements can be read and
10149  written using `[]` operator. Note the addition of `null`
10150  values.,operatorarray__size_type}
10151 
10152  @since version 1.0.0
10153  */
10154  reference operator[](size_type idx)
10155  {
10156  // implicitly convert null value to an empty array
10157  if (is_null())
10158  {
10159  m_type = value_t::array;
10160  m_value.array = create<array_t>();
10161  assert_invariant();
10162  }
10163 
10164  // operator[] only works for arrays
10165  if (JSON_LIKELY(is_array()))
10166  {
10167  // fill up array with null values if given idx is outside range
10168  if (idx >= m_value.array->size())
10169  {
10170  m_value.array->insert(m_value.array->end(),
10171  idx - m_value.array->size() + 1,
10172  basic_json());
10173  }
10174 
10175  return m_value.array->operator[](idx);
10176  }
10177 
10178  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10179  }
10180 
10181  /*!
10182  @brief access specified array element
10183 
10184  Returns a const reference to the element at specified location @a idx.
10185 
10186  @param[in] idx index of the element to access
10187 
10188  @return const reference to the element at index @a idx
10189 
10190  @throw type_error.305 if the JSON value is not an array; in that case,
10191  using the [] operator with an index makes no sense.
10192 
10193  @complexity Constant.
10194 
10195  @liveexample{The example below shows how array elements can be read using
10196  the `[]` operator.,operatorarray__size_type_const}
10197 
10198  @since version 1.0.0
10199  */
10200  const_reference operator[](size_type idx) const
10201  {
10202  // const operator[] only works for arrays
10203  if (JSON_LIKELY(is_array()))
10204  {
10205  return m_value.array->operator[](idx);
10206  }
10207 
10208  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10209  }
10210 
10211  /*!
10212  @brief access specified object element
10213 
10214  Returns a reference to the element at with specified key @a key.
10216  @note If @a key is not found in the object, then it is silently added to
10217  the object and filled with a `null` value to make `key` a valid reference.
10218  In case the value was `null` before, it is converted to an object.
10219 
10220  @param[in] key key of the element to access
10221 
10222  @return reference to the element at key @a key
10223 
10224  @throw type_error.305 if the JSON value is not an object or null; in that
10225  cases, using the [] operator with a key makes no sense.
10226 
10227  @complexity Logarithmic in the size of the container.
10228 
10229  @liveexample{The example below shows how object elements can be read and
10230  written using the `[]` operator.,operatorarray__key_type}
10231 
10232  @sa @ref at(const typename object_t::key_type&) for access by reference
10233  with range checking
10234  @sa @ref value() for access by value with a default value
10235 
10236  @since version 1.0.0
10237  */
10238  reference operator[](const typename object_t::key_type& key)
10239  {
10240  // implicitly convert null value to an empty object
10241  if (is_null())
10242  {
10243  m_type = value_t::object;
10244  m_value.object = create<object_t>();
10245  assert_invariant();
10246  }
10247 
10248  // operator[] only works for objects
10249  if (JSON_LIKELY(is_object()))
10250  {
10251  return m_value.object->operator[](key);
10252  }
10254  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10255  }
10256 
10257  /*!
10258  @brief read-only access specified object element
10259 
10260  Returns a const reference to the element at with specified key @a key. No
10261  bounds checking is performed.
10262 
10263  @warning If the element with key @a key does not exist, the behavior is
10264  undefined.
10265 
10266  @param[in] key key of the element to access
10267 
10268  @return const reference to the element at key @a key
10269 
10270  @pre The element with key @a key must exist. **This precondition is
10271  enforced with an assertion.**
10272 
10273  @throw type_error.305 if the JSON value is not an object; in that case,
10274  using the [] operator with a key makes no sense.
10275 
10276  @complexity Logarithmic in the size of the container.
10277 
10278  @liveexample{The example below shows how object elements can be read using
10279  the `[]` operator.,operatorarray__key_type_const}
10280 
10281  @sa @ref at(const typename object_t::key_type&) for access by reference
10282  with range checking
10283  @sa @ref value() for access by value with a default value
10284 
10285  @since version 1.0.0
10286  */
10287  const_reference operator[](const typename object_t::key_type& key) const
10288  {
10289  // const operator[] only works for objects
10290  if (JSON_LIKELY(is_object()))
10291  {
10292  assert(m_value.object->find(key) != m_value.object->end());
10293  return m_value.object->find(key)->second;
10294  }
10295 
10296  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10297  }
10298 
10299  /*!
10300  @brief access specified object element
10301 
10302  Returns a reference to the element at with specified key @a key.
10303 
10304  @note If @a key is not found in the object, then it is silently added to
10305  the object and filled with a `null` value to make `key` a valid reference.
10306  In case the value was `null` before, it is converted to an object.
10307 
10308  @param[in] key key of the element to access
10309 
10310  @return reference to the element at key @a key
10311 
10312  @throw type_error.305 if the JSON value is not an object or null; in that
10313  cases, using the [] operator with a key makes no sense.
10314 
10315  @complexity Logarithmic in the size of the container.
10316 
10317  @liveexample{The example below shows how object elements can be read and
10318  written using the `[]` operator.,operatorarray__key_type}
10319 
10320  @sa @ref at(const typename object_t::key_type&) for access by reference
10321  with range checking
10322  @sa @ref value() for access by value with a default value
10323 
10324  @since version 1.1.0
10325  */
10326  template<typename T>
10327  reference operator[](T* key)
10328  {
10329  // implicitly convert null to object
10330  if (is_null())
10331  {
10332  m_type = value_t::object;
10333  m_value = value_t::object;
10334  assert_invariant();
10335  }
10336 
10337  // at only works for objects
10338  if (JSON_LIKELY(is_object()))
10339  {
10340  return m_value.object->operator[](key);
10341  }
10343  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10344  }
10345 
10346  /*!
10347  @brief read-only access specified object element
10348 
10349  Returns a const reference to the element at with specified key @a key. No
10350  bounds checking is performed.
10351 
10352  @warning If the element with key @a key does not exist, the behavior is
10353  undefined.
10354 
10355  @param[in] key key of the element to access
10356 
10357  @return const reference to the element at key @a key
10358 
10359  @pre The element with key @a key must exist. **This precondition is
10360  enforced with an assertion.**
10361 
10362  @throw type_error.305 if the JSON value is not an object; in that case,
10363  using the [] operator with a key makes no sense.
10364 
10365  @complexity Logarithmic in the size of the container.
10366 
10367  @liveexample{The example below shows how object elements can be read using
10368  the `[]` operator.,operatorarray__key_type_const}
10369 
10370  @sa @ref at(const typename object_t::key_type&) for access by reference
10371  with range checking
10372  @sa @ref value() for access by value with a default value
10373 
10374  @since version 1.1.0
10375  */
10376  template<typename T>
10377  const_reference operator[](T* key) const
10378  {
10379  // at only works for objects
10380  if (JSON_LIKELY(is_object()))
10381  {
10382  assert(m_value.object->find(key) != m_value.object->end());
10383  return m_value.object->find(key)->second;
10384  }
10385 
10386  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10387  }
10388 
10389  /*!
10390  @brief access specified object element with default value
10391 
10392  Returns either a copy of an object's element at the specified key @a key
10393  or a given default value if no element with key @a key exists.
10394 
10395  The function is basically equivalent to executing
10396  @code {.cpp}
10397  try {
10398  return at(key);
10399  } catch(out_of_range) {
10400  return default_value;
10401  }
10402  @endcode
10403 
10404  @note Unlike @ref at(const typename object_t::key_type&), this function
10405  does not throw if the given key @a key was not found.
10406 
10407  @note Unlike @ref operator[](const typename object_t::key_type& key), this
10408  function does not implicitly add an element to the position defined by @a
10409  key. This function is furthermore also applicable to const objects.
10410 
10411  @param[in] key key of the element to access
10412  @param[in] default_value the value to return if @a key is not found
10413 
10414  @tparam ValueType type compatible to JSON values, for instance `int` for
10415  JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
10416  JSON arrays. Note the type of the expected value at @a key and the default
10417  value @a default_value must be compatible.
10418 
10419  @return copy of the element at key @a key or @a default_value if @a key
10420  is not found
10421 
10422  @throw type_error.306 if the JSON value is not an object; in that case,
10423  using `value()` with a key makes no sense.
10424 
10425  @complexity Logarithmic in the size of the container.
10426 
10427  @liveexample{The example below shows how object elements can be queried
10428  with a default value.,basic_json__value}
10429 
10430  @sa @ref at(const typename object_t::key_type&) for access by reference
10431  with range checking
10432  @sa @ref operator[](const typename object_t::key_type&) for unchecked
10433  access by reference
10434 
10435  @since version 1.0.0
10436  */
10437  template<class ValueType, typename std::enable_if<
10438  std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
10439  ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
10440  {
10441  // at only works for objects
10442  if (JSON_LIKELY(is_object()))
10443  {
10444  // if key is found, return value and given default value otherwise
10445  const auto it = find(key);
10446  if (it != end())
10447  {
10448  return *it;
10449  }
10450 
10451  return default_value;
10452  }
10453 
10454  JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
10455  }
10456 
10457  /*!
10458  @brief overload for a default value of type const char*
10459  @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
10460  */
10461  string_t value(const typename object_t::key_type& key, const char* default_value) const
10462  {
10463  return value(key, string_t(default_value));
10464  }
10465 
10466  /*!
10467  @brief access specified object element via JSON Pointer with default value
10468 
10469  Returns either a copy of an object's element at the specified key @a key
10470  or a given default value if no element with key @a key exists.
10471 
10472  The function is basically equivalent to executing
10473  @code {.cpp}
10474  try {
10475  return at(ptr);
10476  } catch(out_of_range) {
10477  return default_value;
10478  }
10479  @endcode
10480 
10481  @note Unlike @ref at(const json_pointer&), this function does not throw
10482  if the given key @a key was not found.
10483 
10484  @param[in] ptr a JSON pointer to the element to access
10485  @param[in] default_value the value to return if @a ptr found no value
10486 
10487  @tparam ValueType type compatible to JSON values, for instance `int` for
10488  JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
10489  JSON arrays. Note the type of the expected value at @a key and the default
10490  value @a default_value must be compatible.
10491 
10492  @return copy of the element at key @a key or @a default_value if @a key
10493  is not found
10494 
10495  @throw type_error.306 if the JSON value is not an objec; in that case,
10496  using `value()` with a key makes no sense.
10497 
10498  @complexity Logarithmic in the size of the container.
10499 
10500  @liveexample{The example below shows how object elements can be queried
10501  with a default value.,basic_json__value_ptr}
10502 
10503  @sa @ref operator[](const json_pointer&) for unchecked access by reference
10504 
10505  @since version 2.0.2
10506  */
10507  template<class ValueType, typename std::enable_if<
10508  std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
10509  ValueType value(const json_pointer& ptr, const ValueType& default_value) const
10510  {
10511  // at only works for objects
10512  if (JSON_LIKELY(is_object()))
10513  {
10514  // if pointer resolves a value, return it or use default value
10515  JSON_TRY
10516  {
10517  return ptr.get_checked(this);
10518  }
10519  JSON_CATCH (out_of_range&)
10520  {
10521  return default_value;
10522  }
10523  }
10525  JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
10526  }
10527 
10528  /*!
10529  @brief overload for a default value of type const char*
10530  @copydoc basic_json::value(const json_pointer&, ValueType) const
10531  */
10532  string_t value(const json_pointer& ptr, const char* default_value) const
10533  {
10534  return value(ptr, string_t(default_value));
10535  }
10536 
10537  /*!
10538  @brief access the first element
10539 
10540  Returns a reference to the first element in the container. For a JSON
10541  container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
10542 
10543  @return In case of a structured type (array or object), a reference to the
10544  first element is returned. In case of number, string, or boolean values, a
10545  reference to the value is returned.
10546 
10547  @complexity Constant.
10548 
10549  @pre The JSON value must not be `null` (would throw `std::out_of_range`)
10550  or an empty array or object (undefined behavior, **guarded by
10551  assertions**).
10552  @post The JSON value remains unchanged.
10553 
10554  @throw invalid_iterator.214 when called on `null` value
10555 
10556  @liveexample{The following code shows an example for `front()`.,front}
10557 
10558  @sa @ref back() -- access the last element
10559 
10560  @since version 1.0.0
10561  */
10562  reference front()
10563  {
10564  return *begin();
10565  }
10566 
10567  /*!
10568  @copydoc basic_json::front()
10569  */
10570  const_reference front() const
10571  {
10572  return *cbegin();
10573  }
10574 
10575  /*!
10576  @brief access the last element
10578  Returns a reference to the last element in the container. For a JSON
10579  container `c`, the expression `c.back()` is equivalent to
10580  @code {.cpp}
10581  auto tmp = c.end();
10582  --tmp;
10583  return *tmp;
10584  @endcode
10586  @return In case of a structured type (array or object), a reference to the
10587  last element is returned. In case of number, string, or boolean values, a
10588  reference to the value is returned.
10589 
10590  @complexity Constant.
10591 
10592  @pre The JSON value must not be `null` (would throw `std::out_of_range`)
10593  or an empty array or object (undefined behavior, **guarded by
10594  assertions**).
10595  @post The JSON value remains unchanged.
10596 
10597  @throw invalid_iterator.214 when called on a `null` value. See example
10598  below.
10599 
10600  @liveexample{The following code shows an example for `back()`.,back}
10601 
10602  @sa @ref front() -- access the first element
10603 
10604  @since version 1.0.0
10605  */
10606  reference back()
10607  {
10608  auto tmp = end();
10609  --tmp;
10610  return *tmp;
10611  }
10612 
10613  /*!
10614  @copydoc basic_json::back()
10615  */
10616  const_reference back() const
10617  {
10618  auto tmp = cend();
10619  --tmp;
10620  return *tmp;
10621  }
10622 
10623  /*!
10624  @brief remove element given an iterator
10625 
10626  Removes the element specified by iterator @a pos. The iterator @a pos must
10627  be valid and dereferenceable. Thus the `end()` iterator (which is valid,
10628  but is not dereferenceable) cannot be used as a value for @a pos.
10629 
10630  If called on a primitive type other than `null`, the resulting JSON value
10631  will be `null`.
10632 
10633  @param[in] pos iterator to the element to remove
10634  @return Iterator following the last removed element. If the iterator @a
10635  pos refers to the last element, the `end()` iterator is returned.
10636 
10637  @tparam IteratorType an @ref iterator or @ref const_iterator
10638 
10639  @post Invalidates iterators and references at or after the point of the
10640  erase, including the `end()` iterator.
10641 
10642  @throw type_error.307 if called on a `null` value; example: `"cannot use
10643  erase() with null"`
10644  @throw invalid_iterator.202 if called on an iterator which does not belong
10645  to the current JSON value; example: `"iterator does not fit current
10646  value"`
10647  @throw invalid_iterator.205 if called on a primitive type with invalid
10648  iterator (i.e., any iterator which is not `begin()`); example: `"iterator
10649  out of range"`
10650 
10651  @complexity The complexity depends on the type:
10652  - objects: amortized constant
10653  - arrays: linear in distance between @a pos and the end of the container
10654  - strings: linear in the length of the string
10655  - other types: constant
10656 
10657  @liveexample{The example shows the result of `erase()` for different JSON
10658  types.,erase__IteratorType}
10659 
10660  @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
10661  the given range
10662  @sa @ref erase(const typename object_t::key_type&) -- removes the element
10663  from an object at the given key
10664  @sa @ref erase(const size_type) -- removes the element from an array at
10665  the given index
10666 
10667  @since version 1.0.0
10668  */
10669  template<class IteratorType, typename std::enable_if<
10670  std::is_same<IteratorType, typename basic_json_t::iterator>::value or
10671  std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
10672  = 0>
10673  IteratorType erase(IteratorType pos)
10674  {
10675  // make sure iterator fits the current value
10676  if (JSON_UNLIKELY(this != pos.m_object))
10677  {
10678  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
10679  }
10680 
10681  IteratorType result = end();
10682 
10683  switch (m_type)
10684  {
10685  case value_t::boolean:
10686  case value_t::number_float:
10687  case value_t::number_integer:
10688  case value_t::number_unsigned:
10689  case value_t::string:
10690  {
10691  if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
10692  {
10693  JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
10694  }
10695 
10696  if (is_string())
10697  {
10698  AllocatorType<string_t> alloc;
10699  std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
10700  std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
10701  m_value.string = nullptr;
10702  }
10703 
10704  m_type = value_t::null;
10705  assert_invariant();
10706  break;
10707  }
10708 
10709  case value_t::object:
10710  {
10711  result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
10712  break;
10713  }
10714 
10715  case value_t::array:
10716  {
10717  result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
10718  break;
10719  }
10720 
10721  default:
10722  JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
10723  }
10724 
10725  return result;
10726  }
10727 
10728  /*!
10729  @brief remove elements given an iterator range
10730 
10731  Removes the element specified by the range `[first; last)`. The iterator
10732  @a first does not need to be dereferenceable if `first == last`: erasing
10733  an empty range is a no-op.
10734 
10735  If called on a primitive type other than `null`, the resulting JSON value
10736  will be `null`.
10737 
10738  @param[in] first iterator to the beginning of the range to remove
10739  @param[in] last iterator past the end of the range to remove
10740  @return Iterator following the last removed element. If the iterator @a
10741  second refers to the last element, the `end()` iterator is returned.
10742 
10743  @tparam IteratorType an @ref iterator or @ref const_iterator
10744 
10745  @post Invalidates iterators and references at or after the point of the
10746  erase, including the `end()` iterator.
10747 
10748  @throw type_error.307 if called on a `null` value; example: `"cannot use
10749  erase() with null"`
10750  @throw invalid_iterator.203 if called on iterators which does not belong
10751  to the current JSON value; example: `"iterators do not fit current value"`
10752  @throw invalid_iterator.204 if called on a primitive type with invalid
10753  iterators (i.e., if `first != begin()` and `last != end()`); example:
10754  `"iterators out of range"`
10755 
10756  @complexity The complexity depends on the type:
10757  - objects: `log(size()) + std::distance(first, last)`
10758  - arrays: linear in the distance between @a first and @a last, plus linear
10759  in the distance between @a last and end of the container
10760  - strings: linear in the length of the string
10761  - other types: constant
10762 
10763  @liveexample{The example shows the result of `erase()` for different JSON
10764  types.,erase__IteratorType_IteratorType}
10765 
10766  @sa @ref erase(IteratorType) -- removes the element at a given position
10767  @sa @ref erase(const typename object_t::key_type&) -- removes the element
10768  from an object at the given key
10769  @sa @ref erase(const size_type) -- removes the element from an array at
10770  the given index
10771 
10772  @since version 1.0.0
10773  */
10774  template<class IteratorType, typename std::enable_if<
10775  std::is_same<IteratorType, typename basic_json_t::iterator>::value or
10776  std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
10777  = 0>
10778  IteratorType erase(IteratorType first, IteratorType last)
10779  {
10780  // make sure iterator fits the current value
10781  if (JSON_UNLIKELY(this != first.m_object or this != last.m_object))
10782  {
10783  JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
10784  }
10785 
10786  IteratorType result = end();
10787 
10788  switch (m_type)
10789  {
10790  case value_t::boolean:
10791  case value_t::number_float:
10792  case value_t::number_integer:
10793  case value_t::number_unsigned:
10794  case value_t::string:
10795  {
10796  if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin()
10797  or not last.m_it.primitive_iterator.is_end()))
10798  {
10799  JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
10800  }
10801 
10802  if (is_string())
10803  {
10804  AllocatorType<string_t> alloc;
10805  std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
10806  std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
10807  m_value.string = nullptr;
10808  }
10809 
10810  m_type = value_t::null;
10811  assert_invariant();
10812  break;
10813  }
10814 
10815  case value_t::object:
10816  {
10817  result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
10818  last.m_it.object_iterator);
10819  break;
10820  }
10821 
10822  case value_t::array:
10823  {
10824  result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
10825  last.m_it.array_iterator);
10826  break;
10827  }
10828 
10829  default:
10830  JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
10831  }
10832 
10833  return result;
10834  }
10835 
10836  /*!
10837  @brief remove element from a JSON object given a key
10838 
10839  Removes elements from a JSON object with the key value @a key.
10840 
10841  @param[in] key value of the elements to remove
10842 
10843  @return Number of elements removed. If @a ObjectType is the default
10844  `std::map` type, the return value will always be `0` (@a key was not
10845  found) or `1` (@a key was found).
10846 
10847  @post References and iterators to the erased elements are invalidated.
10848  Other references and iterators are not affected.
10849 
10850  @throw type_error.307 when called on a type other than JSON object;
10851  example: `"cannot use erase() with null"`
10852 
10853  @complexity `log(size()) + count(key)`
10854 
10855  @liveexample{The example shows the effect of `erase()`.,erase__key_type}
10856 
10857  @sa @ref erase(IteratorType) -- removes the element at a given position
10858  @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
10859  the given range
10860  @sa @ref erase(const size_type) -- removes the element from an array at
10861  the given index
10862 
10863  @since version 1.0.0
10864  */
10865  size_type erase(const typename object_t::key_type& key)
10866  {
10867  // this erase only works for objects
10868  if (JSON_LIKELY(is_object()))
10869  {
10870  return m_value.object->erase(key);
10871  }
10872 
10873  JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
10874  }
10875 
10876  /*!
10877  @brief remove element from a JSON array given an index
10878 
10879  Removes element from a JSON array at the index @a idx.
10881  @param[in] idx index of the element to remove
10882 
10883  @throw type_error.307 when called on a type other than JSON object;
10884  example: `"cannot use erase() with null"`
10885  @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
10886  is out of range"`
10887 
10888  @complexity Linear in distance between @a idx and the end of the container.
10889 
10890  @liveexample{The example shows the effect of `erase()`.,erase__size_type}
10891 
10892  @sa @ref erase(IteratorType) -- removes the element at a given position
10893  @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
10894  the given range
10895  @sa @ref erase(const typename object_t::key_type&) -- removes the element
10896  from an object at the given key
10897 
10898  @since version 1.0.0
10899  */
10900  void erase(const size_type idx)
10901  {
10902  // this erase only works for arrays
10903  if (JSON_LIKELY(is_array()))
10904  {
10905  if (JSON_UNLIKELY(idx >= size()))
10906  {
10907  JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
10908  }
10909 
10910  m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
10911  }
10912  else
10913  {
10914  JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
10915  }
10916  }
10917 
10918  /// @}
10919 
10920 
10921  ////////////
10922  // lookup //
10923  ////////////
10924 
10925  /// @name lookup
10926  /// @{
10927 
10928  /*!
10929  @brief find an element in a JSON object
10930 
10931  Finds an element in a JSON object with key equivalent to @a key. If the
10932  element is not found or the JSON value is not an object, end() is
10933  returned.
10934 
10935  @note This method always returns @ref end() when executed on a JSON type
10936  that is not an object.
10937 
10938  @param[in] key key value of the element to search for.
10939 
10940  @return Iterator to an element with key equivalent to @a key. If no such
10941  element is found or the JSON value is not an object, past-the-end (see
10942  @ref end()) iterator is returned.
10943 
10944  @complexity Logarithmic in the size of the JSON object.
10945 
10946  @liveexample{The example shows how `find()` is used.,find__key_type}
10947 
10948  @since version 1.0.0
10949  */
10950  template<typename KeyT>
10951  iterator find(KeyT&& key)
10952  {
10953  auto result = end();
10954 
10955  if (is_object())
10956  {
10957  result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
10958  }
10959 
10960  return result;
10961  }
10962 
10963  /*!
10964  @brief find an element in a JSON object
10965  @copydoc find(KeyT&&)
10966  */
10967  template<typename KeyT>
10968  const_iterator find(KeyT&& key) const
10969  {
10970  auto result = cend();
10971 
10972  if (is_object())
10973  {
10974  result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
10975  }
10976 
10977  return result;
10978  }
10979 
10980  /*!
10981  @brief returns the number of occurrences of a key in a JSON object
10982 
10983  Returns the number of elements with key @a key. If ObjectType is the
10984  default `std::map` type, the return value will always be `0` (@a key was
10985  not found) or `1` (@a key was found).
10986 
10987  @note This method always returns `0` when executed on a JSON type that is
10988  not an object.
10989 
10990  @param[in] key key value of the element to count
10991 
10992  @return Number of elements with key @a key. If the JSON value is not an
10993  object, the return value will be `0`.
10994 
10995  @complexity Logarithmic in the size of the JSON object.
10996 
10997  @liveexample{The example shows how `count()` is used.,count}
10998 
10999  @since version 1.0.0
11000  */
11001  template<typename KeyT>
11002  size_type count(KeyT&& key) const
11003  {
11004  // return 0 for all nonobject types
11005  return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
11006  }
11007 
11008  /// @}
11009 
11010 
11011  ///////////////
11012  // iterators //
11013  ///////////////
11014 
11015  /// @name iterators
11016  /// @{
11018  /*!
11019  @brief returns an iterator to the first element
11020 
11021  Returns an iterator to the first element.
11022 
11023  @image html range-begin-end.svg "Illustration from cppreference.com"
11024 
11025  @return iterator to the first element
11026 
11027  @complexity Constant.
11028 
11029  @requirement This function helps `basic_json` satisfying the
11030  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11031  requirements:
11032  - The complexity is constant.
11033 
11034  @liveexample{The following code shows an example for `begin()`.,begin}
11035 
11036  @sa @ref cbegin() -- returns a const iterator to the beginning
11037  @sa @ref end() -- returns an iterator to the end
11038  @sa @ref cend() -- returns a const iterator to the end
11039 
11040  @since version 1.0.0
11041  */
11042  iterator begin() noexcept
11043  {
11044  iterator result(this);
11045  result.set_begin();
11046  return result;
11047  }
11048 
11049  /*!
11050  @copydoc basic_json::cbegin()
11051  */
11052  const_iterator begin() const noexcept
11053  {
11054  return cbegin();
11055  }
11056 
11057  /*!
11058  @brief returns a const iterator to the first element
11059 
11060  Returns a const iterator to the first element.
11061 
11062  @image html range-begin-end.svg "Illustration from cppreference.com"
11063 
11064  @return const iterator to the first element
11065 
11066  @complexity Constant.
11068  @requirement This function helps `basic_json` satisfying the
11069  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11070  requirements:
11071  - The complexity is constant.
11072  - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
11073 
11074  @liveexample{The following code shows an example for `cbegin()`.,cbegin}
11075 
11076  @sa @ref begin() -- returns an iterator to the beginning
11077  @sa @ref end() -- returns an iterator to the end
11078  @sa @ref cend() -- returns a const iterator to the end
11079 
11080  @since version 1.0.0
11081  */
11082  const_iterator cbegin() const noexcept
11083  {
11084  const_iterator result(this);
11085  result.set_begin();
11086  return result;
11087  }
11088 
11089  /*!
11090  @brief returns an iterator to one past the last element
11091 
11092  Returns an iterator to one past the last element.
11093 
11094  @image html range-begin-end.svg "Illustration from cppreference.com"
11095 
11096  @return iterator one past the last element
11098  @complexity Constant.
11099 
11100  @requirement This function helps `basic_json` satisfying the
11101  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11102  requirements:
11103  - The complexity is constant.
11104 
11105  @liveexample{The following code shows an example for `end()`.,end}
11106 
11107  @sa @ref cend() -- returns a const iterator to the end
11108  @sa @ref begin() -- returns an iterator to the beginning
11109  @sa @ref cbegin() -- returns a const iterator to the beginning
11110 
11111  @since version 1.0.0
11112  */
11113  iterator end() noexcept
11114  {
11115  iterator result(this);
11116  result.set_end();
11117  return result;
11118  }
11119 
11120  /*!
11121  @copydoc basic_json::cend()
11122  */
11123  const_iterator end() const noexcept
11124  {
11125  return cend();
11126  }
11127 
11128  /*!
11129  @brief returns a const iterator to one past the last element
11130 
11131  Returns a const iterator to one past the last element.
11132 
11133  @image html range-begin-end.svg "Illustration from cppreference.com"
11134 
11135  @return const iterator one past the last element
11136 
11137  @complexity Constant.
11139  @requirement This function helps `basic_json` satisfying the
11140  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11141  requirements:
11142  - The complexity is constant.
11143  - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
11144 
11145  @liveexample{The following code shows an example for `cend()`.,cend}
11146 
11147  @sa @ref end() -- returns an iterator to the end
11148  @sa @ref begin() -- returns an iterator to the beginning
11149  @sa @ref cbegin() -- returns a const iterator to the beginning
11150 
11151  @since version 1.0.0
11152  */
11153  const_iterator cend() const noexcept
11154  {
11155  const_iterator result(this);
11156  result.set_end();
11157  return result;
11158  }
11159 
11160  /*!
11161  @brief returns an iterator to the reverse-beginning
11162 
11163  Returns an iterator to the reverse-beginning; that is, the last element.
11164 
11165  @image html range-rbegin-rend.svg "Illustration from cppreference.com"
11166 
11167  @complexity Constant.
11169  @requirement This function helps `basic_json` satisfying the
11170  [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
11171  requirements:
11172  - The complexity is constant.
11173  - Has the semantics of `reverse_iterator(end())`.
11174 
11175  @liveexample{The following code shows an example for `rbegin()`.,rbegin}
11176 
11177  @sa @ref crbegin() -- returns a const reverse iterator to the beginning
11178  @sa @ref rend() -- returns a reverse iterator to the end
11179  @sa @ref crend() -- returns a const reverse iterator to the end
11180 
11181  @since version 1.0.0
11182  */
11183  reverse_iterator rbegin() noexcept
11184  {
11185  return reverse_iterator(end());
11186  }
11187 
11188  /*!
11189  @copydoc basic_json::crbegin()
11190  */
11191  const_reverse_iterator rbegin() const noexcept
11192  {
11193  return crbegin();
11194  }
11195 
11196  /*!
11197  @brief returns an iterator to the reverse-end
11199  Returns an iterator to the reverse-end; that is, one before the first
11200  element.
11201 
11202  @image html range-rbegin-rend.svg "Illustration from cppreference.com"
11203 
11204  @complexity Constant.
11205 
11206  @requirement This function helps `basic_json` satisfying the
11207  [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
11208  requirements:
11209  - The complexity is constant.
11210  - Has the semantics of `reverse_iterator(begin())`.
11211 
11212  @liveexample{The following code shows an example for `rend()`.,rend}
11213 
11214  @sa @ref crend() -- returns a const reverse iterator to the end
11215  @sa @ref rbegin() -- returns a reverse iterator to the beginning
11216  @sa @ref crbegin() -- returns a const reverse iterator to the beginning
11217 
11218  @since version 1.0.0
11219  */
11220  reverse_iterator rend() noexcept
11221  {
11222  return reverse_iterator(begin());
11223  }
11224 
11225  /*!
11226  @copydoc basic_json::crend()
11227  */
11228  const_reverse_iterator rend() const noexcept
11229  {
11230  return crend();
11231  }
11232 
11233  /*!
11234  @brief returns a const reverse iterator to the last element
11236  Returns a const iterator to the reverse-beginning; that is, the last
11237  element.
11238 
11239  @image html range-rbegin-rend.svg "Illustration from cppreference.com"
11240 
11241  @complexity Constant.
11242 
11243  @requirement This function helps `basic_json` satisfying the
11244  [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
11245  requirements:
11246  - The complexity is constant.
11247  - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
11248 
11249  @liveexample{The following code shows an example for `crbegin()`.,crbegin}
11250 
11251  @sa @ref rbegin() -- returns a reverse iterator to the beginning
11252  @sa @ref rend() -- returns a reverse iterator to the end
11253  @sa @ref crend() -- returns a const reverse iterator to the end
11254 
11255  @since version 1.0.0
11256  */
11257  const_reverse_iterator crbegin() const noexcept
11258  {
11259  return const_reverse_iterator(cend());
11260  }
11261 
11262  /*!
11263  @brief returns a const reverse iterator to one before the first
11264 
11265  Returns a const reverse iterator to the reverse-end; that is, one before
11266  the first element.
11267 
11268  @image html range-rbegin-rend.svg "Illustration from cppreference.com"
11269 
11270  @complexity Constant.
11271 
11272  @requirement This function helps `basic_json` satisfying the
11273  [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
11274  requirements:
11275  - The complexity is constant.
11276  - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
11277 
11278  @liveexample{The following code shows an example for `crend()`.,crend}
11279 
11280  @sa @ref rend() -- returns a reverse iterator to the end
11281  @sa @ref rbegin() -- returns a reverse iterator to the beginning
11282  @sa @ref crbegin() -- returns a const reverse iterator to the beginning
11283 
11284  @since version 1.0.0
11285  */
11286  const_reverse_iterator crend() const noexcept
11287  {
11288  return const_reverse_iterator(cbegin());
11289  }
11290 
11291  public:
11292  /*!
11293  @brief wrapper to access iterator member functions in range-based for
11294 
11295  This function allows to access @ref iterator::key() and @ref
11296  iterator::value() during range-based for loops. In these loops, a
11297  reference to the JSON values is returned, so there is no access to the
11298  underlying iterator.
11299 
11300  For loop without iterator_wrapper:
11302  @code{cpp}
11303  for (auto it = j_object.begin(); it != j_object.end(); ++it)
11304  {
11305  std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
11306  }
11307  @endcode
11308 
11309  Range-based for loop without iterator proxy:
11310 
11311  @code{cpp}
11312  for (auto it : j_object)
11313  {
11314  // "it" is of type json::reference and has no key() member
11315  std::cout << "value: " << it << '\n';
11316  }
11317  @endcode
11318 
11319  Range-based for loop with iterator proxy:
11320 
11321  @code{cpp}
11322  for (auto it : json::iterator_wrapper(j_object))
11323  {
11324  std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
11325  }
11326  @endcode
11327 
11328  @note When iterating over an array, `key()` will return the index of the
11329  element as string (see example).
11330 
11331  @param[in] ref reference to a JSON value
11332  @return iteration proxy object wrapping @a ref with an interface to use in
11333  range-based for loops
11334 
11335  @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
11336 
11337  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
11338  changes in the JSON value.
11339 
11340  @complexity Constant.
11341 
11342  @note The name of this function is not yet final and may change in the
11343  future.
11344  */
11345  static iteration_proxy<iterator> iterator_wrapper(reference ref)
11346  {
11347  return iteration_proxy<iterator>(ref);
11348  }
11349 
11350  /*!
11351  @copydoc iterator_wrapper(reference)
11352  */
11353  static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref)
11354  {
11355  return iteration_proxy<const_iterator>(ref);
11356  }
11357 
11358  /// @}
11359 
11361  //////////////
11362  // capacity //
11363  //////////////
11364 
11365  /// @name capacity
11366  /// @{
11367 
11368  /*!
11369  @brief checks whether the container is empty.
11370 
11371  Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
11372 
11373  @return The return value depends on the different types and is
11374  defined as follows:
11375  Value type | return value
11376  ----------- | -------------
11377  null | `true`
11378  boolean | `false`
11379  string | `false`
11380  number | `false`
11381  object | result of function `object_t::empty()`
11382  array | result of function `array_t::empty()`
11383 
11384  @liveexample{The following code uses `empty()` to check if a JSON
11385  object contains any elements.,empty}
11386 
11387  @complexity Constant, as long as @ref array_t and @ref object_t satisfy
11388  the Container concept; that is, their `empty()` functions have constant
11389  complexity.
11390 
11391  @iterators No changes.
11392 
11393  @exceptionsafety No-throw guarantee: this function never throws exceptions.
11394 
11395  @note This function does not return whether a string stored as JSON value
11396  is empty - it returns whether the JSON container itself is empty which is
11397  false in the case of a string.
11398 
11399  @requirement This function helps `basic_json` satisfying the
11400  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11401  requirements:
11402  - The complexity is constant.
11403  - Has the semantics of `begin() == end()`.
11404 
11405  @sa @ref size() -- returns the number of elements
11406 
11407  @since version 1.0.0
11408  */
11409  bool empty() const noexcept
11410  {
11411  switch (m_type)
11412  {
11413  case value_t::null:
11414  {
11415  // null values are empty
11416  return true;
11417  }
11418 
11419  case value_t::array:
11420  {
11421  // delegate call to array_t::empty()
11422  return m_value.array->empty();
11423  }
11425  case value_t::object:
11426  {
11427  // delegate call to object_t::empty()
11428  return m_value.object->empty();
11429  }
11430 
11431  default:
11432  {
11433  // all other types are nonempty
11434  return false;
11435  }
11436  }
11437  }
11438 
11439  /*!
11440  @brief returns the number of elements
11441 
11442  Returns the number of elements in a JSON value.
11443 
11444  @return The return value depends on the different types and is
11445  defined as follows:
11446  Value type | return value
11447  ----------- | -------------
11448  null | `0`
11449  boolean | `1`
11450  string | `1`
11451  number | `1`
11452  object | result of function object_t::size()
11453  array | result of function array_t::size()
11454 
11455  @liveexample{The following code calls `size()` on the different value
11456  types.,size}
11457 
11458  @complexity Constant, as long as @ref array_t and @ref object_t satisfy
11459  the Container concept; that is, their size() functions have constant
11460  complexity.
11461 
11462  @iterators No changes.
11463 
11464  @exceptionsafety No-throw guarantee: this function never throws exceptions.
11465 
11466  @note This function does not return the length of a string stored as JSON
11467  value - it returns the number of elements in the JSON value which is 1 in
11468  the case of a string.
11469 
11470  @requirement This function helps `basic_json` satisfying the
11471  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11472  requirements:
11473  - The complexity is constant.
11474  - Has the semantics of `std::distance(begin(), end())`.
11475 
11476  @sa @ref empty() -- checks whether the container is empty
11477  @sa @ref max_size() -- returns the maximal number of elements
11478 
11479  @since version 1.0.0
11480  */
11481  size_type size() const noexcept
11482  {
11483  switch (m_type)
11484  {
11485  case value_t::null:
11486  {
11487  // null values are empty
11488  return 0;
11489  }
11490 
11491  case value_t::array:
11492  {
11493  // delegate call to array_t::size()
11494  return m_value.array->size();
11495  }
11497  case value_t::object:
11498  {
11499  // delegate call to object_t::size()
11500  return m_value.object->size();
11501  }
11502 
11503  default:
11504  {
11505  // all other types have size 1
11506  return 1;
11507  }
11508  }
11509  }
11510 
11511  /*!
11512  @brief returns the maximum possible number of elements
11513 
11514  Returns the maximum number of elements a JSON value is able to hold due to
11515  system or library implementation limitations, i.e. `std::distance(begin(),
11516  end())` for the JSON value.
11517 
11518  @return The return value depends on the different types and is
11519  defined as follows:
11520  Value type | return value
11521  ----------- | -------------
11522  null | `0` (same as `size()`)
11523  boolean | `1` (same as `size()`)
11524  string | `1` (same as `size()`)
11525  number | `1` (same as `size()`)
11526  object | result of function `object_t::max_size()`
11527  array | result of function `array_t::max_size()`
11528 
11529  @liveexample{The following code calls `max_size()` on the different value
11530  types. Note the output is implementation specific.,max_size}
11531 
11532  @complexity Constant, as long as @ref array_t and @ref object_t satisfy
11533  the Container concept; that is, their `max_size()` functions have constant
11534  complexity.
11535 
11536  @iterators No changes.
11537 
11538  @exceptionsafety No-throw guarantee: this function never throws exceptions.
11539 
11540  @requirement This function helps `basic_json` satisfying the
11541  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11542  requirements:
11543  - The complexity is constant.
11544  - Has the semantics of returning `b.size()` where `b` is the largest
11545  possible JSON value.
11546 
11547  @sa @ref size() -- returns the number of elements
11548 
11549  @since version 1.0.0
11550  */
11551  size_type max_size() const noexcept
11552  {
11553  switch (m_type)
11554  {
11555  case value_t::array:
11556  {
11557  // delegate call to array_t::max_size()
11558  return m_value.array->max_size();
11559  }
11560 
11561  case value_t::object:
11562  {
11563  // delegate call to object_t::max_size()
11564  return m_value.object->max_size();
11565  }
11567  default:
11568  {
11569  // all other types have max_size() == size()
11570  return size();
11571  }
11572  }
11573  }
11574 
11575  /// @}
11576 
11577 
11578  ///////////////
11579  // modifiers //
11580  ///////////////
11581 
11582  /// @name modifiers
11583  /// @{
11584 
11585  /*!
11586  @brief clears the contents
11587 
11588  Clears the content of a JSON value and resets it to the default value as
11589  if @ref basic_json(value_t) would have been called with the current value
11590  type from @ref type():
11591 
11592  Value type | initial value
11593  ----------- | -------------
11594  null | `null`
11595  boolean | `false`
11596  string | `""`
11597  number | `0`
11598  object | `{}`
11599  array | `[]`
11600 
11601  @post Has the same effect as calling
11602  @code {.cpp}
11603  *this = basic_json(type());
11604  @endcode
11605 
11606  @liveexample{The example below shows the effect of `clear()` to different
11607  JSON types.,clear}
11608 
11609  @complexity Linear in the size of the JSON value.
11610 
11611  @iterators All iterators, pointers and references related to this container
11612  are invalidated.
11613 
11614  @exceptionsafety No-throw guarantee: this function never throws exceptions.
11615 
11616  @sa @ref basic_json(value_t) -- constructor that creates an object with the
11617  same value than calling `clear()`
11618 
11619  @since version 1.0.0
11620  */
11621  void clear() noexcept
11622  {
11623  switch (m_type)
11624  {
11625  case value_t::number_integer:
11626  {
11627  m_value.number_integer = 0;
11628  break;
11629  }
11630 
11631  case value_t::number_unsigned:
11632  {
11633  m_value.number_unsigned = 0;
11634  break;
11635  }
11637  case value_t::number_float:
11638  {
11639  m_value.number_float = 0.0;
11640  break;
11641  }
11642 
11643  case value_t::boolean:
11644  {
11645  m_value.boolean = false;
11646  break;
11647  }
11648 
11649  case value_t::string:
11650  {
11651  m_value.string->clear();
11652  break;
11653  }
11654 
11655  case value_t::array:
11656  {
11657  m_value.array->clear();
11658  break;
11659  }
11660 
11661  case value_t::object:
11662  {
11663  m_value.object->clear();
11664  break;
11665  }
11666 
11667  default:
11668  break;
11669  }
11670  }
11671 
11672  /*!
11673  @brief add an object to an array
11674 
11675  Appends the given element @a val to the end of the JSON value. If the
11676  function is called on a JSON null value, an empty array is created before
11677  appending @a val.
11678 
11679  @param[in] val the value to add to the JSON array
11680 
11681  @throw type_error.308 when called on a type other than JSON array or
11682  null; example: `"cannot use push_back() with number"`
11683 
11684  @complexity Amortized constant.
11685 
11686  @liveexample{The example shows how `push_back()` and `+=` can be used to
11687  add elements to a JSON array. Note how the `null` value was silently
11688  converted to a JSON array.,push_back}
11689 
11690  @since version 1.0.0
11691  */
11692  void push_back(basic_json&& val)
11693  {
11694  // push_back only works for null objects or arrays
11695  if (JSON_UNLIKELY(not(is_null() or is_array())))
11696  {
11697  JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
11698  }
11699 
11700  // transform null object into an array
11701  if (is_null())
11702  {
11703  m_type = value_t::array;
11704  m_value = value_t::array;
11705  assert_invariant();
11706  }
11708  // add element to array (move semantics)
11709  m_value.array->push_back(std::move(val));
11710  // invalidate object
11711  val.m_type = value_t::null;
11712  }
11713 
11714  /*!
11715  @brief add an object to an array
11716  @copydoc push_back(basic_json&&)
11717  */
11718  reference operator+=(basic_json&& val)
11719  {
11720  push_back(std::move(val));
11721  return *this;
11722  }
11723 
11724  /*!
11725  @brief add an object to an array
11726  @copydoc push_back(basic_json&&)
11727  */
11728  void push_back(const basic_json& val)
11729  {
11730  // push_back only works for null objects or arrays
11731  if (JSON_UNLIKELY(not(is_null() or is_array())))
11732  {
11733  JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
11734  }
11735 
11736  // transform null object into an array
11737  if (is_null())
11738  {
11739  m_type = value_t::array;
11740  m_value = value_t::array;
11741  assert_invariant();
11742  }
11744  // add element to array
11745  m_value.array->push_back(val);
11746  }
11747 
11748  /*!
11749  @brief add an object to an array
11750  @copydoc push_back(basic_json&&)
11751  */
11752  reference operator+=(const basic_json& val)
11753  {
11754  push_back(val);
11755  return *this;
11756  }
11757 
11758  /*!
11759  @brief add an object to an object
11760 
11761  Inserts the given element @a val to the JSON object. If the function is
11762  called on a JSON null value, an empty object is created before inserting
11763  @a val.
11764 
11765  @param[in] val the value to add to the JSON object
11766 
11767  @throw type_error.308 when called on a type other than JSON object or
11768  null; example: `"cannot use push_back() with number"`
11769 
11770  @complexity Logarithmic in the size of the container, O(log(`size()`)).
11771 
11772  @liveexample{The example shows how `push_back()` and `+=` can be used to
11773  add elements to a JSON object. Note how the `null` value was silently
11774  converted to a JSON object.,push_back__object_t__value}
11775 
11776  @since version 1.0.0
11777  */
11778  void push_back(const typename object_t::value_type& val)
11779  {
11780  // push_back only works for null objects or objects
11781  if (JSON_UNLIKELY(not(is_null() or is_object())))
11782  {
11783  JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
11784  }
11785 
11786  // transform null object into an object
11787  if (is_null())
11788  {
11789  m_type = value_t::object;
11790  m_value = value_t::object;
11791  assert_invariant();
11792  }
11794  // add element to array
11795  m_value.object->insert(val);
11796  }
11797 
11798  /*!
11799  @brief add an object to an object
11800  @copydoc push_back(const typename object_t::value_type&)
11801  */
11802  reference operator+=(const typename object_t::value_type& val)
11803  {
11804  push_back(val);
11805  return *this;
11806  }
11807 
11808  /*!
11809  @brief add an object to an object
11810 
11811  This function allows to use `push_back` with an initializer list. In case
11812 
11813  1. the current value is an object,
11814  2. the initializer list @a init contains only two elements, and
11815  3. the first element of @a init is a string,
11816 
11817  @a init is converted into an object element and added using
11818  @ref push_back(const typename object_t::value_type&). Otherwise, @a init
11819  is converted to a JSON value and added using @ref push_back(basic_json&&).
11820 
11821  @param[in] init an initializer list
11822 
11823  @complexity Linear in the size of the initializer list @a init.
11824 
11825  @note This function is required to resolve an ambiguous overload error,
11826  because pairs like `{"key", "value"}` can be both interpreted as
11827  `object_t::value_type` or `std::initializer_list<basic_json>`, see
11828  https://github.com/nlohmann/json/issues/235 for more information.
11829 
11830  @liveexample{The example shows how initializer lists are treated as
11831  objects when possible.,push_back__initializer_list}
11832  */
11833  void push_back(initializer_list_t init)
11834  {
11835  if (is_object() and init.size() == 2 and (*init.begin())->is_string())
11836  {
11837  basic_json&& key = init.begin()->moved_or_copied();
11838  push_back(typename object_t::value_type(
11839  std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
11840  }
11841  else
11842  {
11843  push_back(basic_json(init));
11844  }
11845  }
11846 
11847  /*!
11848  @brief add an object to an object
11849  @copydoc push_back(initializer_list_t)
11850  */
11851  reference operator+=(initializer_list_t init)
11852  {
11853  push_back(init);
11854  return *this;
11855  }
11856 
11857  /*!
11858  @brief add an object to an array
11859 
11860  Creates a JSON value from the passed parameters @a args to the end of the
11861  JSON value. If the function is called on a JSON null value, an empty array
11862  is created before appending the value created from @a args.
11863 
11864  @param[in] args arguments to forward to a constructor of @ref basic_json
11865  @tparam Args compatible types to create a @ref basic_json object
11867  @throw type_error.311 when called on a type other than JSON array or
11868  null; example: `"cannot use emplace_back() with number"`
11869 
11870  @complexity Amortized constant.
11871 
11872  @liveexample{The example shows how `push_back()` can be used to add
11873  elements to a JSON array. Note how the `null` value was silently converted
11874  to a JSON array.,emplace_back}
11875 
11876  @since version 2.0.8
11877  */
11878  template<class... Args>
11879  void emplace_back(Args&& ... args)
11880  {
11881  // emplace_back only works for null objects or arrays
11882  if (JSON_UNLIKELY(not(is_null() or is_array())))
11883  {
11884  JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
11885  }
11886 
11887  // transform null object into an array
11888  if (is_null())
11889  {
11890  m_type = value_t::array;
11891  m_value = value_t::array;
11892  assert_invariant();
11893  }
11895  // add element to array (perfect forwarding)
11896  m_value.array->emplace_back(std::forward<Args>(args)...);
11897  }
11898 
11899  /*!
11900  @brief add an object to an object if key does not exist
11901 
11902  Inserts a new element into a JSON object constructed in-place with the
11903  given @a args if there is no element with the key in the container. If the
11904  function is called on a JSON null value, an empty object is created before
11905  appending the value created from @a args.
11906 
11907  @param[in] args arguments to forward to a constructor of @ref basic_json
11908  @tparam Args compatible types to create a @ref basic_json object
11909 
11910  @return a pair consisting of an iterator to the inserted element, or the
11911  already-existing element if no insertion happened, and a bool
11912  denoting whether the insertion took place.
11913 
11914  @throw type_error.311 when called on a type other than JSON object or
11915  null; example: `"cannot use emplace() with number"`
11916 
11917  @complexity Logarithmic in the size of the container, O(log(`size()`)).
11918 
11919  @liveexample{The example shows how `emplace()` can be used to add elements
11920  to a JSON object. Note how the `null` value was silently converted to a
11921  JSON object. Further note how no value is added if there was already one
11922  value stored with the same key.,emplace}
11923 
11924  @since version 2.0.8
11925  */
11926  template<class... Args>
11927  std::pair<iterator, bool> emplace(Args&& ... args)
11928  {
11929  // emplace only works for null objects or arrays
11930  if (JSON_UNLIKELY(not(is_null() or is_object())))
11931  {
11932  JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
11933  }
11934 
11935  // transform null object into an object
11936  if (is_null())
11937  {
11938  m_type = value_t::object;
11939  m_value = value_t::object;
11940  assert_invariant();
11941  }
11943  // add element to array (perfect forwarding)
11944  auto res = m_value.object->emplace(std::forward<Args>(args)...);
11945  // create result iterator and set iterator to the result of emplace
11946  auto it = begin();
11947  it.m_it.object_iterator = res.first;
11948 
11949  // return pair of iterator and boolean
11950  return {it, res.second};
11951  }
11952 
11953  /*!
11954  @brief inserts element
11955 
11956  Inserts element @a val before iterator @a pos.
11957 
11958  @param[in] pos iterator before which the content will be inserted; may be
11959  the end() iterator
11960  @param[in] val element to insert
11961  @return iterator pointing to the inserted @a val.
11962 
11963  @throw type_error.309 if called on JSON values other than arrays;
11964  example: `"cannot use insert() with string"`
11965  @throw invalid_iterator.202 if @a pos is not an iterator of *this;
11966  example: `"iterator does not fit current value"`
11967 
11968  @complexity Constant plus linear in the distance between @a pos and end of
11969  the container.
11970 
11971  @liveexample{The example shows how `insert()` is used.,insert}
11972 
11973  @since version 1.0.0
11974  */
11975  iterator insert(const_iterator pos, const basic_json& val)
11976  {
11977  // insert only works for arrays
11978  if (JSON_LIKELY(is_array()))
11979  {
11980  // check if iterator pos fits to this JSON value
11981  if (JSON_UNLIKELY(pos.m_object != this))
11982  {
11983  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
11984  }
11985 
11986  // insert to array and return iterator
11987  iterator result(this);
11988  result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
11989  return result;
11990  }
11991 
11992  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
11993  }
11994 
11995  /*!
11996  @brief inserts element
11997  @copydoc insert(const_iterator, const basic_json&)
11998  */
11999  iterator insert(const_iterator pos, basic_json&& val)
12000  {
12001  return insert(pos, val);
12002  }
12003 
12004  /*!
12005  @brief inserts elements
12006 
12007  Inserts @a cnt copies of @a val before iterator @a pos.
12008 
12009  @param[in] pos iterator before which the content will be inserted; may be
12010  the end() iterator
12011  @param[in] cnt number of copies of @a val to insert
12012  @param[in] val element to insert
12013  @return iterator pointing to the first element inserted, or @a pos if
12014  `cnt==0`
12015 
12016  @throw type_error.309 if called on JSON values other than arrays; example:
12017  `"cannot use insert() with string"`
12018  @throw invalid_iterator.202 if @a pos is not an iterator of *this;
12019  example: `"iterator does not fit current value"`
12020 
12021  @complexity Linear in @a cnt plus linear in the distance between @a pos
12022  and end of the container.
12023 
12024  @liveexample{The example shows how `insert()` is used.,insert__count}
12025 
12026  @since version 1.0.0
12027  */
12028  iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
12029  {
12030  // insert only works for arrays
12031  if (JSON_LIKELY(is_array()))
12032  {
12033  // check if iterator pos fits to this JSON value
12034  if (JSON_UNLIKELY(pos.m_object != this))
12035  {
12036  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
12037  }
12038 
12039  // insert to array and return iterator
12040  iterator result(this);
12041  result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
12042  return result;
12043  }
12044 
12045  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12046  }
12047 
12048  /*!
12049  @brief inserts elements
12050 
12051  Inserts elements from range `[first, last)` before iterator @a pos.
12052 
12053  @param[in] pos iterator before which the content will be inserted; may be
12054  the end() iterator
12055  @param[in] first begin of the range of elements to insert
12056  @param[in] last end of the range of elements to insert
12057 
12058  @throw type_error.309 if called on JSON values other than arrays; example:
12059  `"cannot use insert() with string"`
12060  @throw invalid_iterator.202 if @a pos is not an iterator of *this;
12061  example: `"iterator does not fit current value"`
12062  @throw invalid_iterator.210 if @a first and @a last do not belong to the
12063  same JSON value; example: `"iterators do not fit"`
12064  @throw invalid_iterator.211 if @a first or @a last are iterators into
12065  container for which insert is called; example: `"passed iterators may not
12066  belong to container"`
12067 
12068  @return iterator pointing to the first element inserted, or @a pos if
12069  `first==last`
12070 
12071  @complexity Linear in `std::distance(first, last)` plus linear in the
12072  distance between @a pos and end of the container.
12073 
12074  @liveexample{The example shows how `insert()` is used.,insert__range}
12075 
12076  @since version 1.0.0
12077  */
12078  iterator insert(const_iterator pos, const_iterator first, const_iterator last)
12079  {
12080  // insert only works for arrays
12081  if (JSON_UNLIKELY(not is_array()))
12082  {
12083  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12084  }
12085 
12086  // check if iterator pos fits to this JSON value
12087  if (JSON_UNLIKELY(pos.m_object != this))
12088  {
12089  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
12090  }
12091 
12092  // check if range iterators belong to the same JSON object
12093  if (JSON_UNLIKELY(first.m_object != last.m_object))
12094  {
12095  JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
12096  }
12097 
12098  if (JSON_UNLIKELY(first.m_object == this))
12099  {
12100  JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
12101  }
12102 
12103  // insert to array and return iterator
12104  iterator result(this);
12105  result.m_it.array_iterator = m_value.array->insert(
12106  pos.m_it.array_iterator,
12107  first.m_it.array_iterator,
12108  last.m_it.array_iterator);
12109  return result;
12110  }
12111 
12112  /*!
12113  @brief inserts elements
12114 
12115  Inserts elements from initializer list @a ilist before iterator @a pos.
12116 
12117  @param[in] pos iterator before which the content will be inserted; may be
12118  the end() iterator
12119  @param[in] ilist initializer list to insert the values from
12120 
12121  @throw type_error.309 if called on JSON values other than arrays; example:
12122  `"cannot use insert() with string"`
12123  @throw invalid_iterator.202 if @a pos is not an iterator of *this;
12124  example: `"iterator does not fit current value"`
12125 
12126  @return iterator pointing to the first element inserted, or @a pos if
12127  `ilist` is empty
12128 
12129  @complexity Linear in `ilist.size()` plus linear in the distance between
12130  @a pos and end of the container.
12131 
12132  @liveexample{The example shows how `insert()` is used.,insert__ilist}
12133 
12134  @since version 1.0.0
12135  */
12136  iterator insert(const_iterator pos, initializer_list_t ilist)
12137  {
12138  // insert only works for arrays
12139  if (JSON_UNLIKELY(not is_array()))
12140  {
12141  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12142  }
12143 
12144  // check if iterator pos fits to this JSON value
12145  if (JSON_UNLIKELY(pos.m_object != this))
12146  {
12147  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
12148  }
12149 
12150  // insert to array and return iterator
12151  iterator result(this);
12152  result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end());
12153  return result;
12154  }
12155 
12156  /*!
12157  @brief inserts elements
12158 
12159  Inserts elements from range `[first, last)`.
12160 
12161  @param[in] first begin of the range of elements to insert
12162  @param[in] last end of the range of elements to insert
12163 
12164  @throw type_error.309 if called on JSON values other than objects; example:
12165  `"cannot use insert() with string"`
12166  @throw invalid_iterator.202 if iterator @a first or @a last does does not
12167  point to an object; example: `"iterators first and last must point to
12168  objects"`
12169  @throw invalid_iterator.210 if @a first and @a last do not belong to the
12170  same JSON value; example: `"iterators do not fit"`
12171 
12172  @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
12173  of elements to insert.
12174 
12175  @liveexample{The example shows how `insert()` is used.,insert__range_object}
12176 
12177  @since version 3.0.0
12178  */
12179  void insert(const_iterator first, const_iterator last)
12180  {
12181  // insert only works for objects
12182  if (JSON_UNLIKELY(not is_object()))
12183  {
12184  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12185  }
12186 
12187  // check if range iterators belong to the same JSON object
12188  if (JSON_UNLIKELY(first.m_object != last.m_object))
12189  {
12190  JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
12191  }
12192 
12193  // passed iterators must belong to objects
12194  if (JSON_UNLIKELY(not first.m_object->is_object()))
12195  {
12196  JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
12197  }
12198 
12199  m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
12200  }
12201 
12202  /*!
12203  @brief updates a JSON object from another object, overwriting existing keys
12204 
12205  Inserts all values from JSON object @a j and overwrites existing keys.
12206 
12207  @param[in] j JSON object to read values from
12208 
12209  @throw type_error.312 if called on JSON values other than objects; example:
12210  `"cannot use update() with string"`
12211 
12212  @complexity O(N*log(size() + N)), where N is the number of elements to
12213  insert.
12214 
12215  @liveexample{The example shows how `update()` is used.,update}
12216 
12217  @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
12218 
12219  @since version 3.0.0
12220  */
12221  void update(const_reference j)
12222  {
12223  // implicitly convert null value to an empty object
12224  if (is_null())
12225  {
12226  m_type = value_t::object;
12227  m_value.object = create<object_t>();
12228  assert_invariant();
12229  }
12230 
12231  if (JSON_UNLIKELY(not is_object()))
12232  {
12233  JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
12234  }
12235  if (JSON_UNLIKELY(not j.is_object()))
12236  {
12237  JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
12238  }
12239 
12240  for (auto it = j.begin(); it != j.end(); ++it)
12241  {
12242  m_value.object->operator[](it.key()) = it.value();
12243  }
12244  }
12245 
12246  /*!
12247  @brief updates a JSON object from another object, overwriting existing keys
12248 
12249  Inserts all values from from range `[first, last)` and overwrites existing
12250  keys.
12251 
12252  @param[in] first begin of the range of elements to insert
12253  @param[in] last end of the range of elements to insert
12254 
12255  @throw type_error.312 if called on JSON values other than objects; example:
12256  `"cannot use update() with string"`
12257  @throw invalid_iterator.202 if iterator @a first or @a last does does not
12258  point to an object; example: `"iterators first and last must point to
12259  objects"`
12260  @throw invalid_iterator.210 if @a first and @a last do not belong to the
12261  same JSON value; example: `"iterators do not fit"`
12262 
12263  @complexity O(N*log(size() + N)), where N is the number of elements to
12264  insert.
12265 
12266  @liveexample{The example shows how `update()` is used__range.,update}
12267 
12268  @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
12269 
12270  @since version 3.0.0
12271  */
12272  void update(const_iterator first, const_iterator last)
12273  {
12274  // implicitly convert null value to an empty object
12275  if (is_null())
12276  {
12277  m_type = value_t::object;
12278  m_value.object = create<object_t>();
12279  assert_invariant();
12280  }
12281 
12282  if (JSON_UNLIKELY(not is_object()))
12283  {
12284  JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
12285  }
12286 
12287  // check if range iterators belong to the same JSON object
12288  if (JSON_UNLIKELY(first.m_object != last.m_object))
12289  {
12290  JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
12291  }
12292 
12293  // passed iterators must belong to objects
12294  if (JSON_UNLIKELY(not first.m_object->is_object()
12295  or not first.m_object->is_object()))
12296  {
12297  JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
12298  }
12299 
12300  for (auto it = first; it != last; ++it)
12301  {
12302  m_value.object->operator[](it.key()) = it.value();
12303  }
12304  }
12305 
12306  /*!
12307  @brief exchanges the values
12308 
12309  Exchanges the contents of the JSON value with those of @a other. Does not
12310  invoke any move, copy, or swap operations on individual elements. All
12311  iterators and references remain valid. The past-the-end iterator is
12312  invalidated.
12313 
12314  @param[in,out] other JSON value to exchange the contents with
12315 
12316  @complexity Constant.
12317 
12318  @liveexample{The example below shows how JSON values can be swapped with
12319  `swap()`.,swap__reference}
12320 
12321  @since version 1.0.0
12322  */
12323  void swap(reference other) noexcept (
12324  std::is_nothrow_move_constructible<value_t>::value and
12325  std::is_nothrow_move_assignable<value_t>::value and
12326  std::is_nothrow_move_constructible<json_value>::value and
12327  std::is_nothrow_move_assignable<json_value>::value
12328  )
12329  {
12330  std::swap(m_type, other.m_type);
12331  std::swap(m_value, other.m_value);
12332  assert_invariant();
12333  }
12334 
12335  /*!
12336  @brief exchanges the values
12337 
12338  Exchanges the contents of a JSON array with those of @a other. Does not
12339  invoke any move, copy, or swap operations on individual elements. All
12340  iterators and references remain valid. The past-the-end iterator is
12341  invalidated.
12342 
12343  @param[in,out] other array to exchange the contents with
12344 
12345  @throw type_error.310 when JSON value is not an array; example: `"cannot
12346  use swap() with string"`
12347 
12348  @complexity Constant.
12349 
12350  @liveexample{The example below shows how arrays can be swapped with
12351  `swap()`.,swap__array_t}
12352 
12353  @since version 1.0.0
12354  */
12355  void swap(array_t& other)
12356  {
12357  // swap only works for arrays
12358  if (JSON_LIKELY(is_array()))
12359  {
12360  std::swap(*(m_value.array), other);
12361  }
12362  else
12363  {
12364  JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
12365  }
12366  }
12367 
12368  /*!
12369  @brief exchanges the values
12371  Exchanges the contents of a JSON object with those of @a other. Does not
12372  invoke any move, copy, or swap operations on individual elements. All
12373  iterators and references remain valid. The past-the-end iterator is
12374  invalidated.
12375 
12376  @param[in,out] other object to exchange the contents with
12377 
12378  @throw type_error.310 when JSON value is not an object; example:
12379  `"cannot use swap() with string"`
12380 
12381  @complexity Constant.
12382 
12383  @liveexample{The example below shows how objects can be swapped with
12384  `swap()`.,swap__object_t}
12385 
12386  @since version 1.0.0
12387  */
12388  void swap(object_t& other)
12389  {
12390  // swap only works for objects
12391  if (JSON_LIKELY(is_object()))
12392  {
12393  std::swap(*(m_value.object), other);
12394  }
12395  else
12396  {
12397  JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
12398  }
12399  }
12400 
12401  /*!
12402  @brief exchanges the values
12404  Exchanges the contents of a JSON string with those of @a other. Does not
12405  invoke any move, copy, or swap operations on individual elements. All
12406  iterators and references remain valid. The past-the-end iterator is
12407  invalidated.
12408 
12409  @param[in,out] other string to exchange the contents with
12410 
12411  @throw type_error.310 when JSON value is not a string; example: `"cannot
12412  use swap() with boolean"`
12413 
12414  @complexity Constant.
12415 
12416  @liveexample{The example below shows how strings can be swapped with
12417  `swap()`.,swap__string_t}
12418 
12419  @since version 1.0.0
12420  */
12421  void swap(string_t& other)
12422  {
12423  // swap only works for strings
12424  if (JSON_LIKELY(is_string()))
12425  {
12426  std::swap(*(m_value.string), other);
12427  }
12428  else
12429  {
12430  JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
12431  }
12432  }
12433 
12434  /// @}
12435 
12436  public:
12437  //////////////////////////////////////////
12438  // lexicographical comparison operators //
12439  //////////////////////////////////////////
12440 
12441  /// @name lexicographical comparison operators
12442  /// @{
12443 
12444  /*!
12445  @brief comparison: equal
12446 
12447  Compares two JSON values for equality according to the following rules:
12448  - Two JSON values are equal if (1) they are from the same type and (2)
12449  their stored values are the same according to their respective
12450  `operator==`.
12451  - Integer and floating-point numbers are automatically converted before
12452  comparison. Note than two NaN values are always treated as unequal.
12453  - Two JSON null values are equal.
12454 
12455  @note Floating-point inside JSON values numbers are compared with
12456  `json::number_float_t::operator==` which is `double::operator==` by
12457  default. To compare floating-point while respecting an epsilon, an alternative
12458  [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
12459  could be used, for instance
12460  @code {.cpp}
12461  template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
12462  inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
12463  {
12464  return std::abs(a - b) <= epsilon;
12465  }
12466  @endcode
12467 
12468  @note NaN values never compare equal to themselves or to other NaN values.
12469 
12470  @param[in] lhs first JSON value to consider
12471  @param[in] rhs second JSON value to consider
12472  @return whether the values @a lhs and @a rhs are equal
12473 
12474  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12475 
12476  @complexity Linear.
12477 
12478  @liveexample{The example demonstrates comparing several JSON
12479  types.,operator__equal}
12480 
12481  @since version 1.0.0
12482  */
12483  friend bool operator==(const_reference lhs, const_reference rhs) noexcept
12484  {
12485  const auto lhs_type = lhs.type();
12486  const auto rhs_type = rhs.type();
12487 
12488  if (lhs_type == rhs_type)
12489  {
12490  switch (lhs_type)
12491  {
12492  case value_t::array:
12493  return (*lhs.m_value.array == *rhs.m_value.array);
12494 
12495  case value_t::object:
12496  return (*lhs.m_value.object == *rhs.m_value.object);
12497 
12498  case value_t::null:
12499  return true;
12500 
12501  case value_t::string:
12502  return (*lhs.m_value.string == *rhs.m_value.string);
12503 
12504  case value_t::boolean:
12505  return (lhs.m_value.boolean == rhs.m_value.boolean);
12506 
12507  case value_t::number_integer:
12508  return (lhs.m_value.number_integer == rhs.m_value.number_integer);
12509 
12510  case value_t::number_unsigned:
12511  return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned);
12512 
12513  case value_t::number_float:
12514  return (lhs.m_value.number_float == rhs.m_value.number_float);
12515 
12516  default:
12517  return false;
12518  }
12519  }
12520  else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
12521  {
12522  return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float);
12523  }
12524  else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
12525  {
12526  return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer));
12527  }
12528  else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
12529  {
12530  return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float);
12531  }
12532  else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
12533  {
12534  return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned));
12535  }
12536  else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
12537  {
12538  return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer);
12539  }
12540  else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
12541  {
12542  return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned));
12543  }
12544 
12545  return false;
12546  }
12547 
12548  /*!
12549  @brief comparison: equal
12550  @copydoc operator==(const_reference, const_reference)
12551  */
12552  template<typename ScalarType, typename std::enable_if<
12553  std::is_scalar<ScalarType>::value, int>::type = 0>
12554  friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
12555  {
12556  return (lhs == basic_json(rhs));
12557  }
12558 
12559  /*!
12560  @brief comparison: equal
12561  @copydoc operator==(const_reference, const_reference)
12562  */
12563  template<typename ScalarType, typename std::enable_if<
12564  std::is_scalar<ScalarType>::value, int>::type = 0>
12565  friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
12566  {
12567  return (basic_json(lhs) == rhs);
12568  }
12570  /*!
12571  @brief comparison: not equal
12572 
12573  Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
12574 
12575  @param[in] lhs first JSON value to consider
12576  @param[in] rhs second JSON value to consider
12577  @return whether the values @a lhs and @a rhs are not equal
12578 
12579  @complexity Linear.
12581  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12582 
12583  @liveexample{The example demonstrates comparing several JSON
12584  types.,operator__notequal}
12585 
12586  @since version 1.0.0
12587  */
12588  friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
12589  {
12590  return not (lhs == rhs);
12591  }
12592 
12593  /*!
12594  @brief comparison: not equal
12595  @copydoc operator!=(const_reference, const_reference)
12596  */
12597  template<typename ScalarType, typename std::enable_if<
12598  std::is_scalar<ScalarType>::value, int>::type = 0>
12599  friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
12600  {
12601  return (lhs != basic_json(rhs));
12602  }
12604  /*!
12605  @brief comparison: not equal
12606  @copydoc operator!=(const_reference, const_reference)
12607  */
12608  template<typename ScalarType, typename std::enable_if<
12609  std::is_scalar<ScalarType>::value, int>::type = 0>
12610  friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
12611  {
12612  return (basic_json(lhs) != rhs);
12613  }
12615  /*!
12616  @brief comparison: less than
12617 
12618  Compares whether one JSON value @a lhs is less than another JSON value @a
12619  rhs according to the following rules:
12620  - If @a lhs and @a rhs have the same type, the values are compared using
12621  the default `<` operator.
12622  - Integer and floating-point numbers are automatically converted before
12623  comparison
12624  - In case @a lhs and @a rhs have different types, the values are ignored
12625  and the order of the types is considered, see
12626  @ref operator<(const value_t, const value_t).
12627 
12628  @param[in] lhs first JSON value to consider
12629  @param[in] rhs second JSON value to consider
12630  @return whether @a lhs is less than @a rhs
12631 
12632  @complexity Linear.
12633 
12634  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12635 
12636  @liveexample{The example demonstrates comparing several JSON
12637  types.,operator__less}
12638 
12639  @since version 1.0.0
12640  */
12641  friend bool operator<(const_reference lhs, const_reference rhs) noexcept
12642  {
12643  const auto lhs_type = lhs.type();
12644  const auto rhs_type = rhs.type();
12645 
12646  if (lhs_type == rhs_type)
12647  {
12648  switch (lhs_type)
12649  {
12650  case value_t::array:
12651  return (*lhs.m_value.array) < (*rhs.m_value.array);
12652 
12653  case value_t::object:
12654  return *lhs.m_value.object < *rhs.m_value.object;
12655 
12656  case value_t::null:
12657  return false;
12658 
12659  case value_t::string:
12660  return *lhs.m_value.string < *rhs.m_value.string;
12661 
12662  case value_t::boolean:
12663  return lhs.m_value.boolean < rhs.m_value.boolean;
12664 
12665  case value_t::number_integer:
12666  return lhs.m_value.number_integer < rhs.m_value.number_integer;
12667 
12668  case value_t::number_unsigned:
12669  return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
12670 
12671  case value_t::number_float:
12672  return lhs.m_value.number_float < rhs.m_value.number_float;
12673 
12674  default:
12675  return false;
12676  }
12677  }
12678  else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
12679  {
12680  return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
12681  }
12682  else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
12683  {
12684  return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
12685  }
12686  else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
12687  {
12688  return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
12689  }
12690  else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
12691  {
12692  return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
12693  }
12694  else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
12695  {
12696  return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
12697  }
12698  else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
12699  {
12700  return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
12701  }
12702 
12703  // We only reach this line if we cannot compare values. In that case,
12704  // we compare types. Note we have to call the operator explicitly,
12705  // because MSVC has problems otherwise.
12706  return operator<(lhs_type, rhs_type);
12707  }
12708 
12709  /*!
12710  @brief comparison: less than
12711  @copydoc operator<(const_reference, const_reference)
12712  */
12713  template<typename ScalarType, typename std::enable_if<
12714  std::is_scalar<ScalarType>::value, int>::type = 0>
12715  friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
12716  {
12717  return (lhs < basic_json(rhs));
12718  }
12719 
12720  /*!
12721  @brief comparison: less than
12722  @copydoc operator<(const_reference, const_reference)
12723  */
12724  template<typename ScalarType, typename std::enable_if<
12725  std::is_scalar<ScalarType>::value, int>::type = 0>
12726  friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
12727  {
12728  return (basic_json(lhs) < rhs);
12729  }
12731  /*!
12732  @brief comparison: less than or equal
12733 
12734  Compares whether one JSON value @a lhs is less than or equal to another
12735  JSON value by calculating `not (rhs < lhs)`.
12736 
12737  @param[in] lhs first JSON value to consider
12738  @param[in] rhs second JSON value to consider
12739  @return whether @a lhs is less than or equal to @a rhs
12740 
12741  @complexity Linear.
12742 
12743  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12744 
12745  @liveexample{The example demonstrates comparing several JSON
12746  types.,operator__greater}
12747 
12748  @since version 1.0.0
12749  */
12750  friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
12751  {
12752  return not (rhs < lhs);
12753  }
12754 
12755  /*!
12756  @brief comparison: less than or equal
12757  @copydoc operator<=(const_reference, const_reference)
12758  */
12759  template<typename ScalarType, typename std::enable_if<
12760  std::is_scalar<ScalarType>::value, int>::type = 0>
12761  friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
12762  {
12763  return (lhs <= basic_json(rhs));
12764  }
12766  /*!
12767  @brief comparison: less than or equal
12768  @copydoc operator<=(const_reference, const_reference)
12769  */
12770  template<typename ScalarType, typename std::enable_if<
12771  std::is_scalar<ScalarType>::value, int>::type = 0>
12772  friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
12773  {
12774  return (basic_json(lhs) <= rhs);
12775  }
12777  /*!
12778  @brief comparison: greater than
12779 
12780  Compares whether one JSON value @a lhs is greater than another
12781  JSON value by calculating `not (lhs <= rhs)`.
12782 
12783  @param[in] lhs first JSON value to consider
12784  @param[in] rhs second JSON value to consider
12785  @return whether @a lhs is greater than to @a rhs
12786 
12787  @complexity Linear.
12788 
12789  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12790 
12791  @liveexample{The example demonstrates comparing several JSON
12792  types.,operator__lessequal}
12793 
12794  @since version 1.0.0
12795  */
12796  friend bool operator>(const_reference lhs, const_reference rhs) noexcept
12797  {
12798  return not (lhs <= rhs);
12799  }
12800 
12801  /*!
12802  @brief comparison: greater than
12803  @copydoc operator>(const_reference, const_reference)
12804  */
12805  template<typename ScalarType, typename std::enable_if<
12806  std::is_scalar<ScalarType>::value, int>::type = 0>
12807  friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
12808  {
12809  return (lhs > basic_json(rhs));
12810  }
12812  /*!
12813  @brief comparison: greater than
12814  @copydoc operator>(const_reference, const_reference)
12815  */
12816  template<typename ScalarType, typename std::enable_if<
12817  std::is_scalar<ScalarType>::value, int>::type = 0>
12818  friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
12819  {
12820  return (basic_json(lhs) > rhs);
12821  }
12823  /*!
12824  @brief comparison: greater than or equal
12825 
12826  Compares whether one JSON value @a lhs is greater than or equal to another
12827  JSON value by calculating `not (lhs < rhs)`.
12828 
12829  @param[in] lhs first JSON value to consider
12830  @param[in] rhs second JSON value to consider
12831  @return whether @a lhs is greater than or equal to @a rhs
12832 
12833  @complexity Linear.
12834 
12835  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12836 
12837  @liveexample{The example demonstrates comparing several JSON
12838  types.,operator__greaterequal}
12839 
12840  @since version 1.0.0
12841  */
12842  friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
12843  {
12844  return not (lhs < rhs);
12845  }
12846 
12847  /*!
12848  @brief comparison: greater than or equal
12849  @copydoc operator>=(const_reference, const_reference)
12850  */
12851  template<typename ScalarType, typename std::enable_if<
12852  std::is_scalar<ScalarType>::value, int>::type = 0>
12853  friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
12854  {
12855  return (lhs >= basic_json(rhs));
12856  }
12858  /*!
12859  @brief comparison: greater than or equal
12860  @copydoc operator>=(const_reference, const_reference)
12861  */
12862  template<typename ScalarType, typename std::enable_if<
12863  std::is_scalar<ScalarType>::value, int>::type = 0>
12864  friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
12865  {
12866  return (basic_json(lhs) >= rhs);
12867  }
12869  /// @}
12870 
12871  ///////////////////
12872  // serialization //
12873  ///////////////////
12874 
12875  /// @name serialization
12876  /// @{
12877 
12878  /*!
12879  @brief serialize to stream
12880 
12881  Serialize the given JSON value @a j to the output stream @a o. The JSON
12882  value will be serialized using the @ref dump member function.
12883 
12884  - The indentation of the output can be controlled with the member variable
12885  `width` of the output stream @a o. For instance, using the manipulator
12886  `std::setw(4)` on @a o sets the indentation level to `4` and the
12887  serialization result is the same as calling `dump(4)`.
12888 
12889  - The indentation character can be controlled with the member variable
12890  `fill` of the output stream @a o. For instance, the manipulator
12891  `std::setfill('\\t')` sets indentation to use a tab character rather than
12892  the default space character.
12893 
12894  @param[in,out] o stream to serialize to
12895  @param[in] j JSON value to serialize
12896 
12897  @return the stream @a o
12898 
12899  @throw type_error.316 if a string stored inside the JSON value is not
12900  UTF-8 encoded
12901 
12902  @complexity Linear.
12903 
12904  @liveexample{The example below shows the serialization with different
12905  parameters to `width` to adjust the indentation level.,operator_serialize}
12906 
12907  @since version 1.0.0; indentation character added in version 3.0.0
12908  */
12909  friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
12910  {
12911  // read width member and use it as indentation parameter if nonzero
12912  const bool pretty_print = (o.width() > 0);
12913  const auto indentation = (pretty_print ? o.width() : 0);
12914 
12915  // reset width to 0 for subsequent calls to this stream
12916  o.width(0);
12917 
12918  // do the actual serialization
12919  serializer s(detail::output_adapter<char>(o), o.fill());
12920  s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
12921  return o;
12922  }
12923 
12924  /*!
12925  @brief serialize to stream
12926  @deprecated This stream operator is deprecated and will be removed in a
12927  future version of the library. Please use
12928  @ref operator<<(std::ostream&, const basic_json&)
12929  instead; that is, replace calls like `j >> o;` with `o << j;`.
12930  @since version 1.0.0; deprecated since version 3.0.0
12931  */
12933  friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
12934  {
12935  return o << j;
12936  }
12937 
12938  /// @}
12939 
12940 
12941  /////////////////////
12942  // deserialization //
12943  /////////////////////
12944 
12945  /// @name deserialization
12946  /// @{
12947 
12948  /*!
12949  @brief deserialize from a compatible input
12950 
12951  This function reads from a compatible input. Examples are:
12952  - an array of 1-byte values
12953  - strings with character/literal type with size of 1 byte
12954  - input streams
12955  - container with contiguous storage of 1-byte values. Compatible container
12956  types include `std::vector`, `std::string`, `std::array`,
12957  `std::valarray`, and `std::initializer_list`. Furthermore, C-style
12958  arrays can be used with `std::begin()`/`std::end()`. User-defined
12959  containers can be used as long as they implement random-access iterators
12960  and a contiguous storage.
12961 
12962  @pre Each element of the container has a size of 1 byte. Violating this
12963  precondition yields undefined behavior. **This precondition is enforced
12964  with a static assertion.**
12965 
12966  @pre The container storage is contiguous. Violating this precondition
12967  yields undefined behavior. **This precondition is enforced with an
12968  assertion.**
12969  @pre Each element of the container has a size of 1 byte. Violating this
12970  precondition yields undefined behavior. **This precondition is enforced
12971  with a static assertion.**
12972 
12973  @warning There is no way to enforce all preconditions at compile-time. If
12974  the function is called with a noncompliant container and with
12975  assertions switched off, the behavior is undefined and will most
12976  likely yield segmentation violation.
12977 
12978  @param[in] i input to read from
12979  @param[in] cb a parser callback function of type @ref parser_callback_t
12980  which is used to control the deserialization by filtering unwanted values
12981  (optional)
12982 
12983  @return result of the deserialization
12984 
12985  @throw parse_error.101 if a parse error occurs; example: `""unexpected end
12986  of input; expected string literal""`
12987  @throw parse_error.102 if to_unicode fails or surrogate error
12988  @throw parse_error.103 if to_unicode fails
12989 
12990  @complexity Linear in the length of the input. The parser is a predictive
12991  LL(1) parser. The complexity can be higher if the parser callback function
12992  @a cb has a super-linear complexity.
12993 
12994  @note A UTF-8 byte order mark is silently ignored.
12995 
12996  @liveexample{The example below demonstrates the `parse()` function reading
12997  from an array.,parse__array__parser_callback_t}
12998 
12999  @liveexample{The example below demonstrates the `parse()` function with
13000  and without callback function.,parse__string__parser_callback_t}
13001 
13002  @liveexample{The example below demonstrates the `parse()` function with
13003  and without callback function.,parse__istream__parser_callback_t}
13004 
13005  @liveexample{The example below demonstrates the `parse()` function reading
13006  from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
13007 
13008  @since version 2.0.3 (contiguous containers)
13009  */
13010  static basic_json parse(detail::input_adapter i,
13011  const parser_callback_t cb = nullptr,
13012  const bool allow_exceptions = true)
13013  {
13014  basic_json result;
13015  parser(i, cb, allow_exceptions).parse(true, result);
13016  return result;
13017  }
13018 
13019  /*!
13020  @copydoc basic_json parse(detail::input_adapter, const parser_callback_t)
13021  */
13022  static basic_json parse(detail::input_adapter& i,
13023  const parser_callback_t cb = nullptr,
13024  const bool allow_exceptions = true)
13025  {
13026  basic_json result;
13027  parser(i, cb, allow_exceptions).parse(true, result);
13028  return result;
13029  }
13030 
13031  static bool accept(detail::input_adapter i)
13032  {
13033  return parser(i).accept(true);
13034  }
13035 
13036  static bool accept(detail::input_adapter& i)
13037  {
13038  return parser(i).accept(true);
13039  }
13040 
13041  /*!
13042  @brief deserialize from an iterator range with contiguous storage
13043 
13044  This function reads from an iterator range of a container with contiguous
13045  storage of 1-byte values. Compatible container types include
13046  `std::vector`, `std::string`, `std::array`, `std::valarray`, and
13047  `std::initializer_list`. Furthermore, C-style arrays can be used with
13048  `std::begin()`/`std::end()`. User-defined containers can be used as long
13049  as they implement random-access iterators and a contiguous storage.
13050 
13051  @pre The iterator range is contiguous. Violating this precondition yields
13052  undefined behavior. **This precondition is enforced with an assertion.**
13053  @pre Each element in the range has a size of 1 byte. Violating this
13054  precondition yields undefined behavior. **This precondition is enforced
13055  with a static assertion.**
13056 
13057  @warning There is no way to enforce all preconditions at compile-time. If
13058  the function is called with noncompliant iterators and with
13059  assertions switched off, the behavior is undefined and will most
13060  likely yield segmentation violation.
13061 
13062  @tparam IteratorType iterator of container with contiguous storage
13063  @param[in] first begin of the range to parse (included)
13064  @param[in] last end of the range to parse (excluded)
13065  @param[in] cb a parser callback function of type @ref parser_callback_t
13066  which is used to control the deserialization by filtering unwanted values
13067  (optional)
13068  @param[in] allow_exceptions whether to throw exceptions in case of a
13069  parse error (optional, true by default)
13070 
13071  @return result of the deserialization
13072 
13073  @throw parse_error.101 in case of an unexpected token
13074  @throw parse_error.102 if to_unicode fails or surrogate error
13075  @throw parse_error.103 if to_unicode fails
13076 
13077  @complexity Linear in the length of the input. The parser is a predictive
13078  LL(1) parser. The complexity can be higher if the parser callback function
13079  @a cb has a super-linear complexity.
13080 
13081  @note A UTF-8 byte order mark is silently ignored.
13082 
13083  @liveexample{The example below demonstrates the `parse()` function reading
13084  from an iterator range.,parse__iteratortype__parser_callback_t}
13085 
13086  @since version 2.0.3
13087  */
13088  template<class IteratorType, typename std::enable_if<
13089  std::is_base_of<
13090  std::random_access_iterator_tag,
13091  typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
13092  static basic_json parse(IteratorType first, IteratorType last,
13093  const parser_callback_t cb = nullptr,
13094  const bool allow_exceptions = true)
13095  {
13096  basic_json result;
13097  parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
13098  return result;
13099  }
13100 
13101  template<class IteratorType, typename std::enable_if<
13102  std::is_base_of<
13103  std::random_access_iterator_tag,
13104  typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
13105  static bool accept(IteratorType first, IteratorType last)
13106  {
13107  return parser(detail::input_adapter(first, last)).accept(true);
13108  }
13109 
13110  /*!
13111  @brief deserialize from stream
13112  @deprecated This stream operator is deprecated and will be removed in a
13113  future version of the library. Please use
13114  @ref operator>>(std::istream&, basic_json&)
13115  instead; that is, replace calls like `j << i;` with `i >> j;`.
13116  @since version 1.0.0; deprecated since version 3.0.0
13117  */
13119  friend std::istream& operator<<(basic_json& j, std::istream& i)
13120  {
13121  return operator>>(i, j);
13122  }
13123 
13124  /*!
13125  @brief deserialize from stream
13126 
13127  Deserializes an input stream to a JSON value.
13128 
13129  @param[in,out] i input stream to read a serialized JSON value from
13130  @param[in,out] j JSON value to write the deserialized input to
13131 
13132  @throw parse_error.101 in case of an unexpected token
13133  @throw parse_error.102 if to_unicode fails or surrogate error
13134  @throw parse_error.103 if to_unicode fails
13135 
13136  @complexity Linear in the length of the input. The parser is a predictive
13137  LL(1) parser.
13138 
13139  @note A UTF-8 byte order mark is silently ignored.
13140 
13141  @liveexample{The example below shows how a JSON value is constructed by
13142  reading a serialization from a stream.,operator_deserialize}
13143 
13144  @sa parse(std::istream&, const parser_callback_t) for a variant with a
13145  parser callback function to filter values while parsing
13146 
13147  @since version 1.0.0
13148  */
13149  friend std::istream& operator>>(std::istream& i, basic_json& j)
13150  {
13151  parser(detail::input_adapter(i)).parse(false, j);
13152  return i;
13153  }
13154 
13155  /// @}
13156 
13157  ///////////////////////////
13158  // convenience functions //
13159  ///////////////////////////
13160 
13161  /*!
13162  @brief return the type as string
13163 
13164  Returns the type name as string to be used in error messages - usually to
13165  indicate that a function was called on a wrong JSON type.
13166 
13167  @return a string representation of a the @a m_type member:
13168  Value type | return value
13169  ----------- | -------------
13170  null | `"null"`
13171  boolean | `"boolean"`
13172  string | `"string"`
13173  number | `"number"` (for all number types)
13174  object | `"object"`
13175  array | `"array"`
13176  discarded | `"discarded"`
13177 
13178  @exceptionsafety No-throw guarantee: this function never throws exceptions.
13179 
13180  @complexity Constant.
13181 
13182  @liveexample{The following code exemplifies `type_name()` for all JSON
13183  types.,type_name}
13184 
13185  @sa @ref type() -- return the type of the JSON value
13186  @sa @ref operator value_t() -- return the type of the JSON value (implicit)
13187 
13188  @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
13189  since 3.0.0
13190  */
13191  const char* type_name() const noexcept
13192  {
13193  {
13194  switch (m_type)
13195  {
13196  case value_t::null:
13197  return "null";
13198  case value_t::object:
13199  return "object";
13200  case value_t::array:
13201  return "array";
13202  case value_t::string:
13203  return "string";
13204  case value_t::boolean:
13205  return "boolean";
13206  case value_t::discarded:
13207  return "discarded";
13208  default:
13209  return "number";
13210  }
13211  }
13212  }
13213 
13214 
13215  private:
13216  //////////////////////
13217  // member variables //
13218  //////////////////////
13219 
13220  /// the type of the current element
13221  value_t m_type = value_t::null;
13222 
13223  /// the value of the current element
13224  json_value m_value = {};
13225 
13226  //////////////////////////////////////////
13227  // binary serialization/deserialization //
13228  //////////////////////////////////////////
13229 
13230  /// @name binary serialization/deserialization support
13231  /// @{
13232 
13233  public:
13234  /*!
13235  @brief create a CBOR serialization of a given JSON value
13236 
13237  Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
13238  Binary Object Representation) serialization format. CBOR is a binary
13239  serialization format which aims to be more compact than JSON itself, yet
13240  more efficient to parse.
13241 
13242  The library uses the following mapping from JSON values types to
13243  CBOR types according to the CBOR specification (RFC 7049):
13244 
13245  JSON value type | value/range | CBOR type | first byte
13246  --------------- | ------------------------------------------ | ---------------------------------- | ---------------
13247  null | `null` | Null | 0xF6
13248  boolean | `true` | True | 0xF5
13249  boolean | `false` | False | 0xF4
13250  number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
13251  number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
13252  number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
13253  number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
13254  number_integer | -24..-1 | Negative integer | 0x20..0x37
13255  number_integer | 0..23 | Integer | 0x00..0x17
13256  number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
13257  number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
13258  number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
13259  number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
13260  number_unsigned | 0..23 | Integer | 0x00..0x17
13261  number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
13262  number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
13263  number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
13264  number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
13265  number_float | *any value* | Double-Precision Float | 0xFB
13266  string | *length*: 0..23 | UTF-8 string | 0x60..0x77
13267  string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
13268  string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
13269  string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
13270  string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
13271  array | *size*: 0..23 | array | 0x80..0x97
13272  array | *size*: 23..255 | array (1 byte follow) | 0x98
13273  array | *size*: 256..65535 | array (2 bytes follow) | 0x99
13274  array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
13275  array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
13276  object | *size*: 0..23 | map | 0xA0..0xB7
13277  object | *size*: 23..255 | map (1 byte follow) | 0xB8
13278  object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
13279  object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
13280  object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
13281 
13282  @note The mapping is **complete** in the sense that any JSON value type
13283  can be converted to a CBOR value.
13284 
13285  @note If NaN or Infinity are stored inside a JSON number, they are
13286  serialized properly. This behavior differs from the @ref dump()
13287  function which serializes NaN or Infinity to `null`.
13288 
13289  @note The following CBOR types are not used in the conversion:
13290  - byte strings (0x40..0x5F)
13291  - UTF-8 strings terminated by "break" (0x7F)
13292  - arrays terminated by "break" (0x9F)
13293  - maps terminated by "break" (0xBF)
13294  - date/time (0xC0..0xC1)
13295  - bignum (0xC2..0xC3)
13296  - decimal fraction (0xC4)
13297  - bigfloat (0xC5)
13298  - tagged items (0xC6..0xD4, 0xD8..0xDB)
13299  - expected conversions (0xD5..0xD7)
13300  - simple values (0xE0..0xF3, 0xF8)
13301  - undefined (0xF7)
13302  - half and single-precision floats (0xF9-0xFA)
13303  - break (0xFF)
13304 
13305  @param[in] j JSON value to serialize
13306  @return MessagePack serialization as byte vector
13307 
13308  @complexity Linear in the size of the JSON value @a j.
13309 
13310  @liveexample{The example shows the serialization of a JSON value to a byte
13311  vector in CBOR format.,to_cbor}
13312 
13313  @sa http://cbor.io
13314  @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the
13315  analogous deserialization
13316  @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
13317 
13318  @since version 2.0.9
13319  */
13320  static std::vector<uint8_t> to_cbor(const basic_json& j)
13321  {
13322  std::vector<uint8_t> result;
13323  to_cbor(j, result);
13324  return result;
13325  }
13326 
13327  static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
13328  {
13329  binary_writer<uint8_t>(o).write_cbor(j);
13330  }
13331 
13332  static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
13333  {
13334  binary_writer<char>(o).write_cbor(j);
13335  }
13336 
13337  /*!
13338  @brief create a MessagePack serialization of a given JSON value
13339 
13340  Serializes a given JSON value @a j to a byte vector using the MessagePack
13341  serialization format. MessagePack is a binary serialization format which
13342  aims to be more compact than JSON itself, yet more efficient to parse.
13343 
13344  The library uses the following mapping from JSON values types to
13345  MessagePack types according to the MessagePack specification:
13346 
13347  JSON value type | value/range | MessagePack type | first byte
13348  --------------- | --------------------------------- | ---------------- | ----------
13349  null | `null` | nil | 0xC0
13350  boolean | `true` | true | 0xC3
13351  boolean | `false` | false | 0xC2
13352  number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
13353  number_integer | -2147483648..-32769 | int32 | 0xD2
13354  number_integer | -32768..-129 | int16 | 0xD1
13355  number_integer | -128..-33 | int8 | 0xD0
13356  number_integer | -32..-1 | negative fixint | 0xE0..0xFF
13357  number_integer | 0..127 | positive fixint | 0x00..0x7F
13358  number_integer | 128..255 | uint 8 | 0xCC
13359  number_integer | 256..65535 | uint 16 | 0xCD
13360  number_integer | 65536..4294967295 | uint 32 | 0xCE
13361  number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
13362  number_unsigned | 0..127 | positive fixint | 0x00..0x7F
13363  number_unsigned | 128..255 | uint 8 | 0xCC
13364  number_unsigned | 256..65535 | uint 16 | 0xCD
13365  number_unsigned | 65536..4294967295 | uint 32 | 0xCE
13366  number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
13367  number_float | *any value* | float 64 | 0xCB
13368  string | *length*: 0..31 | fixstr | 0xA0..0xBF
13369  string | *length*: 32..255 | str 8 | 0xD9
13370  string | *length*: 256..65535 | str 16 | 0xDA
13371  string | *length*: 65536..4294967295 | str 32 | 0xDB
13372  array | *size*: 0..15 | fixarray | 0x90..0x9F
13373  array | *size*: 16..65535 | array 16 | 0xDC
13374  array | *size*: 65536..4294967295 | array 32 | 0xDD
13375  object | *size*: 0..15 | fix map | 0x80..0x8F
13376  object | *size*: 16..65535 | map 16 | 0xDE
13377  object | *size*: 65536..4294967295 | map 32 | 0xDF
13378 
13379  @note The mapping is **complete** in the sense that any JSON value type
13380  can be converted to a MessagePack value.
13381 
13382  @note The following values can **not** be converted to a MessagePack value:
13383  - strings with more than 4294967295 bytes
13384  - arrays with more than 4294967295 elements
13385  - objects with more than 4294967295 elements
13386 
13387  @note The following MessagePack types are not used in the conversion:
13388  - bin 8 - bin 32 (0xC4..0xC6)
13389  - ext 8 - ext 32 (0xC7..0xC9)
13390  - float 32 (0xCA)
13391  - fixext 1 - fixext 16 (0xD4..0xD8)
13392 
13393  @note Any MessagePack output created @ref to_msgpack can be successfully
13394  parsed by @ref from_msgpack.
13395 
13396  @note If NaN or Infinity are stored inside a JSON number, they are
13397  serialized properly. This behavior differs from the @ref dump()
13398  function which serializes NaN or Infinity to `null`.
13399 
13400  @param[in] j JSON value to serialize
13401  @return MessagePack serialization as byte vector
13402 
13403  @complexity Linear in the size of the JSON value @a j.
13404 
13405  @liveexample{The example shows the serialization of a JSON value to a byte
13406  vector in MessagePack format.,to_msgpack}
13407 
13408  @sa http://msgpack.org
13409  @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
13410  analogous deserialization
13411  @sa @ref to_cbor(const basic_json& for the related CBOR format
13412 
13413  @since version 2.0.9
13414  */
13415  static std::vector<uint8_t> to_msgpack(const basic_json& j)
13416  {
13417  std::vector<uint8_t> result;
13418  to_msgpack(j, result);
13419  return result;
13420  }
13421 
13422  static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
13423  {
13424  binary_writer<uint8_t>(o).write_msgpack(j);
13425  }
13426 
13427  static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
13428  {
13429  binary_writer<char>(o).write_msgpack(j);
13430  }
13431 
13432  /*!
13433  @brief create a JSON value from an input in CBOR format
13434 
13435  Deserializes a given input @a i to a JSON value using the CBOR (Concise
13436  Binary Object Representation) serialization format.
13438  The library maps CBOR types to JSON value types as follows:
13439 
13440  CBOR type | JSON value type | first byte
13441  ---------------------- | --------------- | ----------
13442  Integer | number_unsigned | 0x00..0x17
13443  Unsigned integer | number_unsigned | 0x18
13444  Unsigned integer | number_unsigned | 0x19
13445  Unsigned integer | number_unsigned | 0x1A
13446  Unsigned integer | number_unsigned | 0x1B
13447  Negative integer | number_integer | 0x20..0x37
13448  Negative integer | number_integer | 0x38
13449  Negative integer | number_integer | 0x39
13450  Negative integer | number_integer | 0x3A
13451  Negative integer | number_integer | 0x3B
13452  Negative integer | number_integer | 0x40..0x57
13453  UTF-8 string | string | 0x60..0x77
13454  UTF-8 string | string | 0x78
13455  UTF-8 string | string | 0x79
13456  UTF-8 string | string | 0x7A
13457  UTF-8 string | string | 0x7B
13458  UTF-8 string | string | 0x7F
13459  array | array | 0x80..0x97
13460  array | array | 0x98
13461  array | array | 0x99
13462  array | array | 0x9A
13463  array | array | 0x9B
13464  array | array | 0x9F
13465  map | object | 0xA0..0xB7
13466  map | object | 0xB8
13467  map | object | 0xB9
13468  map | object | 0xBA
13469  map | object | 0xBB
13470  map | object | 0xBF
13471  False | `false` | 0xF4
13472  True | `true` | 0xF5
13473  Nill | `null` | 0xF6
13474  Half-Precision Float | number_float | 0xF9
13475  Single-Precision Float | number_float | 0xFA
13476  Double-Precision Float | number_float | 0xFB
13477 
13478  @warning The mapping is **incomplete** in the sense that not all CBOR
13479  types can be converted to a JSON value. The following CBOR types
13480  are not supported and will yield parse errors (parse_error.112):
13481  - byte strings (0x40..0x5F)
13482  - date/time (0xC0..0xC1)
13483  - bignum (0xC2..0xC3)
13484  - decimal fraction (0xC4)
13485  - bigfloat (0xC5)
13486  - tagged items (0xC6..0xD4, 0xD8..0xDB)
13487  - expected conversions (0xD5..0xD7)
13488  - simple values (0xE0..0xF3, 0xF8)
13489  - undefined (0xF7)
13490 
13491  @warning CBOR allows map keys of any type, whereas JSON only allows
13492  strings as keys in object values. Therefore, CBOR maps with keys
13493  other than UTF-8 strings are rejected (parse_error.113).
13494 
13495  @note Any CBOR output created @ref to_cbor can be successfully parsed by
13496  @ref from_cbor.
13497 
13498  @param[in] i an input in CBOR format convertible to an input adapter
13499  @param[in] strict whether to expect the input to be consumed until EOF
13500  (true by default)
13501  @return deserialized JSON value
13502 
13503  @throw parse_error.110 if the given input ends prematurely or the end of
13504  file was not reached when @a strict was set to true
13505  @throw parse_error.112 if unsupported features from CBOR were
13506  used in the given input @a v or if the input is not valid CBOR
13507  @throw parse_error.113 if a string was expected as map key, but not found
13508 
13509  @complexity Linear in the size of the input @a i.
13510 
13511  @liveexample{The example shows the deserialization of a byte vector in CBOR
13512  format to a JSON value.,from_cbor}
13513 
13514  @sa http://cbor.io
13515  @sa @ref to_cbor(const basic_json&) for the analogous serialization
13516  @sa @ref from_msgpack(detail::input_adapter, const bool) for the
13517  related MessagePack format
13518 
13519  @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
13520  consume input adapters, removed start_index parameter, and added
13521  @a strict parameter since 3.0.0
13522  */
13523  static basic_json from_cbor(detail::input_adapter i,
13524  const bool strict = true)
13525  {
13526  return binary_reader(i).parse_cbor(strict);
13527  }
13528 
13529  /*!
13530  @copydoc from_cbor(detail::input_adapter, const bool)
13531  */
13532  template<typename A1, typename A2,
13533  detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
13534  static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true)
13535  {
13536  return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_cbor(strict);
13537  }
13539  /*!
13540  @brief create a JSON value from an input in MessagePack format
13541 
13542  Deserializes a given input @a i to a JSON value using the MessagePack
13543  serialization format.
13544 
13545  The library maps MessagePack types to JSON value types as follows:
13546 
13547  MessagePack type | JSON value type | first byte
13548  ---------------- | --------------- | ----------
13549  positive fixint | number_unsigned | 0x00..0x7F
13550  fixmap | object | 0x80..0x8F
13551  fixarray | array | 0x90..0x9F
13552  fixstr | string | 0xA0..0xBF
13553  nil | `null` | 0xC0
13554  false | `false` | 0xC2
13555  true | `true` | 0xC3
13556  float 32 | number_float | 0xCA
13557  float 64 | number_float | 0xCB
13558  uint 8 | number_unsigned | 0xCC
13559  uint 16 | number_unsigned | 0xCD
13560  uint 32 | number_unsigned | 0xCE
13561  uint 64 | number_unsigned | 0xCF
13562  int 8 | number_integer | 0xD0
13563  int 16 | number_integer | 0xD1
13564  int 32 | number_integer | 0xD2
13565  int 64 | number_integer | 0xD3
13566  str 8 | string | 0xD9
13567  str 16 | string | 0xDA
13568  str 32 | string | 0xDB
13569  array 16 | array | 0xDC
13570  array 32 | array | 0xDD
13571  map 16 | object | 0xDE
13572  map 32 | object | 0xDF
13573  negative fixint | number_integer | 0xE0-0xFF
13574 
13575  @warning The mapping is **incomplete** in the sense that not all
13576  MessagePack types can be converted to a JSON value. The following
13577  MessagePack types are not supported and will yield parse errors:
13578  - bin 8 - bin 32 (0xC4..0xC6)
13579  - ext 8 - ext 32 (0xC7..0xC9)
13580  - fixext 1 - fixext 16 (0xD4..0xD8)
13581 
13582  @note Any MessagePack output created @ref to_msgpack can be successfully
13583  parsed by @ref from_msgpack.
13584 
13585  @param[in] i an input in MessagePack format convertible to an input
13586  adapter
13587  @param[in] strict whether to expect the input to be consumed until EOF
13588  (true by default)
13589 
13590  @throw parse_error.110 if the given input ends prematurely or the end of
13591  file was not reached when @a strict was set to true
13592  @throw parse_error.112 if unsupported features from MessagePack were
13593  used in the given input @a i or if the input is not valid MessagePack
13594  @throw parse_error.113 if a string was expected as map key, but not found
13595 
13596  @complexity Linear in the size of the input @a i.
13597 
13598  @liveexample{The example shows the deserialization of a byte vector in
13599  MessagePack format to a JSON value.,from_msgpack}
13600 
13601  @sa http://msgpack.org
13602  @sa @ref to_msgpack(const basic_json&) for the analogous serialization
13603  @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR
13604  format
13605 
13606  @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
13607  consume input adapters, removed start_index parameter, and added
13608  @a strict parameter since 3.0.0
13609  */
13610  static basic_json from_msgpack(detail::input_adapter i,
13611  const bool strict = true)
13612  {
13613  return binary_reader(i).parse_msgpack(strict);
13614  }
13615 
13616  /*!
13617  @copydoc from_msgpack(detail::input_adapter, const bool)
13618  */
13619  template<typename A1, typename A2,
13620  detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
13621  static basic_json from_msgpack(A1 && a1, A2 && a2, const bool strict = true)
13622  {
13623  return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_msgpack(strict);
13624  }
13626  /// @}
13627 
13628  //////////////////////////
13629  // JSON Pointer support //
13630  //////////////////////////
13631 
13632  /// @name JSON Pointer functions
13633  /// @{
13634 
13635  /*!
13636  @brief access specified element via JSON Pointer
13637 
13638  Uses a JSON pointer to retrieve a reference to the respective JSON value.
13639  No bound checking is performed. Similar to @ref operator[](const typename
13640  object_t::key_type&), `null` values are created in arrays and objects if
13641  necessary.
13642 
13643  In particular:
13644  - If the JSON pointer points to an object key that does not exist, it
13645  is created an filled with a `null` value before a reference to it
13646  is returned.
13647  - If the JSON pointer points to an array index that does not exist, it
13648  is created an filled with a `null` value before a reference to it
13649  is returned. All indices between the current maximum and the given
13650  index are also filled with `null`.
13651  - The special value `-` is treated as a synonym for the index past the
13652  end.
13653 
13654  @param[in] ptr a JSON pointer
13655 
13656  @return reference to the element pointed to by @a ptr
13657 
13658  @complexity Constant.
13659 
13660  @throw parse_error.106 if an array index begins with '0'
13661  @throw parse_error.109 if an array index was not a number
13662  @throw out_of_range.404 if the JSON pointer can not be resolved
13663 
13664  @liveexample{The behavior is shown in the example.,operatorjson_pointer}
13665 
13666  @since version 2.0.0
13667  */
13668  reference operator[](const json_pointer& ptr)
13669  {
13670  return ptr.get_unchecked(this);
13671  }
13672 
13673  /*!
13674  @brief access specified element via JSON Pointer
13675 
13676  Uses a JSON pointer to retrieve a reference to the respective JSON value.
13677  No bound checking is performed. The function does not change the JSON
13678  value; no `null` values are created. In particular, the the special value
13679  `-` yields an exception.
13680 
13681  @param[in] ptr JSON pointer to the desired element
13682 
13683  @return const reference to the element pointed to by @a ptr
13684 
13685  @complexity Constant.
13686 
13687  @throw parse_error.106 if an array index begins with '0'
13688  @throw parse_error.109 if an array index was not a number
13689  @throw out_of_range.402 if the array index '-' is used
13690  @throw out_of_range.404 if the JSON pointer can not be resolved
13691 
13692  @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
13693 
13694  @since version 2.0.0
13695  */
13696  const_reference operator[](const json_pointer& ptr) const
13697  {
13698  return ptr.get_unchecked(this);
13699  }
13700 
13701  /*!
13702  @brief access specified element via JSON Pointer
13703 
13704  Returns a reference to the element at with specified JSON pointer @a ptr,
13705  with bounds checking.
13706 
13707  @param[in] ptr JSON pointer to the desired element
13708 
13709  @return reference to the element pointed to by @a ptr
13710 
13711  @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
13712  begins with '0'. See example below.
13713 
13714  @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
13715  is not a number. See example below.
13716 
13717  @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
13718  is out of range. See example below.
13719 
13720  @throw out_of_range.402 if the array index '-' is used in the passed JSON
13721  pointer @a ptr. As `at` provides checked access (and no elements are
13722  implicitly inserted), the index '-' is always invalid. See example below.
13723 
13724  @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
13725  See example below.
13726 
13727  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
13728  changes in the JSON value.
13729 
13730  @complexity Constant.
13731 
13732  @since version 2.0.0
13733 
13734  @liveexample{The behavior is shown in the example.,at_json_pointer}
13735  */
13736  reference at(const json_pointer& ptr)
13737  {
13738  return ptr.get_checked(this);
13739  }
13740 
13741  /*!
13742  @brief access specified element via JSON Pointer
13743 
13744  Returns a const reference to the element at with specified JSON pointer @a
13745  ptr, with bounds checking.
13746 
13747  @param[in] ptr JSON pointer to the desired element
13748 
13749  @return reference to the element pointed to by @a ptr
13750 
13751  @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
13752  begins with '0'. See example below.
13753 
13754  @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
13755  is not a number. See example below.
13756 
13757  @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
13758  is out of range. See example below.
13759 
13760  @throw out_of_range.402 if the array index '-' is used in the passed JSON
13761  pointer @a ptr. As `at` provides checked access (and no elements are
13762  implicitly inserted), the index '-' is always invalid. See example below.
13763 
13764  @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
13765  See example below.
13766 
13767  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
13768  changes in the JSON value.
13769 
13770  @complexity Constant.
13771 
13772  @since version 2.0.0
13773 
13774  @liveexample{The behavior is shown in the example.,at_json_pointer_const}
13775  */
13776  const_reference at(const json_pointer& ptr) const
13777  {
13778  return ptr.get_checked(this);
13779  }
13780 
13781  /*!
13782  @brief return flattened JSON value
13783 
13784  The function creates a JSON object whose keys are JSON pointers (see [RFC
13785  6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
13786  primitive. The original JSON value can be restored using the @ref
13787  unflatten() function.
13788 
13789  @return an object that maps JSON pointers to primitive values
13790 
13791  @note Empty objects and arrays are flattened to `null` and will not be
13792  reconstructed correctly by the @ref unflatten() function.
13793 
13794  @complexity Linear in the size the JSON value.
13795 
13796  @liveexample{The following code shows how a JSON object is flattened to an
13797  object whose keys consist of JSON pointers.,flatten}
13798 
13799  @sa @ref unflatten() for the reverse function
13800 
13801  @since version 2.0.0
13802  */
13803  basic_json flatten() const
13804  {
13805  basic_json result(value_t::object);
13806  json_pointer::flatten("", *this, result);
13807  return result;
13808  }
13809 
13810  /*!
13811  @brief unflatten a previously flattened JSON value
13812 
13813  The function restores the arbitrary nesting of a JSON value that has been
13814  flattened before using the @ref flatten() function. The JSON value must
13815  meet certain constraints:
13816  1. The value must be an object.
13817  2. The keys must be JSON pointers (see
13818  [RFC 6901](https://tools.ietf.org/html/rfc6901))
13819  3. The mapped values must be primitive JSON types.
13820 
13821  @return the original JSON from a flattened version
13822 
13823  @note Empty objects and arrays are flattened by @ref flatten() to `null`
13824  values and can not unflattened to their original type. Apart from
13825  this example, for a JSON value `j`, the following is always true:
13826  `j == j.flatten().unflatten()`.
13827 
13828  @complexity Linear in the size the JSON value.
13829 
13830  @throw type_error.314 if value is not an object
13831  @throw type_error.315 if object values are not primitive
13832 
13833  @liveexample{The following code shows how a flattened JSON object is
13834  unflattened into the original nested JSON object.,unflatten}
13835 
13836  @sa @ref flatten() for the reverse function
13837 
13838  @since version 2.0.0
13839  */
13840  basic_json unflatten() const
13841  {
13842  return json_pointer::unflatten(*this);
13843  }
13844 
13845  /// @}
13846 
13847  //////////////////////////
13848  // JSON Patch functions //
13849  //////////////////////////
13850 
13851  /// @name JSON Patch functions
13852  /// @{
13853 
13854  /*!
13855  @brief applies a JSON patch
13856 
13857  [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
13858  expressing a sequence of operations to apply to a JSON) document. With
13859  this function, a JSON Patch is applied to the current JSON value by
13860  executing all operations from the patch.
13861 
13862  @param[in] json_patch JSON patch document
13863  @return patched document
13864 
13865  @note The application of a patch is atomic: Either all operations succeed
13866  and the patched document is returned or an exception is thrown. In
13867  any case, the original value is not changed: the patch is applied
13868  to a copy of the value.
13869 
13870  @throw parse_error.104 if the JSON patch does not consist of an array of
13871  objects
13872 
13873  @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
13874  attributes are missing); example: `"operation add must have member path"`
13875 
13876  @throw out_of_range.401 if an array index is out of range.
13877 
13878  @throw out_of_range.403 if a JSON pointer inside the patch could not be
13879  resolved successfully in the current JSON value; example: `"key baz not
13880  found"`
13881 
13882  @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
13883  "move")
13884 
13885  @throw other_error.501 if "test" operation was unsuccessful
13886 
13887  @complexity Linear in the size of the JSON value and the length of the
13888  JSON patch. As usually only a fraction of the JSON value is affected by
13889  the patch, the complexity can usually be neglected.
13890 
13891  @liveexample{The following code shows how a JSON patch is applied to a
13892  value.,patch}
13893 
13894  @sa @ref diff -- create a JSON patch by comparing two JSON values
13895 
13896  @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
13897  @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
13898 
13899  @since version 2.0.0
13900  */
13901  basic_json patch(const basic_json& json_patch) const
13902  {
13903  // make a working copy to apply the patch to
13904  basic_json result = *this;
13905 
13906  // the valid JSON Patch operations
13907  enum class patch_operations {add, remove, replace, move, copy, test, invalid};
13908 
13909  const auto get_op = [](const std::string & op)
13910  {
13911  if (op == "add")
13912  {
13913  return patch_operations::add;
13914  }
13915  if (op == "remove")
13916  {
13917  return patch_operations::remove;
13918  }
13919  if (op == "replace")
13920  {
13921  return patch_operations::replace;
13922  }
13923  if (op == "move")
13924  {
13925  return patch_operations::move;
13926  }
13927  if (op == "copy")
13928  {
13929  return patch_operations::copy;
13930  }
13931  if (op == "test")
13932  {
13933  return patch_operations::test;
13934  }
13935 
13936  return patch_operations::invalid;
13937  };
13938 
13939  // wrapper for "add" operation; add value at ptr
13940  const auto operation_add = [&result](json_pointer & ptr, basic_json val)
13941  {
13942  // adding to the root of the target document means replacing it
13943  if (ptr.is_root())
13944  {
13945  result = val;
13946  }
13947  else
13948  {
13949  // make sure the top element of the pointer exists
13950  json_pointer top_pointer = ptr.top();
13951  if (top_pointer != ptr)
13952  {
13953  result.at(top_pointer);
13954  }
13955 
13956  // get reference to parent of JSON pointer ptr
13957  const auto last_path = ptr.pop_back();
13958  basic_json& parent = result[ptr];
13959 
13960  switch (parent.m_type)
13961  {
13962  case value_t::null:
13963  case value_t::object:
13964  {
13965  // use operator[] to add value
13966  parent[last_path] = val;
13967  break;
13968  }
13969 
13970  case value_t::array:
13971  {
13972  if (last_path == "-")
13973  {
13974  // special case: append to back
13975  parent.push_back(val);
13976  }
13977  else
13978  {
13979  const auto idx = std::stoi(last_path);
13980  if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
13981  {
13982  // avoid undefined behavior
13983  JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
13984  }
13985  else
13986  {
13987  // default case: insert add offset
13988  parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
13989  }
13990  }
13991  break;
13992  }
13993 
13994  default:
13995  {
13996  // if there exists a parent it cannot be primitive
13997  assert(false); // LCOV_EXCL_LINE
13998  }
13999  }
14000  }
14001  };
14002 
14003  // wrapper for "remove" operation; remove value at ptr
14004  const auto operation_remove = [&result](json_pointer & ptr)
14005  {
14006  // get reference to parent of JSON pointer ptr
14007  const auto last_path = ptr.pop_back();
14008  basic_json& parent = result.at(ptr);
14009 
14010  // remove child
14011  if (parent.is_object())
14012  {
14013  // perform range check
14014  auto it = parent.find(last_path);
14015  if (JSON_LIKELY(it != parent.end()))
14016  {
14017  parent.erase(it);
14018  }
14019  else
14020  {
14021  JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
14022  }
14023  }
14024  else if (parent.is_array())
14025  {
14026  // note erase performs range check
14027  parent.erase(static_cast<size_type>(std::stoi(last_path)));
14028  }
14029  };
14030 
14031  // type check: top level value must be an array
14032  if (JSON_UNLIKELY(not json_patch.is_array()))
14033  {
14034  JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
14035  }
14036 
14037  // iterate and apply the operations
14038  for (const auto& val : json_patch)
14039  {
14040  // wrapper to get a value for an operation
14041  const auto get_value = [&val](const std::string & op,
14042  const std::string & member,
14043  bool string_type) -> basic_json&
14044  {
14045  // find value
14046  auto it = val.m_value.object->find(member);
14047 
14048  // context-sensitive error message
14049  const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
14050 
14051  // check if desired value is present
14052  if (JSON_UNLIKELY(it == val.m_value.object->end()))
14053  {
14054  JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
14055  }
14056 
14057  // check if result is of type string
14058  if (JSON_UNLIKELY(string_type and not it->second.is_string()))
14059  {
14060  JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
14061  }
14062 
14063  // no error: return value
14064  return it->second;
14065  };
14066 
14067  // type check: every element of the array must be an object
14068  if (JSON_UNLIKELY(not val.is_object()))
14069  {
14070  JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
14071  }
14072 
14073  // collect mandatory members
14074  const std::string op = get_value("op", "op", true);
14075  const std::string path = get_value(op, "path", true);
14076  json_pointer ptr(path);
14077 
14078  switch (get_op(op))
14079  {
14080  case patch_operations::add:
14081  {
14082  operation_add(ptr, get_value("add", "value", false));
14083  break;
14084  }
14085 
14086  case patch_operations::remove:
14087  {
14088  operation_remove(ptr);
14089  break;
14090  }
14091 
14092  case patch_operations::replace:
14093  {
14094  // the "path" location must exist - use at()
14095  result.at(ptr) = get_value("replace", "value", false);
14096  break;
14097  }
14098 
14099  case patch_operations::move:
14100  {
14101  const std::string from_path = get_value("move", "from", true);
14102  json_pointer from_ptr(from_path);
14103 
14104  // the "from" location must exist - use at()
14105  basic_json v = result.at(from_ptr);
14106 
14107  // The move operation is functionally identical to a
14108  // "remove" operation on the "from" location, followed
14109  // immediately by an "add" operation at the target
14110  // location with the value that was just removed.
14111  operation_remove(from_ptr);
14112  operation_add(ptr, v);
14113  break;
14114  }
14115 
14116  case patch_operations::copy:
14117  {
14118  const std::string from_path = get_value("copy", "from", true);
14119  const json_pointer from_ptr(from_path);
14120 
14121  // the "from" location must exist - use at()
14122  result[ptr] = result.at(from_ptr);
14123  break;
14124  }
14125 
14126  case patch_operations::test:
14127  {
14128  bool success = false;
14129  JSON_TRY
14130  {
14131  // check if "value" matches the one at "path"
14132  // the "path" location must exist - use at()
14133  success = (result.at(ptr) == get_value("test", "value", false));
14134  }
14135  JSON_CATCH (out_of_range&)
14136  {
14137  // ignore out of range errors: success remains false
14138  }
14139 
14140  // throw an exception if test fails
14141  if (JSON_UNLIKELY(not success))
14142  {
14143  JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
14144  }
14145 
14146  break;
14147  }
14148 
14149  case patch_operations::invalid:
14150  {
14151  // op must be "add", "remove", "replace", "move", "copy", or
14152  // "test"
14153  JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
14154  }
14155  }
14156  }
14157 
14158  return result;
14159  }
14160 
14161  /*!
14162  @brief creates a diff as a JSON patch
14163 
14164  Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
14165  be changed into the value @a target by calling @ref patch function.
14166 
14167  @invariant For two JSON values @a source and @a target, the following code
14168  yields always `true`:
14169  @code {.cpp}
14170  source.patch(diff(source, target)) == target;
14171  @endcode
14172 
14173  @note Currently, only `remove`, `add`, and `replace` operations are
14174  generated.
14175 
14176  @param[in] source JSON value to compare from
14177  @param[in] target JSON value to compare against
14178  @param[in] path helper value to create JSON pointers
14179 
14180  @return a JSON patch to convert the @a source to @a target
14181 
14182  @complexity Linear in the lengths of @a source and @a target.
14183 
14184  @liveexample{The following code shows how a JSON patch is created as a
14185  diff for two JSON values.,diff}
14186 
14187  @sa @ref patch -- apply a JSON patch
14188 
14189  @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
14190 
14191  @since version 2.0.0
14192  */
14193  static basic_json diff(const basic_json& source, const basic_json& target,
14194  const std::string& path = "")
14195  {
14196  // the patch
14197  basic_json result(value_t::array);
14198 
14199  // if the values are the same, return empty patch
14200  if (source == target)
14201  {
14202  return result;
14203  }
14204 
14205  if (source.type() != target.type())
14206  {
14207  // different types: replace value
14208  result.push_back(
14209  {
14210  {"op", "replace"}, {"path", path}, {"value", target}
14211  });
14212  }
14213  else
14214  {
14215  switch (source.type())
14216  {
14217  case value_t::array:
14218  {
14219  // first pass: traverse common elements
14220  std::size_t i = 0;
14221  while (i < source.size() and i < target.size())
14222  {
14223  // recursive call to compare array values at index i
14224  auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
14225  result.insert(result.end(), temp_diff.begin(), temp_diff.end());
14226  ++i;
14227  }
14228 
14229  // i now reached the end of at least one array
14230  // in a second pass, traverse the remaining elements
14231 
14232  // remove my remaining elements
14233  const auto end_index = static_cast<difference_type>(result.size());
14234  while (i < source.size())
14235  {
14236  // add operations in reverse order to avoid invalid
14237  // indices
14238  result.insert(result.begin() + end_index, object(
14239  {
14240  {"op", "remove"},
14241  {"path", path + "/" + std::to_string(i)}
14242  }));
14243  ++i;
14244  }
14245 
14246  // add other remaining elements
14247  while (i < target.size())
14248  {
14249  result.push_back(
14250  {
14251  {"op", "add"},
14252  {"path", path + "/" + std::to_string(i)},
14253  {"value", target[i]}
14254  });
14255  ++i;
14256  }
14257 
14258  break;
14259  }
14260 
14261  case value_t::object:
14262  {
14263  // first pass: traverse this object's elements
14264  for (auto it = source.begin(); it != source.end(); ++it)
14265  {
14266  // escape the key name to be used in a JSON patch
14267  const auto key = json_pointer::escape(it.key());
14268 
14269  if (target.find(it.key()) != target.end())
14270  {
14271  // recursive call to compare object values at key it
14272  auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
14273  result.insert(result.end(), temp_diff.begin(), temp_diff.end());
14274  }
14275  else
14276  {
14277  // found a key that is not in o -> remove it
14278  result.push_back(object(
14279  {
14280  {"op", "remove"}, {"path", path + "/" + key}
14281  }));
14282  }
14283  }
14284 
14285  // second pass: traverse other object's elements
14286  for (auto it = target.begin(); it != target.end(); ++it)
14287  {
14288  if (source.find(it.key()) == source.end())
14289  {
14290  // found a key that is not in this -> add it
14291  const auto key = json_pointer::escape(it.key());
14292  result.push_back(
14293  {
14294  {"op", "add"}, {"path", path + "/" + key},
14295  {"value", it.value()}
14296  });
14297  }
14298  }
14299 
14300  break;
14301  }
14302 
14303  default:
14304  {
14305  // both primitive type: replace value
14306  result.push_back(
14307  {
14308  {"op", "replace"}, {"path", path}, {"value", target}
14309  });
14310  break;
14311  }
14312  }
14313  }
14314 
14315  return result;
14316  }
14317 
14318  /// @}
14319 };
14320 
14321 /////////////
14322 // presets //
14323 /////////////
14324 
14325 /*!
14326 @brief default JSON class
14327 
14328 This type is the default specialization of the @ref basic_json class which
14329 uses the standard template types.
14330 
14331 @since version 1.0.0
14332 */
14333 using json = basic_json<>;
14334 
14335 //////////////////
14336 // json_pointer //
14337 //////////////////
14338 
14341 json_pointer::get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const
14342 {
14343  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14344  auto result = &j;
14345 
14346  // in case no reference tokens exist, return a reference to the JSON value
14347  // j which will be overwritten by a primitive value
14348  for (const auto& reference_token : reference_tokens)
14349  {
14350  switch (result->m_type)
14351  {
14352  case detail::value_t::null:
14353  {
14354  if (reference_token == "0")
14355  {
14356  // start a new array if reference token is 0
14357  result = &result->operator[](0);
14358  }
14359  else
14360  {
14361  // start a new object otherwise
14362  result = &result->operator[](reference_token);
14363  }
14364  break;
14365  }
14366 
14367  case detail::value_t::object:
14368  {
14369  // create an entry in the object
14370  result = &result->operator[](reference_token);
14371  break;
14372  }
14373 
14374  case detail::value_t::array:
14375  {
14376  // create an entry in the array
14377  JSON_TRY
14378  {
14379  result = &result->operator[](static_cast<size_type>(std::stoi(reference_token)));
14380  }
14381  JSON_CATCH(std::invalid_argument&)
14382  {
14383  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14384  }
14385  break;
14386  }
14387 
14388  /*
14389  The following code is only reached if there exists a reference
14390  token _and_ the current value is primitive. In this case, we have
14391  an error situation, because primitive values may only occur as
14392  single value; that is, with an empty list of reference tokens.
14393  */
14394  default:
14395  JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
14396  }
14397  }
14398 
14399  return *result;
14400 }
14401 
14404 json_pointer::get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const
14405 {
14406  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14407  for (const auto& reference_token : reference_tokens)
14408  {
14409  // convert null values to arrays or objects before continuing
14410  if (ptr->m_type == detail::value_t::null)
14411  {
14412  // check if reference token is a number
14413  const bool nums =
14414  std::all_of(reference_token.begin(), reference_token.end(),
14415  [](const char x)
14416  {
14417  return (x >= '0' and x <= '9');
14418  });
14419 
14420  // change value to array for numbers or "-" or to object otherwise
14421  *ptr = (nums or reference_token == "-")
14422  ? detail::value_t::array
14423  : detail::value_t::object;
14424  }
14425 
14426  switch (ptr->m_type)
14427  {
14428  case detail::value_t::object:
14429  {
14430  // use unchecked object access
14431  ptr = &ptr->operator[](reference_token);
14432  break;
14433  }
14434 
14435  case detail::value_t::array:
14436  {
14437  // error condition (cf. RFC 6901, Sect. 4)
14438  if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
14439  {
14440  JSON_THROW(detail::parse_error::create(106, 0,
14441  "array index '" + reference_token +
14442  "' must not begin with '0'"));
14443  }
14444 
14445  if (reference_token == "-")
14446  {
14447  // explicitly treat "-" as index beyond the end
14448  ptr = &ptr->operator[](ptr->m_value.array->size());
14449  }
14450  else
14451  {
14452  // convert array index to number; unchecked access
14453  JSON_TRY
14454  {
14455  ptr = &ptr->operator[](
14456  static_cast<size_type>(std::stoi(reference_token)));
14457  }
14458  JSON_CATCH(std::invalid_argument&)
14459  {
14460  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14461  }
14462  }
14463  break;
14464  }
14465 
14466  default:
14467  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
14468  }
14469  }
14470 
14471  return *ptr;
14472 }
14473 
14476 json_pointer::get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const
14477 {
14478  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14479  for (const auto& reference_token : reference_tokens)
14480  {
14481  switch (ptr->m_type)
14482  {
14483  case detail::value_t::object:
14484  {
14485  // note: at performs range check
14486  ptr = &ptr->at(reference_token);
14487  break;
14488  }
14489 
14490  case detail::value_t::array:
14491  {
14492  if (JSON_UNLIKELY(reference_token == "-"))
14493  {
14494  // "-" always fails the range check
14495  JSON_THROW(detail::out_of_range::create(402,
14496  "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
14497  ") is out of range"));
14498  }
14499 
14500  // error condition (cf. RFC 6901, Sect. 4)
14501  if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
14502  {
14503  JSON_THROW(detail::parse_error::create(106, 0,
14504  "array index '" + reference_token +
14505  "' must not begin with '0'"));
14506  }
14507 
14508  // note: at performs range check
14509  JSON_TRY
14510  {
14511  ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
14512  }
14513  JSON_CATCH(std::invalid_argument&)
14514  {
14515  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14516  }
14517  break;
14518  }
14519 
14520  default:
14521  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
14522  }
14523  }
14524 
14525  return *ptr;
14526 }
14527 
14530 json_pointer::get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const
14531 {
14532  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14533  for (const auto& reference_token : reference_tokens)
14534  {
14535  switch (ptr->m_type)
14536  {
14537  case detail::value_t::object:
14538  {
14539  // use unchecked object access
14540  ptr = &ptr->operator[](reference_token);
14541  break;
14542  }
14543 
14544  case detail::value_t::array:
14545  {
14546  if (JSON_UNLIKELY(reference_token == "-"))
14547  {
14548  // "-" cannot be used for const access
14549  JSON_THROW(detail::out_of_range::create(402,
14550  "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
14551  ") is out of range"));
14552  }
14553 
14554  // error condition (cf. RFC 6901, Sect. 4)
14555  if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
14556  {
14557  JSON_THROW(detail::parse_error::create(106, 0,
14558  "array index '" + reference_token +
14559  "' must not begin with '0'"));
14560  }
14561 
14562  // use unchecked array access
14563  JSON_TRY
14564  {
14565  ptr = &ptr->operator[](
14566  static_cast<size_type>(std::stoi(reference_token)));
14567  }
14568  JSON_CATCH(std::invalid_argument&)
14569  {
14570  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14571  }
14572  break;
14573  }
14574 
14575  default:
14576  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
14577  }
14578  }
14579 
14580  return *ptr;
14581 }
14582 
14585 json_pointer::get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const
14586 {
14587  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14588  for (const auto& reference_token : reference_tokens)
14589  {
14590  switch (ptr->m_type)
14591  {
14592  case detail::value_t::object:
14593  {
14594  // note: at performs range check
14595  ptr = &ptr->at(reference_token);
14596  break;
14597  }
14598 
14599  case detail::value_t::array:
14600  {
14601  if (JSON_UNLIKELY(reference_token == "-"))
14602  {
14603  // "-" always fails the range check
14604  JSON_THROW(detail::out_of_range::create(402,
14605  "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
14606  ") is out of range"));
14607  }
14608 
14609  // error condition (cf. RFC 6901, Sect. 4)
14610  if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
14611  {
14612  JSON_THROW(detail::parse_error::create(106, 0,
14613  "array index '" + reference_token +
14614  "' must not begin with '0'"));
14615  }
14616 
14617  // note: at performs range check
14618  JSON_TRY
14619  {
14620  ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
14621  }
14622  JSON_CATCH(std::invalid_argument&)
14623  {
14624  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14625  }
14626  break;
14627  }
14628 
14629  default:
14630  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
14631  }
14632  }
14633 
14634  return *ptr;
14635 }
14636 
14638 void json_pointer::flatten(const std::string& reference_string,
14639  const NLOHMANN_BASIC_JSON_TPL& value,
14640  NLOHMANN_BASIC_JSON_TPL& result)
14641 {
14642  switch (value.m_type)
14643  {
14644  case detail::value_t::array:
14645  {
14646  if (value.m_value.array->empty())
14647  {
14648  // flatten empty array as null
14649  result[reference_string] = nullptr;
14650  }
14651  else
14652  {
14653  // iterate array and use index as reference string
14654  for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
14655  {
14656  flatten(reference_string + "/" + std::to_string(i),
14657  value.m_value.array->operator[](i), result);
14658  }
14659  }
14660  break;
14661  }
14662 
14663  case detail::value_t::object:
14664  {
14665  if (value.m_value.object->empty())
14666  {
14667  // flatten empty object as null
14668  result[reference_string] = nullptr;
14669  }
14670  else
14671  {
14672  // iterate object and use keys as reference string
14673  for (const auto& element : *value.m_value.object)
14674  {
14675  flatten(reference_string + "/" + escape(element.first), element.second, result);
14676  }
14677  }
14678  break;
14679  }
14680 
14681  default:
14682  {
14683  // add primitive value with its reference string
14684  result[reference_string] = value;
14685  break;
14686  }
14687  }
14688 }
14689 
14692 json_pointer::unflatten(const NLOHMANN_BASIC_JSON_TPL& value)
14693 {
14694  if (JSON_UNLIKELY(not value.is_object()))
14695  {
14696  JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
14697  }
14698 
14699  NLOHMANN_BASIC_JSON_TPL result;
14700 
14701  // iterate the JSON object values
14702  for (const auto& element : *value.m_value.object)
14703  {
14704  if (JSON_UNLIKELY(not element.second.is_primitive()))
14705  {
14706  JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
14707  }
14708 
14709  // assign value to reference pointed to by JSON pointer; Note that if
14710  // the JSON pointer is "" (i.e., points to the whole value), function
14711  // get_and_create returns a reference to result itself. An assignment
14712  // will then create a primitive value.
14713  json_pointer(element.first).get_and_create(result) = element.second;
14714  }
14715 
14716  return result;
14717 }
14718 
14719 inline bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept
14720 {
14721  return (lhs.reference_tokens == rhs.reference_tokens);
14722 }
14723 
14724 inline bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept
14725 {
14726  return not (lhs == rhs);
14727 }
14728 } // namespace nlohmann
14729 
14730 
14731 ///////////////////////
14732 // nonmember support //
14733 ///////////////////////
14735 // specialization of std::swap, and std::hash
14736 namespace std
14737 {
14738 /*!
14739 @brief exchanges the values of two JSON objects
14740 
14741 @since version 1.0.0
14742 */
14743 template<>
14744 inline void swap(nlohmann::json& j1,
14745  nlohmann::json& j2) noexcept(
14746  is_nothrow_move_constructible<nlohmann::json>::value and
14747  is_nothrow_move_assignable<nlohmann::json>::value
14748  )
14749 {
14750  j1.swap(j2);
14751 }
14752 
14753 /// hash value for JSON objects
14754 template<>
14755 struct hash<nlohmann::json>
14756 {
14757  /*!
14758  @brief return a hash value for a JSON object
14759 
14760  @since version 1.0.0
14761  */
14762  std::size_t operator()(const nlohmann::json& j) const
14763  {
14764  // a naive hashing via the string representation
14765  const auto& h = hash<nlohmann::json::string_t>();
14766  return h(j.dump());
14767  }
14768 };
14769 
14770 /// specialization for std::less<value_t>
14771 /// @note: do not remove the space after '<',
14772 /// see https://github.com/nlohmann/json/pull/679
14773 template<>
14774 struct less< ::nlohmann::detail::value_t>
14775 {
14776  /*!
14777  @brief compare two value_t enum values
14778  @since version 3.0.0
14779  */
14780  bool operator()(nlohmann::detail::value_t lhs,
14781  nlohmann::detail::value_t rhs) const noexcept
14782  {
14783  return nlohmann::detail::operator<(lhs, rhs);
14784  }
14785 };
14786 
14787 } // namespace std
14788 
14789 /*!
14790 @brief user-defined string literal for JSON values
14791 
14792 This operator implements a user-defined string literal for JSON objects. It
14793 can be used by adding `"_json"` to a string literal and returns a JSON object
14794 if no parse error occurred.
14795 
14796 @param[in] s a string representation of a JSON object
14797 @param[in] n the length of string @a s
14798 @return a JSON object
14799 
14800 @since version 1.0.0
14801 */
14802 inline nlohmann::json operator "" _json(const char* s, std::size_t n)
14803 {
14804  return nlohmann::json::parse(s, s + n);
14805 }
14806 
14807 /*!
14808 @brief user-defined string literal for JSON pointer
14809 
14810 This operator implements a user-defined string literal for JSON Pointers. It
14811 can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
14812 object if no parse error occurred.
14813 
14814 @param[in] s a string representation of a JSON Pointer
14815 @param[in] n the length of string @a s
14816 @return a JSON pointer object
14817 
14818 @since version 2.0.0
14819 */
14820 inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
14821 {
14822  return nlohmann::json::json_pointer(std::string(s, n));
14823 }
14824 
14825 // restore GCC/clang diagnostic settings
14826 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
14827  #pragma GCC diagnostic pop
14828 #endif
14829 #if defined(__clang__)
14830  #pragma GCC diagnostic pop
14831 #endif
14832 
14833 // clean up
14834 #undef JSON_CATCH
14835 #undef JSON_THROW
14836 #undef JSON_TRY
14837 #undef JSON_LIKELY
14838 #undef JSON_UNLIKELY
14839 #undef JSON_DEPRECATED
14840 #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
14841 #undef NLOHMANN_BASIC_JSON_TPL
14842 
14843 #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:802
#define JSON_UNLIKELY(x)
Definition: json.hpp:109
friend class basic_json
allow basic_json to access private members
Definition: json.hpp:6958
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:6920
constexpr const auto & from_json
Definition: json.hpp:6896
#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:6936
#define JSON_TRY
Definition: json.hpp:99
#define JSON_THROW(exception)
Definition: json.hpp:98
constexpr const auto & to_json
Definition: json.hpp:6895
json_pointer(const std::string &s="")
create JSON pointer
Definition: json.hpp:6982
JSON Pointer.
Definition: json.hpp:6954