JSON for Modern C++  3.0.1
json.hpp
1 /*
2  __ _____ _____ _____
3  __| | __| | | | JSON for Modern C++
4 | | |__ | | | | | | version 3.0.1
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>
139 class basic_json;
140 
141 // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
142 // may be removed in the future once the class is split.
143 
144 #define NLOHMANN_BASIC_JSON_TPL_DECLARATION
145  template<template<typename, typename, typename...> class ObjectType,
146  template<typename, typename...> class ArrayType,
147  class StringType, class BooleanType, class NumberIntegerType,
148  class NumberUnsignedType, class NumberFloatType,
149  template<typename> class AllocatorType,
150  template<typename, typename = void> class JSONSerializer>
151 
152 #define NLOHMANN_BASIC_JSON_TPL
153  basic_json<ObjectType, ArrayType, StringType, BooleanType,
154  NumberIntegerType, NumberUnsignedType, NumberFloatType,
155  AllocatorType, JSONSerializer>
156 
157 
158 /*!
159 @brief unnamed namespace with internal helper functions
160 
161 This namespace collects some functions that could not be defined inside the
162 @ref basic_json class.
163 
164 @since version 2.1.0
165 */
166 namespace detail
167 {
168 ////////////////
169 // exceptions //
170 ////////////////
171 
172 /*!
173 @brief general exception of the @ref basic_json class
174 
175 This class is an extension of `std::exception` objects with a member @a id for
176 exception ids. It is used as the base class for all exceptions thrown by the
177 @ref basic_json class. This class can hence be used as "wildcard" to catch
178 exceptions.
179 
180 Subclasses:
181 - @ref parse_error for exceptions indicating a parse error
182 - @ref invalid_iterator for exceptions indicating errors with iterators
183 - @ref type_error for exceptions indicating executing a member function with
184  a wrong type
185 - @ref out_of_range for exceptions indicating access out of the defined range
186 - @ref other_error for exceptions indicating other library errors
187 
188 @internal
189 @note To have nothrow-copy-constructible exceptions, we internally use
190  `std::runtime_error` which can cope with arbitrary-length error messages.
191  Intermediate strings are built with static functions and then passed to
192  the actual constructor.
193 @endinternal
194 
195 @liveexample{The following code shows how arbitrary library exceptions can be
196 caught.,exception}
197 
198 @since version 3.0.0
199 */
200 class exception : public std::exception
201 {
202  public:
203  /// returns the explanatory string
204  const char* what() const noexcept override
205  {
206  return m.what();
207  }
208 
209  /// the id of the exception
210  const int id;
211 
212  protected:
213  exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
214 
215  static std::string name(const std::string& ename, int id_)
216  {
217  return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
218  }
219 
220  private:
221  /// an exception object as storage for error messages
222  std::runtime_error m;
223 };
224 
225 /*!
226 @brief exception indicating a parse error
227 
228 This exception is thrown by the library when a parse error occurs. Parse errors
229 can occur during the deserialization of JSON text, CBOR, MessagePack, as well
230 as when using JSON Patch.
231 
232 Member @a byte holds the byte index of the last read character in the input
233 file.
234 
235 Exceptions have ids 1xx.
236 
237 name / id | example message | description
238 ------------------------------ | --------------- | -------------------------
239 json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position.
240 json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
241 json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
242 json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects.
243 json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors.
244 json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`.
245 json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character.
246 json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences.
247 json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
248 json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
249 json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.
250 json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read.
251 
252 @note For an input with n bytes, 1 is the index of the first character and n+1
253  is the index of the terminating null byte or the end of file. This also
254  holds true when reading a byte vector (CBOR or MessagePack).
255 
256 @liveexample{The following code shows how a `parse_error` exception can be
257 caught.,parse_error}
258 
259 @sa @ref exception for the base class of the library exceptions
260 @sa @ref invalid_iterator for exceptions indicating errors with iterators
261 @sa @ref type_error for exceptions indicating executing a member function with
262  a wrong type
263 @sa @ref out_of_range for exceptions indicating access out of the defined range
264 @sa @ref other_error for exceptions indicating other library errors
265 
266 @since version 3.0.0
267 */
268 class parse_error : public exception
269 {
270  public:
271  /*!
272  @brief create a parse error exception
273  @param[in] id_ the id of the exception
274  @param[in] byte_ the byte index where the error occurred (or 0 if the
275  position cannot be determined)
276  @param[in] what_arg the explanatory string
277  @return parse_error object
278  */
279  static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
280  {
281  std::string w = exception::name("parse_error", id_) + "parse error" +
282  (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") +
283  ": " + what_arg;
284  return parse_error(id_, byte_, w.c_str());
285  }
286 
287  /*!
288  @brief byte index of the parse error
289 
290  The byte index of the last read character in the input file.
291 
292  @note For an input with n bytes, 1 is the index of the first character and
293  n+1 is the index of the terminating null byte or the end of file.
294  This also holds true when reading a byte vector (CBOR or MessagePack).
295  */
296  const std::size_t byte;
297 
298  private:
299  parse_error(int id_, std::size_t byte_, const char* what_arg)
300  : exception(id_, what_arg), byte(byte_) {}
301 };
302 
303 /*!
304 @brief exception indicating errors with iterators
305 
306 This exception is thrown if iterators passed to a library function do not match
307 the expected semantics.
308 
309 Exceptions have ids 2xx.
310 
311 name / id | example message | description
312 ----------------------------------- | --------------- | -------------------------
313 json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
314 json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
315 json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
316 json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid.
317 json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.
318 json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.
319 json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
320 json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
321 json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
322 json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
323 json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to.
324 json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
325 json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
326 json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin().
327 
328 @liveexample{The following code shows how an `invalid_iterator` exception can be
329 caught.,invalid_iterator}
330 
331 @sa @ref exception for the base class of the library exceptions
332 @sa @ref parse_error for exceptions indicating a parse error
333 @sa @ref type_error for exceptions indicating executing a member function with
334  a wrong type
335 @sa @ref out_of_range for exceptions indicating access out of the defined range
336 @sa @ref other_error for exceptions indicating other library errors
337 
338 @since version 3.0.0
339 */
340 class invalid_iterator : public exception
341 {
342  public:
343  static invalid_iterator create(int id_, const std::string& what_arg)
344  {
345  std::string w = exception::name("invalid_iterator", id_) + what_arg;
346  return invalid_iterator(id_, w.c_str());
347  }
348 
349  private:
350  invalid_iterator(int id_, const char* what_arg)
351  : exception(id_, what_arg) {}
352 };
353 
354 /*!
355 @brief exception indicating executing a member function with a wrong type
356 
357 This exception is thrown in case of a type error; that is, a library function is
358 executed on a JSON value whose type does not match the expected semantics.
359 
360 Exceptions have ids 3xx.
361 
362 name / id | example message | description
363 ----------------------------- | --------------- | -------------------------
364 json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
365 json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
366 json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&.
367 json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
368 json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
369 json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
370 json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
371 json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types.
372 json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
373 json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
374 json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types.
375 json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
376 json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined.
377 json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
378 json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive.
379 json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. |
380 
381 @liveexample{The following code shows how a `type_error` exception can be
382 caught.,type_error}
383 
384 @sa @ref exception for the base class of the library exceptions
385 @sa @ref parse_error for exceptions indicating a parse error
386 @sa @ref invalid_iterator for exceptions indicating errors with iterators
387 @sa @ref out_of_range for exceptions indicating access out of the defined range
388 @sa @ref other_error for exceptions indicating other library errors
389 
390 @since version 3.0.0
391 */
392 class type_error : public exception
393 {
394  public:
395  static type_error create(int id_, const std::string& what_arg)
396  {
397  std::string w = exception::name("type_error", id_) + what_arg;
398  return type_error(id_, w.c_str());
399  }
400 
401  private:
402  type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
403 };
404 
405 /*!
406 @brief exception indicating access out of the defined range
407 
408 This exception is thrown in case a library function is called on an input
409 parameter that exceeds the expected range, for instance in case of array
410 indices or nonexisting object keys.
411 
412 Exceptions have ids 4xx.
413 
414 name / id | example message | description
415 ------------------------------- | --------------- | -------------------------
416 json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1.
417 json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
418 json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
419 json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
420 json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
421 json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF.
422 
423 @liveexample{The following code shows how an `out_of_range` exception can be
424 caught.,out_of_range}
425 
426 @sa @ref exception for the base class of the library exceptions
427 @sa @ref parse_error for exceptions indicating a parse error
428 @sa @ref invalid_iterator for exceptions indicating errors with iterators
429 @sa @ref type_error for exceptions indicating executing a member function with
430  a wrong type
431 @sa @ref other_error for exceptions indicating other library errors
432 
433 @since version 3.0.0
434 */
435 class out_of_range : public exception
436 {
437  public:
438  static out_of_range create(int id_, const std::string& what_arg)
439  {
440  std::string w = exception::name("out_of_range", id_) + what_arg;
441  return out_of_range(id_, w.c_str());
442  }
443 
444  private:
445  out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
446 };
447 
448 /*!
449 @brief exception indicating other library errors
450 
451 This exception is thrown in case of errors that cannot be classified with the
452 other exception types.
453 
454 Exceptions have ids 5xx.
455 
456 name / id | example message | description
457 ------------------------------ | --------------- | -------------------------
458 json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
459 
460 @sa @ref exception for the base class of the library exceptions
461 @sa @ref parse_error for exceptions indicating a parse error
462 @sa @ref invalid_iterator for exceptions indicating errors with iterators
463 @sa @ref type_error for exceptions indicating executing a member function with
464  a wrong type
465 @sa @ref out_of_range for exceptions indicating access out of the defined range
466 
467 @liveexample{The following code shows how an `other_error` exception can be
468 caught.,other_error}
469 
470 @since version 3.0.0
471 */
472 class other_error : public exception
473 {
474  public:
475  static other_error create(int id_, const std::string& what_arg)
476  {
477  std::string w = exception::name("other_error", id_) + what_arg;
478  return other_error(id_, w.c_str());
479  }
480 
481  private:
482  other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
483 };
484 
485 
486 
487 ///////////////////////////
488 // JSON type enumeration //
489 ///////////////////////////
490 
491 /*!
492 @brief the JSON type enumeration
493 
494 This enumeration collects the different JSON types. It is internally used to
495 distinguish the stored values, and the functions @ref basic_json::is_null(),
496 @ref basic_json::is_object(), @ref basic_json::is_array(),
497 @ref basic_json::is_string(), @ref basic_json::is_boolean(),
498 @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
499 @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
500 @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
501 @ref basic_json::is_structured() rely on it.
502 
503 @note There are three enumeration entries (number_integer, number_unsigned, and
504 number_float), because the library distinguishes these three types for numbers:
505 @ref basic_json::number_unsigned_t is used for unsigned integers,
506 @ref basic_json::number_integer_t is used for signed integers, and
507 @ref basic_json::number_float_t is used for floating-point numbers or to
508 approximate integers which do not fit in the limits of their respective type.
509 
510 @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
511 value with the default value for a given type
512 
513 @since version 1.0.0
514 */
515 enum class value_t : uint8_t
516 {
517  null, ///< null value
518  object, ///< object (unordered set of name/value pairs)
519  array, ///< array (ordered collection of values)
520  string, ///< string value
521  boolean, ///< boolean value
522  number_integer, ///< number value (signed integer)
523  number_unsigned, ///< number value (unsigned integer)
524  number_float, ///< number value (floating-point)
525  discarded ///< discarded by the the parser callback function
526 };
527 
528 /*!
529 @brief comparison operator for JSON types
530 
531 Returns an ordering that is similar to Python:
532 - order: null < boolean < number < object < array < string
533 - furthermore, each type is not smaller than itself
534 - discarded values are not comparable
535 
536 @since version 1.0.0
537 */
538 inline bool operator<(const value_t lhs, const value_t rhs) noexcept
539 {
540  static constexpr std::array<uint8_t, 8> order = {{
541  0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
542  1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
543  }
544  };
545 
546  const auto l_index = static_cast<std::size_t>(lhs);
547  const auto r_index = static_cast<std::size_t>(rhs);
548  return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
549 }
550 
551 
552 /////////////
553 // helpers //
554 /////////////
555 
556 template<typename> struct is_basic_json : std::false_type {};
557 
559 struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
560 
561 // alias templates to reduce boilerplate
562 template<bool B, typename T = void>
563 using enable_if_t = typename std::enable_if<B, T>::type;
564 
565 template<typename T>
566 using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
567 
568 // implementation of C++14 index_sequence and affiliates
569 // source: https://stackoverflow.com/a/32223343
570 template<std::size_t... Ints>
571 struct index_sequence
572 {
573  using type = index_sequence;
574  using value_type = std::size_t;
575  static constexpr std::size_t size() noexcept
576  {
577  return sizeof...(Ints);
578  }
579 };
580 
581 template<class Sequence1, class Sequence2>
582 struct merge_and_renumber;
583 
584 template<std::size_t... I1, std::size_t... I2>
585 struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
586  : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
587 
588 template<std::size_t N>
589 struct make_index_sequence
590  : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
591  typename make_index_sequence < N - N / 2 >::type > {};
592 
593 template<> struct make_index_sequence<0> : index_sequence<> {};
594 template<> struct make_index_sequence<1> : index_sequence<0> {};
595 
596 template<typename... Ts>
597 using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
598 
599 /*
600 Implementation of two C++17 constructs: conjunction, negation. This is needed
601 to avoid evaluating all the traits in a condition
602 
603 For example: not std::is_same<void, T>::value and has_value_type<T>::value
604 will not compile when T = void (on MSVC at least). Whereas
605 conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
606 stop evaluating if negation<...>::value == false
607 
608 Please note that those constructs must be used with caution, since symbols can
609 become very long quickly (which can slow down compilation and cause MSVC
610 internal compiler errors). Only use it when you have to (see example ahead).
611 */
612 template<class...> struct conjunction : std::true_type {};
613 template<class B1> struct conjunction<B1> : B1 {};
614 template<class B1, class... Bn>
615 struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
616 
617 template<class B> struct negation : std::integral_constant<bool, not B::value> {};
618 
619 // dispatch utility (taken from ranges-v3)
620 template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
621 template<> struct priority_tag<0> {};
622 
623 
624 //////////////////
625 // constructors //
626 //////////////////
627 
628 template<value_t> struct external_constructor;
629 
630 template<>
631 struct external_constructor<value_t::boolean>
632 {
633  template<typename BasicJsonType>
634  static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
635  {
636  j.m_type = value_t::boolean;
637  j.m_value = b;
638  j.assert_invariant();
639  }
640 };
641 
642 template<>
643 struct external_constructor<value_t::string>
644 {
645  template<typename BasicJsonType>
646  static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
647  {
648  j.m_type = value_t::string;
649  j.m_value = s;
650  j.assert_invariant();
651  }
652 
653  template<typename BasicJsonType>
654  static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
655  {
656  j.m_type = value_t::string;
657  j.m_value = std::move(s);
658  j.assert_invariant();
659  }
660 };
661 
662 template<>
663 struct external_constructor<value_t::number_float>
664 {
665  template<typename BasicJsonType>
666  static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
667  {
668  j.m_type = value_t::number_float;
669  j.m_value = val;
670  j.assert_invariant();
671  }
672 };
673 
674 template<>
675 struct external_constructor<value_t::number_unsigned>
676 {
677  template<typename BasicJsonType>
678  static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
679  {
680  j.m_type = value_t::number_unsigned;
681  j.m_value = val;
682  j.assert_invariant();
683  }
684 };
685 
686 template<>
687 struct external_constructor<value_t::number_integer>
688 {
689  template<typename BasicJsonType>
690  static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
691  {
692  j.m_type = value_t::number_integer;
693  j.m_value = val;
694  j.assert_invariant();
695  }
696 };
697 
698 template<>
699 struct external_constructor<value_t::array>
700 {
701  template<typename BasicJsonType>
702  static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
703  {
704  j.m_type = value_t::array;
705  j.m_value = arr;
706  j.assert_invariant();
707  }
708 
709  template<typename BasicJsonType>
710  static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
711  {
712  j.m_type = value_t::array;
713  j.m_value = std::move(arr);
714  j.assert_invariant();
715  }
716 
717  template<typename BasicJsonType, typename CompatibleArrayType,
718  enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
719  int> = 0>
720  static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
721  {
722  using std::begin;
723  using std::end;
724  j.m_type = value_t::array;
725  j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
726  j.assert_invariant();
727  }
728 
729  template<typename BasicJsonType>
730  static void construct(BasicJsonType& j, const std::vector<bool>& arr)
731  {
732  j.m_type = value_t::array;
733  j.m_value = value_t::array;
734  j.m_value.array->reserve(arr.size());
735  for (const bool x : arr)
736  {
737  j.m_value.array->push_back(x);
738  }
739  j.assert_invariant();
740  }
741 
742  template<typename BasicJsonType, typename T,
743  enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
744  static void construct(BasicJsonType& j, const std::valarray<T>& arr)
745  {
746  j.m_type = value_t::array;
747  j.m_value = value_t::array;
748  j.m_value.array->resize(arr.size());
749  std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
750  j.assert_invariant();
751  }
752 };
753 
754 template<>
755 struct external_constructor<value_t::object>
756 {
757  template<typename BasicJsonType>
758  static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
759  {
760  j.m_type = value_t::object;
761  j.m_value = obj;
762  j.assert_invariant();
763  }
764 
765  template<typename BasicJsonType>
766  static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
767  {
768  j.m_type = value_t::object;
769  j.m_value = std::move(obj);
770  j.assert_invariant();
771  }
772 
773  template<typename BasicJsonType, typename CompatibleObjectType,
774  enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
775  static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
776  {
777  using std::begin;
778  using std::end;
779 
780  j.m_type = value_t::object;
781  j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
782  j.assert_invariant();
783  }
784 };
785 
786 
787 ////////////////////////
788 // has_/is_ functions //
789 ////////////////////////
790 
791 /*!
792 @brief Helper to determine whether there's a key_type for T.
793 
794 This helper is used to tell associative containers apart from other containers
795 such as sequence containers. For instance, `std::map` passes the test as it
796 contains a `mapped_type`, whereas `std::vector` fails the test.
797 
798 @sa http://stackoverflow.com/a/7728728/266378
799 @since version 1.0.0, overworked in version 2.0.6
800 */
801 #define NLOHMANN_JSON_HAS_HELPER(type)
802  template<typename T> struct has_##type {
803  private:
804  template<typename U, typename = typename U::type>
805  static int detect(U &&);
806  static void detect(...);
807  public:
808  static constexpr bool value =
809  std::is_integral<decltype(detect(std::declval<T>()))>::value;
810  }
811 
812 NLOHMANN_JSON_HAS_HELPER(mapped_type);
813 NLOHMANN_JSON_HAS_HELPER(key_type);
814 NLOHMANN_JSON_HAS_HELPER(value_type);
815 NLOHMANN_JSON_HAS_HELPER(iterator);
816 
817 #undef NLOHMANN_JSON_HAS_HELPER
818 
819 
820 template<bool B, class RealType, class CompatibleObjectType>
821 struct is_compatible_object_type_impl : std::false_type {};
822 
823 template<class RealType, class CompatibleObjectType>
824 struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
825 {
826  static constexpr auto value =
827  std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and
828  std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value;
829 };
830 
831 template<class BasicJsonType, class CompatibleObjectType>
832 struct is_compatible_object_type
833 {
834  static auto constexpr value = is_compatible_object_type_impl <
835  conjunction<negation<std::is_same<void, CompatibleObjectType>>,
836  has_mapped_type<CompatibleObjectType>,
837  has_key_type<CompatibleObjectType>>::value,
838  typename BasicJsonType::object_t, CompatibleObjectType >::value;
839 };
840 
841 template<typename BasicJsonType, typename T>
842 struct is_basic_json_nested_type
843 {
844  static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
845  std::is_same<T, typename BasicJsonType::const_iterator>::value or
846  std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
847  std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value;
848 };
849 
850 template<class BasicJsonType, class CompatibleArrayType>
851 struct is_compatible_array_type
852 {
853  static auto constexpr value =
854  conjunction<negation<std::is_same<void, CompatibleArrayType>>,
855  negation<is_compatible_object_type<
856  BasicJsonType, CompatibleArrayType>>,
857  negation<std::is_constructible<typename BasicJsonType::string_t,
858  CompatibleArrayType>>,
859  negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
860  has_value_type<CompatibleArrayType>,
861  has_iterator<CompatibleArrayType>>::value;
862 };
863 
864 template<bool, typename, typename>
865 struct is_compatible_integer_type_impl : std::false_type {};
866 
867 template<typename RealIntegerType, typename CompatibleNumberIntegerType>
868 struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
869 {
870  // is there an assert somewhere on overflows?
871  using RealLimits = std::numeric_limits<RealIntegerType>;
872  using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
873 
874  static constexpr auto value =
875  std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and
876  CompatibleLimits::is_integer and
877  RealLimits::is_signed == CompatibleLimits::is_signed;
878 };
879 
880 template<typename RealIntegerType, typename CompatibleNumberIntegerType>
881 struct is_compatible_integer_type
882 {
883  static constexpr auto value =
884  is_compatible_integer_type_impl <
885  std::is_integral<CompatibleNumberIntegerType>::value and
886  not std::is_same<bool, CompatibleNumberIntegerType>::value,
887  RealIntegerType, CompatibleNumberIntegerType >::value;
888 };
889 
890 
891 // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
892 template<typename BasicJsonType, typename T>
893 struct has_from_json
894 {
895  private:
896  // also check the return type of from_json
897  template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
898  std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
899  static int detect(U&&);
900  static void detect(...);
901 
902  public:
903  static constexpr bool value = std::is_integral<decltype(
904  detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
905 };
906 
907 // This trait checks if JSONSerializer<T>::from_json(json const&) exists
908 // this overload is used for non-default-constructible user-defined-types
909 template<typename BasicJsonType, typename T>
910 struct has_non_default_from_json
911 {
912  private:
913  template<typename U, typename =
914  enable_if_t<std::is_same<T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value>>
915  static int detect(U&&);
916  static void detect(...);
917 
918  public:
919  static constexpr bool value = std::is_integral<decltype(detect(
920  std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
921 };
922 
923 // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
924 template<typename BasicJsonType, typename T>
925 struct has_to_json
926 {
927  private:
928  template<typename U, typename = decltype(uncvref_t<U>::to_json(
929  std::declval<BasicJsonType&>(), std::declval<T>()))>
930  static int detect(U&&);
931  static void detect(...);
932 
933  public:
934  static constexpr bool value = std::is_integral<decltype(detect(
935  std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
936 };
937 
938 
939 /////////////
940 // to_json //
941 /////////////
942 
943 template<typename BasicJsonType, typename T,
944  enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
945 void to_json(BasicJsonType& j, T b) noexcept
946 {
947  external_constructor<value_t::boolean>::construct(j, b);
948 }
949 
950 template<typename BasicJsonType, typename CompatibleString,
951  enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
952 void to_json(BasicJsonType& j, const CompatibleString& s)
953 {
954  external_constructor<value_t::string>::construct(j, s);
955 }
956 
957 template<typename BasicJsonType>
958 void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
959 {
960  external_constructor<value_t::string>::construct(j, std::move(s));
961 }
962 
963 template<typename BasicJsonType, typename FloatType,
964  enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
965 void to_json(BasicJsonType& j, FloatType val) noexcept
966 {
967  external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
968 }
969 
970 template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
971  enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
972 void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
973 {
974  external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
975 }
976 
977 template<typename BasicJsonType, typename CompatibleNumberIntegerType,
978  enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
979 void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
980 {
981  external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
982 }
983 
984 template<typename BasicJsonType, typename EnumType,
985  enable_if_t<std::is_enum<EnumType>::value, int> = 0>
986 void to_json(BasicJsonType& j, EnumType e) noexcept
987 {
988  using underlying_type = typename std::underlying_type<EnumType>::type;
989  external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
990 }
991 
992 template<typename BasicJsonType>
993 void to_json(BasicJsonType& j, const std::vector<bool>& e)
994 {
995  external_constructor<value_t::array>::construct(j, e);
996 }
997 
998 template<typename BasicJsonType, typename CompatibleArrayType,
999  enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
1000  std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
1001  int> = 0>
1002 void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
1003 {
1004  external_constructor<value_t::array>::construct(j, arr);
1005 }
1006 
1007 template<typename BasicJsonType, typename T,
1008  enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
1009 void to_json(BasicJsonType& j, std::valarray<T> arr)
1010 {
1011  external_constructor<value_t::array>::construct(j, std::move(arr));
1012 }
1013 
1014 template<typename BasicJsonType>
1015 void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
1016 {
1017  external_constructor<value_t::array>::construct(j, std::move(arr));
1018 }
1019 
1020 template<typename BasicJsonType, typename CompatibleObjectType,
1021  enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
1022 void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
1023 {
1024  external_constructor<value_t::object>::construct(j, obj);
1025 }
1026 
1027 template<typename BasicJsonType>
1028 void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
1029 {
1030  external_constructor<value_t::object>::construct(j, std::move(obj));
1031 }
1032 
1033 template<typename BasicJsonType, typename T, std::size_t N,
1034  enable_if_t<not std::is_constructible<typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0>
1035 void to_json(BasicJsonType& j, T (&arr)[N])
1036 {
1037  external_constructor<value_t::array>::construct(j, arr);
1038 }
1039 
1040 template<typename BasicJsonType, typename... Args>
1041 void to_json(BasicJsonType& j, const std::pair<Args...>& p)
1042 {
1043  j = {p.first, p.second};
1044 }
1045 
1046 template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
1047 void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>)
1048 {
1049  j = {std::get<Idx>(t)...};
1050 }
1051 
1052 template<typename BasicJsonType, typename... Args>
1053 void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
1054 {
1055  to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
1056 }
1057 
1058 ///////////////
1059 // from_json //
1060 ///////////////
1061 
1062 // overloads for basic_json template parameters
1063 template<typename BasicJsonType, typename ArithmeticType,
1064  enable_if_t<std::is_arithmetic<ArithmeticType>::value and
1065  not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
1066  int> = 0>
1067 void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
1068 {
1069  switch (static_cast<value_t>(j))
1070  {
1071  case value_t::number_unsigned:
1072  {
1073  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
1074  break;
1075  }
1076  case value_t::number_integer:
1077  {
1078  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
1079  break;
1080  }
1081  case value_t::number_float:
1082  {
1083  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
1084  break;
1085  }
1086 
1087  default:
1088  JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
1089  }
1090 }
1091 
1092 template<typename BasicJsonType>
1093 void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
1094 {
1095  if (JSON_UNLIKELY(not j.is_boolean()))
1096  {
1097  JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
1098  }
1099  b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
1100 }
1101 
1102 template<typename BasicJsonType>
1103 void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
1104 {
1105  if (JSON_UNLIKELY(not j.is_string()))
1106  {
1107  JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
1108  }
1109  s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
1110 }
1111 
1112 template<typename BasicJsonType>
1113 void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
1114 {
1115  get_arithmetic_value(j, val);
1116 }
1117 
1118 template<typename BasicJsonType>
1119 void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
1120 {
1121  get_arithmetic_value(j, val);
1122 }
1123 
1124 template<typename BasicJsonType>
1125 void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
1126 {
1127  get_arithmetic_value(j, val);
1128 }
1129 
1130 template<typename BasicJsonType, typename EnumType,
1131  enable_if_t<std::is_enum<EnumType>::value, int> = 0>
1132 void from_json(const BasicJsonType& j, EnumType& e)
1133 {
1134  typename std::underlying_type<EnumType>::type val;
1135  get_arithmetic_value(j, val);
1136  e = static_cast<EnumType>(val);
1137 }
1138 
1139 template<typename BasicJsonType>
1140 void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
1141 {
1142  if (JSON_UNLIKELY(not j.is_array()))
1143  {
1144  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1145  }
1146  arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
1147 }
1148 
1149 // forward_list doesn't have an insert method
1150 template<typename BasicJsonType, typename T, typename Allocator,
1151  enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
1152 void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
1153 {
1154  if (JSON_UNLIKELY(not j.is_array()))
1155  {
1156  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1157  }
1158  std::transform(j.rbegin(), j.rend(),
1159  std::front_inserter(l), [](const BasicJsonType & i)
1160  {
1161  return i.template get<T>();
1162  });
1163 }
1164 
1165 // valarray doesn't have an insert method
1166 template<typename BasicJsonType, typename T,
1167  enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
1168 void from_json(const BasicJsonType& j, std::valarray<T>& l)
1169 {
1170  if (JSON_UNLIKELY(not j.is_array()))
1171  {
1172  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1173  }
1174  l.resize(j.size());
1175  std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
1176 }
1177 
1178 template<typename BasicJsonType, typename CompatibleArrayType>
1179 void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/)
1180 {
1181  using std::end;
1182 
1183  std::transform(j.begin(), j.end(),
1184  std::inserter(arr, end(arr)), [](const BasicJsonType & i)
1185  {
1186  // get<BasicJsonType>() returns *this, this won't call a from_json
1187  // method when value_type is BasicJsonType
1188  return i.template get<typename CompatibleArrayType::value_type>();
1189  });
1190 }
1191 
1192 template<typename BasicJsonType, typename CompatibleArrayType>
1193 auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/)
1194 -> decltype(
1195  arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
1196  void())
1197 {
1198  using std::end;
1199 
1200  arr.reserve(j.size());
1201  std::transform(j.begin(), j.end(),
1202  std::inserter(arr, end(arr)), [](const BasicJsonType & i)
1203  {
1204  // get<BasicJsonType>() returns *this, this won't call a from_json
1205  // method when value_type is BasicJsonType
1206  return i.template get<typename CompatibleArrayType::value_type>();
1207  });
1208 }
1209 
1210 template<typename BasicJsonType, typename T, std::size_t N>
1211 void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/)
1212 {
1213  for (std::size_t i = 0; i < N; ++i)
1214  {
1215  arr[i] = j.at(i).template get<T>();
1216  }
1217 }
1218 
1219 template<typename BasicJsonType, typename CompatibleArrayType,
1220  enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
1221  std::is_convertible<BasicJsonType, typename CompatibleArrayType::value_type>::value and
1222  not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0>
1223 void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
1224 {
1225  if (JSON_UNLIKELY(not j.is_array()))
1226  {
1227  JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
1228  }
1229 
1230  from_json_array_impl(j, arr, priority_tag<2> {});
1231 }
1232 
1233 template<typename BasicJsonType, typename CompatibleObjectType,
1234  enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
1235 void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
1236 {
1237  if (JSON_UNLIKELY(not j.is_object()))
1238  {
1239  JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
1240  }
1241 
1242  auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
1243  using value_type = typename CompatibleObjectType::value_type;
1244  std::transform(
1245  inner_object->begin(), inner_object->end(),
1246  std::inserter(obj, obj.begin()),
1247  [](typename BasicJsonType::object_t::value_type const & p)
1248  {
1249  return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>());
1250  });
1251 }
1252 
1253 // overload for arithmetic types, not chosen for basic_json template arguments
1254 // (BooleanType, etc..); note: Is it really necessary to provide explicit
1255 // overloads for boolean_t etc. in case of a custom BooleanType which is not
1256 // an arithmetic type?
1257 template<typename BasicJsonType, typename ArithmeticType,
1258  enable_if_t <
1259  std::is_arithmetic<ArithmeticType>::value and
1260  not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
1261  not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
1262  not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
1263  not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
1264  int> = 0>
1265 void from_json(const BasicJsonType& j, ArithmeticType& val)
1266 {
1267  switch (static_cast<value_t>(j))
1268  {
1269  case value_t::number_unsigned:
1270  {
1271  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
1272  break;
1273  }
1274  case value_t::number_integer:
1275  {
1276  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
1277  break;
1278  }
1279  case value_t::number_float:
1280  {
1281  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
1282  break;
1283  }
1284  case value_t::boolean:
1285  {
1286  val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
1287  break;
1288  }
1289 
1290  default:
1291  JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
1292  }
1293 }
1294 
1295 template<typename BasicJsonType, typename A1, typename A2>
1296 void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
1297 {
1298  p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
1299 }
1300 
1301 template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
1302 void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>)
1303 {
1304  t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
1305 }
1306 
1307 template<typename BasicJsonType, typename... Args>
1308 void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
1309 {
1310  from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
1311 }
1312 
1313 struct to_json_fn
1314 {
1315  private:
1316  template<typename BasicJsonType, typename T>
1317  auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
1318  -> decltype(to_json(j, std::forward<T>(val)), void())
1319  {
1320  return to_json(j, std::forward<T>(val));
1321  }
1322 
1323  template<typename BasicJsonType, typename T>
1324  void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept
1325  {
1326  static_assert(sizeof(BasicJsonType) == 0,
1327  "could not find to_json() method in T's namespace");
1328 
1329 #ifdef _MSC_VER
1330  // MSVC does not show a stacktrace for the above assert
1331  using decayed = uncvref_t<T>;
1332  static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
1333  "forcing MSVC stacktrace to show which T we're talking about.");
1334 #endif
1335  }
1336 
1337  public:
1338  template<typename BasicJsonType, typename T>
1339  void operator()(BasicJsonType& j, T&& val) const
1340  noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
1341  {
1342  return call(j, std::forward<T>(val), priority_tag<1> {});
1343  }
1344 };
1345 
1346 struct from_json_fn
1347 {
1348  private:
1349  template<typename BasicJsonType, typename T>
1350  auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const
1351  noexcept(noexcept(from_json(j, val)))
1352  -> decltype(from_json(j, val), void())
1353  {
1354  return from_json(j, val);
1355  }
1356 
1357  template<typename BasicJsonType, typename T>
1358  void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept
1359  {
1360  static_assert(sizeof(BasicJsonType) == 0,
1361  "could not find from_json() method in T's namespace");
1362 #ifdef _MSC_VER
1363  // MSVC does not show a stacktrace for the above assert
1364  using decayed = uncvref_t<T>;
1365  static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
1366  "forcing MSVC stacktrace to show which T we're talking about.");
1367 #endif
1368  }
1369 
1370  public:
1371  template<typename BasicJsonType, typename T>
1372  void operator()(const BasicJsonType& j, T& val) const
1373  noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
1374  {
1375  return call(j, val, priority_tag<1> {});
1376  }
1377 };
1378 
1379 // taken from ranges-v3
1380 template<typename T>
1381 struct static_const
1382 {
1383  static constexpr T value{};
1384 };
1385 
1386 template<typename T>
1387 constexpr T static_const<T>::value;
1388 
1389 ////////////////////
1390 // input adapters //
1391 ////////////////////
1392 
1393 /*!
1394 @brief abstract input adapter interface
1395 
1396 Produces a stream of std::char_traits<char>::int_type characters from a
1397 std::istream, a buffer, or some other input type. Accepts the return of exactly
1398 one non-EOF character for future input. The int_type characters returned
1399 consist of all valid char values as positive values (typically unsigned char),
1400 plus an EOF value outside that range, specified by the value of the function
1401 std::char_traits<char>::eof(). This value is typically -1, but could be any
1402 arbitrary value which is not a valid char value.
1403 */
1404 struct input_adapter_protocol
1405 {
1406  /// get a character [0,255] or std::char_traits<char>::eof().
1407  virtual std::char_traits<char>::int_type get_character() = 0;
1408  /// restore the last non-eof() character to input
1409  virtual void unget_character() = 0;
1410  virtual ~input_adapter_protocol() = default;
1411 };
1412 
1413 /// a type to simplify interfaces
1414 using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
1415 
1416 /*!
1417 Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
1418 beginning of input. Does not support changing the underlying std::streambuf
1419 in mid-input. Maintains underlying std::istream and std::streambuf to support
1420 subsequent use of standard std::istream operations to process any input
1421 characters following those used in parsing the JSON input. Clears the
1422 std::istream flags; any input errors (e.g., EOF) will be detected by the first
1423 subsequent call for input from the std::istream.
1424 */
1425 class input_stream_adapter : public input_adapter_protocol
1426 {
1427  public:
1428  ~input_stream_adapter() override
1429  {
1430  // clear stream flags; we use underlying streambuf I/O, do not
1431  // maintain ifstream flags
1432  is.clear();
1433  }
1434 
1435  explicit input_stream_adapter(std::istream& i)
1436  : is(i), sb(*i.rdbuf())
1437  {
1438  // skip byte order mark
1439  std::char_traits<char>::int_type c;
1440  if ((c = get_character()) == 0xEF)
1441  {
1442  if ((c = get_character()) == 0xBB)
1443  {
1444  if ((c = get_character()) == 0xBF)
1445  {
1446  return; // Ignore BOM
1447  }
1448  else if (c != std::char_traits<char>::eof())
1449  {
1450  is.unget();
1451  }
1452  is.putback('\xBB');
1453  }
1454  else if (c != std::char_traits<char>::eof())
1455  {
1456  is.unget();
1457  }
1458  is.putback('\xEF');
1459  }
1460  else if (c != std::char_traits<char>::eof())
1461  {
1462  is.unget(); // no byte order mark; process as usual
1463  }
1464  }
1465 
1466  // delete because of pointer members
1467  input_stream_adapter(const input_stream_adapter&) = delete;
1468  input_stream_adapter& operator=(input_stream_adapter&) = delete;
1469 
1470  // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
1471  // ensure that std::char_traits<char>::eof() and the character 0xFF do not
1472  // end up as the same value, eg. 0xFFFFFFFF.
1473  std::char_traits<char>::int_type get_character() override
1474  {
1475  return sb.sbumpc();
1476  }
1477 
1478  void unget_character() override
1479  {
1480  sb.sungetc(); // is.unget() avoided for performance
1481  }
1482 
1483  private:
1484  /// the associated input stream
1485  std::istream& is;
1486  std::streambuf& sb;
1487 };
1488 
1489 /// input adapter for buffer input
1490 class input_buffer_adapter : public input_adapter_protocol
1491 {
1492  public:
1493  input_buffer_adapter(const char* b, const std::size_t l)
1494  : cursor(b), limit(b + l), start(b)
1495  {
1496  // skip byte order mark
1497  if (l >= 3 and b[0] == '\xEF' and b[1] == '\xBB' and b[2] == '\xBF')
1498  {
1499  cursor += 3;
1500  }
1501  }
1502 
1503  // delete because of pointer members
1504  input_buffer_adapter(const input_buffer_adapter&) = delete;
1505  input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
1506 
1507  std::char_traits<char>::int_type get_character() noexcept override
1508  {
1509  if (JSON_LIKELY(cursor < limit))
1510  {
1511  return std::char_traits<char>::to_int_type(*(cursor++));
1512  }
1513 
1514  return std::char_traits<char>::eof();
1515  }
1516 
1517  void unget_character() noexcept override
1518  {
1519  if (JSON_LIKELY(cursor > start))
1520  {
1521  --cursor;
1522  }
1523  }
1524 
1525  private:
1526  /// pointer to the current character
1527  const char* cursor;
1528  /// pointer past the last character
1529  const char* limit;
1530  /// pointer to the first character
1531  const char* start;
1532 };
1533 
1534 class input_adapter
1535 {
1536  public:
1537  // native support
1538 
1539  /// input adapter for input stream
1540  input_adapter(std::istream& i)
1541  : ia(std::make_shared<input_stream_adapter>(i)) {}
1542 
1543  /// input adapter for input stream
1544  input_adapter(std::istream&& i)
1545  : ia(std::make_shared<input_stream_adapter>(i)) {}
1546 
1547  /// input adapter for buffer
1548  template<typename CharT,
1549  typename std::enable_if<
1550  std::is_pointer<CharT>::value and
1551  std::is_integral<typename std::remove_pointer<CharT>::type>::value and
1552  sizeof(typename std::remove_pointer<CharT>::type) == 1,
1553  int>::type = 0>
1554  input_adapter(CharT b, std::size_t l)
1555  : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
1556 
1557  // derived support
1558 
1559  /// input adapter for string literal
1560  template<typename CharT,
1561  typename std::enable_if<
1562  std::is_pointer<CharT>::value and
1563  std::is_integral<typename std::remove_pointer<CharT>::type>::value and
1564  sizeof(typename std::remove_pointer<CharT>::type) == 1,
1565  int>::type = 0>
1566  input_adapter(CharT b)
1567  : input_adapter(reinterpret_cast<const char*>(b),
1568  std::strlen(reinterpret_cast<const char*>(b))) {}
1569 
1570  /// input adapter for iterator range with contiguous storage
1571  template<class IteratorType,
1572  typename std::enable_if<
1573  std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
1574  int>::type = 0>
1575  input_adapter(IteratorType first, IteratorType last)
1576  {
1577  // assertion to check that the iterator range is indeed contiguous,
1578  // see http://stackoverflow.com/a/35008842/266378 for more discussion
1579  assert(std::accumulate(
1580  first, last, std::pair<bool, int>(true, 0),
1581  [&first](std::pair<bool, int> res, decltype(*first) val)
1582  {
1583  res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
1584  return res;
1585  }).first);
1586 
1587  // assertion to check that each element is 1 byte long
1588  static_assert(
1589  sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
1590  "each element in the iterator range must have the size of 1 byte");
1591 
1592  const auto len = static_cast<size_t>(std::distance(first, last));
1593  if (JSON_LIKELY(len > 0))
1594  {
1595  // there is at least one element: use the address of first
1596  ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
1597  }
1598  else
1599  {
1600  // the address of first cannot be used: use nullptr
1601  ia = std::make_shared<input_buffer_adapter>(nullptr, len);
1602  }
1603  }
1604 
1605  /// input adapter for array
1606  template<class T, std::size_t N>
1607  input_adapter(T (&array)[N])
1608  : input_adapter(std::begin(array), std::end(array)) {}
1609 
1610  /// input adapter for contiguous container
1611  template<class ContiguousContainer, typename
1612  std::enable_if<not std::is_pointer<ContiguousContainer>::value and
1613  std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
1614  int>::type = 0>
1615  input_adapter(const ContiguousContainer& c)
1616  : input_adapter(std::begin(c), std::end(c)) {}
1617 
1618  operator input_adapter_t()
1619  {
1620  return ia;
1621  }
1622 
1623  private:
1624  /// the actual adapter
1625  input_adapter_t ia = nullptr;
1626 };
1627 
1628 //////////////////////
1629 // lexer and parser //
1630 //////////////////////
1631 
1632 /*!
1633 @brief lexical analysis
1634 
1635 This class organizes the lexical analysis during JSON deserialization.
1636 */
1637 template<typename BasicJsonType>
1638 class lexer
1639 {
1640  using number_integer_t = typename BasicJsonType::number_integer_t;
1641  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
1642  using number_float_t = typename BasicJsonType::number_float_t;
1643 
1644  public:
1645  /// token types for the parser
1646  enum class token_type
1647  {
1648  uninitialized, ///< indicating the scanner is uninitialized
1649  literal_true, ///< the `true` literal
1650  literal_false, ///< the `false` literal
1651  literal_null, ///< the `null` literal
1652  value_string, ///< a string -- use get_string() for actual value
1653  value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
1654  value_integer, ///< a signed integer -- use get_number_integer() for actual value
1655  value_float, ///< an floating point number -- use get_number_float() for actual value
1656  begin_array, ///< the character for array begin `[`
1657  begin_object, ///< the character for object begin `{`
1658  end_array, ///< the character for array end `]`
1659  end_object, ///< the character for object end `}`
1660  name_separator, ///< the name separator `:`
1661  value_separator, ///< the value separator `,`
1662  parse_error, ///< indicating a parse error
1663  end_of_input, ///< indicating the end of the input buffer
1664  literal_or_value ///< a literal or the begin of a value (only for diagnostics)
1665  };
1666 
1667  /// return name of values of type token_type (only used for errors)
1668  static const char* token_type_name(const token_type t) noexcept
1669  {
1670  switch (t)
1671  {
1672  case token_type::uninitialized:
1673  return "<uninitialized>";
1674  case token_type::literal_true:
1675  return "true literal";
1676  case token_type::literal_false:
1677  return "false literal";
1678  case token_type::literal_null:
1679  return "null literal";
1680  case token_type::value_string:
1681  return "string literal";
1682  case lexer::token_type::value_unsigned:
1683  case lexer::token_type::value_integer:
1684  case lexer::token_type::value_float:
1685  return "number literal";
1686  case token_type::begin_array:
1687  return "'['";
1688  case token_type::begin_object:
1689  return "'{'";
1690  case token_type::end_array:
1691  return "']'";
1692  case token_type::end_object:
1693  return "'}'";
1694  case token_type::name_separator:
1695  return "':'";
1696  case token_type::value_separator:
1697  return "','";
1698  case token_type::parse_error:
1699  return "<parse error>";
1700  case token_type::end_of_input:
1701  return "end of input";
1702  case token_type::literal_or_value:
1703  return "'[', '{', or a literal";
1704  default: // catch non-enum values
1705  return "unknown token"; // LCOV_EXCL_LINE
1706  }
1707  }
1708 
1709  explicit lexer(detail::input_adapter_t adapter)
1710  : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
1711 
1712  // delete because of pointer members
1713  lexer(const lexer&) = delete;
1714  lexer& operator=(lexer&) = delete;
1715 
1716  private:
1717  /////////////////////
1718  // locales
1719  /////////////////////
1720 
1721  /// return the locale-dependent decimal point
1722  static char get_decimal_point() noexcept
1723  {
1724  const auto loc = localeconv();
1725  assert(loc != nullptr);
1726  return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
1727  }
1728 
1729  /////////////////////
1730  // scan functions
1731  /////////////////////
1732 
1733  /*!
1734  @brief get codepoint from 4 hex characters following `\u`
1735 
1736  For input "\u c1 c2 c3 c4" the codepoint is:
1737  (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
1738  = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
1739 
1740  Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
1741  must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
1742  conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
1743  between the ASCII value of the character and the desired integer value.
1744 
1745  @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
1746  non-hex character)
1747  */
1748  int get_codepoint()
1749  {
1750  // this function only makes sense after reading `\u`
1751  assert(current == 'u');
1752  int codepoint = 0;
1753 
1754  const auto factors = { 12, 8, 4, 0 };
1755  for (const auto factor : factors)
1756  {
1757  get();
1758 
1759  if (current >= '0' and current <= '9')
1760  {
1761  codepoint += ((current - 0x30) << factor);
1762  }
1763  else if (current >= 'A' and current <= 'F')
1764  {
1765  codepoint += ((current - 0x37) << factor);
1766  }
1767  else if (current >= 'a' and current <= 'f')
1768  {
1769  codepoint += ((current - 0x57) << factor);
1770  }
1771  else
1772  {
1773  return -1;
1774  }
1775  }
1776 
1777  assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
1778  return codepoint;
1779  }
1780 
1781  /*!
1782  @brief check if the next byte(s) are inside a given range
1783 
1784  Adds the current byte and, for each passed range, reads a new byte and
1785  checks if it is inside the range. If a violation was detected, set up an
1786  error message and return false. Otherwise, return true.
1787 
1788  @param[in] ranges list of integers; interpreted as list of pairs of
1789  inclusive lower and upper bound, respectively
1790 
1791  @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
1792  1, 2, or 3 pairs. This precondition is enforced by an assertion.
1793 
1794  @return true if and only if no range violation was detected
1795  */
1796  bool next_byte_in_range(std::initializer_list<int> ranges)
1797  {
1798  assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
1799  add(current);
1800 
1801  for (auto range = ranges.begin(); range != ranges.end(); ++range)
1802  {
1803  get();
1804  if (JSON_LIKELY(*range <= current and current <= *(++range)))
1805  {
1806  add(current);
1807  }
1808  else
1809  {
1810  error_message = "invalid string: ill-formed UTF-8 byte";
1811  return false;
1812  }
1813  }
1814 
1815  return true;
1816  }
1817 
1818  /*!
1819  @brief scan a string literal
1820 
1821  This function scans a string according to Sect. 7 of RFC 7159. While
1822  scanning, bytes are escaped and copied into buffer yytext. Then the function
1823  returns successfully, yytext is *not* null-terminated (as it may contain \0
1824  bytes), and yytext.size() is the number of bytes in the string.
1825 
1826  @return token_type::value_string if string could be successfully scanned,
1827  token_type::parse_error otherwise
1828 
1829  @note In case of errors, variable error_message contains a textual
1830  description.
1831  */
1832  token_type scan_string()
1833  {
1834  // reset yytext (ignore opening quote)
1835  reset();
1836 
1837  // we entered the function by reading an open quote
1838  assert(current == '\"');
1839 
1840  while (true)
1841  {
1842  // get next character
1843  switch (get())
1844  {
1845  // end of file while parsing string
1846  case std::char_traits<char>::eof():
1847  {
1848  error_message = "invalid string: missing closing quote";
1849  return token_type::parse_error;
1850  }
1851 
1852  // closing quote
1853  case '\"':
1854  {
1855  return token_type::value_string;
1856  }
1857 
1858  // escapes
1859  case '\\':
1860  {
1861  switch (get())
1862  {
1863  // quotation mark
1864  case '\"':
1865  add('\"');
1866  break;
1867  // reverse solidus
1868  case '\\':
1869  add('\\');
1870  break;
1871  // solidus
1872  case '/':
1873  add('/');
1874  break;
1875  // backspace
1876  case 'b':
1877  add('\b');
1878  break;
1879  // form feed
1880  case 'f':
1881  add('\f');
1882  break;
1883  // line feed
1884  case 'n':
1885  add('\n');
1886  break;
1887  // carriage return
1888  case 'r':
1889  add('\r');
1890  break;
1891  // tab
1892  case 't':
1893  add('\t');
1894  break;
1895 
1896  // unicode escapes
1897  case 'u':
1898  {
1899  const int codepoint1 = get_codepoint();
1900  int codepoint = codepoint1; // start with codepoint1
1901 
1902  if (JSON_UNLIKELY(codepoint1 == -1))
1903  {
1904  error_message = "invalid string: '\\u' must be followed by 4 hex digits";
1905  return token_type::parse_error;
1906  }
1907 
1908  // check if code point is a high surrogate
1909  if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
1910  {
1911  // expect next \uxxxx entry
1912  if (JSON_LIKELY(get() == '\\' and get() == 'u'))
1913  {
1914  const int codepoint2 = get_codepoint();
1915 
1916  if (JSON_UNLIKELY(codepoint2 == -1))
1917  {
1918  error_message = "invalid string: '\\u' must be followed by 4 hex digits";
1919  return token_type::parse_error;
1920  }
1921 
1922  // check if codepoint2 is a low surrogate
1923  if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
1924  {
1925  // overwrite codepoint
1926  codepoint =
1927  // high surrogate occupies the most significant 22 bits
1928  (codepoint1 << 10)
1929  // low surrogate occupies the least significant 15 bits
1930  + codepoint2
1931  // there is still the 0xD800, 0xDC00 and 0x10000 noise
1932  // in the result so we have to subtract with:
1933  // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
1934  - 0x35FDC00;
1935  }
1936  else
1937  {
1938  error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
1939  return token_type::parse_error;
1940  }
1941  }
1942  else
1943  {
1944  error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
1945  return token_type::parse_error;
1946  }
1947  }
1948  else
1949  {
1950  if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
1951  {
1952  error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
1953  return token_type::parse_error;
1954  }
1955  }
1956 
1957  // result of the above calculation yields a proper codepoint
1958  assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
1959 
1960  // translate codepoint into bytes
1961  if (codepoint < 0x80)
1962  {
1963  // 1-byte characters: 0xxxxxxx (ASCII)
1964  add(codepoint);
1965  }
1966  else if (codepoint <= 0x7FF)
1967  {
1968  // 2-byte characters: 110xxxxx 10xxxxxx
1969  add(0xC0 | (codepoint >> 6));
1970  add(0x80 | (codepoint & 0x3F));
1971  }
1972  else if (codepoint <= 0xFFFF)
1973  {
1974  // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
1975  add(0xE0 | (codepoint >> 12));
1976  add(0x80 | ((codepoint >> 6) & 0x3F));
1977  add(0x80 | (codepoint & 0x3F));
1978  }
1979  else
1980  {
1981  // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1982  add(0xF0 | (codepoint >> 18));
1983  add(0x80 | ((codepoint >> 12) & 0x3F));
1984  add(0x80 | ((codepoint >> 6) & 0x3F));
1985  add(0x80 | (codepoint & 0x3F));
1986  }
1987 
1988  break;
1989  }
1990 
1991  // other characters after escape
1992  default:
1993  error_message = "invalid string: forbidden character after backslash";
1994  return token_type::parse_error;
1995  }
1996 
1997  break;
1998  }
1999 
2000  // invalid control characters
2001  case 0x00:
2002  case 0x01:
2003  case 0x02:
2004  case 0x03:
2005  case 0x04:
2006  case 0x05:
2007  case 0x06:
2008  case 0x07:
2009  case 0x08:
2010  case 0x09:
2011  case 0x0A:
2012  case 0x0B:
2013  case 0x0C:
2014  case 0x0D:
2015  case 0x0E:
2016  case 0x0F:
2017  case 0x10:
2018  case 0x11:
2019  case 0x12:
2020  case 0x13:
2021  case 0x14:
2022  case 0x15:
2023  case 0x16:
2024  case 0x17:
2025  case 0x18:
2026  case 0x19:
2027  case 0x1A:
2028  case 0x1B:
2029  case 0x1C:
2030  case 0x1D:
2031  case 0x1E:
2032  case 0x1F:
2033  {
2034  error_message = "invalid string: control character must be escaped";
2035  return token_type::parse_error;
2036  }
2037 
2038  // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
2039  case 0x20:
2040  case 0x21:
2041  case 0x23:
2042  case 0x24:
2043  case 0x25:
2044  case 0x26:
2045  case 0x27:
2046  case 0x28:
2047  case 0x29:
2048  case 0x2A:
2049  case 0x2B:
2050  case 0x2C:
2051  case 0x2D:
2052  case 0x2E:
2053  case 0x2F:
2054  case 0x30:
2055  case 0x31:
2056  case 0x32:
2057  case 0x33:
2058  case 0x34:
2059  case 0x35:
2060  case 0x36:
2061  case 0x37:
2062  case 0x38:
2063  case 0x39:
2064  case 0x3A:
2065  case 0x3B:
2066  case 0x3C:
2067  case 0x3D:
2068  case 0x3E:
2069  case 0x3F:
2070  case 0x40:
2071  case 0x41:
2072  case 0x42:
2073  case 0x43:
2074  case 0x44:
2075  case 0x45:
2076  case 0x46:
2077  case 0x47:
2078  case 0x48:
2079  case 0x49:
2080  case 0x4A:
2081  case 0x4B:
2082  case 0x4C:
2083  case 0x4D:
2084  case 0x4E:
2085  case 0x4F:
2086  case 0x50:
2087  case 0x51:
2088  case 0x52:
2089  case 0x53:
2090  case 0x54:
2091  case 0x55:
2092  case 0x56:
2093  case 0x57:
2094  case 0x58:
2095  case 0x59:
2096  case 0x5A:
2097  case 0x5B:
2098  case 0x5D:
2099  case 0x5E:
2100  case 0x5F:
2101  case 0x60:
2102  case 0x61:
2103  case 0x62:
2104  case 0x63:
2105  case 0x64:
2106  case 0x65:
2107  case 0x66:
2108  case 0x67:
2109  case 0x68:
2110  case 0x69:
2111  case 0x6A:
2112  case 0x6B:
2113  case 0x6C:
2114  case 0x6D:
2115  case 0x6E:
2116  case 0x6F:
2117  case 0x70:
2118  case 0x71:
2119  case 0x72:
2120  case 0x73:
2121  case 0x74:
2122  case 0x75:
2123  case 0x76:
2124  case 0x77:
2125  case 0x78:
2126  case 0x79:
2127  case 0x7A:
2128  case 0x7B:
2129  case 0x7C:
2130  case 0x7D:
2131  case 0x7E:
2132  case 0x7F:
2133  {
2134  add(current);
2135  break;
2136  }
2137 
2138  // U+0080..U+07FF: bytes C2..DF 80..BF
2139  case 0xC2:
2140  case 0xC3:
2141  case 0xC4:
2142  case 0xC5:
2143  case 0xC6:
2144  case 0xC7:
2145  case 0xC8:
2146  case 0xC9:
2147  case 0xCA:
2148  case 0xCB:
2149  case 0xCC:
2150  case 0xCD:
2151  case 0xCE:
2152  case 0xCF:
2153  case 0xD0:
2154  case 0xD1:
2155  case 0xD2:
2156  case 0xD3:
2157  case 0xD4:
2158  case 0xD5:
2159  case 0xD6:
2160  case 0xD7:
2161  case 0xD8:
2162  case 0xD9:
2163  case 0xDA:
2164  case 0xDB:
2165  case 0xDC:
2166  case 0xDD:
2167  case 0xDE:
2168  case 0xDF:
2169  {
2170  if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
2171  {
2172  return token_type::parse_error;
2173  }
2174  break;
2175  }
2176 
2177  // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
2178  case 0xE0:
2179  {
2180  if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
2181  {
2182  return token_type::parse_error;
2183  }
2184  break;
2185  }
2186 
2187  // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
2188  // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
2189  case 0xE1:
2190  case 0xE2:
2191  case 0xE3:
2192  case 0xE4:
2193  case 0xE5:
2194  case 0xE6:
2195  case 0xE7:
2196  case 0xE8:
2197  case 0xE9:
2198  case 0xEA:
2199  case 0xEB:
2200  case 0xEC:
2201  case 0xEE:
2202  case 0xEF:
2203  {
2204  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
2205  {
2206  return token_type::parse_error;
2207  }
2208  break;
2209  }
2210 
2211  // U+D000..U+D7FF: bytes ED 80..9F 80..BF
2212  case 0xED:
2213  {
2214  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
2215  {
2216  return token_type::parse_error;
2217  }
2218  break;
2219  }
2220 
2221  // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
2222  case 0xF0:
2223  {
2224  if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
2225  {
2226  return token_type::parse_error;
2227  }
2228  break;
2229  }
2230 
2231  // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
2232  case 0xF1:
2233  case 0xF2:
2234  case 0xF3:
2235  {
2236  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
2237  {
2238  return token_type::parse_error;
2239  }
2240  break;
2241  }
2242 
2243  // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
2244  case 0xF4:
2245  {
2246  if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
2247  {
2248  return token_type::parse_error;
2249  }
2250  break;
2251  }
2252 
2253  // remaining bytes (80..C1 and F5..FF) are ill-formed
2254  default:
2255  {
2256  error_message = "invalid string: ill-formed UTF-8 byte";
2257  return token_type::parse_error;
2258  }
2259  }
2260  }
2261  }
2262 
2263  static void strtof(float& f, const char* str, char** endptr) noexcept
2264  {
2265  f = std::strtof(str, endptr);
2266  }
2267 
2268  static void strtof(double& f, const char* str, char** endptr) noexcept
2269  {
2270  f = std::strtod(str, endptr);
2271  }
2272 
2273  static void strtof(long double& f, const char* str, char** endptr) noexcept
2274  {
2275  f = std::strtold(str, endptr);
2276  }
2277 
2278  /*!
2279  @brief scan a number literal
2280 
2281  This function scans a string according to Sect. 6 of RFC 7159.
2282 
2283  The function is realized with a deterministic finite state machine derived
2284  from the grammar described in RFC 7159. Starting in state "init", the
2285  input is read and used to determined the next state. Only state "done"
2286  accepts the number. State "error" is a trap state to model errors. In the
2287  table below, "anything" means any character but the ones listed before.
2288 
2289  state | 0 | 1-9 | e E | + | - | . | anything
2290  ---------|----------|----------|----------|---------|---------|----------|-----------
2291  init | zero | any1 | [error] | [error] | minus | [error] | [error]
2292  minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
2293  zero | done | done | exponent | done | done | decimal1 | done
2294  any1 | any1 | any1 | exponent | done | done | decimal1 | done
2295  decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
2296  decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
2297  exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
2298  sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
2299  any2 | any2 | any2 | done | done | done | done | done
2300 
2301  The state machine is realized with one label per state (prefixed with
2302  "scan_number_") and `goto` statements between them. The state machine
2303  contains cycles, but any cycle can be left when EOF is read. Therefore,
2304  the function is guaranteed to terminate.
2305 
2306  During scanning, the read bytes are stored in yytext. This string is
2307  then converted to a signed integer, an unsigned integer, or a
2308  floating-point number.
2309 
2310  @return token_type::value_unsigned, token_type::value_integer, or
2311  token_type::value_float if number could be successfully scanned,
2312  token_type::parse_error otherwise
2313 
2314  @note The scanner is independent of the current locale. Internally, the
2315  locale's decimal point is used instead of `.` to work with the
2316  locale-dependent converters.
2317  */
2318  token_type scan_number()
2319  {
2320  // reset yytext to store the number's bytes
2321  reset();
2322 
2323  // the type of the parsed number; initially set to unsigned; will be
2324  // changed if minus sign, decimal point or exponent is read
2325  token_type number_type = token_type::value_unsigned;
2326 
2327  // state (init): we just found out we need to scan a number
2328  switch (current)
2329  {
2330  case '-':
2331  {
2332  add(current);
2333  goto scan_number_minus;
2334  }
2335 
2336  case '0':
2337  {
2338  add(current);
2339  goto scan_number_zero;
2340  }
2341 
2342  case '1':
2343  case '2':
2344  case '3':
2345  case '4':
2346  case '5':
2347  case '6':
2348  case '7':
2349  case '8':
2350  case '9':
2351  {
2352  add(current);
2353  goto scan_number_any1;
2354  }
2355 
2356  default:
2357  {
2358  // all other characters are rejected outside scan_number()
2359  assert(false); // LCOV_EXCL_LINE
2360  }
2361  }
2362 
2363 scan_number_minus:
2364  // state: we just parsed a leading minus sign
2365  number_type = token_type::value_integer;
2366  switch (get())
2367  {
2368  case '0':
2369  {
2370  add(current);
2371  goto scan_number_zero;
2372  }
2373 
2374  case '1':
2375  case '2':
2376  case '3':
2377  case '4':
2378  case '5':
2379  case '6':
2380  case '7':
2381  case '8':
2382  case '9':
2383  {
2384  add(current);
2385  goto scan_number_any1;
2386  }
2387 
2388  default:
2389  {
2390  error_message = "invalid number; expected digit after '-'";
2391  return token_type::parse_error;
2392  }
2393  }
2394 
2395 scan_number_zero:
2396  // state: we just parse a zero (maybe with a leading minus sign)
2397  switch (get())
2398  {
2399  case '.':
2400  {
2401  add(decimal_point_char);
2402  goto scan_number_decimal1;
2403  }
2404 
2405  case 'e':
2406  case 'E':
2407  {
2408  add(current);
2409  goto scan_number_exponent;
2410  }
2411 
2412  default:
2413  goto scan_number_done;
2414  }
2415 
2416 scan_number_any1:
2417  // state: we just parsed a number 0-9 (maybe with a leading minus sign)
2418  switch (get())
2419  {
2420  case '0':
2421  case '1':
2422  case '2':
2423  case '3':
2424  case '4':
2425  case '5':
2426  case '6':
2427  case '7':
2428  case '8':
2429  case '9':
2430  {
2431  add(current);
2432  goto scan_number_any1;
2433  }
2434 
2435  case '.':
2436  {
2437  add(decimal_point_char);
2438  goto scan_number_decimal1;
2439  }
2440 
2441  case 'e':
2442  case 'E':
2443  {
2444  add(current);
2445  goto scan_number_exponent;
2446  }
2447 
2448  default:
2449  goto scan_number_done;
2450  }
2451 
2452 scan_number_decimal1:
2453  // state: we just parsed a decimal point
2454  number_type = token_type::value_float;
2455  switch (get())
2456  {
2457  case '0':
2458  case '1':
2459  case '2':
2460  case '3':
2461  case '4':
2462  case '5':
2463  case '6':
2464  case '7':
2465  case '8':
2466  case '9':
2467  {
2468  add(current);
2469  goto scan_number_decimal2;
2470  }
2471 
2472  default:
2473  {
2474  error_message = "invalid number; expected digit after '.'";
2475  return token_type::parse_error;
2476  }
2477  }
2478 
2479 scan_number_decimal2:
2480  // we just parsed at least one number after a decimal point
2481  switch (get())
2482  {
2483  case '0':
2484  case '1':
2485  case '2':
2486  case '3':
2487  case '4':
2488  case '5':
2489  case '6':
2490  case '7':
2491  case '8':
2492  case '9':
2493  {
2494  add(current);
2495  goto scan_number_decimal2;
2496  }
2497 
2498  case 'e':
2499  case 'E':
2500  {
2501  add(current);
2502  goto scan_number_exponent;
2503  }
2504 
2505  default:
2506  goto scan_number_done;
2507  }
2508 
2509 scan_number_exponent:
2510  // we just parsed an exponent
2511  number_type = token_type::value_float;
2512  switch (get())
2513  {
2514  case '+':
2515  case '-':
2516  {
2517  add(current);
2518  goto scan_number_sign;
2519  }
2520 
2521  case '0':
2522  case '1':
2523  case '2':
2524  case '3':
2525  case '4':
2526  case '5':
2527  case '6':
2528  case '7':
2529  case '8':
2530  case '9':
2531  {
2532  add(current);
2533  goto scan_number_any2;
2534  }
2535 
2536  default:
2537  {
2538  error_message =
2539  "invalid number; expected '+', '-', or digit after exponent";
2540  return token_type::parse_error;
2541  }
2542  }
2543 
2544 scan_number_sign:
2545  // we just parsed an exponent sign
2546  switch (get())
2547  {
2548  case '0':
2549  case '1':
2550  case '2':
2551  case '3':
2552  case '4':
2553  case '5':
2554  case '6':
2555  case '7':
2556  case '8':
2557  case '9':
2558  {
2559  add(current);
2560  goto scan_number_any2;
2561  }
2562 
2563  default:
2564  {
2565  error_message = "invalid number; expected digit after exponent sign";
2566  return token_type::parse_error;
2567  }
2568  }
2569 
2570 scan_number_any2:
2571  // we just parsed a number after the exponent or exponent sign
2572  switch (get())
2573  {
2574  case '0':
2575  case '1':
2576  case '2':
2577  case '3':
2578  case '4':
2579  case '5':
2580  case '6':
2581  case '7':
2582  case '8':
2583  case '9':
2584  {
2585  add(current);
2586  goto scan_number_any2;
2587  }
2588 
2589  default:
2590  goto scan_number_done;
2591  }
2592 
2593 scan_number_done:
2594  // unget the character after the number (we only read it to know that
2595  // we are done scanning a number)
2596  unget();
2597 
2598  char* endptr = nullptr;
2599  errno = 0;
2600 
2601  // try to parse integers first and fall back to floats
2602  if (number_type == token_type::value_unsigned)
2603  {
2604  const auto x = std::strtoull(yytext.data(), &endptr, 10);
2605 
2606  // we checked the number format before
2607  assert(endptr == yytext.data() + yytext.size());
2608 
2609  if (errno == 0)
2610  {
2611  value_unsigned = static_cast<number_unsigned_t>(x);
2612  if (value_unsigned == x)
2613  {
2614  return token_type::value_unsigned;
2615  }
2616  }
2617  }
2618  else if (number_type == token_type::value_integer)
2619  {
2620  const auto x = std::strtoll(yytext.data(), &endptr, 10);
2621 
2622  // we checked the number format before
2623  assert(endptr == yytext.data() + yytext.size());
2624 
2625  if (errno == 0)
2626  {
2627  value_integer = static_cast<number_integer_t>(x);
2628  if (value_integer == x)
2629  {
2630  return token_type::value_integer;
2631  }
2632  }
2633  }
2634 
2635  // this code is reached if we parse a floating-point number or if an
2636  // integer conversion above failed
2637  strtof(value_float, yytext.data(), &endptr);
2638 
2639  // we checked the number format before
2640  assert(endptr == yytext.data() + yytext.size());
2641 
2642  return token_type::value_float;
2643  }
2644 
2645  /*!
2646  @param[in] literal_text the literal text to expect
2647  @param[in] length the length of the passed literal text
2648  @param[in] return_type the token type to return on success
2649  */
2650  token_type scan_literal(const char* literal_text, const std::size_t length,
2651  token_type return_type)
2652  {
2653  assert(current == literal_text[0]);
2654  for (std::size_t i = 1; i < length; ++i)
2655  {
2656  if (JSON_UNLIKELY(get() != literal_text[i]))
2657  {
2658  error_message = "invalid literal";
2659  return token_type::parse_error;
2660  }
2661  }
2662  return return_type;
2663  }
2664 
2665  /////////////////////
2666  // input management
2667  /////////////////////
2668 
2669  /// reset yytext; current character is beginning of token
2670  void reset() noexcept
2671  {
2672  yytext.clear();
2673  token_string.clear();
2674  token_string.push_back(std::char_traits<char>::to_char_type(current));
2675  }
2676 
2677  /*
2678  @brief get next character from the input
2679 
2680  This function provides the interface to the used input adapter. It does
2681  not throw in case the input reached EOF, but returns a
2682  `std::char_traits<char>::eof()` in that case. Stores the scanned characters
2683  for use in error messages.
2684 
2685  @return character read from the input
2686  */
2687  std::char_traits<char>::int_type get()
2688  {
2689  ++chars_read;
2690  current = ia->get_character();
2691  if (JSON_LIKELY(current != std::char_traits<char>::eof()))
2692  {
2693  token_string.push_back(std::char_traits<char>::to_char_type(current));
2694  }
2695  return current;
2696  }
2697 
2698  /// unget current character (return it again on next get)
2699  void unget()
2700  {
2701  --chars_read;
2702  if (JSON_LIKELY(current != std::char_traits<char>::eof()))
2703  {
2704  ia->unget_character();
2705  assert(token_string.size() != 0);
2706  token_string.pop_back();
2707  }
2708  }
2709 
2710  /// add a character to yytext
2711  void add(int c)
2712  {
2713  yytext.push_back(std::char_traits<char>::to_char_type(c));
2714  }
2715 
2716  public:
2717  /////////////////////
2718  // value getters
2719  /////////////////////
2720 
2721  /// return integer value
2722  constexpr number_integer_t get_number_integer() const noexcept
2723  {
2724  return value_integer;
2725  }
2726 
2727  /// return unsigned integer value
2728  constexpr number_unsigned_t get_number_unsigned() const noexcept
2729  {
2730  return value_unsigned;
2731  }
2732 
2733  /// return floating-point value
2734  constexpr number_float_t get_number_float() const noexcept
2735  {
2736  return value_float;
2737  }
2738 
2739  /// return current string value (implicitly resets the token; useful only once)
2740  std::string move_string()
2741  {
2742  return std::move(yytext);
2743  }
2744 
2745  /////////////////////
2746  // diagnostics
2747  /////////////////////
2748 
2749  /// return position of last read token
2750  constexpr std::size_t get_position() const noexcept
2751  {
2752  return chars_read;
2753  }
2754 
2755  /// return the last read token (for errors only). Will never contain EOF
2756  /// (an arbitrary value that is not a valid char value, often -1), because
2757  /// 255 may legitimately occur. May contain NUL, which should be escaped.
2758  std::string get_token_string() const
2759  {
2760  // escape control characters
2761  std::string result;
2762  for (const auto c : token_string)
2763  {
2764  if ('\x00' <= c and c <= '\x1F')
2765  {
2766  // escape control characters
2767  std::stringstream ss;
2768  ss << "<U+" << std::setw(4) << std::uppercase << std::setfill('0')
2769  << std::hex << static_cast<int>(c) << ">";
2770  result += ss.str();
2771  }
2772  else
2773  {
2774  // add character as is
2775  result.push_back(c);
2776  }
2777  }
2778 
2779  return result;
2780  }
2781 
2782  /// return syntax error message
2783  constexpr const char* get_error_message() const noexcept
2784  {
2785  return error_message;
2786  }
2787 
2788  /////////////////////
2789  // actual scanner
2790  /////////////////////
2791 
2792  token_type scan()
2793  {
2794  // read next character and ignore whitespace
2795  do
2796  {
2797  get();
2798  }
2799  while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
2800 
2801  switch (current)
2802  {
2803  // structural characters
2804  case '[':
2805  return token_type::begin_array;
2806  case ']':
2807  return token_type::end_array;
2808  case '{':
2809  return token_type::begin_object;
2810  case '}':
2811  return token_type::end_object;
2812  case ':':
2813  return token_type::name_separator;
2814  case ',':
2815  return token_type::value_separator;
2816 
2817  // literals
2818  case 't':
2819  return scan_literal("true", 4, token_type::literal_true);
2820  case 'f':
2821  return scan_literal("false", 5, token_type::literal_false);
2822  case 'n':
2823  return scan_literal("null", 4, token_type::literal_null);
2824 
2825  // string
2826  case '\"':
2827  return scan_string();
2828 
2829  // number
2830  case '-':
2831  case '0':
2832  case '1':
2833  case '2':
2834  case '3':
2835  case '4':
2836  case '5':
2837  case '6':
2838  case '7':
2839  case '8':
2840  case '9':
2841  return scan_number();
2842 
2843  // end of input (the null byte is needed when parsing from
2844  // string literals)
2845  case '\0':
2846  case std::char_traits<char>::eof():
2847  return token_type::end_of_input;
2848 
2849  // error
2850  default:
2851  error_message = "invalid literal";
2852  return token_type::parse_error;
2853  }
2854  }
2855 
2856  private:
2857  /// input adapter
2858  detail::input_adapter_t ia = nullptr;
2859 
2860  /// the current character
2861  std::char_traits<char>::int_type current = std::char_traits<char>::eof();
2862 
2863  /// the number of characters read
2864  std::size_t chars_read = 0;
2865 
2866  /// raw input token string (for error messages)
2867  std::vector<char> token_string {};
2868 
2869  /// buffer for variable-length tokens (numbers, strings)
2870  std::string yytext {};
2871 
2872  /// a description of occurred lexer errors
2873  const char* error_message = "";
2874 
2875  // number values
2876  number_integer_t value_integer = 0;
2877  number_unsigned_t value_unsigned = 0;
2878  number_float_t value_float = 0;
2879 
2880  /// the decimal point
2881  const char decimal_point_char = '.';
2882 };
2883 
2884 /*!
2885 @brief syntax analysis
2886 
2887 This class implements a recursive decent parser.
2888 */
2889 template<typename BasicJsonType>
2890 class parser
2891 {
2892  using number_integer_t = typename BasicJsonType::number_integer_t;
2893  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
2894  using number_float_t = typename BasicJsonType::number_float_t;
2895  using lexer_t = lexer<BasicJsonType>;
2896  using token_type = typename lexer_t::token_type;
2897 
2898  public:
2899  enum class parse_event_t : uint8_t
2900  {
2901  /// the parser read `{` and started to process a JSON object
2902  object_start,
2903  /// the parser read `}` and finished processing a JSON object
2904  object_end,
2905  /// the parser read `[` and started to process a JSON array
2906  array_start,
2907  /// the parser read `]` and finished processing a JSON array
2908  array_end,
2909  /// the parser read a key of a value in an object
2910  key,
2911  /// the parser finished reading a JSON value
2912  value
2913  };
2914 
2915  using parser_callback_t =
2916  std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
2917 
2918  /// a parser reading from an input adapter
2919  explicit parser(detail::input_adapter_t adapter,
2920  const parser_callback_t cb = nullptr,
2921  const bool allow_exceptions_ = true)
2922  : callback(cb), m_lexer(adapter), allow_exceptions(allow_exceptions_)
2923  {}
2924 
2925  /*!
2926  @brief public parser interface
2927 
2928  @param[in] strict whether to expect the last token to be EOF
2929  @param[in,out] result parsed JSON value
2930 
2931  @throw parse_error.101 in case of an unexpected token
2932  @throw parse_error.102 if to_unicode fails or surrogate error
2933  @throw parse_error.103 if to_unicode fails
2934  */
2935  void parse(const bool strict, BasicJsonType& result)
2936  {
2937  // read first token
2938  get_token();
2939 
2940  parse_internal(true, result);
2941  result.assert_invariant();
2942 
2943  // in strict mode, input must be completely read
2944  if (strict)
2945  {
2946  get_token();
2947  expect(token_type::end_of_input);
2948  }
2949 
2950  // in case of an error, return discarded value
2951  if (errored)
2952  {
2953  result = value_t::discarded;
2954  return;
2955  }
2956 
2957  // set top-level value to null if it was discarded by the callback
2958  // function
2959  if (result.is_discarded())
2960  {
2961  result = nullptr;
2962  }
2963  }
2964 
2965  /*!
2966  @brief public accept interface
2967 
2968  @param[in] strict whether to expect the last token to be EOF
2969  @return whether the input is a proper JSON text
2970  */
2971  bool accept(const bool strict = true)
2972  {
2973  // read first token
2974  get_token();
2975 
2976  if (not accept_internal())
2977  {
2978  return false;
2979  }
2980 
2981  // strict => last token must be EOF
2982  return not strict or (get_token() == token_type::end_of_input);
2983  }
2984 
2985  private:
2986  /*!
2987  @brief the actual parser
2988  @throw parse_error.101 in case of an unexpected token
2989  @throw parse_error.102 if to_unicode fails or surrogate error
2990  @throw parse_error.103 if to_unicode fails
2991  */
2992  void parse_internal(bool keep, BasicJsonType& result)
2993  {
2994  // never parse after a parse error was detected
2995  assert(not errored);
2996 
2997  // start with a discarded value
2998  if (not result.is_discarded())
2999  {
3000  result.m_value.destroy(result.m_type);
3001  result.m_type = value_t::discarded;
3002  }
3003 
3004  switch (last_token)
3005  {
3006  case token_type::begin_object:
3007  {
3008  if (keep)
3009  {
3010  if (callback)
3011  {
3012  keep = callback(depth++, parse_event_t::object_start, result);
3013  }
3014 
3015  if (not callback or keep)
3016  {
3017  // explicitly set result to object to cope with {}
3018  result.m_type = value_t::object;
3019  result.m_value = value_t::object;
3020  }
3021  }
3022 
3023  // read next token
3024  get_token();
3025 
3026  // closing } -> we are done
3027  if (last_token == token_type::end_object)
3028  {
3029  if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
3030  {
3031  result.m_value.destroy(result.m_type);
3032  result.m_type = value_t::discarded;
3033  }
3034  break;
3035  }
3036 
3037  // parse values
3038  std::string key;
3039  BasicJsonType value;
3040  while (true)
3041  {
3042  // store key
3043  if (not expect(token_type::value_string))
3044  {
3045  return;
3046  }
3047  key = m_lexer.move_string();
3048 
3049  bool keep_tag = false;
3050  if (keep)
3051  {
3052  if (callback)
3053  {
3054  BasicJsonType k(key);
3055  keep_tag = callback(depth, parse_event_t::key, k);
3056  }
3057  else
3058  {
3059  keep_tag = true;
3060  }
3061  }
3062 
3063  // parse separator (:)
3064  get_token();
3065  if (not expect(token_type::name_separator))
3066  {
3067  return;
3068  }
3069 
3070  // parse and add value
3071  get_token();
3072  value.m_value.destroy(value.m_type);
3073  value.m_type = value_t::discarded;
3074  parse_internal(keep, value);
3075 
3076  if (JSON_UNLIKELY(errored))
3077  {
3078  return;
3079  }
3080 
3081  if (keep and keep_tag and not value.is_discarded())
3082  {
3083  result.m_value.object->emplace(std::move(key), std::move(value));
3084  }
3085 
3086  // comma -> next value
3087  get_token();
3088  if (last_token == token_type::value_separator)
3089  {
3090  get_token();
3091  continue;
3092  }
3093 
3094  // closing }
3095  if (not expect(token_type::end_object))
3096  {
3097  return;
3098  }
3099  break;
3100  }
3101 
3102  if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
3103  {
3104  result.m_value.destroy(result.m_type);
3105  result.m_type = value_t::discarded;
3106  }
3107  break;
3108  }
3109 
3110  case token_type::begin_array:
3111  {
3112  if (keep)
3113  {
3114  if (callback)
3115  {
3116  keep = callback(depth++, parse_event_t::array_start, result);
3117  }
3118 
3119  if (not callback or keep)
3120  {
3121  // explicitly set result to array to cope with []
3122  result.m_type = value_t::array;
3123  result.m_value = value_t::array;
3124  }
3125  }
3126 
3127  // read next token
3128  get_token();
3129 
3130  // closing ] -> we are done
3131  if (last_token == token_type::end_array)
3132  {
3133  if (callback and not callback(--depth, parse_event_t::array_end, result))
3134  {
3135  result.m_value.destroy(result.m_type);
3136  result.m_type = value_t::discarded;
3137  }
3138  break;
3139  }
3140 
3141  // parse values
3142  BasicJsonType value;
3143  while (true)
3144  {
3145  // parse value
3146  value.m_value.destroy(value.m_type);
3147  value.m_type = value_t::discarded;
3148  parse_internal(keep, value);
3149 
3150  if (JSON_UNLIKELY(errored))
3151  {
3152  return;
3153  }
3154 
3155  if (keep and not value.is_discarded())
3156  {
3157  result.m_value.array->push_back(std::move(value));
3158  }
3159 
3160  // comma -> next value
3161  get_token();
3162  if (last_token == token_type::value_separator)
3163  {
3164  get_token();
3165  continue;
3166  }
3167 
3168  // closing ]
3169  if (not expect(token_type::end_array))
3170  {
3171  return;
3172  }
3173  break;
3174  }
3175 
3176  if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
3177  {
3178  result.m_value.destroy(result.m_type);
3179  result.m_type = value_t::discarded;
3180  }
3181  break;
3182  }
3183 
3184  case token_type::literal_null:
3185  {
3186  result.m_type = value_t::null;
3187  break;
3188  }
3189 
3190  case token_type::value_string:
3191  {
3192  result.m_type = value_t::string;
3193  result.m_value = m_lexer.move_string();
3194  break;
3195  }
3196 
3197  case token_type::literal_true:
3198  {
3199  result.m_type = value_t::boolean;
3200  result.m_value = true;
3201  break;
3202  }
3203 
3204  case token_type::literal_false:
3205  {
3206  result.m_type = value_t::boolean;
3207  result.m_value = false;
3208  break;
3209  }
3210 
3211  case token_type::value_unsigned:
3212  {
3213  result.m_type = value_t::number_unsigned;
3214  result.m_value = m_lexer.get_number_unsigned();
3215  break;
3216  }
3217 
3218  case token_type::value_integer:
3219  {
3220  result.m_type = value_t::number_integer;
3221  result.m_value = m_lexer.get_number_integer();
3222  break;
3223  }
3224 
3225  case token_type::value_float:
3226  {
3227  result.m_type = value_t::number_float;
3228  result.m_value = m_lexer.get_number_float();
3229 
3230  // throw in case of infinity or NAN
3231  if (JSON_UNLIKELY(not std::isfinite(result.m_value.number_float)))
3232  {
3233  if (allow_exceptions)
3234  {
3235  JSON_THROW(out_of_range::create(406, "number overflow parsing '" +
3236  m_lexer.get_token_string() + "'"));
3237  }
3238  expect(token_type::uninitialized);
3239  }
3240  break;
3241  }
3242 
3243  case token_type::parse_error:
3244  {
3245  // using "uninitialized" to avoid "expected" message
3246  if (not expect(token_type::uninitialized))
3247  {
3248  return;
3249  }
3250  break; // LCOV_EXCL_LINE
3251  }
3252 
3253  default:
3254  {
3255  // the last token was unexpected; we expected a value
3256  if (not expect(token_type::literal_or_value))
3257  {
3258  return;
3259  }
3260  break; // LCOV_EXCL_LINE
3261  }
3262  }
3263 
3264  if (keep and callback and not callback(depth, parse_event_t::value, result))
3265  {
3266  result.m_type = value_t::discarded;
3267  }
3268  }
3269 
3270  /*!
3271  @brief the actual acceptor
3272 
3273  @invariant 1. The last token is not yet processed. Therefore, the caller
3274  of this function must make sure a token has been read.
3275  2. When this function returns, the last token is processed.
3276  That is, the last read character was already considered.
3277 
3278  This invariant makes sure that no token needs to be "unput".
3279  */
3280  bool accept_internal()
3281  {
3282  switch (last_token)
3283  {
3284  case token_type::begin_object:
3285  {
3286  // read next token
3287  get_token();
3288 
3289  // closing } -> we are done
3290  if (last_token == token_type::end_object)
3291  {
3292  return true;
3293  }
3294 
3295  // parse values
3296  while (true)
3297  {
3298  // parse key
3299  if (last_token != token_type::value_string)
3300  {
3301  return false;
3302  }
3303 
3304  // parse separator (:)
3305  get_token();
3306  if (last_token != token_type::name_separator)
3307  {
3308  return false;
3309  }
3310 
3311  // parse value
3312  get_token();
3313  if (not accept_internal())
3314  {
3315  return false;
3316  }
3317 
3318  // comma -> next value
3319  get_token();
3320  if (last_token == token_type::value_separator)
3321  {
3322  get_token();
3323  continue;
3324  }
3325 
3326  // closing }
3327  return (last_token == token_type::end_object);
3328  }
3329  }
3330 
3331  case token_type::begin_array:
3332  {
3333  // read next token
3334  get_token();
3335 
3336  // closing ] -> we are done
3337  if (last_token == token_type::end_array)
3338  {
3339  return true;
3340  }
3341 
3342  // parse values
3343  while (true)
3344  {
3345  // parse value
3346  if (not accept_internal())
3347  {
3348  return false;
3349  }
3350 
3351  // comma -> next value
3352  get_token();
3353  if (last_token == token_type::value_separator)
3354  {
3355  get_token();
3356  continue;
3357  }
3358 
3359  // closing ]
3360  return (last_token == token_type::end_array);
3361  }
3362  }
3363 
3364  case token_type::value_float:
3365  {
3366  // reject infinity or NAN
3367  return std::isfinite(m_lexer.get_number_float());
3368  }
3369 
3370  case token_type::literal_false:
3371  case token_type::literal_null:
3372  case token_type::literal_true:
3373  case token_type::value_integer:
3374  case token_type::value_string:
3375  case token_type::value_unsigned:
3376  return true;
3377 
3378  default: // the last token was unexpected
3379  return false;
3380  }
3381  }
3382 
3383  /// get next token from lexer
3384  token_type get_token()
3385  {
3386  return (last_token = m_lexer.scan());
3387  }
3388 
3389  /*!
3390  @throw parse_error.101 if expected token did not occur
3391  */
3392  bool expect(token_type t)
3393  {
3394  if (JSON_UNLIKELY(t != last_token))
3395  {
3396  errored = true;
3397  expected = t;
3398  if (allow_exceptions)
3399  {
3400  throw_exception();
3401  }
3402  else
3403  {
3404  return false;
3405  }
3406  }
3407 
3408  return true;
3409  }
3410 
3411  [[noreturn]] void throw_exception() const
3412  {
3413  std::string error_msg = "syntax error - ";
3414  if (last_token == token_type::parse_error)
3415  {
3416  error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
3417  m_lexer.get_token_string() + "'";
3418  }
3419  else
3420  {
3421  error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
3422  }
3423 
3424  if (expected != token_type::uninitialized)
3425  {
3426  error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
3427  }
3428 
3429  JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg));
3430  }
3431 
3432  private:
3433  /// current level of recursion
3434  int depth = 0;
3435  /// callback function
3436  const parser_callback_t callback = nullptr;
3437  /// the type of the last read token
3438  token_type last_token = token_type::uninitialized;
3439  /// the lexer
3440  lexer_t m_lexer;
3441  /// whether a syntax error occurred
3442  bool errored = false;
3443  /// possible reason for the syntax error
3444  token_type expected = token_type::uninitialized;
3445  /// whether to throw exceptions in case of errors
3446  const bool allow_exceptions = true;
3447 };
3448 
3449 ///////////////
3450 // iterators //
3451 ///////////////
3452 
3453 /*!
3454 @brief an iterator for primitive JSON types
3455 
3456 This class models an iterator for primitive JSON types (boolean, number,
3457 string). It's only purpose is to allow the iterator/const_iterator classes
3458 to "iterate" over primitive values. Internally, the iterator is modeled by
3459 a `difference_type` variable. Value begin_value (`0`) models the begin,
3460 end_value (`1`) models past the end.
3461 */
3462 class primitive_iterator_t
3463 {
3464  public:
3465  using difference_type = std::ptrdiff_t;
3466 
3467  constexpr difference_type get_value() const noexcept
3468  {
3469  return m_it;
3470  }
3471 
3472  /// set iterator to a defined beginning
3473  void set_begin() noexcept
3474  {
3475  m_it = begin_value;
3476  }
3477 
3478  /// set iterator to a defined past the end
3479  void set_end() noexcept
3480  {
3481  m_it = end_value;
3482  }
3483 
3484  /// return whether the iterator can be dereferenced
3485  constexpr bool is_begin() const noexcept
3486  {
3487  return m_it == begin_value;
3488  }
3489 
3490  /// return whether the iterator is at end
3491  constexpr bool is_end() const noexcept
3492  {
3493  return m_it == end_value;
3494  }
3495 
3496  friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3497  {
3498  return lhs.m_it == rhs.m_it;
3499  }
3500 
3501  friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3502  {
3503  return lhs.m_it < rhs.m_it;
3504  }
3505 
3506  primitive_iterator_t operator+(difference_type i)
3507  {
3508  auto result = *this;
3509  result += i;
3510  return result;
3511  }
3512 
3513  friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
3514  {
3515  return lhs.m_it - rhs.m_it;
3516  }
3517 
3518  friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it)
3519  {
3520  return os << it.m_it;
3521  }
3522 
3523  primitive_iterator_t& operator++()
3524  {
3525  ++m_it;
3526  return *this;
3527  }
3528 
3529  primitive_iterator_t const operator++(int)
3530  {
3531  auto result = *this;
3532  m_it++;
3533  return result;
3534  }
3535 
3536  primitive_iterator_t& operator--()
3537  {
3538  --m_it;
3539  return *this;
3540  }
3541 
3542  primitive_iterator_t const operator--(int)
3543  {
3544  auto result = *this;
3545  m_it--;
3546  return result;
3547  }
3548 
3549  primitive_iterator_t& operator+=(difference_type n)
3550  {
3551  m_it += n;
3552  return *this;
3553  }
3554 
3555  primitive_iterator_t& operator-=(difference_type n)
3556  {
3557  m_it -= n;
3558  return *this;
3559  }
3560 
3561  private:
3562  static constexpr difference_type begin_value = 0;
3563  static constexpr difference_type end_value = begin_value + 1;
3564 
3565  /// iterator as signed integer type
3566  difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
3567 };
3568 
3569 /*!
3570 @brief an iterator value
3571 
3572 @note This structure could easily be a union, but MSVC currently does not allow
3573 unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
3574 */
3575 template<typename BasicJsonType> struct internal_iterator
3576 {
3577  /// iterator for JSON objects
3578  typename BasicJsonType::object_t::iterator object_iterator {};
3579  /// iterator for JSON arrays
3580  typename BasicJsonType::array_t::iterator array_iterator {};
3581  /// generic iterator for all other types
3582  primitive_iterator_t primitive_iterator {};
3583 };
3584 
3585 template<typename IteratorType> class iteration_proxy;
3586 
3587 /*!
3588 @brief a template for a bidirectional iterator for the @ref basic_json class
3589 
3590 This class implements a both iterators (iterator and const_iterator) for the
3591 @ref basic_json class.
3592 
3593 @note An iterator is called *initialized* when a pointer to a JSON value has
3594  been set (e.g., by a constructor or a copy assignment). If the iterator is
3595  default-constructed, it is *uninitialized* and most methods are undefined.
3596  **The library uses assertions to detect calls on uninitialized iterators.**
3597 
3598 @requirement The class satisfies the following concept requirements:
3599 -
3600 [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):
3601  The iterator that can be moved can be moved in both directions (i.e.
3602  incremented and decremented).
3603 
3604 @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
3605  iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
3606 */
3607 template<typename BasicJsonType>
3608 class iter_impl
3609 {
3610  /// allow basic_json to access private members
3611  friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
3612  friend BasicJsonType;
3613  friend iteration_proxy<iter_impl>;
3614 
3615  using object_t = typename BasicJsonType::object_t;
3616  using array_t = typename BasicJsonType::array_t;
3617  // make sure BasicJsonType is basic_json or const basic_json
3618  static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
3619  "iter_impl only accepts (const) basic_json");
3620 
3621  public:
3622 
3623  /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
3624  /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
3625  /// A user-defined iterator should provide publicly accessible typedefs named
3626  /// iterator_category, value_type, difference_type, pointer, and reference.
3627  /// Note that value_type is required to be non-const, even for constant iterators.
3628  using iterator_category = std::bidirectional_iterator_tag;
3629 
3630  /// the type of the values when the iterator is dereferenced
3631  using value_type = typename BasicJsonType::value_type;
3632  /// a type to represent differences between iterators
3633  using difference_type = typename BasicJsonType::difference_type;
3634  /// defines a pointer to the type iterated over (value_type)
3635  using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
3636  typename BasicJsonType::const_pointer,
3637  typename BasicJsonType::pointer>::type;
3638  /// defines a reference to the type iterated over (value_type)
3639  using reference =
3640  typename std::conditional<std::is_const<BasicJsonType>::value,
3641  typename BasicJsonType::const_reference,
3642  typename BasicJsonType::reference>::type;
3643 
3644  /// default constructor
3645  iter_impl() = default;
3646 
3647  /*!
3648  @brief constructor for a given JSON instance
3649  @param[in] object pointer to a JSON object for this iterator
3650  @pre object != nullptr
3651  @post The iterator is initialized; i.e. `m_object != nullptr`.
3652  */
3653  explicit iter_impl(pointer object) noexcept : m_object(object)
3654  {
3655  assert(m_object != nullptr);
3656 
3657  switch (m_object->m_type)
3658  {
3659  case value_t::object:
3660  {
3661  m_it.object_iterator = typename object_t::iterator();
3662  break;
3663  }
3664 
3665  case value_t::array:
3666  {
3667  m_it.array_iterator = typename array_t::iterator();
3668  break;
3669  }
3670 
3671  default:
3672  {
3673  m_it.primitive_iterator = primitive_iterator_t();
3674  break;
3675  }
3676  }
3677  }
3678 
3679  /*!
3680  @note The conventional copy constructor and copy assignment are implicitly
3681  defined. Combined with the following converting constructor and
3682  assignment, they support: (1) copy from iterator to iterator, (2)
3683  copy from const iterator to const iterator, and (3) conversion from
3684  iterator to const iterator. However conversion from const iterator
3685  to iterator is not defined.
3686  */
3687 
3688  /*!
3689  @brief converting constructor
3690  @param[in] other non-const iterator to copy from
3691  @note It is not checked whether @a other is initialized.
3692  */
3693  iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
3694  : m_object(other.m_object), m_it(other.m_it) {}
3695 
3696  /*!
3697  @brief converting assignment
3698  @param[in,out] other non-const iterator to copy from
3699  @return const/non-const iterator
3700  @note It is not checked whether @a other is initialized.
3701  */
3702  iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
3703  {
3704  m_object = other.m_object;
3705  m_it = other.m_it;
3706  return *this;
3707  }
3708 
3709  private:
3710  /*!
3711  @brief set the iterator to the first value
3712  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3713  */
3714  void set_begin() noexcept
3715  {
3716  assert(m_object != nullptr);
3717 
3718  switch (m_object->m_type)
3719  {
3720  case value_t::object:
3721  {
3722  m_it.object_iterator = m_object->m_value.object->begin();
3723  break;
3724  }
3725 
3726  case value_t::array:
3727  {
3728  m_it.array_iterator = m_object->m_value.array->begin();
3729  break;
3730  }
3731 
3732  case value_t::null:
3733  {
3734  // set to end so begin()==end() is true: null is empty
3735  m_it.primitive_iterator.set_end();
3736  break;
3737  }
3738 
3739  default:
3740  {
3741  m_it.primitive_iterator.set_begin();
3742  break;
3743  }
3744  }
3745  }
3746 
3747  /*!
3748  @brief set the iterator past the last value
3749  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3750  */
3751  void set_end() noexcept
3752  {
3753  assert(m_object != nullptr);
3754 
3755  switch (m_object->m_type)
3756  {
3757  case value_t::object:
3758  {
3759  m_it.object_iterator = m_object->m_value.object->end();
3760  break;
3761  }
3762 
3763  case value_t::array:
3764  {
3765  m_it.array_iterator = m_object->m_value.array->end();
3766  break;
3767  }
3768 
3769  default:
3770  {
3771  m_it.primitive_iterator.set_end();
3772  break;
3773  }
3774  }
3775  }
3776 
3777  public:
3778  /*!
3779  @brief return a reference to the value pointed to by the iterator
3780  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3781  */
3782  reference operator*() const
3783  {
3784  assert(m_object != nullptr);
3785 
3786  switch (m_object->m_type)
3787  {
3788  case value_t::object:
3789  {
3790  assert(m_it.object_iterator != m_object->m_value.object->end());
3791  return m_it.object_iterator->second;
3792  }
3793 
3794  case value_t::array:
3795  {
3796  assert(m_it.array_iterator != m_object->m_value.array->end());
3797  return *m_it.array_iterator;
3798  }
3799 
3800  case value_t::null:
3801  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
3802 
3803  default:
3804  {
3805  if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
3806  {
3807  return *m_object;
3808  }
3809 
3810  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
3811  }
3812  }
3813  }
3814 
3815  /*!
3816  @brief dereference the iterator
3817  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3818  */
3819  pointer operator->() const
3820  {
3821  assert(m_object != nullptr);
3822 
3823  switch (m_object->m_type)
3824  {
3825  case value_t::object:
3826  {
3827  assert(m_it.object_iterator != m_object->m_value.object->end());
3828  return &(m_it.object_iterator->second);
3829  }
3830 
3831  case value_t::array:
3832  {
3833  assert(m_it.array_iterator != m_object->m_value.array->end());
3834  return &*m_it.array_iterator;
3835  }
3836 
3837  default:
3838  {
3839  if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
3840  {
3841  return m_object;
3842  }
3843 
3844  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
3845  }
3846  }
3847  }
3848 
3849  /*!
3850  @brief post-increment (it++)
3851  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3852  */
3853  iter_impl const operator++(int)
3854  {
3855  auto result = *this;
3856  ++(*this);
3857  return result;
3858  }
3859 
3860  /*!
3861  @brief pre-increment (++it)
3862  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3863  */
3864  iter_impl& operator++()
3865  {
3866  assert(m_object != nullptr);
3867 
3868  switch (m_object->m_type)
3869  {
3870  case value_t::object:
3871  {
3872  std::advance(m_it.object_iterator, 1);
3873  break;
3874  }
3875 
3876  case value_t::array:
3877  {
3878  std::advance(m_it.array_iterator, 1);
3879  break;
3880  }
3881 
3882  default:
3883  {
3884  ++m_it.primitive_iterator;
3885  break;
3886  }
3887  }
3888 
3889  return *this;
3890  }
3891 
3892  /*!
3893  @brief post-decrement (it--)
3894  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3895  */
3896  iter_impl const operator--(int)
3897  {
3898  auto result = *this;
3899  --(*this);
3900  return result;
3901  }
3902 
3903  /*!
3904  @brief pre-decrement (--it)
3905  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3906  */
3907  iter_impl& operator--()
3908  {
3909  assert(m_object != nullptr);
3910 
3911  switch (m_object->m_type)
3912  {
3913  case value_t::object:
3914  {
3915  std::advance(m_it.object_iterator, -1);
3916  break;
3917  }
3918 
3919  case value_t::array:
3920  {
3921  std::advance(m_it.array_iterator, -1);
3922  break;
3923  }
3924 
3925  default:
3926  {
3927  --m_it.primitive_iterator;
3928  break;
3929  }
3930  }
3931 
3932  return *this;
3933  }
3934 
3935  /*!
3936  @brief comparison: equal
3937  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3938  */
3939  bool operator==(const iter_impl& other) const
3940  {
3941  // if objects are not the same, the comparison is undefined
3942  if (JSON_UNLIKELY(m_object != other.m_object))
3943  {
3944  JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
3945  }
3946 
3947  assert(m_object != nullptr);
3948 
3949  switch (m_object->m_type)
3950  {
3951  case value_t::object:
3952  return (m_it.object_iterator == other.m_it.object_iterator);
3953 
3954  case value_t::array:
3955  return (m_it.array_iterator == other.m_it.array_iterator);
3956 
3957  default:
3958  return (m_it.primitive_iterator == other.m_it.primitive_iterator);
3959  }
3960  }
3961 
3962  /*!
3963  @brief comparison: not equal
3964  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3965  */
3966  bool operator!=(const iter_impl& other) const
3967  {
3968  return not operator==(other);
3969  }
3970 
3971  /*!
3972  @brief comparison: smaller
3973  @pre The iterator is initialized; i.e. `m_object != nullptr`.
3974  */
3975  bool operator<(const iter_impl& other) const
3976  {
3977  // if objects are not the same, the comparison is undefined
3978  if (JSON_UNLIKELY(m_object != other.m_object))
3979  {
3980  JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
3981  }
3982 
3983  assert(m_object != nullptr);
3984 
3985  switch (m_object->m_type)
3986  {
3987  case value_t::object:
3988  JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
3989 
3990  case value_t::array:
3991  return (m_it.array_iterator < other.m_it.array_iterator);
3992 
3993  default:
3994  return (m_it.primitive_iterator < other.m_it.primitive_iterator);
3995  }
3996  }
3997 
3998  /*!
3999  @brief comparison: less than or equal
4000  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4001  */
4002  bool operator<=(const iter_impl& other) const
4003  {
4004  return not other.operator < (*this);
4005  }
4006 
4007  /*!
4008  @brief comparison: greater than
4009  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4010  */
4011  bool operator>(const iter_impl& other) const
4012  {
4013  return not operator<=(other);
4014  }
4015 
4016  /*!
4017  @brief comparison: greater than or equal
4018  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4019  */
4020  bool operator>=(const iter_impl& other) const
4021  {
4022  return not operator<(other);
4023  }
4024 
4025  /*!
4026  @brief add to iterator
4027  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4028  */
4029  iter_impl& operator+=(difference_type i)
4030  {
4031  assert(m_object != nullptr);
4032 
4033  switch (m_object->m_type)
4034  {
4035  case value_t::object:
4036  JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
4037 
4038  case value_t::array:
4039  {
4040  std::advance(m_it.array_iterator, i);
4041  break;
4042  }
4043 
4044  default:
4045  {
4046  m_it.primitive_iterator += i;
4047  break;
4048  }
4049  }
4050 
4051  return *this;
4052  }
4053 
4054  /*!
4055  @brief subtract from iterator
4056  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4057  */
4058  iter_impl& operator-=(difference_type i)
4059  {
4060  return operator+=(-i);
4061  }
4062 
4063  /*!
4064  @brief add to iterator
4065  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4066  */
4067  iter_impl operator+(difference_type i) const
4068  {
4069  auto result = *this;
4070  result += i;
4071  return result;
4072  }
4073 
4074  /*!
4075  @brief addition of distance and iterator
4076  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4077  */
4078  friend iter_impl operator+(difference_type i, const iter_impl& it)
4079  {
4080  auto result = it;
4081  result += i;
4082  return result;
4083  }
4084 
4085  /*!
4086  @brief subtract from iterator
4087  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4088  */
4089  iter_impl operator-(difference_type i) const
4090  {
4091  auto result = *this;
4092  result -= i;
4093  return result;
4094  }
4095 
4096  /*!
4097  @brief return difference
4098  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4099  */
4100  difference_type operator-(const iter_impl& other) const
4101  {
4102  assert(m_object != nullptr);
4103 
4104  switch (m_object->m_type)
4105  {
4106  case value_t::object:
4107  JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
4108 
4109  case value_t::array:
4110  return m_it.array_iterator - other.m_it.array_iterator;
4111 
4112  default:
4113  return m_it.primitive_iterator - other.m_it.primitive_iterator;
4114  }
4115  }
4116 
4117  /*!
4118  @brief access to successor
4119  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4120  */
4121  reference operator[](difference_type n) const
4122  {
4123  assert(m_object != nullptr);
4124 
4125  switch (m_object->m_type)
4126  {
4127  case value_t::object:
4128  JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
4129 
4130  case value_t::array:
4131  return *std::next(m_it.array_iterator, n);
4132 
4133  case value_t::null:
4134  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4135 
4136  default:
4137  {
4138  if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
4139  {
4140  return *m_object;
4141  }
4142 
4143  JSON_THROW(invalid_iterator::create(214, "cannot get value"));
4144  }
4145  }
4146  }
4147 
4148  /*!
4149  @brief return the key of an object iterator
4150  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4151  */
4152  typename object_t::key_type key() const
4153  {
4154  assert(m_object != nullptr);
4155 
4156  if (JSON_LIKELY(m_object->is_object()))
4157  {
4158  return m_it.object_iterator->first;
4159  }
4160 
4161  JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
4162  }
4163 
4164  /*!
4165  @brief return the value of an iterator
4166  @pre The iterator is initialized; i.e. `m_object != nullptr`.
4167  */
4168  reference value() const
4169  {
4170  return operator*();
4171  }
4172 
4173  private:
4174  /// associated JSON instance
4175  pointer m_object = nullptr;
4176  /// the actual iterator of the associated instance
4177  internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it = {};
4178 };
4179 
4180 /// proxy class for the iterator_wrapper functions
4181 template<typename IteratorType> class iteration_proxy
4182 {
4183  private:
4184  /// helper class for iteration
4185  class iteration_proxy_internal
4186  {
4187  private:
4188  /// the iterator
4189  IteratorType anchor;
4190  /// an index for arrays (used to create key names)
4191  std::size_t array_index = 0;
4192 
4193  public:
4194  explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {}
4195 
4196  /// dereference operator (needed for range-based for)
4197  iteration_proxy_internal& operator*()
4198  {
4199  return *this;
4200  }
4201 
4202  /// increment operator (needed for range-based for)
4203  iteration_proxy_internal& operator++()
4204  {
4205  ++anchor;
4206  ++array_index;
4207 
4208  return *this;
4209  }
4210 
4211  /// inequality operator (needed for range-based for)
4212  bool operator!=(const iteration_proxy_internal& o) const noexcept
4213  {
4214  return anchor != o.anchor;
4215  }
4216 
4217  /// return key of the iterator
4218  std::string key() const
4219  {
4220  assert(anchor.m_object != nullptr);
4221 
4222  switch (anchor.m_object->type())
4223  {
4224  // use integer array index as key
4225  case value_t::array:
4226  return std::to_string(array_index);
4227 
4228  // use key from the object
4229  case value_t::object:
4230  return anchor.key();
4231 
4232  // use an empty key for all primitive types
4233  default:
4234  return "";
4235  }
4236  }
4237 
4238  /// return value of the iterator
4239  typename IteratorType::reference value() const
4240  {
4241  return anchor.value();
4242  }
4243  };
4244 
4245  /// the container to iterate
4246  typename IteratorType::reference container;
4247 
4248  public:
4249  /// construct iteration proxy from a container
4250  explicit iteration_proxy(typename IteratorType::reference cont)
4251  : container(cont) {}
4252 
4253  /// return iterator begin (needed for range-based for)
4254  iteration_proxy_internal begin() noexcept
4255  {
4256  return iteration_proxy_internal(container.begin());
4257  }
4258 
4259  /// return iterator end (needed for range-based for)
4260  iteration_proxy_internal end() noexcept
4261  {
4262  return iteration_proxy_internal(container.end());
4263  }
4264 };
4265 
4266 /*!
4267 @brief a template for a reverse iterator class
4268 
4269 @tparam Base the base iterator type to reverse. Valid types are @ref
4270 iterator (to create @ref reverse_iterator) and @ref const_iterator (to
4271 create @ref const_reverse_iterator).
4272 
4273 @requirement The class satisfies the following concept requirements:
4274 -
4275 [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):
4276  The iterator that can be moved can be moved in both directions (i.e.
4277  incremented and decremented).
4278 - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
4279  It is possible to write to the pointed-to element (only if @a Base is
4280  @ref iterator).
4281 
4282 @since version 1.0.0
4283 */
4284 template<typename Base>
4285 class json_reverse_iterator : public std::reverse_iterator<Base>
4286 {
4287  public:
4288  using difference_type = std::ptrdiff_t;
4289  /// shortcut to the reverse iterator adapter
4290  using base_iterator = std::reverse_iterator<Base>;
4291  /// the reference type for the pointed-to element
4292  using reference = typename Base::reference;
4293 
4294  /// create reverse iterator from iterator
4295  json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
4296  : base_iterator(it) {}
4297 
4298  /// create reverse iterator from base class
4299  json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
4300 
4301  /// post-increment (it++)
4302  json_reverse_iterator const operator++(int)
4303  {
4304  return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
4305  }
4306 
4307  /// pre-increment (++it)
4308  json_reverse_iterator& operator++()
4309  {
4310  return static_cast<json_reverse_iterator&>(base_iterator::operator++());
4311  }
4312 
4313  /// post-decrement (it--)
4314  json_reverse_iterator const operator--(int)
4315  {
4316  return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
4317  }
4318 
4319  /// pre-decrement (--it)
4320  json_reverse_iterator& operator--()
4321  {
4322  return static_cast<json_reverse_iterator&>(base_iterator::operator--());
4323  }
4324 
4325  /// add to iterator
4326  json_reverse_iterator& operator+=(difference_type i)
4327  {
4328  return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
4329  }
4330 
4331  /// add to iterator
4332  json_reverse_iterator operator+(difference_type i) const
4333  {
4334  return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
4335  }
4336 
4337  /// subtract from iterator
4338  json_reverse_iterator operator-(difference_type i) const
4339  {
4340  return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
4341  }
4342 
4343  /// return difference
4344  difference_type operator-(const json_reverse_iterator& other) const
4345  {
4346  return base_iterator(*this) - base_iterator(other);
4347  }
4348 
4349  /// access to successor
4350  reference operator[](difference_type n) const
4351  {
4352  return *(this->operator+(n));
4353  }
4354 
4355  /// return the key of an object iterator
4356  auto key() const -> decltype(std::declval<Base>().key())
4357  {
4358  auto it = --this->base();
4359  return it.key();
4360  }
4361 
4362  /// return the value of an iterator
4363  reference value() const
4364  {
4365  auto it = --this->base();
4366  return it.operator * ();
4367  }
4368 };
4369 
4370 /////////////////////
4371 // output adapters //
4372 /////////////////////
4373 
4374 /// abstract output adapter interface
4375 template<typename CharType> struct output_adapter_protocol
4376 {
4377  virtual void write_character(CharType c) = 0;
4378  virtual void write_characters(const CharType* s, std::size_t length) = 0;
4379  virtual ~output_adapter_protocol() = default;
4380 };
4381 
4382 /// a type to simplify interfaces
4383 template<typename CharType>
4384 using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
4385 
4386 /// output adapter for byte vectors
4387 template<typename CharType>
4388 class output_vector_adapter : public output_adapter_protocol<CharType>
4389 {
4390  public:
4391  explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {}
4392 
4393  void write_character(CharType c) override
4394  {
4395  v.push_back(c);
4396  }
4397 
4398  void write_characters(const CharType* s, std::size_t length) override
4399  {
4400  std::copy(s, s + length, std::back_inserter(v));
4401  }
4402 
4403  private:
4404  std::vector<CharType>& v;
4405 };
4406 
4407 /// output adapter for output streams
4408 template<typename CharType>
4409 class output_stream_adapter : public output_adapter_protocol<CharType>
4410 {
4411  public:
4412  explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {}
4413 
4414  void write_character(CharType c) override
4415  {
4416  stream.put(c);
4417  }
4418 
4419  void write_characters(const CharType* s, std::size_t length) override
4420  {
4421  stream.write(s, static_cast<std::streamsize>(length));
4422  }
4423 
4424  private:
4425  std::basic_ostream<CharType>& stream;
4426 };
4427 
4428 /// output adapter for basic_string
4429 template<typename CharType>
4430 class output_string_adapter : public output_adapter_protocol<CharType>
4431 {
4432  public:
4433  explicit output_string_adapter(std::basic_string<CharType>& s) : str(s) {}
4434 
4435  void write_character(CharType c) override
4436  {
4437  str.push_back(c);
4438  }
4439 
4440  void write_characters(const CharType* s, std::size_t length) override
4441  {
4442  str.append(s, length);
4443  }
4444 
4445  private:
4446  std::basic_string<CharType>& str;
4447 };
4448 
4449 template<typename CharType>
4450 class output_adapter
4451 {
4452  public:
4453  output_adapter(std::vector<CharType>& vec)
4454  : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
4455 
4456  output_adapter(std::basic_ostream<CharType>& s)
4457  : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
4458 
4459  output_adapter(std::basic_string<CharType>& s)
4460  : oa(std::make_shared<output_string_adapter<CharType>>(s)) {}
4461 
4462  operator output_adapter_t<CharType>()
4463  {
4464  return oa;
4465  }
4466 
4467  private:
4468  output_adapter_t<CharType> oa = nullptr;
4469 };
4470 
4471 //////////////////////////////
4472 // binary reader and writer //
4473 //////////////////////////////
4474 
4475 /*!
4476 @brief deserialization of CBOR and MessagePack values
4477 */
4478 template<typename BasicJsonType>
4479 class binary_reader
4480 {
4481  using number_integer_t = typename BasicJsonType::number_integer_t;
4482  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
4483 
4484  public:
4485  /*!
4486  @brief create a binary reader
4487 
4488  @param[in] adapter input adapter to read from
4489  */
4490  explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
4491  {
4492  assert(ia);
4493  }
4494 
4495  /*!
4496  @brief create a JSON value from CBOR input
4497 
4498  @param[in] strict whether to expect the input to be consumed completed
4499  @return JSON value created from CBOR input
4500 
4501  @throw parse_error.110 if input ended unexpectedly or the end of file was
4502  not reached when @a strict was set to true
4503  @throw parse_error.112 if unsupported byte was read
4504  */
4505  BasicJsonType parse_cbor(const bool strict)
4506  {
4507  const auto res = parse_cbor_internal();
4508  if (strict)
4509  {
4510  get();
4511  check_eof(true);
4512  }
4513  return res;
4514  }
4515 
4516  /*!
4517  @brief create a JSON value from MessagePack input
4518 
4519  @param[in] strict whether to expect the input to be consumed completed
4520  @return JSON value created from MessagePack input
4521 
4522  @throw parse_error.110 if input ended unexpectedly or the end of file was
4523  not reached when @a strict was set to true
4524  @throw parse_error.112 if unsupported byte was read
4525  */
4526  BasicJsonType parse_msgpack(const bool strict)
4527  {
4528  const auto res = parse_msgpack_internal();
4529  if (strict)
4530  {
4531  get();
4532  check_eof(true);
4533  }
4534  return res;
4535  }
4536 
4537  /*!
4538  @brief determine system byte order
4539 
4540  @return true if and only if system's byte order is little endian
4541 
4542  @note from http://stackoverflow.com/a/1001328/266378
4543  */
4544  static constexpr bool little_endianess(int num = 1) noexcept
4545  {
4546  return (*reinterpret_cast<char*>(&num) == 1);
4547  }
4548 
4549  private:
4550  /*!
4551  @param[in] get_char whether a new character should be retrieved from the
4552  input (true, default) or whether the last read
4553  character should be considered instead
4554  */
4555  BasicJsonType parse_cbor_internal(const bool get_char = true)
4556  {
4557  switch (get_char ? get() : current)
4558  {
4559  // EOF
4560  case std::char_traits<char>::eof():
4561  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
4562 
4563  // Integer 0x00..0x17 (0..23)
4564  case 0x00:
4565  case 0x01:
4566  case 0x02:
4567  case 0x03:
4568  case 0x04:
4569  case 0x05:
4570  case 0x06:
4571  case 0x07:
4572  case 0x08:
4573  case 0x09:
4574  case 0x0A:
4575  case 0x0B:
4576  case 0x0C:
4577  case 0x0D:
4578  case 0x0E:
4579  case 0x0F:
4580  case 0x10:
4581  case 0x11:
4582  case 0x12:
4583  case 0x13:
4584  case 0x14:
4585  case 0x15:
4586  case 0x16:
4587  case 0x17:
4588  return static_cast<number_unsigned_t>(current);
4589 
4590  case 0x18: // Unsigned integer (one-byte uint8_t follows)
4591  return get_number<uint8_t>();
4592 
4593  case 0x19: // Unsigned integer (two-byte uint16_t follows)
4594  return get_number<uint16_t>();
4595 
4596  case 0x1A: // Unsigned integer (four-byte uint32_t follows)
4597  return get_number<uint32_t>();
4598 
4599  case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
4600  return get_number<uint64_t>();
4601 
4602  // Negative integer -1-0x00..-1-0x17 (-1..-24)
4603  case 0x20:
4604  case 0x21:
4605  case 0x22:
4606  case 0x23:
4607  case 0x24:
4608  case 0x25:
4609  case 0x26:
4610  case 0x27:
4611  case 0x28:
4612  case 0x29:
4613  case 0x2A:
4614  case 0x2B:
4615  case 0x2C:
4616  case 0x2D:
4617  case 0x2E:
4618  case 0x2F:
4619  case 0x30:
4620  case 0x31:
4621  case 0x32:
4622  case 0x33:
4623  case 0x34:
4624  case 0x35:
4625  case 0x36:
4626  case 0x37:
4627  return static_cast<int8_t>(0x20 - 1 - current);
4628 
4629  case 0x38: // Negative integer (one-byte uint8_t follows)
4630  {
4631  // must be uint8_t !
4632  return static_cast<number_integer_t>(-1) - get_number<uint8_t>();
4633  }
4634 
4635  case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
4636  {
4637  return static_cast<number_integer_t>(-1) - get_number<uint16_t>();
4638  }
4639 
4640  case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
4641  {
4642  return static_cast<number_integer_t>(-1) - get_number<uint32_t>();
4643  }
4644 
4645  case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
4646  {
4647  return static_cast<number_integer_t>(-1) -
4648  static_cast<number_integer_t>(get_number<uint64_t>());
4649  }
4650 
4651  // UTF-8 string (0x00..0x17 bytes follow)
4652  case 0x60:
4653  case 0x61:
4654  case 0x62:
4655  case 0x63:
4656  case 0x64:
4657  case 0x65:
4658  case 0x66:
4659  case 0x67:
4660  case 0x68:
4661  case 0x69:
4662  case 0x6A:
4663  case 0x6B:
4664  case 0x6C:
4665  case 0x6D:
4666  case 0x6E:
4667  case 0x6F:
4668  case 0x70:
4669  case 0x71:
4670  case 0x72:
4671  case 0x73:
4672  case 0x74:
4673  case 0x75:
4674  case 0x76:
4675  case 0x77:
4676  case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
4677  case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
4678  case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
4679  case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
4680  case 0x7F: // UTF-8 string (indefinite length)
4681  {
4682  return get_cbor_string();
4683  }
4684 
4685  // array (0x00..0x17 data items follow)
4686  case 0x80:
4687  case 0x81:
4688  case 0x82:
4689  case 0x83:
4690  case 0x84:
4691  case 0x85:
4692  case 0x86:
4693  case 0x87:
4694  case 0x88:
4695  case 0x89:
4696  case 0x8A:
4697  case 0x8B:
4698  case 0x8C:
4699  case 0x8D:
4700  case 0x8E:
4701  case 0x8F:
4702  case 0x90:
4703  case 0x91:
4704  case 0x92:
4705  case 0x93:
4706  case 0x94:
4707  case 0x95:
4708  case 0x96:
4709  case 0x97:
4710  {
4711  return get_cbor_array(current & 0x1F);
4712  }
4713 
4714  case 0x98: // array (one-byte uint8_t for n follows)
4715  {
4716  return get_cbor_array(get_number<uint8_t>());
4717  }
4718 
4719  case 0x99: // array (two-byte uint16_t for n follow)
4720  {
4721  return get_cbor_array(get_number<uint16_t>());
4722  }
4723 
4724  case 0x9A: // array (four-byte uint32_t for n follow)
4725  {
4726  return get_cbor_array(get_number<uint32_t>());
4727  }
4728 
4729  case 0x9B: // array (eight-byte uint64_t for n follow)
4730  {
4731  return get_cbor_array(get_number<uint64_t>());
4732  }
4733 
4734  case 0x9F: // array (indefinite length)
4735  {
4736  BasicJsonType result = value_t::array;
4737  while (get() != 0xFF)
4738  {
4739  result.push_back(parse_cbor_internal(false));
4740  }
4741  return result;
4742  }
4743 
4744  // map (0x00..0x17 pairs of data items follow)
4745  case 0xA0:
4746  case 0xA1:
4747  case 0xA2:
4748  case 0xA3:
4749  case 0xA4:
4750  case 0xA5:
4751  case 0xA6:
4752  case 0xA7:
4753  case 0xA8:
4754  case 0xA9:
4755  case 0xAA:
4756  case 0xAB:
4757  case 0xAC:
4758  case 0xAD:
4759  case 0xAE:
4760  case 0xAF:
4761  case 0xB0:
4762  case 0xB1:
4763  case 0xB2:
4764  case 0xB3:
4765  case 0xB4:
4766  case 0xB5:
4767  case 0xB6:
4768  case 0xB7:
4769  {
4770  return get_cbor_object(current & 0x1F);
4771  }
4772 
4773  case 0xB8: // map (one-byte uint8_t for n follows)
4774  {
4775  return get_cbor_object(get_number<uint8_t>());
4776  }
4777 
4778  case 0xB9: // map (two-byte uint16_t for n follow)
4779  {
4780  return get_cbor_object(get_number<uint16_t>());
4781  }
4782 
4783  case 0xBA: // map (four-byte uint32_t for n follow)
4784  {
4785  return get_cbor_object(get_number<uint32_t>());
4786  }
4787 
4788  case 0xBB: // map (eight-byte uint64_t for n follow)
4789  {
4790  return get_cbor_object(get_number<uint64_t>());
4791  }
4792 
4793  case 0xBF: // map (indefinite length)
4794  {
4795  BasicJsonType result = value_t::object;
4796  while (get() != 0xFF)
4797  {
4798  auto key = get_cbor_string();
4799  result[key] = parse_cbor_internal();
4800  }
4801  return result;
4802  }
4803 
4804  case 0xF4: // false
4805  {
4806  return false;
4807  }
4808 
4809  case 0xF5: // true
4810  {
4811  return true;
4812  }
4813 
4814  case 0xF6: // null
4815  {
4816  return value_t::null;
4817  }
4818 
4819  case 0xF9: // Half-Precision Float (two-byte IEEE 754)
4820  {
4821  const int byte1 = get();
4822  check_eof();
4823  const int byte2 = get();
4824  check_eof();
4825 
4826  // code from RFC 7049, Appendix D, Figure 3:
4827  // As half-precision floating-point numbers were only added
4828  // to IEEE 754 in 2008, today's programming platforms often
4829  // still only have limited support for them. It is very
4830  // easy to include at least decoding support for them even
4831  // without such support. An example of a small decoder for
4832  // half-precision floating-point numbers in the C language
4833  // is shown in Fig. 3.
4834  const int half = (byte1 << 8) + byte2;
4835  const int exp = (half >> 10) & 0x1F;
4836  const int mant = half & 0x3FF;
4837  double val;
4838  if (exp == 0)
4839  {
4840  val = std::ldexp(mant, -24);
4841  }
4842  else if (exp != 31)
4843  {
4844  val = std::ldexp(mant + 1024, exp - 25);
4845  }
4846  else
4847  {
4848  val = (mant == 0) ? std::numeric_limits<double>::infinity()
4849  : std::numeric_limits<double>::quiet_NaN();
4850  }
4851  return (half & 0x8000) != 0 ? -val : val;
4852  }
4853 
4854  case 0xFA: // Single-Precision Float (four-byte IEEE 754)
4855  {
4856  return get_number<float>();
4857  }
4858 
4859  case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
4860  {
4861  return get_number<double>();
4862  }
4863 
4864  default: // anything else (0xFF is handled inside the other types)
4865  {
4866  std::stringstream ss;
4867  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
4868  JSON_THROW(parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + ss.str()));
4869  }
4870  }
4871  }
4872 
4873  BasicJsonType parse_msgpack_internal()
4874  {
4875  switch (get())
4876  {
4877  // EOF
4878  case std::char_traits<char>::eof():
4879  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
4880 
4881  // positive fixint
4882  case 0x00:
4883  case 0x01:
4884  case 0x02:
4885  case 0x03:
4886  case 0x04:
4887  case 0x05:
4888  case 0x06:
4889  case 0x07:
4890  case 0x08:
4891  case 0x09:
4892  case 0x0A:
4893  case 0x0B:
4894  case 0x0C:
4895  case 0x0D:
4896  case 0x0E:
4897  case 0x0F:
4898  case 0x10:
4899  case 0x11:
4900  case 0x12:
4901  case 0x13:
4902  case 0x14:
4903  case 0x15:
4904  case 0x16:
4905  case 0x17:
4906  case 0x18:
4907  case 0x19:
4908  case 0x1A:
4909  case 0x1B:
4910  case 0x1C:
4911  case 0x1D:
4912  case 0x1E:
4913  case 0x1F:
4914  case 0x20:
4915  case 0x21:
4916  case 0x22:
4917  case 0x23:
4918  case 0x24:
4919  case 0x25:
4920  case 0x26:
4921  case 0x27:
4922  case 0x28:
4923  case 0x29:
4924  case 0x2A:
4925  case 0x2B:
4926  case 0x2C:
4927  case 0x2D:
4928  case 0x2E:
4929  case 0x2F:
4930  case 0x30:
4931  case 0x31:
4932  case 0x32:
4933  case 0x33:
4934  case 0x34:
4935  case 0x35:
4936  case 0x36:
4937  case 0x37:
4938  case 0x38:
4939  case 0x39:
4940  case 0x3A:
4941  case 0x3B:
4942  case 0x3C:
4943  case 0x3D:
4944  case 0x3E:
4945  case 0x3F:
4946  case 0x40:
4947  case 0x41:
4948  case 0x42:
4949  case 0x43:
4950  case 0x44:
4951  case 0x45:
4952  case 0x46:
4953  case 0x47:
4954  case 0x48:
4955  case 0x49:
4956  case 0x4A:
4957  case 0x4B:
4958  case 0x4C:
4959  case 0x4D:
4960  case 0x4E:
4961  case 0x4F:
4962  case 0x50:
4963  case 0x51:
4964  case 0x52:
4965  case 0x53:
4966  case 0x54:
4967  case 0x55:
4968  case 0x56:
4969  case 0x57:
4970  case 0x58:
4971  case 0x59:
4972  case 0x5A:
4973  case 0x5B:
4974  case 0x5C:
4975  case 0x5D:
4976  case 0x5E:
4977  case 0x5F:
4978  case 0x60:
4979  case 0x61:
4980  case 0x62:
4981  case 0x63:
4982  case 0x64:
4983  case 0x65:
4984  case 0x66:
4985  case 0x67:
4986  case 0x68:
4987  case 0x69:
4988  case 0x6A:
4989  case 0x6B:
4990  case 0x6C:
4991  case 0x6D:
4992  case 0x6E:
4993  case 0x6F:
4994  case 0x70:
4995  case 0x71:
4996  case 0x72:
4997  case 0x73:
4998  case 0x74:
4999  case 0x75:
5000  case 0x76:
5001  case 0x77:
5002  case 0x78:
5003  case 0x79:
5004  case 0x7A:
5005  case 0x7B:
5006  case 0x7C:
5007  case 0x7D:
5008  case 0x7E:
5009  case 0x7F:
5010  return static_cast<number_unsigned_t>(current);
5011 
5012  // fixmap
5013  case 0x80:
5014  case 0x81:
5015  case 0x82:
5016  case 0x83:
5017  case 0x84:
5018  case 0x85:
5019  case 0x86:
5020  case 0x87:
5021  case 0x88:
5022  case 0x89:
5023  case 0x8A:
5024  case 0x8B:
5025  case 0x8C:
5026  case 0x8D:
5027  case 0x8E:
5028  case 0x8F:
5029  {
5030  return get_msgpack_object(current & 0x0F);
5031  }
5032 
5033  // fixarray
5034  case 0x90:
5035  case 0x91:
5036  case 0x92:
5037  case 0x93:
5038  case 0x94:
5039  case 0x95:
5040  case 0x96:
5041  case 0x97:
5042  case 0x98:
5043  case 0x99:
5044  case 0x9A:
5045  case 0x9B:
5046  case 0x9C:
5047  case 0x9D:
5048  case 0x9E:
5049  case 0x9F:
5050  {
5051  return get_msgpack_array(current & 0x0F);
5052  }
5053 
5054  // fixstr
5055  case 0xA0:
5056  case 0xA1:
5057  case 0xA2:
5058  case 0xA3:
5059  case 0xA4:
5060  case 0xA5:
5061  case 0xA6:
5062  case 0xA7:
5063  case 0xA8:
5064  case 0xA9:
5065  case 0xAA:
5066  case 0xAB:
5067  case 0xAC:
5068  case 0xAD:
5069  case 0xAE:
5070  case 0xAF:
5071  case 0xB0:
5072  case 0xB1:
5073  case 0xB2:
5074  case 0xB3:
5075  case 0xB4:
5076  case 0xB5:
5077  case 0xB6:
5078  case 0xB7:
5079  case 0xB8:
5080  case 0xB9:
5081  case 0xBA:
5082  case 0xBB:
5083  case 0xBC:
5084  case 0xBD:
5085  case 0xBE:
5086  case 0xBF:
5087  return get_msgpack_string();
5088 
5089  case 0xC0: // nil
5090  return value_t::null;
5091 
5092  case 0xC2: // false
5093  return false;
5094 
5095  case 0xC3: // true
5096  return true;
5097 
5098  case 0xCA: // float 32
5099  return get_number<float>();
5100 
5101  case 0xCB: // float 64
5102  return get_number<double>();
5103 
5104  case 0xCC: // uint 8
5105  return get_number<uint8_t>();
5106 
5107  case 0xCD: // uint 16
5108  return get_number<uint16_t>();
5109 
5110  case 0xCE: // uint 32
5111  return get_number<uint32_t>();
5112 
5113  case 0xCF: // uint 64
5114  return get_number<uint64_t>();
5115 
5116  case 0xD0: // int 8
5117  return get_number<int8_t>();
5118 
5119  case 0xD1: // int 16
5120  return get_number<int16_t>();
5121 
5122  case 0xD2: // int 32
5123  return get_number<int32_t>();
5124 
5125  case 0xD3: // int 64
5126  return get_number<int64_t>();
5127 
5128  case 0xD9: // str 8
5129  case 0xDA: // str 16
5130  case 0xDB: // str 32
5131  return get_msgpack_string();
5132 
5133  case 0xDC: // array 16
5134  {
5135  return get_msgpack_array(get_number<uint16_t>());
5136  }
5137 
5138  case 0xDD: // array 32
5139  {
5140  return get_msgpack_array(get_number<uint32_t>());
5141  }
5142 
5143  case 0xDE: // map 16
5144  {
5145  return get_msgpack_object(get_number<uint16_t>());
5146  }
5147 
5148  case 0xDF: // map 32
5149  {
5150  return get_msgpack_object(get_number<uint32_t>());
5151  }
5152 
5153  // positive fixint
5154  case 0xE0:
5155  case 0xE1:
5156  case 0xE2:
5157  case 0xE3:
5158  case 0xE4:
5159  case 0xE5:
5160  case 0xE6:
5161  case 0xE7:
5162  case 0xE8:
5163  case 0xE9:
5164  case 0xEA:
5165  case 0xEB:
5166  case 0xEC:
5167  case 0xED:
5168  case 0xEE:
5169  case 0xEF:
5170  case 0xF0:
5171  case 0xF1:
5172  case 0xF2:
5173  case 0xF3:
5174  case 0xF4:
5175  case 0xF5:
5176  case 0xF6:
5177  case 0xF7:
5178  case 0xF8:
5179  case 0xF9:
5180  case 0xFA:
5181  case 0xFB:
5182  case 0xFC:
5183  case 0xFD:
5184  case 0xFE:
5185  case 0xFF:
5186  return static_cast<int8_t>(current);
5187 
5188  default: // anything else
5189  {
5190  std::stringstream ss;
5191  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5192  JSON_THROW(parse_error::create(112, chars_read,
5193  "error reading MessagePack; last byte: 0x" + ss.str()));
5194  }
5195  }
5196  }
5197 
5198  /*!
5199  @brief get next character from the input
5200 
5201  This function provides the interface to the used input adapter. It does
5202  not throw in case the input reached EOF, but returns a -'ve valued
5203  `std::char_traits<char>::eof()` in that case.
5204 
5205  @return character read from the input
5206  */
5207  int get()
5208  {
5209  ++chars_read;
5210  return (current = ia->get_character());
5211  }
5212 
5213  /*
5214  @brief read a number from the input
5215 
5216  @tparam NumberType the type of the number
5217 
5218  @return number of type @a NumberType
5219 
5220  @note This function needs to respect the system's endianess, because
5221  bytes in CBOR and MessagePack are stored in network order (big
5222  endian) and therefore need reordering on little endian systems.
5223 
5224  @throw parse_error.110 if input has less than `sizeof(NumberType)` bytes
5225  */
5226  template<typename NumberType> NumberType get_number()
5227  {
5228  // step 1: read input into array with system's byte order
5229  std::array<uint8_t, sizeof(NumberType)> vec;
5230  for (std::size_t i = 0; i < sizeof(NumberType); ++i)
5231  {
5232  get();
5233  check_eof();
5234 
5235  // reverse byte order prior to conversion if necessary
5236  if (is_little_endian)
5237  {
5238  vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);
5239  }
5240  else
5241  {
5242  vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE
5243  }
5244  }
5245 
5246  // step 2: convert array into number of type T and return
5247  NumberType result;
5248  std::memcpy(&result, vec.data(), sizeof(NumberType));
5249  return result;
5250  }
5251 
5252  /*!
5253  @brief create a string by reading characters from the input
5254 
5255  @param[in] len number of bytes to read
5256 
5257  @note We can not reserve @a len bytes for the result, because @a len
5258  may be too large. Usually, @ref check_eof() detects the end of
5259  the input before we run out of string memory.
5260 
5261  @return string created by reading @a len bytes
5262 
5263  @throw parse_error.110 if input has less than @a len bytes
5264  */
5265  template<typename NumberType>
5266  std::string get_string(const NumberType len)
5267  {
5268  std::string result;
5269  std::generate_n(std::back_inserter(result), len, [this]()
5270  {
5271  get();
5272  check_eof();
5273  return static_cast<char>(current);
5274  });
5275  return result;
5276  }
5277 
5278  /*!
5279  @brief reads a CBOR string
5280 
5281  This function first reads starting bytes to determine the expected
5282  string length and then copies this number of bytes into a string.
5283  Additionally, CBOR's strings with indefinite lengths are supported.
5284 
5285  @return string
5286 
5287  @throw parse_error.110 if input ended
5288  @throw parse_error.113 if an unexpected byte is read
5289  */
5290  std::string get_cbor_string()
5291  {
5292  check_eof();
5293 
5294  switch (current)
5295  {
5296  // UTF-8 string (0x00..0x17 bytes follow)
5297  case 0x60:
5298  case 0x61:
5299  case 0x62:
5300  case 0x63:
5301  case 0x64:
5302  case 0x65:
5303  case 0x66:
5304  case 0x67:
5305  case 0x68:
5306  case 0x69:
5307  case 0x6A:
5308  case 0x6B:
5309  case 0x6C:
5310  case 0x6D:
5311  case 0x6E:
5312  case 0x6F:
5313  case 0x70:
5314  case 0x71:
5315  case 0x72:
5316  case 0x73:
5317  case 0x74:
5318  case 0x75:
5319  case 0x76:
5320  case 0x77:
5321  {
5322  return get_string(current & 0x1F);
5323  }
5324 
5325  case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
5326  {
5327  return get_string(get_number<uint8_t>());
5328  }
5329 
5330  case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
5331  {
5332  return get_string(get_number<uint16_t>());
5333  }
5334 
5335  case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
5336  {
5337  return get_string(get_number<uint32_t>());
5338  }
5339 
5340  case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
5341  {
5342  return get_string(get_number<uint64_t>());
5343  }
5344 
5345  case 0x7F: // UTF-8 string (indefinite length)
5346  {
5347  std::string result;
5348  while (get() != 0xFF)
5349  {
5350  check_eof();
5351  result.push_back(static_cast<char>(current));
5352  }
5353  return result;
5354  }
5355 
5356  default:
5357  {
5358  std::stringstream ss;
5359  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5360  JSON_THROW(parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + ss.str()));
5361  }
5362  }
5363  }
5364 
5365  template<typename NumberType>
5366  BasicJsonType get_cbor_array(const NumberType len)
5367  {
5368  BasicJsonType result = value_t::array;
5369  std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
5370  {
5371  return parse_cbor_internal();
5372  });
5373  return result;
5374  }
5375 
5376  template<typename NumberType>
5377  BasicJsonType get_cbor_object(const NumberType len)
5378  {
5379  BasicJsonType result = value_t::object;
5380  std::generate_n(std::inserter(*result.m_value.object,
5381  result.m_value.object->end()),
5382  len, [this]()
5383  {
5384  get();
5385  auto key = get_cbor_string();
5386  auto val = parse_cbor_internal();
5387  return std::make_pair(std::move(key), std::move(val));
5388  });
5389  return result;
5390  }
5391 
5392  /*!
5393  @brief reads a MessagePack string
5394 
5395  This function first reads starting bytes to determine the expected
5396  string length and then copies this number of bytes into a string.
5397 
5398  @return string
5399 
5400  @throw parse_error.110 if input ended
5401  @throw parse_error.113 if an unexpected byte is read
5402  */
5403  std::string get_msgpack_string()
5404  {
5405  check_eof();
5406 
5407  switch (current)
5408  {
5409  // fixstr
5410  case 0xA0:
5411  case 0xA1:
5412  case 0xA2:
5413  case 0xA3:
5414  case 0xA4:
5415  case 0xA5:
5416  case 0xA6:
5417  case 0xA7:
5418  case 0xA8:
5419  case 0xA9:
5420  case 0xAA:
5421  case 0xAB:
5422  case 0xAC:
5423  case 0xAD:
5424  case 0xAE:
5425  case 0xAF:
5426  case 0xB0:
5427  case 0xB1:
5428  case 0xB2:
5429  case 0xB3:
5430  case 0xB4:
5431  case 0xB5:
5432  case 0xB6:
5433  case 0xB7:
5434  case 0xB8:
5435  case 0xB9:
5436  case 0xBA:
5437  case 0xBB:
5438  case 0xBC:
5439  case 0xBD:
5440  case 0xBE:
5441  case 0xBF:
5442  {
5443  return get_string(current & 0x1F);
5444  }
5445 
5446  case 0xD9: // str 8
5447  {
5448  return get_string(get_number<uint8_t>());
5449  }
5450 
5451  case 0xDA: // str 16
5452  {
5453  return get_string(get_number<uint16_t>());
5454  }
5455 
5456  case 0xDB: // str 32
5457  {
5458  return get_string(get_number<uint32_t>());
5459  }
5460 
5461  default:
5462  {
5463  std::stringstream ss;
5464  ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
5465  JSON_THROW(parse_error::create(113, chars_read,
5466  "expected a MessagePack string; last byte: 0x" + ss.str()));
5467  }
5468  }
5469  }
5470 
5471  template<typename NumberType>
5472  BasicJsonType get_msgpack_array(const NumberType len)
5473  {
5474  BasicJsonType result = value_t::array;
5475  std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
5476  {
5477  return parse_msgpack_internal();
5478  });
5479  return result;
5480  }
5481 
5482  template<typename NumberType>
5483  BasicJsonType get_msgpack_object(const NumberType len)
5484  {
5485  BasicJsonType result = value_t::object;
5486  std::generate_n(std::inserter(*result.m_value.object,
5487  result.m_value.object->end()),
5488  len, [this]()
5489  {
5490  get();
5491  auto key = get_msgpack_string();
5492  auto val = parse_msgpack_internal();
5493  return std::make_pair(std::move(key), std::move(val));
5494  });
5495  return result;
5496  }
5497 
5498  /*!
5499  @brief check if input ended
5500  @throw parse_error.110 if input ended
5501  */
5502  void check_eof(const bool expect_eof = false) const
5503  {
5504  if (expect_eof)
5505  {
5506  if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
5507  {
5508  JSON_THROW(parse_error::create(110, chars_read, "expected end of input"));
5509  }
5510  }
5511  else
5512  {
5513  if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
5514  {
5515  JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
5516  }
5517  }
5518  }
5519 
5520  private:
5521  /// input adapter
5522  input_adapter_t ia = nullptr;
5523 
5524  /// the current character
5525  int current = std::char_traits<char>::eof();
5526 
5527  /// the number of characters read
5528  std::size_t chars_read = 0;
5529 
5530  /// whether we can assume little endianess
5531  const bool is_little_endian = little_endianess();
5532 };
5533 
5534 /*!
5535 @brief serialization to CBOR and MessagePack values
5536 */
5537 template<typename BasicJsonType, typename CharType>
5538 class binary_writer
5539 {
5540  public:
5541  /*!
5542  @brief create a binary writer
5543 
5544  @param[in] adapter output adapter to write to
5545  */
5546  explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
5547  {
5548  assert(oa);
5549  }
5550 
5551  /*!
5552  @brief[in] j JSON value to serialize
5553  */
5554  void write_cbor(const BasicJsonType& j)
5555  {
5556  switch (j.type())
5557  {
5558  case value_t::null:
5559  {
5560  oa->write_character(static_cast<CharType>(0xF6));
5561  break;
5562  }
5563 
5564  case value_t::boolean:
5565  {
5566  oa->write_character(j.m_value.boolean
5567  ? static_cast<CharType>(0xF5)
5568  : static_cast<CharType>(0xF4));
5569  break;
5570  }
5571 
5572  case value_t::number_integer:
5573  {
5574  if (j.m_value.number_integer >= 0)
5575  {
5576  // CBOR does not differentiate between positive signed
5577  // integers and unsigned integers. Therefore, we used the
5578  // code from the value_t::number_unsigned case here.
5579  if (j.m_value.number_integer <= 0x17)
5580  {
5581  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5582  }
5583  else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
5584  {
5585  oa->write_character(static_cast<CharType>(0x18));
5586  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5587  }
5588  else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
5589  {
5590  oa->write_character(static_cast<CharType>(0x19));
5591  write_number(static_cast<uint16_t>(j.m_value.number_integer));
5592  }
5593  else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
5594  {
5595  oa->write_character(static_cast<CharType>(0x1A));
5596  write_number(static_cast<uint32_t>(j.m_value.number_integer));
5597  }
5598  else
5599  {
5600  oa->write_character(static_cast<CharType>(0x1B));
5601  write_number(static_cast<uint64_t>(j.m_value.number_integer));
5602  }
5603  }
5604  else
5605  {
5606  // The conversions below encode the sign in the first
5607  // byte, and the value is converted to a positive number.
5608  const auto positive_number = -1 - j.m_value.number_integer;
5609  if (j.m_value.number_integer >= -24)
5610  {
5611  write_number(static_cast<uint8_t>(0x20 + positive_number));
5612  }
5613  else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
5614  {
5615  oa->write_character(static_cast<CharType>(0x38));
5616  write_number(static_cast<uint8_t>(positive_number));
5617  }
5618  else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
5619  {
5620  oa->write_character(static_cast<CharType>(0x39));
5621  write_number(static_cast<uint16_t>(positive_number));
5622  }
5623  else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
5624  {
5625  oa->write_character(static_cast<CharType>(0x3A));
5626  write_number(static_cast<uint32_t>(positive_number));
5627  }
5628  else
5629  {
5630  oa->write_character(static_cast<CharType>(0x3B));
5631  write_number(static_cast<uint64_t>(positive_number));
5632  }
5633  }
5634  break;
5635  }
5636 
5637  case value_t::number_unsigned:
5638  {
5639  if (j.m_value.number_unsigned <= 0x17)
5640  {
5641  write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
5642  }
5643  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
5644  {
5645  oa->write_character(static_cast<CharType>(0x18));
5646  write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
5647  }
5648  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
5649  {
5650  oa->write_character(static_cast<CharType>(0x19));
5651  write_number(static_cast<uint16_t>(j.m_value.number_unsigned));
5652  }
5653  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
5654  {
5655  oa->write_character(static_cast<CharType>(0x1A));
5656  write_number(static_cast<uint32_t>(j.m_value.number_unsigned));
5657  }
5658  else
5659  {
5660  oa->write_character(static_cast<CharType>(0x1B));
5661  write_number(static_cast<uint64_t>(j.m_value.number_unsigned));
5662  }
5663  break;
5664  }
5665 
5666  case value_t::number_float: // Double-Precision Float
5667  {
5668  oa->write_character(static_cast<CharType>(0xFB));
5669  write_number(j.m_value.number_float);
5670  break;
5671  }
5672 
5673  case value_t::string:
5674  {
5675  // step 1: write control byte and the string length
5676  const auto N = j.m_value.string->size();
5677  if (N <= 0x17)
5678  {
5679  write_number(static_cast<uint8_t>(0x60 + N));
5680  }
5681  else if (N <= 0xFF)
5682  {
5683  oa->write_character(static_cast<CharType>(0x78));
5684  write_number(static_cast<uint8_t>(N));
5685  }
5686  else if (N <= 0xFFFF)
5687  {
5688  oa->write_character(static_cast<CharType>(0x79));
5689  write_number(static_cast<uint16_t>(N));
5690  }
5691  else if (N <= 0xFFFFFFFF)
5692  {
5693  oa->write_character(static_cast<CharType>(0x7A));
5694  write_number(static_cast<uint32_t>(N));
5695  }
5696  // LCOV_EXCL_START
5697  else if (N <= 0xFFFFFFFFFFFFFFFF)
5698  {
5699  oa->write_character(static_cast<CharType>(0x7B));
5700  write_number(static_cast<uint64_t>(N));
5701  }
5702  // LCOV_EXCL_STOP
5703 
5704  // step 2: write the string
5705  oa->write_characters(
5706  reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
5707  j.m_value.string->size());
5708  break;
5709  }
5710 
5711  case value_t::array:
5712  {
5713  // step 1: write control byte and the array size
5714  const auto N = j.m_value.array->size();
5715  if (N <= 0x17)
5716  {
5717  write_number(static_cast<uint8_t>(0x80 + N));
5718  }
5719  else if (N <= 0xFF)
5720  {
5721  oa->write_character(static_cast<CharType>(0x98));
5722  write_number(static_cast<uint8_t>(N));
5723  }
5724  else if (N <= 0xFFFF)
5725  {
5726  oa->write_character(static_cast<CharType>(0x99));
5727  write_number(static_cast<uint16_t>(N));
5728  }
5729  else if (N <= 0xFFFFFFFF)
5730  {
5731  oa->write_character(static_cast<CharType>(0x9A));
5732  write_number(static_cast<uint32_t>(N));
5733  }
5734  // LCOV_EXCL_START
5735  else if (N <= 0xFFFFFFFFFFFFFFFF)
5736  {
5737  oa->write_character(static_cast<CharType>(0x9B));
5738  write_number(static_cast<uint64_t>(N));
5739  }
5740  // LCOV_EXCL_STOP
5741 
5742  // step 2: write each element
5743  for (const auto& el : *j.m_value.array)
5744  {
5745  write_cbor(el);
5746  }
5747  break;
5748  }
5749 
5750  case value_t::object:
5751  {
5752  // step 1: write control byte and the object size
5753  const auto N = j.m_value.object->size();
5754  if (N <= 0x17)
5755  {
5756  write_number(static_cast<uint8_t>(0xA0 + N));
5757  }
5758  else if (N <= 0xFF)
5759  {
5760  oa->write_character(static_cast<CharType>(0xB8));
5761  write_number(static_cast<uint8_t>(N));
5762  }
5763  else if (N <= 0xFFFF)
5764  {
5765  oa->write_character(static_cast<CharType>(0xB9));
5766  write_number(static_cast<uint16_t>(N));
5767  }
5768  else if (N <= 0xFFFFFFFF)
5769  {
5770  oa->write_character(static_cast<CharType>(0xBA));
5771  write_number(static_cast<uint32_t>(N));
5772  }
5773  // LCOV_EXCL_START
5774  else if (N <= 0xFFFFFFFFFFFFFFFF)
5775  {
5776  oa->write_character(static_cast<CharType>(0xBB));
5777  write_number(static_cast<uint64_t>(N));
5778  }
5779  // LCOV_EXCL_STOP
5780 
5781  // step 2: write each element
5782  for (const auto& el : *j.m_value.object)
5783  {
5784  write_cbor(el.first);
5785  write_cbor(el.second);
5786  }
5787  break;
5788  }
5789 
5790  default:
5791  break;
5792  }
5793  }
5794 
5795  /*!
5796  @brief[in] j JSON value to serialize
5797  */
5798  void write_msgpack(const BasicJsonType& j)
5799  {
5800  switch (j.type())
5801  {
5802  case value_t::null: // nil
5803  {
5804  oa->write_character(static_cast<CharType>(0xC0));
5805  break;
5806  }
5807 
5808  case value_t::boolean: // true and false
5809  {
5810  oa->write_character(j.m_value.boolean
5811  ? static_cast<CharType>(0xC3)
5812  : static_cast<CharType>(0xC2));
5813  break;
5814  }
5815 
5816  case value_t::number_integer:
5817  {
5818  if (j.m_value.number_integer >= 0)
5819  {
5820  // MessagePack does not differentiate between positive
5821  // signed integers and unsigned integers. Therefore, we used
5822  // the code from the value_t::number_unsigned case here.
5823  if (j.m_value.number_unsigned < 128)
5824  {
5825  // positive fixnum
5826  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5827  }
5828  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
5829  {
5830  // uint 8
5831  oa->write_character(static_cast<CharType>(0xCC));
5832  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5833  }
5834  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
5835  {
5836  // uint 16
5837  oa->write_character(static_cast<CharType>(0xCD));
5838  write_number(static_cast<uint16_t>(j.m_value.number_integer));
5839  }
5840  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
5841  {
5842  // uint 32
5843  oa->write_character(static_cast<CharType>(0xCE));
5844  write_number(static_cast<uint32_t>(j.m_value.number_integer));
5845  }
5846  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
5847  {
5848  // uint 64
5849  oa->write_character(static_cast<CharType>(0xCF));
5850  write_number(static_cast<uint64_t>(j.m_value.number_integer));
5851  }
5852  }
5853  else
5854  {
5855  if (j.m_value.number_integer >= -32)
5856  {
5857  // negative fixnum
5858  write_number(static_cast<int8_t>(j.m_value.number_integer));
5859  }
5860  else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and
5861  j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
5862  {
5863  // int 8
5864  oa->write_character(static_cast<CharType>(0xD0));
5865  write_number(static_cast<int8_t>(j.m_value.number_integer));
5866  }
5867  else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and
5868  j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
5869  {
5870  // int 16
5871  oa->write_character(static_cast<CharType>(0xD1));
5872  write_number(static_cast<int16_t>(j.m_value.number_integer));
5873  }
5874  else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and
5875  j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
5876  {
5877  // int 32
5878  oa->write_character(static_cast<CharType>(0xD2));
5879  write_number(static_cast<int32_t>(j.m_value.number_integer));
5880  }
5881  else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and
5882  j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
5883  {
5884  // int 64
5885  oa->write_character(static_cast<CharType>(0xD3));
5886  write_number(static_cast<int64_t>(j.m_value.number_integer));
5887  }
5888  }
5889  break;
5890  }
5891 
5892  case value_t::number_unsigned:
5893  {
5894  if (j.m_value.number_unsigned < 128)
5895  {
5896  // positive fixnum
5897  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5898  }
5899  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
5900  {
5901  // uint 8
5902  oa->write_character(static_cast<CharType>(0xCC));
5903  write_number(static_cast<uint8_t>(j.m_value.number_integer));
5904  }
5905  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
5906  {
5907  // uint 16
5908  oa->write_character(static_cast<CharType>(0xCD));
5909  write_number(static_cast<uint16_t>(j.m_value.number_integer));
5910  }
5911  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
5912  {
5913  // uint 32
5914  oa->write_character(static_cast<CharType>(0xCE));
5915  write_number(static_cast<uint32_t>(j.m_value.number_integer));
5916  }
5917  else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
5918  {
5919  // uint 64
5920  oa->write_character(static_cast<CharType>(0xCF));
5921  write_number(static_cast<uint64_t>(j.m_value.number_integer));
5922  }
5923  break;
5924  }
5925 
5926  case value_t::number_float: // float 64
5927  {
5928  oa->write_character(static_cast<CharType>(0xCB));
5929  write_number(j.m_value.number_float);
5930  break;
5931  }
5932 
5933  case value_t::string:
5934  {
5935  // step 1: write control byte and the string length
5936  const auto N = j.m_value.string->size();
5937  if (N <= 31)
5938  {
5939  // fixstr
5940  write_number(static_cast<uint8_t>(0xA0 | N));
5941  }
5942  else if (N <= 255)
5943  {
5944  // str 8
5945  oa->write_character(static_cast<CharType>(0xD9));
5946  write_number(static_cast<uint8_t>(N));
5947  }
5948  else if (N <= 65535)
5949  {
5950  // str 16
5951  oa->write_character(static_cast<CharType>(0xDA));
5952  write_number(static_cast<uint16_t>(N));
5953  }
5954  else if (N <= 4294967295)
5955  {
5956  // str 32
5957  oa->write_character(static_cast<CharType>(0xDB));
5958  write_number(static_cast<uint32_t>(N));
5959  }
5960 
5961  // step 2: write the string
5962  oa->write_characters(
5963  reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
5964  j.m_value.string->size());
5965  break;
5966  }
5967 
5968  case value_t::array:
5969  {
5970  // step 1: write control byte and the array size
5971  const auto N = j.m_value.array->size();
5972  if (N <= 15)
5973  {
5974  // fixarray
5975  write_number(static_cast<uint8_t>(0x90 | N));
5976  }
5977  else if (N <= 0xFFFF)
5978  {
5979  // array 16
5980  oa->write_character(static_cast<CharType>(0xDC));
5981  write_number(static_cast<uint16_t>(N));
5982  }
5983  else if (N <= 0xFFFFFFFF)
5984  {
5985  // array 32
5986  oa->write_character(static_cast<CharType>(0xDD));
5987  write_number(static_cast<uint32_t>(N));
5988  }
5989 
5990  // step 2: write each element
5991  for (const auto& el : *j.m_value.array)
5992  {
5993  write_msgpack(el);
5994  }
5995  break;
5996  }
5997 
5998  case value_t::object:
5999  {
6000  // step 1: write control byte and the object size
6001  const auto N = j.m_value.object->size();
6002  if (N <= 15)
6003  {
6004  // fixmap
6005  write_number(static_cast<uint8_t>(0x80 | (N & 0xF)));
6006  }
6007  else if (N <= 65535)
6008  {
6009  // map 16
6010  oa->write_character(static_cast<CharType>(0xDE));
6011  write_number(static_cast<uint16_t>(N));
6012  }
6013  else if (N <= 4294967295)
6014  {
6015  // map 32
6016  oa->write_character(static_cast<CharType>(0xDF));
6017  write_number(static_cast<uint32_t>(N));
6018  }
6019 
6020  // step 2: write each element
6021  for (const auto& el : *j.m_value.object)
6022  {
6023  write_msgpack(el.first);
6024  write_msgpack(el.second);
6025  }
6026  break;
6027  }
6028 
6029  default:
6030  break;
6031  }
6032  }
6033 
6034  private:
6035  /*
6036  @brief write a number to output input
6037 
6038  @param[in] n number of type @a NumberType
6039  @tparam NumberType the type of the number
6040 
6041  @note This function needs to respect the system's endianess, because bytes
6042  in CBOR and MessagePack are stored in network order (big endian) and
6043  therefore need reordering on little endian systems.
6044  */
6045  template<typename NumberType> void write_number(NumberType n)
6046  {
6047  // step 1: write number to array of length NumberType
6048  std::array<CharType, sizeof(NumberType)> vec;
6049  std::memcpy(vec.data(), &n, sizeof(NumberType));
6050 
6051  // step 2: write array to output (with possible reordering)
6052  if (is_little_endian)
6053  {
6054  // reverse byte order prior to conversion if necessary
6055  std::reverse(vec.begin(), vec.end());
6056  }
6057 
6058  oa->write_characters(vec.data(), sizeof(NumberType));
6059  }
6060 
6061  private:
6062  /// whether we can assume little endianess
6063  const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
6064 
6065  /// the output
6066  output_adapter_t<CharType> oa = nullptr;
6067 };
6068 
6069 ///////////////////
6070 // serialization //
6071 ///////////////////
6072 
6073 template<typename BasicJsonType>
6074 class serializer
6075 {
6076  using string_t = typename BasicJsonType::string_t;
6077  using number_float_t = typename BasicJsonType::number_float_t;
6078  using number_integer_t = typename BasicJsonType::number_integer_t;
6079  using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
6080  public:
6081  /*!
6082  @param[in] s output stream to serialize to
6083  @param[in] ichar indentation character to use
6084  */
6085  serializer(output_adapter_t<char> s, const char ichar)
6086  : o(std::move(s)), loc(std::localeconv()),
6087  thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep)),
6088  decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point)),
6089  indent_char(ichar), indent_string(512, indent_char) {}
6090 
6091  // delete because of pointer members
6092  serializer(const serializer&) = delete;
6093  serializer& operator=(const serializer&) = delete;
6094 
6095  /*!
6096  @brief internal implementation of the serialization function
6097 
6098  This function is called by the public member function dump and organizes
6099  the serialization internally. The indentation level is propagated as
6100  additional parameter. In case of arrays and objects, the function is
6101  called recursively.
6102 
6103  - strings and object keys are escaped using `escape_string()`
6104  - integer numbers are converted implicitly via `operator<<`
6105  - floating-point numbers are converted to a string using `"%g"` format
6106 
6107  @param[in] val value to serialize
6108  @param[in] pretty_print whether the output shall be pretty-printed
6109  @param[in] indent_step the indent level
6110  @param[in] current_indent the current indent level (only used internally)
6111  */
6112  void dump(const BasicJsonType& val, const bool pretty_print,
6113  const bool ensure_ascii,
6114  const unsigned int indent_step,
6115  const unsigned int current_indent = 0)
6116  {
6117  switch (val.m_type)
6118  {
6119  case value_t::object:
6120  {
6121  if (val.m_value.object->empty())
6122  {
6123  o->write_characters("{}", 2);
6124  return;
6125  }
6126 
6127  if (pretty_print)
6128  {
6129  o->write_characters("{\n", 2);
6130 
6131  // variable to hold indentation for recursive calls
6132  const auto new_indent = current_indent + indent_step;
6133  if (JSON_UNLIKELY(indent_string.size() < new_indent))
6134  {
6135  indent_string.resize(indent_string.size() * 2, ' ');
6136  }
6137 
6138  // first n-1 elements
6139  auto i = val.m_value.object->cbegin();
6140  for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
6141  {
6142  o->write_characters(indent_string.c_str(), new_indent);
6143  o->write_character('\"');
6144  dump_escaped(i->first, ensure_ascii);
6145  o->write_characters("\": ", 3);
6146  dump(i->second, true, ensure_ascii, indent_step, new_indent);
6147  o->write_characters(",\n", 2);
6148  }
6149 
6150  // last element
6151  assert(i != val.m_value.object->cend());
6152  assert(std::next(i) == val.m_value.object->cend());
6153  o->write_characters(indent_string.c_str(), new_indent);
6154  o->write_character('\"');
6155  dump_escaped(i->first, ensure_ascii);
6156  o->write_characters("\": ", 3);
6157  dump(i->second, true, ensure_ascii, indent_step, new_indent);
6158 
6159  o->write_character('\n');
6160  o->write_characters(indent_string.c_str(), current_indent);
6161  o->write_character('}');
6162  }
6163  else
6164  {
6165  o->write_character('{');
6166 
6167  // first n-1 elements
6168  auto i = val.m_value.object->cbegin();
6169  for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
6170  {
6171  o->write_character('\"');
6172  dump_escaped(i->first, ensure_ascii);
6173  o->write_characters("\":", 2);
6174  dump(i->second, false, ensure_ascii, indent_step, current_indent);
6175  o->write_character(',');
6176  }
6177 
6178  // last element
6179  assert(i != val.m_value.object->cend());
6180  assert(std::next(i) == val.m_value.object->cend());
6181  o->write_character('\"');
6182  dump_escaped(i->first, ensure_ascii);
6183  o->write_characters("\":", 2);
6184  dump(i->second, false, ensure_ascii, indent_step, current_indent);
6185 
6186  o->write_character('}');
6187  }
6188 
6189  return;
6190  }
6191 
6192  case value_t::array:
6193  {
6194  if (val.m_value.array->empty())
6195  {
6196  o->write_characters("[]", 2);
6197  return;
6198  }
6199 
6200  if (pretty_print)
6201  {
6202  o->write_characters("[\n", 2);
6203 
6204  // variable to hold indentation for recursive calls
6205  const auto new_indent = current_indent + indent_step;
6206  if (JSON_UNLIKELY(indent_string.size() < new_indent))
6207  {
6208  indent_string.resize(indent_string.size() * 2, ' ');
6209  }
6210 
6211  // first n-1 elements
6212  for (auto i = val.m_value.array->cbegin();
6213  i != val.m_value.array->cend() - 1; ++i)
6214  {
6215  o->write_characters(indent_string.c_str(), new_indent);
6216  dump(*i, true, ensure_ascii, indent_step, new_indent);
6217  o->write_characters(",\n", 2);
6218  }
6219 
6220  // last element
6221  assert(not val.m_value.array->empty());
6222  o->write_characters(indent_string.c_str(), new_indent);
6223  dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
6224 
6225  o->write_character('\n');
6226  o->write_characters(indent_string.c_str(), current_indent);
6227  o->write_character(']');
6228  }
6229  else
6230  {
6231  o->write_character('[');
6232 
6233  // first n-1 elements
6234  for (auto i = val.m_value.array->cbegin();
6235  i != val.m_value.array->cend() - 1; ++i)
6236  {
6237  dump(*i, false, ensure_ascii, indent_step, current_indent);
6238  o->write_character(',');
6239  }
6240 
6241  // last element
6242  assert(not val.m_value.array->empty());
6243  dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
6244 
6245  o->write_character(']');
6246  }
6247 
6248  return;
6249  }
6250 
6251  case value_t::string:
6252  {
6253  o->write_character('\"');
6254  dump_escaped(*val.m_value.string, ensure_ascii);
6255  o->write_character('\"');
6256  return;
6257  }
6258 
6259  case value_t::boolean:
6260  {
6261  if (val.m_value.boolean)
6262  {
6263  o->write_characters("true", 4);
6264  }
6265  else
6266  {
6267  o->write_characters("false", 5);
6268  }
6269  return;
6270  }
6271 
6272  case value_t::number_integer:
6273  {
6274  dump_integer(val.m_value.number_integer);
6275  return;
6276  }
6277 
6278  case value_t::number_unsigned:
6279  {
6280  dump_integer(val.m_value.number_unsigned);
6281  return;
6282  }
6283 
6284  case value_t::number_float:
6285  {
6286  dump_float(val.m_value.number_float);
6287  return;
6288  }
6289 
6290  case value_t::discarded:
6291  {
6292  o->write_characters("<discarded>", 11);
6293  return;
6294  }
6295 
6296  case value_t::null:
6297  {
6298  o->write_characters("null", 4);
6299  return;
6300  }
6301  }
6302  }
6303 
6304  private:
6305  /*!
6306  @brief returns the number of expected bytes following in UTF-8 string
6307 
6308  @param[in] u the first byte of a UTF-8 string
6309  @return the number of expected bytes following
6310  */
6311  static constexpr std::size_t bytes_following(const uint8_t u)
6312  {
6313  return ((u <= 127) ? 0
6314  : ((192 <= u and u <= 223) ? 1
6315  : ((224 <= u and u <= 239) ? 2
6316  : ((240 <= u and u <= 247) ? 3 : std::string::npos))));
6317  }
6318 
6319  /*!
6320  @brief calculates the extra space to escape a JSON string
6321 
6322  @param[in] s the string to escape
6323  @param[in] ensure_ascii whether to escape non-ASCII characters with
6324  \uXXXX sequences
6325  @return the number of characters required to escape string @a s
6326 
6327  @complexity Linear in the length of string @a s.
6328  */
6329  static std::size_t extra_space(const string_t& s,
6330  const bool ensure_ascii) noexcept
6331  {
6332  std::size_t res = 0;
6333 
6334  for (std::size_t i = 0; i < s.size(); ++i)
6335  {
6336  switch (s[i])
6337  {
6338  // control characters that can be escaped with a backslash
6339  case '"':
6340  case '\\':
6341  case '\b':
6342  case '\f':
6343  case '\n':
6344  case '\r':
6345  case '\t':
6346  {
6347  // from c (1 byte) to \x (2 bytes)
6348  res += 1;
6349  break;
6350  }
6351 
6352  // control characters that need \uxxxx escaping
6353  case 0x00:
6354  case 0x01:
6355  case 0x02:
6356  case 0x03:
6357  case 0x04:
6358  case 0x05:
6359  case 0x06:
6360  case 0x07:
6361  case 0x0B:
6362  case 0x0E:
6363  case 0x0F:
6364  case 0x10:
6365  case 0x11:
6366  case 0x12:
6367  case 0x13:
6368  case 0x14:
6369  case 0x15:
6370  case 0x16:
6371  case 0x17:
6372  case 0x18:
6373  case 0x19:
6374  case 0x1A:
6375  case 0x1B:
6376  case 0x1C:
6377  case 0x1D:
6378  case 0x1E:
6379  case 0x1F:
6380  {
6381  // from c (1 byte) to \uxxxx (6 bytes)
6382  res += 5;
6383  break;
6384  }
6385 
6386  default:
6387  {
6388  if (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F))
6389  {
6390  const auto bytes = bytes_following(static_cast<uint8_t>(s[i]));
6391  // invalid characters will be detected by throw_if_invalid_utf8
6392  assert (bytes != std::string::npos);
6393 
6394  if (bytes == 3)
6395  {
6396  // codepoints that need 4 bytes (i.e., 3 additional
6397  // bytes) in UTF-8 need a surrogate pair when \u
6398  // escaping is used: from 4 bytes to \uxxxx\uxxxx
6399  // (12 bytes)
6400  res += (12 - bytes - 1);
6401  }
6402  else
6403  {
6404  // from x bytes to \uxxxx (6 bytes)
6405  res += (6 - bytes - 1);
6406  }
6407 
6408  // skip the additional bytes
6409  i += bytes;
6410  }
6411  break;
6412  }
6413  }
6414  }
6415 
6416  return res;
6417  }
6418 
6419  static void escape_codepoint(int codepoint, string_t& result, std::size_t& pos)
6420  {
6421  // expecting a proper codepoint
6422  assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
6423 
6424  // the last written character was the backslash before the 'u'
6425  assert(result[pos] == '\\');
6426 
6427  // write the 'u'
6428  result[++pos] = 'u';
6429 
6430  // convert a number 0..15 to its hex representation (0..f)
6431  static const std::array<char, 16> hexify =
6432  {
6433  {
6434  '0', '1', '2', '3', '4', '5', '6', '7',
6435  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
6436  }
6437  };
6438 
6439  if (codepoint < 0x10000)
6440  {
6441  // codepoints U+0000..U+FFFF can be represented as \uxxxx.
6442  result[++pos] = hexify[(codepoint >> 12) & 0x0F];
6443  result[++pos] = hexify[(codepoint >> 8) & 0x0F];
6444  result[++pos] = hexify[(codepoint >> 4) & 0x0F];
6445  result[++pos] = hexify[codepoint & 0x0F];
6446  }
6447  else
6448  {
6449  // codepoints U+10000..U+10FFFF need a surrogate pair to be
6450  // represented as \uxxxx\uxxxx.
6451  // http://www.unicode.org/faq/utf_bom.html#utf16-4
6452  codepoint -= 0x10000;
6453  const int high_surrogate = 0xD800 | ((codepoint >> 10) & 0x3FF);
6454  const int low_surrogate = 0xDC00 | (codepoint & 0x3FF);
6455  result[++pos] = hexify[(high_surrogate >> 12) & 0x0F];
6456  result[++pos] = hexify[(high_surrogate >> 8) & 0x0F];
6457  result[++pos] = hexify[(high_surrogate >> 4) & 0x0F];
6458  result[++pos] = hexify[high_surrogate & 0x0F];
6459  ++pos; // backslash is already in output
6460  result[++pos] = 'u';
6461  result[++pos] = hexify[(low_surrogate >> 12) & 0x0F];
6462  result[++pos] = hexify[(low_surrogate >> 8) & 0x0F];
6463  result[++pos] = hexify[(low_surrogate >> 4) & 0x0F];
6464  result[++pos] = hexify[low_surrogate & 0x0F];
6465  }
6466 
6467  ++pos;
6468  }
6469 
6470  /*!
6471  @brief dump escaped string
6472 
6473  Escape a string by replacing certain special characters by a sequence of an
6474  escape character (backslash) and another character and other control
6475  characters by a sequence of "\u" followed by a four-digit hex
6476  representation. The escaped string is written to output stream @a o.
6477 
6478  @param[in] s the string to escape
6479  @param[in] ensure_ascii whether to escape non-ASCII characters with
6480  \uXXXX sequences
6481 
6482  @complexity Linear in the length of string @a s.
6483  */
6484  void dump_escaped(const string_t& s, const bool ensure_ascii) const
6485  {
6486  throw_if_invalid_utf8(s);
6487 
6488  const auto space = extra_space(s, ensure_ascii);
6489  if (space == 0)
6490  {
6491  o->write_characters(s.c_str(), s.size());
6492  return;
6493  }
6494 
6495  // create a result string of necessary size
6496  string_t result(s.size() + space, '\\');
6497  std::size_t pos = 0;
6498 
6499  for (std::size_t i = 0; i < s.size(); ++i)
6500  {
6501  switch (s[i])
6502  {
6503  case '"': // quotation mark (0x22)
6504  {
6505  result[pos + 1] = '"';
6506  pos += 2;
6507  break;
6508  }
6509 
6510  case '\\': // reverse solidus (0x5C)
6511  {
6512  // nothing to change
6513  pos += 2;
6514  break;
6515  }
6516 
6517  case '\b': // backspace (0x08)
6518  {
6519  result[pos + 1] = 'b';
6520  pos += 2;
6521  break;
6522  }
6523 
6524  case '\f': // formfeed (0x0C)
6525  {
6526  result[pos + 1] = 'f';
6527  pos += 2;
6528  break;
6529  }
6530 
6531  case '\n': // newline (0x0A)
6532  {
6533  result[pos + 1] = 'n';
6534  pos += 2;
6535  break;
6536  }
6537 
6538  case '\r': // carriage return (0x0D)
6539  {
6540  result[pos + 1] = 'r';
6541  pos += 2;
6542  break;
6543  }
6544 
6545  case '\t': // horizontal tab (0x09)
6546  {
6547  result[pos + 1] = 't';
6548  pos += 2;
6549  break;
6550  }
6551 
6552  default:
6553  {
6554  // escape control characters (0x00..0x1F) or, if
6555  // ensure_ascii parameter is used, non-ASCII characters
6556  if ((0x00 <= s[i] and s[i] <= 0x1F) or
6557  (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F)))
6558  {
6559  const auto bytes = bytes_following(static_cast<uint8_t>(s[i]));
6560  // invalid characters will be detected by throw_if_invalid_utf8
6561  assert (bytes != std::string::npos);
6562 
6563  // check that the additional bytes are present
6564  assert(i + bytes < s.size());
6565 
6566  // to use \uxxxx escaping, we first need to calculate
6567  // the codepoint from the UTF-8 bytes
6568  int codepoint = 0;
6569 
6570  // bytes is unsigned type:
6571  assert(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 */
6954 class json_pointer
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
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  }
7015  /*!
7016  @param[in] s reference token to be converted into an array index
7017 
7018  @return integer representation of @a s
7019 
7020  @throw out_of_range.404 if string @a s could not be converted to an integer
7021  */
7022  static int array_index(const std::string& s)
7023  {
7024  size_t processed_chars = 0;
7025  const int res = std::stoi(s, &processed_chars);
7026 
7027  // check if the string was completely read
7028  if (JSON_UNLIKELY(processed_chars != s.size()))
7029  {
7030  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
7031  }
7032 
7033  return res;
7034  }
7035 
7036  private:
7037  /*!
7038  @brief remove and return last reference pointer
7039  @throw out_of_range.405 if JSON pointer has no parent
7040  */
7041  std::string pop_back()
7042  {
7043  if (JSON_UNLIKELY(is_root()))
7044  {
7045  JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
7046  }
7047 
7048  auto last = reference_tokens.back();
7049  reference_tokens.pop_back();
7050  return last;
7051  }
7052 
7053  /// return whether pointer points to the root document
7054  bool is_root() const
7055  {
7056  return reference_tokens.empty();
7057  }
7058 
7059  json_pointer top() const
7060  {
7061  if (JSON_UNLIKELY(is_root()))
7062  {
7063  JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
7064  }
7065 
7066  json_pointer result = *this;
7067  result.reference_tokens = {reference_tokens[0]};
7068  return result;
7069  }
7070 
7071  /*!
7072  @brief create and return a reference to the pointed to value
7073 
7074  @complexity Linear in the number of reference tokens.
7075 
7076  @throw parse_error.109 if array index is not a number
7077  @throw type_error.313 if value cannot be unflattened
7078  */
7080  NLOHMANN_BASIC_JSON_TPL& get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const;
7081 
7082  /*!
7083  @brief return a reference to the pointed to value
7084 
7085  @note This version does not throw if a value is not present, but tries to
7086  create nested values instead. For instance, calling this function
7087  with pointer `"/this/that"` on a null value is equivalent to calling
7088  `operator[]("this").operator[]("that")` on that value, effectively
7089  changing the null value to an object.
7090 
7091  @param[in] ptr a JSON value
7092 
7093  @return reference to the JSON value pointed to by the JSON pointer
7094 
7095  @complexity Linear in the length of the JSON pointer.
7096 
7097  @throw parse_error.106 if an array index begins with '0'
7098  @throw parse_error.109 if an array index was not a number
7099  @throw out_of_range.404 if the JSON pointer can not be resolved
7100  */
7102  NLOHMANN_BASIC_JSON_TPL& get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const;
7103 
7104  /*!
7105  @throw parse_error.106 if an array index begins with '0'
7106  @throw parse_error.109 if an array index was not a number
7107  @throw out_of_range.402 if the array index '-' is used
7108  @throw out_of_range.404 if the JSON pointer can not be resolved
7109  */
7111  NLOHMANN_BASIC_JSON_TPL& get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const;
7112 
7113  /*!
7114  @brief return a const reference to the pointed to value
7115 
7116  @param[in] ptr a JSON value
7117 
7118  @return const reference to the JSON value pointed to by the JSON
7119  pointer
7120 
7121  @throw parse_error.106 if an array index begins with '0'
7122  @throw parse_error.109 if an array index was not a number
7123  @throw out_of_range.402 if the array index '-' is used
7124  @throw out_of_range.404 if the JSON pointer can not be resolved
7125  */
7127  const NLOHMANN_BASIC_JSON_TPL& get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const;
7128 
7129  /*!
7130  @throw parse_error.106 if an array index begins with '0'
7131  @throw parse_error.109 if an array index was not a number
7132  @throw out_of_range.402 if the array index '-' is used
7133  @throw out_of_range.404 if the JSON pointer can not be resolved
7134  */
7136  const NLOHMANN_BASIC_JSON_TPL& get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const;
7137 
7138  /*!
7139  @brief split the string input to reference tokens
7140 
7141  @note This function is only called by the json_pointer constructor.
7142  All exceptions below are documented there.
7143 
7144  @throw parse_error.107 if the pointer is not empty or begins with '/'
7145  @throw parse_error.108 if character '~' is not followed by '0' or '1'
7146  */
7147  static std::vector<std::string> split(const std::string& reference_string)
7148  {
7149  std::vector<std::string> result;
7150 
7151  // special case: empty reference string -> no reference tokens
7152  if (reference_string.empty())
7153  {
7154  return result;
7155  }
7156 
7157  // check if nonempty reference string begins with slash
7158  if (JSON_UNLIKELY(reference_string[0] != '/'))
7159  {
7160  JSON_THROW(detail::parse_error::create(107, 1,
7161  "JSON pointer must be empty or begin with '/' - was: '" +
7162  reference_string + "'"));
7163  }
7164 
7165  // extract the reference tokens:
7166  // - slash: position of the last read slash (or end of string)
7167  // - start: position after the previous slash
7168  for (
7169  // search for the first slash after the first character
7170  std::size_t slash = reference_string.find_first_of('/', 1),
7171  // set the beginning of the first reference token
7172  start = 1;
7173  // we can stop if start == string::npos+1 = 0
7174  start != 0;
7175  // set the beginning of the next reference token
7176  // (will eventually be 0 if slash == std::string::npos)
7177  start = slash + 1,
7178  // find next slash
7179  slash = reference_string.find_first_of('/', start))
7180  {
7181  // use the text between the beginning of the reference token
7182  // (start) and the last slash (slash).
7183  auto reference_token = reference_string.substr(start, slash - start);
7184 
7185  // check reference tokens are properly escaped
7186  for (std::size_t pos = reference_token.find_first_of('~');
7187  pos != std::string::npos;
7188  pos = reference_token.find_first_of('~', pos + 1))
7189  {
7190  assert(reference_token[pos] == '~');
7191 
7192  // ~ must be followed by 0 or 1
7193  if (JSON_UNLIKELY(pos == reference_token.size() - 1 or
7194  (reference_token[pos + 1] != '0' and
7195  reference_token[pos + 1] != '1')))
7196  {
7197  JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
7198  }
7199  }
7200 
7201  // finally, store the reference token
7202  unescape(reference_token);
7203  result.push_back(reference_token);
7204  }
7205 
7206  return result;
7207  }
7208 
7209  /*!
7210  @brief replace all occurrences of a substring by another string
7211 
7212  @param[in,out] s the string to manipulate; changed so that all
7213  occurrences of @a f are replaced with @a t
7214  @param[in] f the substring to replace with @a t
7215  @param[in] t the string to replace @a f
7216 
7217  @pre The search string @a f must not be empty. **This precondition is
7218  enforced with an assertion.**
7219 
7220  @since version 2.0.0
7221  */
7222  static void replace_substring(std::string& s, const std::string& f,
7223  const std::string& t)
7224  {
7225  assert(not f.empty());
7226  for (auto pos = s.find(f); // find first occurrence of f
7227  pos != std::string::npos; // make sure f was found
7228  s.replace(pos, f.size(), t), // replace with t, and
7229  pos = s.find(f, pos + t.size())) // find next occurrence of f
7230  {}
7231  }
7232 
7233  /// escape "~"" to "~0" and "/" to "~1"
7234  static std::string escape(std::string s)
7235  {
7236  replace_substring(s, "~", "~0");
7237  replace_substring(s, "/", "~1");
7238  return s;
7239  }
7240 
7241  /// unescape "~1" to tilde and "~0" to slash (order is important!)
7242  static void unescape(std::string& s)
7243  {
7244  replace_substring(s, "~1", "/");
7245  replace_substring(s, "~0", "~");
7246  }
7247 
7248  /*!
7249  @param[in] reference_string the reference string to the current value
7250  @param[in] value the value to consider
7251  @param[in,out] result the result object to insert values to
7252 
7253  @note Empty objects or arrays are flattened to `null`.
7254  */
7256  static void flatten(const std::string& reference_string,
7257  const NLOHMANN_BASIC_JSON_TPL& value,
7258  NLOHMANN_BASIC_JSON_TPL& result);
7259 
7260  /*!
7261  @param[in] value flattened JSON
7262 
7263  @return unflattened JSON
7264 
7265  @throw parse_error.109 if array index is not a number
7266  @throw type_error.314 if value is not an object
7267  @throw type_error.315 if object values are not primitive
7268  @throw type_error.313 if value cannot be unflattened
7269  */
7272  unflatten(const NLOHMANN_BASIC_JSON_TPL& value);
7273 
7274  friend bool operator==(json_pointer const& lhs,
7275  json_pointer const& rhs) noexcept;
7276 
7277  friend bool operator!=(json_pointer const& lhs,
7278  json_pointer const& rhs) noexcept;
7279 
7280  /// the reference tokens
7281  std::vector<std::string> reference_tokens;
7282 };
7283 
7284 /*!
7285 @brief a class to store JSON values
7286 
7287 @tparam ObjectType type for JSON objects (`std::map` by default; will be used
7288 in @ref object_t)
7289 @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
7290 in @ref array_t)
7291 @tparam StringType type for JSON strings and object keys (`std::string` by
7292 default; will be used in @ref string_t)
7293 @tparam BooleanType type for JSON booleans (`bool` by default; will be used
7294 in @ref boolean_t)
7295 @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
7296 default; will be used in @ref number_integer_t)
7297 @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
7298 `uint64_t` by default; will be used in @ref number_unsigned_t)
7299 @tparam NumberFloatType type for JSON floating-point numbers (`double` by
7300 default; will be used in @ref number_float_t)
7301 @tparam AllocatorType type of the allocator to use (`std::allocator` by
7302 default)
7303 @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
7304 and `from_json()` (@ref adl_serializer by default)
7305 
7306 @requirement The class satisfies the following concept requirements:
7307 - Basic
7308  - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
7309  JSON values can be default constructed. The result will be a JSON null
7310  value.
7311  - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
7312  A JSON value can be constructed from an rvalue argument.
7313  - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
7314  A JSON value can be copy-constructed from an lvalue expression.
7315  - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
7316  A JSON value van be assigned from an rvalue argument.
7317  - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
7318  A JSON value can be copy-assigned from an lvalue expression.
7319  - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
7320  JSON values can be destructed.
7321 - Layout
7322  - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
7323  JSON values have
7324  [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
7325  All non-static data members are private and standard layout types, the
7326  class has no virtual functions or (virtual) base classes.
7327 - Library-wide
7328  - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
7329  JSON values can be compared with `==`, see @ref
7330  operator==(const_reference,const_reference).
7331  - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
7332  JSON values can be compared with `<`, see @ref
7333  operator<(const_reference,const_reference).
7334  - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
7335  Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
7336  other compatible types, using unqualified function call @ref swap().
7337  - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
7338  JSON values can be compared against `std::nullptr_t` objects which are used
7339  to model the `null` value.
7340 - Container
7341  - [Container](http://en.cppreference.com/w/cpp/concept/Container):
7342  JSON values can be used like STL containers and provide iterator access.
7343  - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
7344  JSON values can be used like STL containers and provide reverse iterator
7345  access.
7346 
7347 @invariant The member variables @a m_value and @a m_type have the following
7348 relationship:
7349 - If `m_type == value_t::object`, then `m_value.object != nullptr`.
7350 - If `m_type == value_t::array`, then `m_value.array != nullptr`.
7351 - If `m_type == value_t::string`, then `m_value.string != nullptr`.
7352 The invariants are checked by member function assert_invariant().
7353 
7354 @internal
7355 @note ObjectType trick from http://stackoverflow.com/a/9860911
7356 @endinternal
7357 
7358 @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
7359 Format](http://rfc7159.net/rfc7159)
7360 
7361 @since version 1.0.0
7362 
7363 @nosubgrouping
7364 */
7366 class basic_json
7367 {
7368  private:
7369  template<detail::value_t> friend struct detail::external_constructor;
7370  friend ::nlohmann::json_pointer;
7371  friend ::nlohmann::detail::parser<basic_json>;
7372  friend ::nlohmann::detail::serializer<basic_json>;
7373  template<typename BasicJsonType>
7374  friend class ::nlohmann::detail::iter_impl;
7375  template<typename BasicJsonType, typename CharType>
7376  friend class ::nlohmann::detail::binary_writer;
7377  template<typename BasicJsonType>
7378  friend class ::nlohmann::detail::binary_reader;
7379 
7380  /// workaround type for MSVC
7381  using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
7382 
7383  // convenience aliases for types residing in namespace detail;
7384  using lexer = ::nlohmann::detail::lexer<basic_json>;
7385  using parser = ::nlohmann::detail::parser<basic_json>;
7386 
7387  using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
7388  template<typename BasicJsonType>
7389  using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
7390  template<typename BasicJsonType>
7391  using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
7392  template<typename Iterator>
7393  using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
7394  template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
7395 
7396  template<typename CharType>
7397  using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
7398 
7399  using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
7400  template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
7401 
7402  using serializer = ::nlohmann::detail::serializer<basic_json>;
7403 
7404  public:
7405  using value_t = detail::value_t;
7406  /// @copydoc nlohmann::json_pointer
7407  using json_pointer = ::nlohmann::json_pointer;
7408  template<typename T, typename SFINAE>
7409  using json_serializer = JSONSerializer<T, SFINAE>;
7410  /// helper type for initializer lists of basic_json values
7411  using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
7412 
7413  ////////////////
7414  // exceptions //
7415  ////////////////
7416 
7417  /// @name exceptions
7418  /// Classes to implement user-defined exceptions.
7419  /// @{
7420 
7421  /// @copydoc detail::exception
7422  using exception = detail::exception;
7423  /// @copydoc detail::parse_error
7424  using parse_error = detail::parse_error;
7425  /// @copydoc detail::invalid_iterator
7426  using invalid_iterator = detail::invalid_iterator;
7427  /// @copydoc detail::type_error
7428  using type_error = detail::type_error;
7429  /// @copydoc detail::out_of_range
7430  using out_of_range = detail::out_of_range;
7431  /// @copydoc detail::other_error
7432  using other_error = detail::other_error;
7433 
7434  /// @}
7435 
7436 
7437  /////////////////////
7438  // container types //
7439  /////////////////////
7440 
7441  /// @name container types
7442  /// The canonic container types to use @ref basic_json like any other STL
7443  /// container.
7444  /// @{
7445 
7446  /// the type of elements in a basic_json container
7447  using value_type = basic_json;
7448 
7449  /// the type of an element reference
7450  using reference = value_type&;
7451  /// the type of an element const reference
7452  using const_reference = const value_type&;
7454  /// a type to represent differences between iterators
7455  using difference_type = std::ptrdiff_t;
7456  /// a type to represent container sizes
7457  using size_type = std::size_t;
7458 
7459  /// the allocator type
7460  using allocator_type = AllocatorType<basic_json>;
7461 
7462  /// the type of an element pointer
7463  using pointer = typename std::allocator_traits<allocator_type>::pointer;
7464  /// the type of an element const pointer
7465  using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
7467  /// an iterator for a basic_json container
7468  using iterator = iter_impl<basic_json>;
7469  /// a const iterator for a basic_json container
7470  using const_iterator = iter_impl<const basic_json>;
7471  /// a reverse iterator for a basic_json container
7472  using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
7473  /// a const reverse iterator for a basic_json container
7474  using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
7475 
7476  /// @}
7477 
7478 
7479  /*!
7480  @brief returns the allocator associated with the container
7481  */
7482  static allocator_type get_allocator()
7483  {
7484  return allocator_type();
7485  }
7486 
7487  /*!
7488  @brief returns version information on the library
7489 
7490  This function returns a JSON object with information about the library,
7491  including the version number and information on the platform and compiler.
7492 
7493  @return JSON object holding version information
7494  key | description
7495  ----------- | ---------------
7496  `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).
7497  `copyright` | The copyright line for the library as string.
7498  `name` | The name of the library as string.
7499  `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
7500  `url` | The URL of the project as string.
7501  `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).
7502 
7503  @liveexample{The following code shows an example output of the `meta()`
7504  function.,meta}
7505 
7506  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
7507  changes to any JSON value.
7508 
7509  @complexity Constant.
7510 
7511  @since 2.1.0
7512  */
7513  static basic_json meta()
7514  {
7515  basic_json result;
7517  result["copyright"] = "(C) 2013-2017 Niels Lohmann";
7518  result["name"] = "JSON for Modern C++";
7519  result["url"] = "https://github.com/nlohmann/json";
7520  result["version"] =
7521  {
7522  {"string", "3.0.1"}, {"major", 3}, {"minor", 0}, {"patch", 1}
7523  };
7524 
7525 #ifdef _WIN32
7526  result["platform"] = "win32";
7527 #elif defined __linux__
7528  result["platform"] = "linux";
7529 #elif defined __APPLE__
7530  result["platform"] = "apple";
7531 #elif defined __unix__
7532  result["platform"] = "unix";
7533 #else
7534  result["platform"] = "unknown";
7535 #endif
7536 
7537 #if defined(__ICC) || defined(__INTEL_COMPILER)
7538  result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
7539 #elif defined(__clang__)
7540  result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
7541 #elif defined(__GNUC__) || defined(__GNUG__)
7542  result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
7543 #elif defined(__HP_cc) || defined(__HP_aCC)
7544  result["compiler"] = "hp"
7545 #elif defined(__IBMCPP__)
7546  result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
7547 #elif defined(_MSC_VER)
7548  result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
7549 #elif defined(__PGI)
7550  result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
7551 #elif defined(__SUNPRO_CC)
7552  result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
7553 #else
7554  result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
7555 #endif
7556 
7557 #ifdef __cplusplus
7558  result["compiler"]["c++"] = std::to_string(__cplusplus);
7559 #else
7560  result["compiler"]["c++"] = "unknown";
7561 #endif
7562  return result;
7563  }
7564 
7565 
7566  ///////////////////////////
7567  // JSON value data types //
7568  ///////////////////////////
7569 
7570  /// @name JSON value data types
7571  /// The data types to store a JSON value. These types are derived from
7572  /// the template arguments passed to class @ref basic_json.
7573  /// @{
7574 
7575 #if defined(JSON_HAS_CPP_14)
7576  // Use transparent comparator if possible, combined with perfect forwarding
7577  // on find() and count() calls prevents unnecessary string construction.
7578  using object_comparator_t = std::less<>;
7579 #else
7580  using object_comparator_t = std::less<StringType>;
7581 #endif
7582 
7583  /*!
7584  @brief a type for an object
7585 
7586  [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
7587  > An object is an unordered collection of zero or more name/value pairs,
7588  > where a name is a string and a value is a string, number, boolean, null,
7589  > object, or array.
7590 
7591  To store objects in C++, a type is defined by the template parameters
7592  described below.
7593 
7594  @tparam ObjectType the container to store objects (e.g., `std::map` or
7595  `std::unordered_map`)
7596  @tparam StringType the type of the keys or names (e.g., `std::string`).
7597  The comparison function `std::less<StringType>` is used to order elements
7598  inside the container.
7599  @tparam AllocatorType the allocator to use for objects (e.g.,
7600  `std::allocator`)
7601 
7602  #### Default type
7603 
7604  With the default values for @a ObjectType (`std::map`), @a StringType
7605  (`std::string`), and @a AllocatorType (`std::allocator`), the default
7606  value for @a object_t is:
7607 
7608  @code {.cpp}
7609  std::map<
7610  std::string, // key_type
7611  basic_json, // value_type
7612  std::less<std::string>, // key_compare
7613  std::allocator<std::pair<const std::string, basic_json>> // allocator_type
7614  >
7615  @endcode
7616 
7617  #### Behavior
7618 
7619  The choice of @a object_t influences the behavior of the JSON class. With
7620  the default type, objects have the following behavior:
7621 
7622  - When all names are unique, objects will be interoperable in the sense
7623  that all software implementations receiving that object will agree on
7624  the name-value mappings.
7625  - When the names within an object are not unique, later stored name/value
7626  pairs overwrite previously stored name/value pairs, leaving the used
7627  names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will
7628  be treated as equal and both stored as `{"key": 1}`.
7629  - Internally, name/value pairs are stored in lexicographical order of the
7630  names. Objects will also be serialized (see @ref dump) in this order.
7631  For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
7632  and serialized as `{"a": 2, "b": 1}`.
7633  - When comparing objects, the order of the name/value pairs is irrelevant.
7634  This makes objects interoperable in the sense that they will not be
7635  affected by these differences. For instance, `{"b": 1, "a": 2}` and
7636  `{"a": 2, "b": 1}` will be treated as equal.
7637 
7638  #### Limits
7639 
7640  [RFC 7159](http://rfc7159.net/rfc7159) specifies:
7641  > An implementation may set limits on the maximum depth of nesting.
7642 
7643  In this class, the object's limit of nesting is not explicitly constrained.
7644  However, a maximum depth of nesting may be introduced by the compiler or
7645  runtime environment. A theoretical limit can be queried by calling the
7646  @ref max_size function of a JSON object.
7647 
7648  #### Storage
7649 
7650  Objects are stored as pointers in a @ref basic_json type. That is, for any
7651  access to object values, a pointer of type `object_t*` must be
7652  dereferenced.
7653 
7654  @sa @ref array_t -- type for an array value
7655 
7656  @since version 1.0.0
7657 
7658  @note The order name/value pairs are added to the object is *not*
7659  preserved by the library. Therefore, iterating an object may return
7660  name/value pairs in a different order than they were originally stored. In
7661  fact, keys will be traversed in alphabetical order as `std::map` with
7662  `std::less` is used by default. Please note this behavior conforms to [RFC
7663  7159](http://rfc7159.net/rfc7159), because any order implements the
7664  specified "unordered" nature of JSON objects.
7665  */
7666  using object_t = ObjectType<StringType,
7667  basic_json,
7668  object_comparator_t,
7669  AllocatorType<std::pair<const StringType,
7670  basic_json>>>;
7671 
7672  /*!
7673  @brief a type for an array
7674 
7675  [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
7676  > An array is an ordered sequence of zero or more values.
7677 
7678  To store objects in C++, a type is defined by the template parameters
7679  explained below.
7680 
7681  @tparam ArrayType container type to store arrays (e.g., `std::vector` or
7682  `std::list`)
7683  @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
7684 
7685  #### Default type
7686 
7687  With the default values for @a ArrayType (`std::vector`) and @a
7688  AllocatorType (`std::allocator`), the default value for @a array_t is:
7689 
7690  @code {.cpp}
7691  std::vector<
7692  basic_json, // value_type
7693  std::allocator<basic_json> // allocator_type
7694  >
7695  @endcode
7696 
7697  #### Limits
7698 
7699  [RFC 7159](http://rfc7159.net/rfc7159) specifies:
7700  > An implementation may set limits on the maximum depth of nesting.
7701 
7702  In this class, the array's limit of nesting is not explicitly constrained.
7703  However, a maximum depth of nesting may be introduced by the compiler or
7704  runtime environment. A theoretical limit can be queried by calling the
7705  @ref max_size function of a JSON array.
7706 
7707  #### Storage
7708 
7709  Arrays are stored as pointers in a @ref basic_json type. That is, for any
7710  access to array values, a pointer of type `array_t*` must be dereferenced.
7711 
7712  @sa @ref object_t -- type for an object value
7713 
7714  @since version 1.0.0
7715  */
7716  using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
7717 
7718  /*!
7719  @brief a type for a string
7721  [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
7722  > A string is a sequence of zero or more Unicode characters.
7723 
7724  To store objects in C++, a type is defined by the template parameter
7725  described below. Unicode values are split by the JSON class into
7726  byte-sized characters during deserialization.
7727 
7728  @tparam StringType the container to store strings (e.g., `std::string`).
7729  Note this container is used for keys/names in objects, see @ref object_t.
7730 
7731  #### Default type
7732 
7733  With the default values for @a StringType (`std::string`), the default
7734  value for @a string_t is:
7735 
7736  @code {.cpp}
7737  std::string
7738  @endcode
7739 
7740  #### Encoding
7741 
7742  Strings are stored in UTF-8 encoding. Therefore, functions like
7743  `std::string::size()` or `std::string::length()` return the number of
7744  bytes in the string rather than the number of characters or glyphs.
7745 
7746  #### String comparison
7747 
7748  [RFC 7159](http://rfc7159.net/rfc7159) states:
7749  > Software implementations are typically required to test names of object
7750  > members for equality. Implementations that transform the textual
7751  > representation into sequences of Unicode code units and then perform the
7752  > comparison numerically, code unit by code unit, are interoperable in the
7753  > sense that implementations will agree in all cases on equality or
7754  > inequality of two strings. For example, implementations that compare
7755  > strings with escaped characters unconverted may incorrectly find that
7756  > `"a\\b"` and `"a\u005Cb"` are not equal.
7757 
7758  This implementation is interoperable as it does compare strings code unit
7759  by code unit.
7760 
7761  #### Storage
7762 
7763  String values are stored as pointers in a @ref basic_json type. That is,
7764  for any access to string values, a pointer of type `string_t*` must be
7765  dereferenced.
7767  @since version 1.0.0
7768  */
7769  using string_t = StringType;
7770 
7771  /*!
7772  @brief a type for a boolean
7773 
7774  [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
7775  type which differentiates the two literals `true` and `false`.
7776 
7777  To store objects in C++, a type is defined by the template parameter @a
7778  BooleanType which chooses the type to use.
7779 
7780  #### Default type
7781 
7782  With the default values for @a BooleanType (`bool`), the default value for
7783  @a boolean_t is:
7784 
7785  @code {.cpp}
7786  bool
7787  @endcode
7788 
7789  #### Storage
7790 
7791  Boolean values are stored directly inside a @ref basic_json type.
7792 
7793  @since version 1.0.0
7794  */
7795  using boolean_t = BooleanType;
7796 
7797  /*!
7798  @brief a type for a number (integer)
7799 
7800  [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
7801  > The representation of numbers is similar to that used in most
7802  > programming languages. A number is represented in base 10 using decimal
7803  > digits. It contains an integer component that may be prefixed with an
7804  > optional minus sign, which may be followed by a fraction part and/or an
7805  > exponent part. Leading zeros are not allowed. (...) Numeric values that
7806  > cannot be represented in the grammar below (such as Infinity and NaN)
7807  > are not permitted.
7808 
7809  This description includes both integer and floating-point numbers.
7810  However, C++ allows more precise storage if it is known whether the number
7811  is a signed integer, an unsigned integer or a floating-point number.
7812  Therefore, three different types, @ref number_integer_t, @ref
7813  number_unsigned_t and @ref number_float_t are used.
7814 
7815  To store integer numbers in C++, a type is defined by the template
7816  parameter @a NumberIntegerType which chooses the type to use.
7817 
7818  #### Default type
7820  With the default values for @a NumberIntegerType (`int64_t`), the default
7821  value for @a number_integer_t is:
7822 
7823  @code {.cpp}
7824  int64_t
7825  @endcode
7826 
7827  #### Default behavior
7828 
7829  - The restrictions about leading zeros is not enforced in C++. Instead,
7830  leading zeros in integer literals lead to an interpretation as octal
7831  number. Internally, the value will be stored as decimal number. For
7832  instance, the C++ integer literal `010` will be serialized to `8`.
7833  During deserialization, leading zeros yield an error.
7834  - Not-a-number (NaN) values will be serialized to `null`.
7835 
7836  #### Limits
7837 
7838  [RFC 7159](http://rfc7159.net/rfc7159) specifies:
7839  > An implementation may set limits on the range and precision of numbers.
7840 
7841  When the default type is used, the maximal integer number that can be
7842  stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
7843  that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
7844  that are out of range will yield over/underflow when used in a
7845  constructor. During deserialization, too large or small integer numbers
7846  will be automatically be stored as @ref number_unsigned_t or @ref
7847  number_float_t.
7848 
7849  [RFC 7159](http://rfc7159.net/rfc7159) further states:
7850  > Note that when such software is used, numbers that are integers and are
7851  > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
7852  > that implementations will agree exactly on their numeric values.
7853 
7854  As this range is a subrange of the exactly supported range [INT64_MIN,
7855  INT64_MAX], this class's integer type is interoperable.
7856 
7857  #### Storage
7858 
7859  Integer number values are stored directly inside a @ref basic_json type.
7860 
7861  @sa @ref number_float_t -- type for number values (floating-point)
7862 
7863  @sa @ref number_unsigned_t -- type for number values (unsigned integer)
7864 
7865  @since version 1.0.0
7866  */
7867  using number_integer_t = NumberIntegerType;
7868 
7869  /*!
7870  @brief a type for a number (unsigned)
7871 
7872  [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
7873  > The representation of numbers is similar to that used in most
7874  > programming languages. A number is represented in base 10 using decimal
7875  > digits. It contains an integer component that may be prefixed with an
7876  > optional minus sign, which may be followed by a fraction part and/or an
7877  > exponent part. Leading zeros are not allowed. (...) Numeric values that
7878  > cannot be represented in the grammar below (such as Infinity and NaN)
7879  > are not permitted.
7880 
7881  This description includes both integer and floating-point numbers.
7882  However, C++ allows more precise storage if it is known whether the number
7883  is a signed integer, an unsigned integer or a floating-point number.
7884  Therefore, three different types, @ref number_integer_t, @ref
7885  number_unsigned_t and @ref number_float_t are used.
7886 
7887  To store unsigned integer numbers in C++, a type is defined by the
7888  template parameter @a NumberUnsignedType which chooses the type to use.
7889 
7890  #### Default type
7891 
7892  With the default values for @a NumberUnsignedType (`uint64_t`), the
7893  default value for @a number_unsigned_t is:
7894 
7895  @code {.cpp}
7896  uint64_t
7897  @endcode
7898 
7899  #### Default behavior
7900 
7901  - The restrictions about leading zeros is not enforced in C++. Instead,
7902  leading zeros in integer literals lead to an interpretation as octal
7903  number. Internally, the value will be stored as decimal number. For
7904  instance, the C++ integer literal `010` will be serialized to `8`.
7905  During deserialization, leading zeros yield an error.
7906  - Not-a-number (NaN) values will be serialized to `null`.
7907 
7908  #### Limits
7909 
7910  [RFC 7159](http://rfc7159.net/rfc7159) specifies:
7911  > An implementation may set limits on the range and precision of numbers.
7912 
7913  When the default type is used, the maximal integer number that can be
7914  stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
7915  number that can be stored is `0`. Integer numbers that are out of range
7916  will yield over/underflow when used in a constructor. During
7917  deserialization, too large or small integer numbers will be automatically
7918  be stored as @ref number_integer_t or @ref number_float_t.
7919 
7920  [RFC 7159](http://rfc7159.net/rfc7159) further states:
7921  > Note that when such software is used, numbers that are integers and are
7922  > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
7923  > that implementations will agree exactly on their numeric values.
7924 
7925  As this range is a subrange (when considered in conjunction with the
7926  number_integer_t type) of the exactly supported range [0, UINT64_MAX],
7927  this class's integer type is interoperable.
7928 
7929  #### Storage
7930 
7931  Integer number values are stored directly inside a @ref basic_json type.
7932 
7933  @sa @ref number_float_t -- type for number values (floating-point)
7934  @sa @ref number_integer_t -- type for number values (integer)
7935 
7936  @since version 2.0.0
7937  */
7938  using number_unsigned_t = NumberUnsignedType;
7939 
7940  /*!
7941  @brief a type for a number (floating-point)
7942 
7943  [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
7944  > The representation of numbers is similar to that used in most
7945  > programming languages. A number is represented in base 10 using decimal
7946  > digits. It contains an integer component that may be prefixed with an
7947  > optional minus sign, which may be followed by a fraction part and/or an
7948  > exponent part. Leading zeros are not allowed. (...) Numeric values that
7949  > cannot be represented in the grammar below (such as Infinity and NaN)
7950  > are not permitted.
7951 
7952  This description includes both integer and floating-point numbers.
7953  However, C++ allows more precise storage if it is known whether the number
7954  is a signed integer, an unsigned integer or a floating-point number.
7955  Therefore, three different types, @ref number_integer_t, @ref
7956  number_unsigned_t and @ref number_float_t are used.
7957 
7958  To store floating-point numbers in C++, a type is defined by the template
7959  parameter @a NumberFloatType which chooses the type to use.
7960 
7961  #### Default type
7962 
7963  With the default values for @a NumberFloatType (`double`), the default
7964  value for @a number_float_t is:
7965 
7966  @code {.cpp}
7967  double
7968  @endcode
7969 
7970  #### Default behavior
7971 
7972  - The restrictions about leading zeros is not enforced in C++. Instead,
7973  leading zeros in floating-point literals will be ignored. Internally,
7974  the value will be stored as decimal number. For instance, the C++
7975  floating-point literal `01.2` will be serialized to `1.2`. During
7976  deserialization, leading zeros yield an error.
7977  - Not-a-number (NaN) values will be serialized to `null`.
7978 
7979  #### Limits
7980 
7981  [RFC 7159](http://rfc7159.net/rfc7159) states:
7982  > This specification allows implementations to set limits on the range and
7983  > precision of numbers accepted. Since software that implements IEEE
7984  > 754-2008 binary64 (double precision) numbers is generally available and
7985  > widely used, good interoperability can be achieved by implementations
7986  > that expect no more precision or range than these provide, in the sense
7987  > that implementations will approximate JSON numbers within the expected
7988  > precision.
7989 
7990  This implementation does exactly follow this approach, as it uses double
7991  precision floating-point numbers. Note values smaller than
7992  `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
7993  will be stored as NaN internally and be serialized to `null`.
7994 
7995  #### Storage
7996 
7997  Floating-point number values are stored directly inside a @ref basic_json
7998  type.
7999 
8000  @sa @ref number_integer_t -- type for number values (integer)
8001 
8002  @sa @ref number_unsigned_t -- type for number values (unsigned integer)
8003 
8004  @since version 1.0.0
8005  */
8006  using number_float_t = NumberFloatType;
8007 
8008  /// @}
8009 
8010  private:
8011 
8012  /// helper for exception-safe object creation
8013  template<typename T, typename... Args>
8014  static T* create(Args&& ... args)
8015  {
8016  AllocatorType<T> alloc;
8017  using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
8018 
8019  auto deleter = [&](T * object)
8020  {
8021  AllocatorTraits::deallocate(alloc, object, 1);
8022  };
8023  std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
8024  AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
8025  assert(object != nullptr);
8026  return object.release();
8027  }
8028 
8029  ////////////////////////
8030  // JSON value storage //
8031  ////////////////////////
8032 
8033  /*!
8034  @brief a JSON value
8035 
8036  The actual storage for a JSON value of the @ref basic_json class. This
8037  union combines the different storage types for the JSON value types
8038  defined in @ref value_t.
8039 
8040  JSON type | value_t type | used type
8041  --------- | --------------- | ------------------------
8042  object | object | pointer to @ref object_t
8043  array | array | pointer to @ref array_t
8044  string | string | pointer to @ref string_t
8045  boolean | boolean | @ref boolean_t
8046  number | number_integer | @ref number_integer_t
8047  number | number_unsigned | @ref number_unsigned_t
8048  number | number_float | @ref number_float_t
8049  null | null | *no value is stored*
8050 
8051  @note Variable-length types (objects, arrays, and strings) are stored as
8052  pointers. The size of the union should not exceed 64 bits if the default
8053  value types are used.
8054 
8055  @since version 1.0.0
8056  */
8057  union json_value
8058  {
8059  /// object (stored with pointer to save storage)
8060  object_t* object;
8061  /// array (stored with pointer to save storage)
8062  array_t* array;
8063  /// string (stored with pointer to save storage)
8064  string_t* string;
8065  /// boolean
8066  boolean_t boolean;
8067  /// number (integer)
8068  number_integer_t number_integer;
8069  /// number (unsigned integer)
8070  number_unsigned_t number_unsigned;
8071  /// number (floating-point)
8072  number_float_t number_float;
8073 
8074  /// default constructor (for null values)
8075  json_value() = default;
8076  /// constructor for booleans
8077  json_value(boolean_t v) noexcept : boolean(v) {}
8078  /// constructor for numbers (integer)
8079  json_value(number_integer_t v) noexcept : number_integer(v) {}
8080  /// constructor for numbers (unsigned)
8081  json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
8082  /// constructor for numbers (floating-point)
8083  json_value(number_float_t v) noexcept : number_float(v) {}
8084  /// constructor for empty values of a given type
8085  json_value(value_t t)
8086  {
8087  switch (t)
8088  {
8089  case value_t::object:
8090  {
8091  object = create<object_t>();
8092  break;
8093  }
8094 
8095  case value_t::array:
8096  {
8097  array = create<array_t>();
8098  break;
8099  }
8100 
8101  case value_t::string:
8102  {
8103  string = create<string_t>("");
8104  break;
8105  }
8106 
8107  case value_t::boolean:
8108  {
8109  boolean = boolean_t(false);
8110  break;
8111  }
8112 
8113  case value_t::number_integer:
8114  {
8115  number_integer = number_integer_t(0);
8116  break;
8117  }
8118 
8119  case value_t::number_unsigned:
8120  {
8121  number_unsigned = number_unsigned_t(0);
8122  break;
8123  }
8124 
8125  case value_t::number_float:
8126  {
8127  number_float = number_float_t(0.0);
8128  break;
8129  }
8130 
8131  case value_t::null:
8132  {
8133  object = nullptr; // silence warning, see #821
8134  break;
8135  }
8136 
8137  default:
8138  {
8139  object = nullptr; // silence warning, see #821
8140  if (JSON_UNLIKELY(t == value_t::null))
8141  {
8142  JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.0.1")); // LCOV_EXCL_LINE
8143  }
8144  break;
8145  }
8146  }
8147  }
8148 
8149  /// constructor for strings
8150  json_value(const string_t& value)
8151  {
8152  string = create<string_t>(value);
8153  }
8154 
8155  /// constructor for rvalue strings
8156  json_value(string_t&& value)
8157  {
8158  string = create<string_t>(std::move(value));
8159  }
8160 
8161  /// constructor for objects
8162  json_value(const object_t& value)
8163  {
8164  object = create<object_t>(value);
8165  }
8166 
8167  /// constructor for rvalue objects
8168  json_value(object_t&& value)
8169  {
8170  object = create<object_t>(std::move(value));
8171  }
8172 
8173  /// constructor for arrays
8174  json_value(const array_t& value)
8175  {
8176  array = create<array_t>(value);
8177  }
8178 
8179  /// constructor for rvalue arrays
8180  json_value(array_t&& value)
8181  {
8182  array = create<array_t>(std::move(value));
8183  }
8184 
8185  void destroy(value_t t)
8186  {
8187  switch (t)
8188  {
8189  case value_t::object:
8190  {
8191  AllocatorType<object_t> alloc;
8192  std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
8193  std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
8194  break;
8195  }
8196 
8197  case value_t::array:
8198  {
8199  AllocatorType<array_t> alloc;
8200  std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
8201  std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
8202  break;
8203  }
8204 
8205  case value_t::string:
8206  {
8207  AllocatorType<string_t> alloc;
8208  std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
8209  std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
8210  break;
8211  }
8212 
8213  default:
8214  {
8215  break;
8216  }
8217  }
8218  }
8219  };
8220 
8221  /*!
8222  @brief checks the class invariants
8223 
8224  This function asserts the class invariants. It needs to be called at the
8225  end of every constructor to make sure that created objects respect the
8226  invariant. Furthermore, it has to be called each time the type of a JSON
8227  value is changed, because the invariant expresses a relationship between
8228  @a m_type and @a m_value.
8229  */
8230  void assert_invariant() const
8231  {
8232  assert(m_type != value_t::object or m_value.object != nullptr);
8233  assert(m_type != value_t::array or m_value.array != nullptr);
8234  assert(m_type != value_t::string or m_value.string != nullptr);
8235  }
8236 
8237  public:
8238  //////////////////////////
8239  // JSON parser callback //
8240  //////////////////////////
8241 
8242  /*!
8243  @brief parser event types
8244 
8245  The parser callback distinguishes the following events:
8246  - `object_start`: the parser read `{` and started to process a JSON object
8247  - `key`: the parser read a key of a value in an object
8248  - `object_end`: the parser read `}` and finished processing a JSON object
8249  - `array_start`: the parser read `[` and started to process a JSON array
8250  - `array_end`: the parser read `]` and finished processing a JSON array
8251  - `value`: the parser finished reading a JSON value
8252 
8253  @image html callback_events.png "Example when certain parse events are triggered"
8254 
8255  @sa @ref parser_callback_t for more information and examples
8256  */
8257  using parse_event_t = typename parser::parse_event_t;
8258 
8259  /*!
8260  @brief per-element parser callback type
8261 
8262  With a parser callback function, the result of parsing a JSON text can be
8263  influenced. When passed to @ref parse, it is called on certain events
8264  (passed as @ref parse_event_t via parameter @a event) with a set recursion
8265  depth @a depth and context JSON value @a parsed. The return value of the
8266  callback function is a boolean indicating whether the element that emitted
8267  the callback shall be kept or not.
8268 
8269  We distinguish six scenarios (determined by the event type) in which the
8270  callback function can be called. The following table describes the values
8271  of the parameters @a depth, @a event, and @a parsed.
8272 
8273  parameter @a event | description | parameter @a depth | parameter @a parsed
8274  ------------------ | ----------- | ------------------ | -------------------
8275  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
8276  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
8277  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
8278  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
8279  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
8280  parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
8281 
8282  @image html callback_events.png "Example when certain parse events are triggered"
8283 
8284  Discarding a value (i.e., returning `false`) has different effects
8285  depending on the context in which function was called:
8286 
8287  - Discarded values in structured types are skipped. That is, the parser
8288  will behave as if the discarded value was never read.
8289  - In case a value outside a structured type is skipped, it is replaced
8290  with `null`. This case happens if the top-level element is skipped.
8291 
8292  @param[in] depth the depth of the recursion during parsing
8293 
8294  @param[in] event an event of type parse_event_t indicating the context in
8295  the callback function has been called
8296 
8297  @param[in,out] parsed the current intermediate parse result; note that
8298  writing to this value has no effect for parse_event_t::key events
8299 
8300  @return Whether the JSON value which called the function during parsing
8301  should be kept (`true`) or not (`false`). In the latter case, it is either
8302  skipped completely or replaced by an empty discarded object.
8303 
8304  @sa @ref parse for examples
8305 
8306  @since version 1.0.0
8307  */
8308  using parser_callback_t = typename parser::parser_callback_t;
8309 
8310 
8311  //////////////////
8312  // constructors //
8313  //////////////////
8314 
8315  /// @name constructors and destructors
8316  /// Constructors of class @ref basic_json, copy/move constructor, copy
8317  /// assignment, static functions creating objects, and the destructor.
8318  /// @{
8319 
8320  /*!
8321  @brief create an empty value with a given type
8322 
8323  Create an empty JSON value with a given type. The value will be default
8324  initialized with an empty value which depends on the type:
8325 
8326  Value type | initial value
8327  ----------- | -------------
8328  null | `null`
8329  boolean | `false`
8330  string | `""`
8331  number | `0`
8332  object | `{}`
8333  array | `[]`
8334 
8335  @param[in] v the type of the value to create
8336 
8337  @complexity Constant.
8338 
8339  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8340  changes to any JSON value.
8341 
8342  @liveexample{The following code shows the constructor for different @ref
8343  value_t values,basic_json__value_t}
8344 
8345  @sa @ref clear() -- restores the postcondition of this constructor
8346 
8347  @since version 1.0.0
8348  */
8349  basic_json(const value_t v)
8350  : m_type(v), m_value(v)
8351  {
8352  assert_invariant();
8353  }
8354 
8355  /*!
8356  @brief create a null object
8357 
8358  Create a `null` JSON value. It either takes a null pointer as parameter
8359  (explicitly creating `null`) or no parameter (implicitly creating `null`).
8360  The passed null pointer itself is not read -- it is only used to choose
8361  the right constructor.
8362 
8363  @complexity Constant.
8364 
8365  @exceptionsafety No-throw guarantee: this constructor never throws
8366  exceptions.
8367 
8368  @liveexample{The following code shows the constructor with and without a
8369  null pointer parameter.,basic_json__nullptr_t}
8370 
8371  @since version 1.0.0
8372  */
8373  basic_json(std::nullptr_t = nullptr) noexcept
8374  : basic_json(value_t::null)
8375  {
8376  assert_invariant();
8377  }
8378 
8379  /*!
8380  @brief create a JSON value
8381 
8382  This is a "catch all" constructor for all compatible JSON types; that is,
8383  types for which a `to_json()` method exists. The constructor forwards the
8384  parameter @a val to that method (to `json_serializer<U>::to_json` method
8385  with `U = uncvref_t<CompatibleType>`, to be exact).
8386 
8387  Template type @a CompatibleType includes, but is not limited to, the
8388  following types:
8389  - **arrays**: @ref array_t and all kinds of compatible containers such as
8390  `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
8391  `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
8392  `std::multiset`, and `std::unordered_multiset` with a `value_type` from
8393  which a @ref basic_json value can be constructed.
8394  - **objects**: @ref object_t and all kinds of compatible associative
8395  containers such as `std::map`, `std::unordered_map`, `std::multimap`,
8396  and `std::unordered_multimap` with a `key_type` compatible to
8397  @ref string_t and a `value_type` from which a @ref basic_json value can
8398  be constructed.
8399  - **strings**: @ref string_t, string literals, and all compatible string
8400  containers can be used.
8401  - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
8402  @ref number_float_t, and all convertible number types such as `int`,
8403  `size_t`, `int64_t`, `float` or `double` can be used.
8404  - **boolean**: @ref boolean_t / `bool` can be used.
8406  See the examples below.
8407 
8408  @tparam CompatibleType a type such that:
8409  - @a CompatibleType is not derived from `std::istream`,
8410  - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
8411  constructors),
8412  - @a CompatibleType is not a @ref basic_json nested type (e.g.,
8413  @ref json_pointer, @ref iterator, etc ...)
8414  - @ref @ref json_serializer<U> has a
8415  `to_json(basic_json_t&, CompatibleType&&)` method
8416 
8417  @tparam U = `uncvref_t<CompatibleType>`
8418 
8419  @param[in] val the value to be forwarded to the respective constructor
8420 
8421  @complexity Usually linear in the size of the passed @a val, also
8422  depending on the implementation of the called `to_json()`
8423  method.
8424 
8425  @exceptionsafety Depends on the called constructor. For types directly
8426  supported by the library (i.e., all types for which no `to_json()` function
8427  was provided), strong guarantee holds: if an exception is thrown, there are
8428  no changes to any JSON value.
8429 
8430  @liveexample{The following code shows the constructor with several
8431  compatible types.,basic_json__CompatibleType}
8432 
8433  @since version 2.1.0
8434  */
8435  template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>,
8436  detail::enable_if_t<not std::is_base_of<std::istream, U>::value and
8437  not std::is_same<U, basic_json_t>::value and
8438  not detail::is_basic_json_nested_type<
8439  basic_json_t, U>::value and
8440  detail::has_to_json<basic_json, U>::value,
8441  int> = 0>
8442  basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json(
8443  std::declval<basic_json_t&>(), std::forward<CompatibleType>(val))))
8444  {
8445  JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
8446  assert_invariant();
8447  }
8448 
8449  /*!
8450  @brief create a container (array or object) from an initializer list
8451 
8452  Creates a JSON value of type array or object from the passed initializer
8453  list @a init. In case @a type_deduction is `true` (default), the type of
8454  the JSON value to be created is deducted from the initializer list @a init
8455  according to the following rules:
8456 
8457  1. If the list is empty, an empty JSON object value `{}` is created.
8458  2. If the list consists of pairs whose first element is a string, a JSON
8459  object value is created where the first elements of the pairs are
8460  treated as keys and the second elements are as values.
8461  3. In all other cases, an array is created.
8462 
8463  The rules aim to create the best fit between a C++ initializer list and
8464  JSON values. The rationale is as follows:
8465 
8466  1. The empty initializer list is written as `{}` which is exactly an empty
8467  JSON object.
8468  2. C++ has no way of describing mapped types other than to list a list of
8469  pairs. As JSON requires that keys must be of type string, rule 2 is the
8470  weakest constraint one can pose on initializer lists to interpret them
8471  as an object.
8472  3. In all other cases, the initializer list could not be interpreted as
8473  JSON object type, so interpreting it as JSON array type is safe.
8474 
8475  With the rules described above, the following JSON values cannot be
8476  expressed by an initializer list:
8477 
8478  - the empty array (`[]`): use @ref array(initializer_list_t)
8479  with an empty initializer list in this case
8480  - arrays whose elements satisfy rule 2: use @ref
8481  array(initializer_list_t) with the same initializer list
8482  in this case
8483 
8484  @note When used without parentheses around an empty initializer list, @ref
8485  basic_json() is called instead of this function, yielding the JSON null
8486  value.
8487 
8488  @param[in] init initializer list with JSON values
8489 
8490  @param[in] type_deduction internal parameter; when set to `true`, the type
8491  of the JSON value is deducted from the initializer list @a init; when set
8492  to `false`, the type provided via @a manual_type is forced. This mode is
8493  used by the functions @ref array(initializer_list_t) and
8494  @ref object(initializer_list_t).
8495 
8496  @param[in] manual_type internal parameter; when @a type_deduction is set
8497  to `false`, the created JSON value will use the provided type (only @ref
8498  value_t::array and @ref value_t::object are valid); when @a type_deduction
8499  is set to `true`, this parameter has no effect
8500 
8501  @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
8502  `value_t::object`, but @a init contains an element which is not a pair
8503  whose first element is a string. In this case, the constructor could not
8504  create an object. If @a type_deduction would have be `true`, an array
8505  would have been created. See @ref object(initializer_list_t)
8506  for an example.
8507 
8508  @complexity Linear in the size of the initializer list @a init.
8509 
8510  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8511  changes to any JSON value.
8512 
8513  @liveexample{The example below shows how JSON values are created from
8514  initializer lists.,basic_json__list_init_t}
8515 
8516  @sa @ref array(initializer_list_t) -- create a JSON array
8517  value from an initializer list
8518  @sa @ref object(initializer_list_t) -- create a JSON object
8519  value from an initializer list
8520 
8521  @since version 1.0.0
8522  */
8523  basic_json(initializer_list_t init,
8524  bool type_deduction = true,
8525  value_t manual_type = value_t::array)
8526  {
8527  // check if each element is an array with two elements whose first
8528  // element is a string
8529  bool is_an_object = std::all_of(init.begin(), init.end(),
8530  [](const detail::json_ref<basic_json>& element_ref)
8531  {
8532  return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string());
8533  });
8534 
8535  // adjust type if type deduction is not wanted
8536  if (not type_deduction)
8537  {
8538  // if array is wanted, do not create an object though possible
8539  if (manual_type == value_t::array)
8540  {
8541  is_an_object = false;
8542  }
8543 
8544  // if object is wanted but impossible, throw an exception
8545  if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object))
8546  {
8547  JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
8548  }
8549  }
8550 
8551  if (is_an_object)
8552  {
8553  // the initializer list is a list of pairs -> create object
8554  m_type = value_t::object;
8555  m_value = value_t::object;
8556 
8557  std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
8558  {
8559  auto element = element_ref.moved_or_copied();
8560  m_value.object->emplace(
8561  std::move(*((*element.m_value.array)[0].m_value.string)),
8562  std::move((*element.m_value.array)[1]));
8563  });
8564  }
8565  else
8566  {
8567  // the initializer list describes an array -> create array
8568  m_type = value_t::array;
8569  m_value.array = create<array_t>(init.begin(), init.end());
8570  }
8571 
8572  assert_invariant();
8573  }
8574 
8575  /*!
8576  @brief explicitly create an array from an initializer list
8577 
8578  Creates a JSON array value from a given initializer list. That is, given a
8579  list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
8580  initializer list is empty, the empty array `[]` is created.
8581 
8582  @note This function is only needed to express two edge cases that cannot
8583  be realized with the initializer list constructor (@ref
8584  basic_json(initializer_list_t, bool, value_t)). These cases
8585  are:
8586  1. creating an array whose elements are all pairs whose first element is a
8587  string -- in this case, the initializer list constructor would create an
8588  object, taking the first elements as keys
8589  2. creating an empty array -- passing the empty initializer list to the
8590  initializer list constructor yields an empty object
8591 
8592  @param[in] init initializer list with JSON values to create an array from
8593  (optional)
8594 
8595  @return JSON array value
8596 
8597  @complexity Linear in the size of @a init.
8598 
8599  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8600  changes to any JSON value.
8601 
8602  @liveexample{The following code shows an example for the `array`
8603  function.,array}
8604 
8605  @sa @ref basic_json(initializer_list_t, bool, value_t) --
8606  create a JSON value from an initializer list
8607  @sa @ref object(initializer_list_t) -- create a JSON object
8608  value from an initializer list
8609 
8610  @since version 1.0.0
8611  */
8612  static basic_json array(initializer_list_t init = {})
8613  {
8614  return basic_json(init, false, value_t::array);
8615  }
8616 
8617  /*!
8618  @brief explicitly create an object from an initializer list
8619 
8620  Creates a JSON object value from a given initializer list. The initializer
8621  lists elements must be pairs, and their first elements must be strings. If
8622  the initializer list is empty, the empty object `{}` is created.
8623 
8624  @note This function is only added for symmetry reasons. In contrast to the
8625  related function @ref array(initializer_list_t), there are
8626  no cases which can only be expressed by this function. That is, any
8627  initializer list @a init can also be passed to the initializer list
8628  constructor @ref basic_json(initializer_list_t, bool, value_t).
8629 
8630  @param[in] init initializer list to create an object from (optional)
8631 
8632  @return JSON object value
8633 
8634  @throw type_error.301 if @a init is not a list of pairs whose first
8635  elements are strings. In this case, no object can be created. When such a
8636  value is passed to @ref basic_json(initializer_list_t, bool, value_t),
8637  an array would have been created from the passed initializer list @a init.
8638  See example below.
8639 
8640  @complexity Linear in the size of @a init.
8641 
8642  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8643  changes to any JSON value.
8644 
8645  @liveexample{The following code shows an example for the `object`
8646  function.,object}
8647 
8648  @sa @ref basic_json(initializer_list_t, bool, value_t) --
8649  create a JSON value from an initializer list
8650  @sa @ref array(initializer_list_t) -- create a JSON array
8651  value from an initializer list
8652 
8653  @since version 1.0.0
8654  */
8655  static basic_json object(initializer_list_t init = {})
8656  {
8657  return basic_json(init, false, value_t::object);
8658  }
8659 
8660  /*!
8661  @brief construct an array with count copies of given value
8662 
8663  Constructs a JSON array value by creating @a cnt copies of a passed value.
8664  In case @a cnt is `0`, an empty array is created.
8665 
8666  @param[in] cnt the number of JSON copies of @a val to create
8667  @param[in] val the JSON value to copy
8668 
8669  @post `std::distance(begin(),end()) == cnt` holds.
8670 
8671  @complexity Linear in @a cnt.
8672 
8673  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8674  changes to any JSON value.
8675 
8676  @liveexample{The following code shows examples for the @ref
8677  basic_json(size_type\, const basic_json&)
8678  constructor.,basic_json__size_type_basic_json}
8679 
8680  @since version 1.0.0
8681  */
8682  basic_json(size_type cnt, const basic_json& val)
8683  : m_type(value_t::array)
8684  {
8685  m_value.array = create<array_t>(cnt, val);
8686  assert_invariant();
8687  }
8688 
8689  /*!
8690  @brief construct a JSON container given an iterator range
8691 
8692  Constructs the JSON value with the contents of the range `[first, last)`.
8693  The semantics depends on the different types a JSON value can have:
8694  - In case of a null type, invalid_iterator.206 is thrown.
8695  - In case of other primitive types (number, boolean, or string), @a first
8696  must be `begin()` and @a last must be `end()`. In this case, the value is
8697  copied. Otherwise, invalid_iterator.204 is thrown.
8698  - In case of structured types (array, object), the constructor behaves as
8699  similar versions for `std::vector` or `std::map`; that is, a JSON array
8700  or object is constructed from the values in the range.
8701 
8702  @tparam InputIT an input iterator type (@ref iterator or @ref
8703  const_iterator)
8704 
8705  @param[in] first begin of the range to copy from (included)
8706  @param[in] last end of the range to copy from (excluded)
8707 
8708  @pre Iterators @a first and @a last must be initialized. **This
8709  precondition is enforced with an assertion (see warning).** If
8710  assertions are switched off, a violation of this precondition yields
8711  undefined behavior.
8712 
8713  @pre Range `[first, last)` is valid. Usually, this precondition cannot be
8714  checked efficiently. Only certain edge cases are detected; see the
8715  description of the exceptions below. A violation of this precondition
8716  yields undefined behavior.
8717 
8718  @warning A precondition is enforced with a runtime assertion that will
8719  result in calling `std::abort` if this precondition is not met.
8720  Assertions can be disabled by defining `NDEBUG` at compile time.
8721  See http://en.cppreference.com/w/cpp/error/assert for more
8722  information.
8723 
8724  @throw invalid_iterator.201 if iterators @a first and @a last are not
8725  compatible (i.e., do not belong to the same JSON value). In this case,
8726  the range `[first, last)` is undefined.
8727  @throw invalid_iterator.204 if iterators @a first and @a last belong to a
8728  primitive type (number, boolean, or string), but @a first does not point
8729  to the first element any more. In this case, the range `[first, last)` is
8730  undefined. See example code below.
8731  @throw invalid_iterator.206 if iterators @a first and @a last belong to a
8732  null value. In this case, the range `[first, last)` is undefined.
8733 
8734  @complexity Linear in distance between @a first and @a last.
8735 
8736  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8737  changes to any JSON value.
8738 
8739  @liveexample{The example below shows several ways to create JSON values by
8740  specifying a subrange with iterators.,basic_json__InputIt_InputIt}
8742  @since version 1.0.0
8743  */
8744  template<class InputIT, typename std::enable_if<
8745  std::is_same<InputIT, typename basic_json_t::iterator>::value or
8746  std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
8747  basic_json(InputIT first, InputIT last)
8748  {
8749  assert(first.m_object != nullptr);
8750  assert(last.m_object != nullptr);
8751 
8752  // make sure iterator fits the current value
8753  if (JSON_UNLIKELY(first.m_object != last.m_object))
8754  {
8755  JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
8756  }
8757 
8758  // copy type from first iterator
8759  m_type = first.m_object->m_type;
8760 
8761  // check if iterator range is complete for primitive values
8762  switch (m_type)
8763  {
8764  case value_t::boolean:
8765  case value_t::number_float:
8766  case value_t::number_integer:
8767  case value_t::number_unsigned:
8768  case value_t::string:
8769  {
8770  if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
8771  or not last.m_it.primitive_iterator.is_end()))
8772  {
8773  JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
8774  }
8775  break;
8776  }
8777 
8778  default:
8779  break;
8780  }
8781 
8782  switch (m_type)
8783  {
8784  case value_t::number_integer:
8785  {
8786  m_value.number_integer = first.m_object->m_value.number_integer;
8787  break;
8788  }
8789 
8790  case value_t::number_unsigned:
8791  {
8792  m_value.number_unsigned = first.m_object->m_value.number_unsigned;
8793  break;
8794  }
8795 
8796  case value_t::number_float:
8797  {
8798  m_value.number_float = first.m_object->m_value.number_float;
8799  break;
8800  }
8801 
8802  case value_t::boolean:
8803  {
8804  m_value.boolean = first.m_object->m_value.boolean;
8805  break;
8806  }
8807 
8808  case value_t::string:
8809  {
8810  m_value = *first.m_object->m_value.string;
8811  break;
8812  }
8813 
8814  case value_t::object:
8815  {
8816  m_value.object = create<object_t>(first.m_it.object_iterator,
8817  last.m_it.object_iterator);
8818  break;
8819  }
8820 
8821  case value_t::array:
8822  {
8823  m_value.array = create<array_t>(first.m_it.array_iterator,
8824  last.m_it.array_iterator);
8825  break;
8826  }
8827 
8828  default:
8829  JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
8830  std::string(first.m_object->type_name())));
8831  }
8832 
8833  assert_invariant();
8834  }
8835 
8836 
8837  ///////////////////////////////////////
8838  // other constructors and destructor //
8839  ///////////////////////////////////////
8840 
8841  /// @private
8842  basic_json(const detail::json_ref<basic_json>& ref)
8843  : basic_json(ref.moved_or_copied())
8844  {}
8846  /*!
8847  @brief copy constructor
8848 
8849  Creates a copy of a given JSON value.
8850 
8851  @param[in] other the JSON value to copy
8852 
8853  @post `*this == other`
8854 
8855  @complexity Linear in the size of @a other.
8856 
8857  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
8858  changes to any JSON value.
8859 
8860  @requirement This function helps `basic_json` satisfying the
8861  [Container](http://en.cppreference.com/w/cpp/concept/Container)
8862  requirements:
8863  - The complexity is linear.
8864  - As postcondition, it holds: `other == basic_json(other)`.
8865 
8866  @liveexample{The following code shows an example for the copy
8867  constructor.,basic_json__basic_json}
8868 
8869  @since version 1.0.0
8870  */
8871  basic_json(const basic_json& other)
8872  : m_type(other.m_type)
8873  {
8874  // check of passed value is valid
8875  other.assert_invariant();
8876 
8877  switch (m_type)
8878  {
8879  case value_t::object:
8880  {
8881  m_value = *other.m_value.object;
8882  break;
8883  }
8884 
8885  case value_t::array:
8886  {
8887  m_value = *other.m_value.array;
8888  break;
8889  }
8890 
8891  case value_t::string:
8892  {
8893  m_value = *other.m_value.string;
8894  break;
8895  }
8896 
8897  case value_t::boolean:
8898  {
8899  m_value = other.m_value.boolean;
8900  break;
8901  }
8902 
8903  case value_t::number_integer:
8904  {
8905  m_value = other.m_value.number_integer;
8906  break;
8907  }
8908 
8909  case value_t::number_unsigned:
8910  {
8911  m_value = other.m_value.number_unsigned;
8912  break;
8913  }
8914 
8915  case value_t::number_float:
8916  {
8917  m_value = other.m_value.number_float;
8918  break;
8919  }
8920 
8921  default:
8922  break;
8923  }
8924 
8925  assert_invariant();
8926  }
8927 
8928  /*!
8929  @brief move constructor
8930 
8931  Move constructor. Constructs a JSON value with the contents of the given
8932  value @a other using move semantics. It "steals" the resources from @a
8933  other and leaves it as JSON null value.
8934 
8935  @param[in,out] other value to move to this object
8936 
8937  @post `*this` has the same value as @a other before the call.
8938  @post @a other is a JSON null value.
8939 
8940  @complexity Constant.
8941 
8942  @exceptionsafety No-throw guarantee: this constructor never throws
8943  exceptions.
8944 
8945  @requirement This function helps `basic_json` satisfying the
8946  [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible)
8947  requirements.
8948 
8949  @liveexample{The code below shows the move constructor explicitly called
8950  via std::move.,basic_json__moveconstructor}
8951 
8952  @since version 1.0.0
8953  */
8954  basic_json(basic_json&& other) noexcept
8955  : m_type(std::move(other.m_type)),
8956  m_value(std::move(other.m_value))
8957  {
8958  // check that passed value is valid
8959  other.assert_invariant();
8960 
8961  // invalidate payload
8962  other.m_type = value_t::null;
8963  other.m_value = {};
8964 
8965  assert_invariant();
8966  }
8967 
8968  /*!
8969  @brief copy assignment
8970 
8971  Copy assignment operator. Copies a JSON value via the "copy and swap"
8972  strategy: It is expressed in terms of the copy constructor, destructor,
8973  and the `swap()` member function.
8974 
8975  @param[in] other value to copy from
8977  @complexity Linear.
8978 
8979  @requirement This function helps `basic_json` satisfying the
8980  [Container](http://en.cppreference.com/w/cpp/concept/Container)
8981  requirements:
8982  - The complexity is linear.
8983 
8984  @liveexample{The code below shows and example for the copy assignment. It
8985  creates a copy of value `a` which is then swapped with `b`. Finally\, the
8986  copy of `a` (which is the null value after the swap) is
8987  destroyed.,basic_json__copyassignment}
8988 
8989  @since version 1.0.0
8990  */
8991  reference& operator=(basic_json other) noexcept (
8992  std::is_nothrow_move_constructible<value_t>::value and
8993  std::is_nothrow_move_assignable<value_t>::value and
8994  std::is_nothrow_move_constructible<json_value>::value and
8995  std::is_nothrow_move_assignable<json_value>::value
8996  )
8997  {
8998  // check that passed value is valid
8999  other.assert_invariant();
9000 
9001  using std::swap;
9002  swap(m_type, other.m_type);
9003  swap(m_value, other.m_value);
9004 
9005  assert_invariant();
9006  return *this;
9007  }
9008 
9009  /*!
9010  @brief destructor
9011 
9012  Destroys the JSON value and frees all allocated memory.
9013 
9014  @complexity Linear.
9015 
9016  @requirement This function helps `basic_json` satisfying the
9017  [Container](http://en.cppreference.com/w/cpp/concept/Container)
9018  requirements:
9019  - The complexity is linear.
9020  - All stored elements are destroyed and all memory is freed.
9021 
9022  @since version 1.0.0
9023  */
9024  ~basic_json()
9025  {
9026  assert_invariant();
9027  m_value.destroy(m_type);
9028  }
9029 
9030  /// @}
9031 
9032  public:
9033  ///////////////////////
9034  // object inspection //
9035  ///////////////////////
9036 
9037  /// @name object inspection
9038  /// Functions to inspect the type of a JSON value.
9039  /// @{
9040 
9041  /*!
9042  @brief serialization
9043 
9044  Serialization function for JSON values. The function tries to mimic
9045  Python's `json.dumps()` function, and currently supports its @a indent
9046  and @a ensure_ascii parameters.
9047 
9048  @param[in] indent If indent is nonnegative, then array elements and object
9049  members will be pretty-printed with that indent level. An indent level of
9050  `0` will only insert newlines. `-1` (the default) selects the most compact
9051  representation.
9052  @param[in] indent_char The character to use for indentation if @a indent is
9053  greater than `0`. The default is ` ` (space).
9054  @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
9055  in the output are escaped with `\uXXXX` sequences, and the result consists
9056  of ASCII characters only.
9057 
9058  @return string containing the serialization of the JSON value
9059 
9060  @throw type_error.316 if a string stored inside the JSON value is not
9061  UTF-8 encoded
9062 
9063  @complexity Linear.
9064 
9065  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
9066  changes in the JSON value.
9067 
9068  @liveexample{The following example shows the effect of different @a indent\,
9069  @a indent_char\, and @a ensure_ascii parameters to the result of the
9070  serialization.,dump}
9071 
9072  @see https://docs.python.org/2/library/json.html#json.dump
9073 
9074  @since version 1.0.0; indentation character @a indent_char, option
9075  @a ensure_ascii and exceptions added in version 3.0.0
9076  */
9077  string_t dump(const int indent = -1, const char indent_char = ' ',
9078  const bool ensure_ascii = false) const
9079  {
9080  string_t result;
9081  serializer s(detail::output_adapter<char>(result), indent_char);
9082 
9083  if (indent >= 0)
9084  {
9085  s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
9086  }
9087  else
9088  {
9089  s.dump(*this, false, ensure_ascii, 0);
9090  }
9091 
9092  return result;
9093  }
9094 
9095  /*!
9096  @brief return the type of the JSON value (explicit)
9097 
9098  Return the type of the JSON value as a value from the @ref value_t
9099  enumeration.
9100 
9101  @return the type of the JSON value
9102  Value type | return value
9103  ------------------------- | -------------------------
9104  null | value_t::null
9105  boolean | value_t::boolean
9106  string | value_t::string
9107  number (integer) | value_t::number_integer
9108  number (unsigned integer) | value_t::number_unsigned
9109  number (floating-point) | value_t::number_float
9110  object | value_t::object
9111  array | value_t::array
9112  discarded | value_t::discarded
9113 
9114  @complexity Constant.
9115 
9116  @exceptionsafety No-throw guarantee: this member function never throws
9117  exceptions.
9118 
9119  @liveexample{The following code exemplifies `type()` for all JSON
9120  types.,type}
9121 
9122  @sa @ref operator value_t() -- return the type of the JSON value (implicit)
9123  @sa @ref type_name() -- return the type as string
9124 
9125  @since version 1.0.0
9126  */
9127  constexpr value_t type() const noexcept
9128  {
9129  return m_type;
9130  }
9131 
9132  /*!
9133  @brief return whether type is primitive
9134 
9135  This function returns true if and only if the JSON type is primitive
9136  (string, number, boolean, or null).
9137 
9138  @return `true` if type is primitive (string, number, boolean, or null),
9139  `false` otherwise.
9140 
9141  @complexity Constant.
9142 
9143  @exceptionsafety No-throw guarantee: this member function never throws
9144  exceptions.
9145 
9146  @liveexample{The following code exemplifies `is_primitive()` for all JSON
9147  types.,is_primitive}
9148 
9149  @sa @ref is_structured() -- returns whether JSON value is structured
9150  @sa @ref is_null() -- returns whether JSON value is `null`
9151  @sa @ref is_string() -- returns whether JSON value is a string
9152  @sa @ref is_boolean() -- returns whether JSON value is a boolean
9153  @sa @ref is_number() -- returns whether JSON value is a number
9154 
9155  @since version 1.0.0
9156  */
9157  constexpr bool is_primitive() const noexcept
9158  {
9159  return is_null() or is_string() or is_boolean() or is_number();
9160  }
9161 
9162  /*!
9163  @brief return whether type is structured
9164 
9165  This function returns true if and only if the JSON type is structured
9166  (array or object).
9167 
9168  @return `true` if type is structured (array or object), `false` otherwise.
9169 
9170  @complexity Constant.
9171 
9172  @exceptionsafety No-throw guarantee: this member function never throws
9173  exceptions.
9174 
9175  @liveexample{The following code exemplifies `is_structured()` for all JSON
9176  types.,is_structured}
9177 
9178  @sa @ref is_primitive() -- returns whether value is primitive
9179  @sa @ref is_array() -- returns whether value is an array
9180  @sa @ref is_object() -- returns whether value is an object
9181 
9182  @since version 1.0.0
9183  */
9184  constexpr bool is_structured() const noexcept
9185  {
9186  return is_array() or is_object();
9187  }
9188 
9189  /*!
9190  @brief return whether value is null
9191 
9192  This function returns true if and only if the JSON value is null.
9193 
9194  @return `true` if type is null, `false` otherwise.
9195 
9196  @complexity Constant.
9197 
9198  @exceptionsafety No-throw guarantee: this member function never throws
9199  exceptions.
9200 
9201  @liveexample{The following code exemplifies `is_null()` for all JSON
9202  types.,is_null}
9204  @since version 1.0.0
9205  */
9206  constexpr bool is_null() const noexcept
9207  {
9208  return (m_type == value_t::null);
9209  }
9210 
9211  /*!
9212  @brief return whether value is a boolean
9213 
9214  This function returns true if and only if the JSON value is a boolean.
9215 
9216  @return `true` if type is boolean, `false` otherwise.
9217 
9218  @complexity Constant.
9219 
9220  @exceptionsafety No-throw guarantee: this member function never throws
9221  exceptions.
9222 
9223  @liveexample{The following code exemplifies `is_boolean()` for all JSON
9224  types.,is_boolean}
9225 
9226  @since version 1.0.0
9227  */
9228  constexpr bool is_boolean() const noexcept
9229  {
9230  return (m_type == value_t::boolean);
9231  }
9232 
9233  /*!
9234  @brief return whether value is a number
9235 
9236  This function returns true if and only if the JSON value is a number. This
9237  includes both integer (signed and unsigned) and floating-point values.
9238 
9239  @return `true` if type is number (regardless whether integer, unsigned
9240  integer or floating-type), `false` otherwise.
9241 
9242  @complexity Constant.
9243 
9244  @exceptionsafety No-throw guarantee: this member function never throws
9245  exceptions.
9246 
9247  @liveexample{The following code exemplifies `is_number()` for all JSON
9248  types.,is_number}
9249 
9250  @sa @ref is_number_integer() -- check if value is an integer or unsigned
9251  integer number
9252  @sa @ref is_number_unsigned() -- check if value is an unsigned integer
9253  number
9254  @sa @ref is_number_float() -- check if value is a floating-point number
9255 
9256  @since version 1.0.0
9257  */
9258  constexpr bool is_number() const noexcept
9259  {
9260  return is_number_integer() or is_number_float();
9261  }
9262 
9263  /*!
9264  @brief return whether value is an integer number
9265 
9266  This function returns true if and only if the JSON value is a signed or
9267  unsigned integer number. This excludes floating-point values.
9268 
9269  @return `true` if type is an integer or unsigned integer number, `false`
9270  otherwise.
9271 
9272  @complexity Constant.
9273 
9274  @exceptionsafety No-throw guarantee: this member function never throws
9275  exceptions.
9276 
9277  @liveexample{The following code exemplifies `is_number_integer()` for all
9278  JSON types.,is_number_integer}
9279 
9280  @sa @ref is_number() -- check if value is a number
9281  @sa @ref is_number_unsigned() -- check if value is an unsigned integer
9282  number
9283  @sa @ref is_number_float() -- check if value is a floating-point number
9284 
9285  @since version 1.0.0
9286  */
9287  constexpr bool is_number_integer() const noexcept
9288  {
9289  return (m_type == value_t::number_integer or m_type == value_t::number_unsigned);
9290  }
9291 
9292  /*!
9293  @brief return whether value is an unsigned integer number
9294 
9295  This function returns true if and only if the JSON value is an unsigned
9296  integer number. This excludes floating-point and signed integer values.
9297 
9298  @return `true` if type is an unsigned integer number, `false` otherwise.
9299 
9300  @complexity Constant.
9301 
9302  @exceptionsafety No-throw guarantee: this member function never throws
9303  exceptions.
9304 
9305  @liveexample{The following code exemplifies `is_number_unsigned()` for all
9306  JSON types.,is_number_unsigned}
9307 
9308  @sa @ref is_number() -- check if value is a number
9309  @sa @ref is_number_integer() -- check if value is an integer or unsigned
9310  integer number
9311  @sa @ref is_number_float() -- check if value is a floating-point number
9312 
9313  @since version 2.0.0
9314  */
9315  constexpr bool is_number_unsigned() const noexcept
9316  {
9317  return (m_type == value_t::number_unsigned);
9318  }
9319 
9320  /*!
9321  @brief return whether value is a floating-point number
9322 
9323  This function returns true if and only if the JSON value is a
9324  floating-point number. This excludes signed and unsigned integer values.
9325 
9326  @return `true` if type is a floating-point number, `false` otherwise.
9327 
9328  @complexity Constant.
9329 
9330  @exceptionsafety No-throw guarantee: this member function never throws
9331  exceptions.
9332 
9333  @liveexample{The following code exemplifies `is_number_float()` for all
9334  JSON types.,is_number_float}
9335 
9336  @sa @ref is_number() -- check if value is number
9337  @sa @ref is_number_integer() -- check if value is an integer number
9338  @sa @ref is_number_unsigned() -- check if value is an unsigned integer
9339  number
9340 
9341  @since version 1.0.0
9342  */
9343  constexpr bool is_number_float() const noexcept
9344  {
9345  return (m_type == value_t::number_float);
9346  }
9347 
9348  /*!
9349  @brief return whether value is an object
9350 
9351  This function returns true if and only if the JSON value is an object.
9352 
9353  @return `true` if type is object, `false` otherwise.
9354 
9355  @complexity Constant.
9357  @exceptionsafety No-throw guarantee: this member function never throws
9358  exceptions.
9359 
9360  @liveexample{The following code exemplifies `is_object()` for all JSON
9361  types.,is_object}
9362 
9363  @since version 1.0.0
9364  */
9365  constexpr bool is_object() const noexcept
9366  {
9367  return (m_type == value_t::object);
9368  }
9369 
9370  /*!
9371  @brief return whether value is an array
9372 
9373  This function returns true if and only if the JSON value is an array.
9374 
9375  @return `true` if type is array, `false` otherwise.
9376 
9377  @complexity Constant.
9378 
9379  @exceptionsafety No-throw guarantee: this member function never throws
9380  exceptions.
9381 
9382  @liveexample{The following code exemplifies `is_array()` for all JSON
9383  types.,is_array}
9385  @since version 1.0.0
9386  */
9387  constexpr bool is_array() const noexcept
9388  {
9389  return (m_type == value_t::array);
9390  }
9391 
9392  /*!
9393  @brief return whether value is a string
9394 
9395  This function returns true if and only if the JSON value is a string.
9396 
9397  @return `true` if type is string, `false` otherwise.
9398 
9399  @complexity Constant.
9400 
9401  @exceptionsafety No-throw guarantee: this member function never throws
9402  exceptions.
9403 
9404  @liveexample{The following code exemplifies `is_string()` for all JSON
9405  types.,is_string}
9406 
9407  @since version 1.0.0
9408  */
9409  constexpr bool is_string() const noexcept
9410  {
9411  return (m_type == value_t::string);
9412  }
9413 
9414  /*!
9415  @brief return whether value is discarded
9416 
9417  This function returns true if and only if the JSON value was discarded
9418  during parsing with a callback function (see @ref parser_callback_t).
9419 
9420  @note This function will always be `false` for JSON values after parsing.
9421  That is, discarded values can only occur during parsing, but will be
9422  removed when inside a structured value or replaced by null in other cases.
9423 
9424  @return `true` if type is discarded, `false` otherwise.
9425 
9426  @complexity Constant.
9427 
9428  @exceptionsafety No-throw guarantee: this member function never throws
9429  exceptions.
9430 
9431  @liveexample{The following code exemplifies `is_discarded()` for all JSON
9432  types.,is_discarded}
9433 
9434  @since version 1.0.0
9435  */
9436  constexpr bool is_discarded() const noexcept
9437  {
9438  return (m_type == value_t::discarded);
9439  }
9440 
9441  /*!
9442  @brief return the type of the JSON value (implicit)
9443 
9444  Implicitly return the type of the JSON value as a value from the @ref
9445  value_t enumeration.
9446 
9447  @return the type of the JSON value
9448 
9449  @complexity Constant.
9450 
9451  @exceptionsafety No-throw guarantee: this member function never throws
9452  exceptions.
9453 
9454  @liveexample{The following code exemplifies the @ref value_t operator for
9455  all JSON types.,operator__value_t}
9456 
9457  @sa @ref type() -- return the type of the JSON value (explicit)
9458  @sa @ref type_name() -- return the type as string
9459 
9460  @since version 1.0.0
9461  */
9462  constexpr operator value_t() const noexcept
9463  {
9464  return m_type;
9465  }
9466 
9467  /// @}
9468 
9469  private:
9470  //////////////////
9471  // value access //
9472  //////////////////
9473 
9474  /// get a boolean (explicit)
9475  boolean_t get_impl(boolean_t* /*unused*/) const
9476  {
9477  if (JSON_LIKELY(is_boolean()))
9478  {
9479  return m_value.boolean;
9480  }
9481 
9482  JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
9483  }
9484 
9485  /// get a pointer to the value (object)
9486  object_t* get_impl_ptr(object_t* /*unused*/) noexcept
9487  {
9488  return is_object() ? m_value.object : nullptr;
9489  }
9490 
9491  /// get a pointer to the value (object)
9492  constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
9493  {
9494  return is_object() ? m_value.object : nullptr;
9495  }
9496 
9497  /// get a pointer to the value (array)
9498  array_t* get_impl_ptr(array_t* /*unused*/) noexcept
9499  {
9500  return is_array() ? m_value.array : nullptr;
9501  }
9502 
9503  /// get a pointer to the value (array)
9504  constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
9505  {
9506  return is_array() ? m_value.array : nullptr;
9507  }
9508 
9509  /// get a pointer to the value (string)
9510  string_t* get_impl_ptr(string_t* /*unused*/) noexcept
9511  {
9512  return is_string() ? m_value.string : nullptr;
9513  }
9514 
9515  /// get a pointer to the value (string)
9516  constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
9517  {
9518  return is_string() ? m_value.string : nullptr;
9519  }
9520 
9521  /// get a pointer to the value (boolean)
9522  boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
9523  {
9524  return is_boolean() ? &m_value.boolean : nullptr;
9525  }
9526 
9527  /// get a pointer to the value (boolean)
9528  constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
9529  {
9530  return is_boolean() ? &m_value.boolean : nullptr;
9531  }
9532 
9533  /// get a pointer to the value (integer number)
9534  number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
9535  {
9536  return is_number_integer() ? &m_value.number_integer : nullptr;
9537  }
9538 
9539  /// get a pointer to the value (integer number)
9540  constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
9541  {
9542  return is_number_integer() ? &m_value.number_integer : nullptr;
9543  }
9544 
9545  /// get a pointer to the value (unsigned number)
9546  number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
9547  {
9548  return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
9549  }
9550 
9551  /// get a pointer to the value (unsigned number)
9552  constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
9553  {
9554  return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
9555  }
9556 
9557  /// get a pointer to the value (floating-point number)
9558  number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
9559  {
9560  return is_number_float() ? &m_value.number_float : nullptr;
9561  }
9562 
9563  /// get a pointer to the value (floating-point number)
9564  constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
9565  {
9566  return is_number_float() ? &m_value.number_float : nullptr;
9567  }
9568 
9569  /*!
9570  @brief helper function to implement get_ref()
9571 
9572  This function helps to implement get_ref() without code duplication for
9573  const and non-const overloads
9574 
9575  @tparam ThisType will be deduced as `basic_json` or `const basic_json`
9576 
9577  @throw type_error.303 if ReferenceType does not match underlying value
9578  type of the current JSON
9579  */
9580  template<typename ReferenceType, typename ThisType>
9581  static ReferenceType get_ref_impl(ThisType& obj)
9582  {
9583  // delegate the call to get_ptr<>()
9584  auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
9585 
9586  if (JSON_LIKELY(ptr != nullptr))
9587  {
9588  return *ptr;
9589  }
9590 
9591  JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
9592  }
9593 
9594  public:
9595  /// @name value access
9596  /// Direct access to the stored value of a JSON value.
9597  /// @{
9598 
9599  /*!
9600  @brief get special-case overload
9601 
9602  This overloads avoids a lot of template boilerplate, it can be seen as the
9603  identity method
9604 
9605  @tparam BasicJsonType == @ref basic_json
9606 
9607  @return a copy of *this
9608 
9609  @complexity Constant.
9610 
9611  @since version 2.1.0
9612  */
9613  template<typename BasicJsonType, detail::enable_if_t<
9614  std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
9615  int> = 0>
9616  basic_json get() const
9617  {
9618  return *this;
9619  }
9620 
9621  /*!
9622  @brief get a value (explicit)
9623 
9624  Explicit type conversion between the JSON value and a compatible value
9625  which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
9626  and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
9627  The value is converted by calling the @ref json_serializer<ValueType>
9628  `from_json()` method.
9629 
9630  The function is equivalent to executing
9631  @code {.cpp}
9632  ValueType ret;
9633  JSONSerializer<ValueType>::from_json(*this, ret);
9634  return ret;
9635  @endcode
9636 
9637  This overloads is chosen if:
9638  - @a ValueType is not @ref basic_json,
9639  - @ref json_serializer<ValueType> has a `from_json()` method of the form
9640  `void from_json(const basic_json&, ValueType&)`, and
9641  - @ref json_serializer<ValueType> does not have a `from_json()` method of
9642  the form `ValueType from_json(const basic_json&)`
9643 
9644  @tparam ValueTypeCV the provided value type
9645  @tparam ValueType the returned value type
9646 
9647  @return copy of the JSON value, converted to @a ValueType
9648 
9649  @throw what @ref json_serializer<ValueType> `from_json()` method throws
9650 
9651  @liveexample{The example below shows several conversions from JSON values
9652  to other types. There a few things to note: (1) Floating-point numbers can
9653  be converted to integers\, (2) A JSON array can be converted to a standard
9654  `std::vector<short>`\, (3) A JSON object can be converted to C++
9655  associative containers such as `std::unordered_map<std::string\,
9656  json>`.,get__ValueType_const}
9657 
9658  @since version 2.1.0
9659  */
9660  template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
9661  detail::enable_if_t <
9662  not std::is_same<basic_json_t, ValueType>::value and
9663  detail::has_from_json<basic_json_t, ValueType>::value and
9664  not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
9665  int> = 0>
9666  ValueType get() const noexcept(noexcept(
9667  JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
9668  {
9669  // we cannot static_assert on ValueTypeCV being non-const, because
9670  // there is support for get<const basic_json_t>(), which is why we
9671  // still need the uncvref
9672  static_assert(not std::is_reference<ValueTypeCV>::value,
9673  "get() cannot be used with reference types, you might want to use get_ref()");
9674  static_assert(std::is_default_constructible<ValueType>::value,
9675  "types must be DefaultConstructible when used with get()");
9676 
9677  ValueType ret;
9678  JSONSerializer<ValueType>::from_json(*this, ret);
9679  return ret;
9680  }
9681 
9682  /*!
9683  @brief get a value (explicit); special case
9684 
9685  Explicit type conversion between the JSON value and a compatible value
9686  which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
9687  and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
9688  The value is converted by calling the @ref json_serializer<ValueType>
9689  `from_json()` method.
9690 
9691  The function is equivalent to executing
9692  @code {.cpp}
9693  return JSONSerializer<ValueTypeCV>::from_json(*this);
9694  @endcode
9695 
9696  This overloads is chosen if:
9697  - @a ValueType is not @ref basic_json and
9698  - @ref json_serializer<ValueType> has a `from_json()` method of the form
9699  `ValueType from_json(const basic_json&)`
9700 
9701  @note If @ref json_serializer<ValueType> has both overloads of
9702  `from_json()`, this one is chosen.
9703 
9704  @tparam ValueTypeCV the provided value type
9705  @tparam ValueType the returned value type
9706 
9707  @return copy of the JSON value, converted to @a ValueType
9708 
9709  @throw what @ref json_serializer<ValueType> `from_json()` method throws
9710 
9711  @since version 2.1.0
9712  */
9713  template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
9714  detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
9715  detail::has_non_default_from_json<basic_json_t, ValueType>::value,
9716  int> = 0>
9717  ValueType get() const noexcept(noexcept(
9718  JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
9719  {
9720  static_assert(not std::is_reference<ValueTypeCV>::value,
9721  "get() cannot be used with reference types, you might want to use get_ref()");
9722  return JSONSerializer<ValueTypeCV>::from_json(*this);
9723  }
9724 
9725  /*!
9726  @brief get a pointer value (explicit)
9727 
9728  Explicit pointer access to the internally stored JSON value. No copies are
9729  made.
9730 
9731  @warning The pointer becomes invalid if the underlying JSON object
9732  changes.
9733 
9734  @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
9735  object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
9736  @ref number_unsigned_t, or @ref number_float_t.
9737 
9738  @return pointer to the internally stored JSON value if the requested
9739  pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
9740 
9741  @complexity Constant.
9742 
9743  @liveexample{The example below shows how pointers to internal values of a
9744  JSON value can be requested. Note that no type conversions are made and a
9745  `nullptr` is returned if the value and the requested pointer type does not
9746  match.,get__PointerType}
9747 
9748  @sa @ref get_ptr() for explicit pointer-member access
9749 
9750  @since version 1.0.0
9751  */
9752  template<typename PointerType, typename std::enable_if<
9753  std::is_pointer<PointerType>::value, int>::type = 0>
9754  PointerType get() noexcept
9755  {
9756  // delegate the call to get_ptr
9757  return get_ptr<PointerType>();
9758  }
9759 
9760  /*!
9761  @brief get a pointer value (explicit)
9762  @copydoc get()
9763  */
9764  template<typename PointerType, typename std::enable_if<
9765  std::is_pointer<PointerType>::value, int>::type = 0>
9766  constexpr const PointerType get() const noexcept
9767  {
9768  // delegate the call to get_ptr
9769  return get_ptr<PointerType>();
9770  }
9771 
9772  /*!
9773  @brief get a pointer value (implicit)
9774 
9775  Implicit pointer access to the internally stored JSON value. No copies are
9776  made.
9777 
9778  @warning Writing data to the pointee of the result yields an undefined
9779  state.
9780 
9781  @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
9782  object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
9783  @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
9784  assertion.
9785 
9786  @return pointer to the internally stored JSON value if the requested
9787  pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
9788 
9789  @complexity Constant.
9790 
9791  @liveexample{The example below shows how pointers to internal values of a
9792  JSON value can be requested. Note that no type conversions are made and a
9793  `nullptr` is returned if the value and the requested pointer type does not
9794  match.,get_ptr}
9795 
9796  @since version 1.0.0
9797  */
9798  template<typename PointerType, typename std::enable_if<
9799  std::is_pointer<PointerType>::value, int>::type = 0>
9800  PointerType get_ptr() noexcept
9801  {
9802  // get the type of the PointerType (remove pointer and const)
9803  using pointee_t = typename std::remove_const<typename
9804  std::remove_pointer<typename
9805  std::remove_const<PointerType>::type>::type>::type;
9806  // make sure the type matches the allowed types
9807  static_assert(
9808  std::is_same<object_t, pointee_t>::value
9809  or std::is_same<array_t, pointee_t>::value
9810  or std::is_same<string_t, pointee_t>::value
9811  or std::is_same<boolean_t, pointee_t>::value
9812  or std::is_same<number_integer_t, pointee_t>::value
9813  or std::is_same<number_unsigned_t, pointee_t>::value
9814  or std::is_same<number_float_t, pointee_t>::value
9815  , "incompatible pointer type");
9816 
9817  // delegate the call to get_impl_ptr<>()
9818  return get_impl_ptr(static_cast<PointerType>(nullptr));
9819  }
9820 
9821  /*!
9822  @brief get a pointer value (implicit)
9823  @copydoc get_ptr()
9824  */
9825  template<typename PointerType, typename std::enable_if<
9826  std::is_pointer<PointerType>::value and
9827  std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
9828  constexpr const PointerType get_ptr() const noexcept
9829  {
9830  // get the type of the PointerType (remove pointer and const)
9831  using pointee_t = typename std::remove_const<typename
9832  std::remove_pointer<typename
9833  std::remove_const<PointerType>::type>::type>::type;
9834  // make sure the type matches the allowed types
9835  static_assert(
9836  std::is_same<object_t, pointee_t>::value
9837  or std::is_same<array_t, pointee_t>::value
9838  or std::is_same<string_t, pointee_t>::value
9839  or std::is_same<boolean_t, pointee_t>::value
9840  or std::is_same<number_integer_t, pointee_t>::value
9841  or std::is_same<number_unsigned_t, pointee_t>::value
9842  or std::is_same<number_float_t, pointee_t>::value
9843  , "incompatible pointer type");
9844 
9845  // delegate the call to get_impl_ptr<>() const
9846  return get_impl_ptr(static_cast<PointerType>(nullptr));
9847  }
9848 
9849  /*!
9850  @brief get a reference value (implicit)
9851 
9852  Implicit reference access to the internally stored JSON value. No copies
9853  are made.
9854 
9855  @warning Writing data to the referee of the result yields an undefined
9856  state.
9857 
9858  @tparam ReferenceType reference type; must be a reference to @ref array_t,
9859  @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
9860  @ref number_float_t. Enforced by static assertion.
9861 
9862  @return reference to the internally stored JSON value if the requested
9863  reference type @a ReferenceType fits to the JSON value; throws
9864  type_error.303 otherwise
9865 
9866  @throw type_error.303 in case passed type @a ReferenceType is incompatible
9867  with the stored JSON value; see example below
9868 
9869  @complexity Constant.
9870 
9871  @liveexample{The example shows several calls to `get_ref()`.,get_ref}
9872 
9873  @since version 1.1.0
9874  */
9875  template<typename ReferenceType, typename std::enable_if<
9876  std::is_reference<ReferenceType>::value, int>::type = 0>
9877  ReferenceType get_ref()
9878  {
9879  // delegate call to get_ref_impl
9880  return get_ref_impl<ReferenceType>(*this);
9881  }
9882 
9883  /*!
9884  @brief get a reference value (implicit)
9885  @copydoc get_ref()
9886  */
9887  template<typename ReferenceType, typename std::enable_if<
9888  std::is_reference<ReferenceType>::value and
9889  std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
9890  ReferenceType get_ref() const
9891  {
9892  // delegate call to get_ref_impl
9893  return get_ref_impl<ReferenceType>(*this);
9894  }
9895 
9896  /*!
9897  @brief get a value (implicit)
9898 
9899  Implicit type conversion between the JSON value and a compatible value.
9900  The call is realized by calling @ref get() const.
9901 
9902  @tparam ValueType non-pointer type compatible to the JSON value, for
9903  instance `int` for JSON integer numbers, `bool` for JSON booleans, or
9904  `std::vector` types for JSON arrays. The character type of @ref string_t
9905  as well as an initializer list of this type is excluded to avoid
9906  ambiguities as these types implicitly convert to `std::string`.
9907 
9908  @return copy of the JSON value, converted to type @a ValueType
9909 
9910  @throw type_error.302 in case passed type @a ValueType is incompatible
9911  to the JSON value type (e.g., the JSON value is of type boolean, but a
9912  string is requested); see example below
9913 
9914  @complexity Linear in the size of the JSON value.
9915 
9916  @liveexample{The example below shows several conversions from JSON values
9917  to other types. There a few things to note: (1) Floating-point numbers can
9918  be converted to integers\, (2) A JSON array can be converted to a standard
9919  `std::vector<short>`\, (3) A JSON object can be converted to C++
9920  associative containers such as `std::unordered_map<std::string\,
9921  json>`.,operator__ValueType}
9922 
9923  @since version 1.0.0
9924  */
9925  template < typename ValueType, typename std::enable_if <
9926  not std::is_pointer<ValueType>::value and
9927  not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
9928  not std::is_same<ValueType, typename string_t::value_type>::value
9929 #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
9930  and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
9931 #endif
9932 #if defined(JSON_HAS_CPP_17)
9933  and not std::is_same<ValueType, typename std::string_view>::value
9934 #endif
9935  , int >::type = 0 >
9936  operator ValueType() const
9937  {
9938  // delegate the call to get<>() const
9939  return get<ValueType>();
9940  }
9941 
9942  /// @}
9943 
9944 
9945  ////////////////////
9946  // element access //
9947  ////////////////////
9948 
9949  /// @name element access
9950  /// Access to the JSON value.
9951  /// @{
9952 
9953  /*!
9954  @brief access specified array element with bounds checking
9955 
9956  Returns a reference to the element at specified location @a idx, with
9957  bounds checking.
9958 
9959  @param[in] idx index of the element to access
9960 
9961  @return reference to the element at index @a idx
9962 
9963  @throw type_error.304 if the JSON value is not an array; in this case,
9964  calling `at` with an index makes no sense. See example below.
9965  @throw out_of_range.401 if the index @a idx is out of range of the array;
9966  that is, `idx >= size()`. See example below.
9967 
9968  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
9969  changes in the JSON value.
9970 
9971  @complexity Constant.
9972 
9973  @since version 1.0.0
9975  @liveexample{The example below shows how array elements can be read and
9976  written using `at()`. It also demonstrates the different exceptions that
9977  can be thrown.,at__size_type}
9978  */
9979  reference at(size_type idx)
9980  {
9981  // at only works for arrays
9982  if (JSON_LIKELY(is_array()))
9983  {
9984  JSON_TRY
9985  {
9986  return m_value.array->at(idx);
9987  }
9988  JSON_CATCH (std::out_of_range&)
9989  {
9990  // create better exception explanation
9991  JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
9992  }
9993  }
9994  else
9995  {
9996  JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
9997  }
9998  }
9999 
10000  /*!
10001  @brief access specified array element with bounds checking
10002 
10003  Returns a const reference to the element at specified location @a idx,
10004  with bounds checking.
10005 
10006  @param[in] idx index of the element to access
10007 
10008  @return const reference to the element at index @a idx
10009 
10010  @throw type_error.304 if the JSON value is not an array; in this case,
10011  calling `at` with an index makes no sense. See example below.
10012  @throw out_of_range.401 if the index @a idx is out of range of the array;
10013  that is, `idx >= size()`. See example below.
10014 
10015  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
10016  changes in the JSON value.
10017 
10018  @complexity Constant.
10019 
10020  @since version 1.0.0
10021 
10022  @liveexample{The example below shows how array elements can be read using
10023  `at()`. It also demonstrates the different exceptions that can be thrown.,
10024  at__size_type_const}
10025  */
10026  const_reference at(size_type idx) const
10027  {
10028  // at only works for arrays
10029  if (JSON_LIKELY(is_array()))
10030  {
10031  JSON_TRY
10032  {
10033  return m_value.array->at(idx);
10034  }
10035  JSON_CATCH (std::out_of_range&)
10036  {
10037  // create better exception explanation
10038  JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
10039  }
10040  }
10041  else
10042  {
10043  JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
10044  }
10045  }
10046 
10047  /*!
10048  @brief access specified object element with bounds checking
10049 
10050  Returns a reference to the element at with specified key @a key, with
10051  bounds checking.
10052 
10053  @param[in] key key of the element to access
10054 
10055  @return reference to the element at key @a key
10056 
10057  @throw type_error.304 if the JSON value is not an object; in this case,
10058  calling `at` with a key makes no sense. See example below.
10059  @throw out_of_range.403 if the key @a key is is not stored in the object;
10060  that is, `find(key) == end()`. See example below.
10061 
10062  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
10063  changes in the JSON value.
10064 
10065  @complexity Logarithmic in the size of the container.
10066 
10067  @sa @ref operator[](const typename object_t::key_type&) for unchecked
10068  access by reference
10069  @sa @ref value() for access by value with a default value
10070 
10071  @since version 1.0.0
10072 
10073  @liveexample{The example below shows how object elements can be read and
10074  written using `at()`. It also demonstrates the different exceptions that
10075  can be thrown.,at__object_t_key_type}
10076  */
10077  reference at(const typename object_t::key_type& key)
10078  {
10079  // at only works for objects
10080  if (JSON_LIKELY(is_object()))
10081  {
10082  JSON_TRY
10083  {
10084  return m_value.object->at(key);
10085  }
10086  JSON_CATCH (std::out_of_range&)
10087  {
10088  // create better exception explanation
10089  JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
10090  }
10091  }
10092  else
10093  {
10094  JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
10095  }
10096  }
10097 
10098  /*!
10099  @brief access specified object element with bounds checking
10100 
10101  Returns a const reference to the element at with specified key @a key,
10102  with bounds checking.
10103 
10104  @param[in] key key of the element to access
10105 
10106  @return const reference to the element at key @a key
10108  @throw type_error.304 if the JSON value is not an object; in this case,
10109  calling `at` with a key makes no sense. See example below.
10110  @throw out_of_range.403 if the key @a key is is not stored in the object;
10111  that is, `find(key) == end()`. See example below.
10112 
10113  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
10114  changes in the JSON value.
10115 
10116  @complexity Logarithmic in the size of the container.
10117 
10118  @sa @ref operator[](const typename object_t::key_type&) for unchecked
10119  access by reference
10120  @sa @ref value() for access by value with a default value
10121 
10122  @since version 1.0.0
10123 
10124  @liveexample{The example below shows how object elements can be read using
10125  `at()`. It also demonstrates the different exceptions that can be thrown.,
10126  at__object_t_key_type_const}
10127  */
10128  const_reference at(const typename object_t::key_type& key) const
10129  {
10130  // at only works for objects
10131  if (JSON_LIKELY(is_object()))
10132  {
10133  JSON_TRY
10134  {
10135  return m_value.object->at(key);
10136  }
10137  JSON_CATCH (std::out_of_range&)
10138  {
10139  // create better exception explanation
10140  JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
10141  }
10142  }
10143  else
10144  {
10145  JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
10146  }
10147  }
10148 
10149  /*!
10150  @brief access specified array element
10151 
10152  Returns a reference to the element at specified location @a idx.
10153 
10154  @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
10155  then the array is silently filled up with `null` values to make `idx` a
10156  valid reference to the last stored element.
10157 
10158  @param[in] idx index of the element to access
10159 
10160  @return reference to the element at index @a idx
10161 
10162  @throw type_error.305 if the JSON value is not an array or null; in that
10163  cases, using the [] operator with an index makes no sense.
10164 
10165  @complexity Constant if @a idx is in the range of the array. Otherwise
10166  linear in `idx - size()`.
10167 
10168  @liveexample{The example below shows how array elements can be read and
10169  written using `[]` operator. Note the addition of `null`
10170  values.,operatorarray__size_type}
10172  @since version 1.0.0
10173  */
10174  reference operator[](size_type idx)
10175  {
10176  // implicitly convert null value to an empty array
10177  if (is_null())
10178  {
10179  m_type = value_t::array;
10180  m_value.array = create<array_t>();
10181  assert_invariant();
10182  }
10183 
10184  // operator[] only works for arrays
10185  if (JSON_LIKELY(is_array()))
10186  {
10187  // fill up array with null values if given idx is outside range
10188  if (idx >= m_value.array->size())
10189  {
10190  m_value.array->insert(m_value.array->end(),
10191  idx - m_value.array->size() + 1,
10192  basic_json());
10193  }
10194 
10195  return m_value.array->operator[](idx);
10196  }
10197 
10198  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10199  }
10200 
10201  /*!
10202  @brief access specified array element
10203 
10204  Returns a const reference to the element at specified location @a idx.
10205 
10206  @param[in] idx index of the element to access
10207 
10208  @return const reference to the element at index @a idx
10209 
10210  @throw type_error.305 if the JSON value is not an array; in that case,
10211  using the [] operator with an index makes no sense.
10212 
10213  @complexity Constant.
10214 
10215  @liveexample{The example below shows how array elements can be read using
10216  the `[]` operator.,operatorarray__size_type_const}
10217 
10218  @since version 1.0.0
10219  */
10220  const_reference operator[](size_type idx) const
10221  {
10222  // const operator[] only works for arrays
10223  if (JSON_LIKELY(is_array()))
10224  {
10225  return m_value.array->operator[](idx);
10226  }
10227 
10228  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10229  }
10230 
10231  /*!
10232  @brief access specified object element
10233 
10234  Returns a reference to the element at with specified key @a key.
10235 
10236  @note If @a key is not found in the object, then it is silently added to
10237  the object and filled with a `null` value to make `key` a valid reference.
10238  In case the value was `null` before, it is converted to an object.
10239 
10240  @param[in] key key of the element to access
10241 
10242  @return reference to the element at key @a key
10243 
10244  @throw type_error.305 if the JSON value is not an object or null; in that
10245  cases, using the [] operator with a key makes no sense.
10246 
10247  @complexity Logarithmic in the size of the container.
10248 
10249  @liveexample{The example below shows how object elements can be read and
10250  written using the `[]` operator.,operatorarray__key_type}
10251 
10252  @sa @ref at(const typename object_t::key_type&) for access by reference
10253  with range checking
10254  @sa @ref value() for access by value with a default value
10255 
10256  @since version 1.0.0
10257  */
10258  reference operator[](const typename object_t::key_type& key)
10259  {
10260  // implicitly convert null value to an empty object
10261  if (is_null())
10262  {
10263  m_type = value_t::object;
10264  m_value.object = create<object_t>();
10265  assert_invariant();
10266  }
10267 
10268  // operator[] only works for objects
10269  if (JSON_LIKELY(is_object()))
10270  {
10271  return m_value.object->operator[](key);
10272  }
10273 
10274  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10275  }
10276 
10277  /*!
10278  @brief read-only access specified object element
10279 
10280  Returns a const reference to the element at with specified key @a key. No
10281  bounds checking is performed.
10282 
10283  @warning If the element with key @a key does not exist, the behavior is
10284  undefined.
10285 
10286  @param[in] key key of the element to access
10287 
10288  @return const reference to the element at key @a key
10289 
10290  @pre The element with key @a key must exist. **This precondition is
10291  enforced with an assertion.**
10292 
10293  @throw type_error.305 if the JSON value is not an object; in that case,
10294  using the [] operator with a key makes no sense.
10295 
10296  @complexity Logarithmic in the size of the container.
10297 
10298  @liveexample{The example below shows how object elements can be read using
10299  the `[]` operator.,operatorarray__key_type_const}
10300 
10301  @sa @ref at(const typename object_t::key_type&) for access by reference
10302  with range checking
10303  @sa @ref value() for access by value with a default value
10304 
10305  @since version 1.0.0
10306  */
10307  const_reference operator[](const typename object_t::key_type& key) const
10308  {
10309  // const operator[] only works for objects
10310  if (JSON_LIKELY(is_object()))
10311  {
10312  assert(m_value.object->find(key) != m_value.object->end());
10313  return m_value.object->find(key)->second;
10314  }
10315 
10316  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10317  }
10318 
10319  /*!
10320  @brief access specified object element
10321 
10322  Returns a reference to the element at with specified key @a key.
10323 
10324  @note If @a key is not found in the object, then it is silently added to
10325  the object and filled with a `null` value to make `key` a valid reference.
10326  In case the value was `null` before, it is converted to an object.
10327 
10328  @param[in] key key of the element to access
10329 
10330  @return reference to the element at key @a key
10331 
10332  @throw type_error.305 if the JSON value is not an object or null; in that
10333  cases, using the [] operator with a key makes no sense.
10334 
10335  @complexity Logarithmic in the size of the container.
10336 
10337  @liveexample{The example below shows how object elements can be read and
10338  written using the `[]` operator.,operatorarray__key_type}
10339 
10340  @sa @ref at(const typename object_t::key_type&) for access by reference
10341  with range checking
10342  @sa @ref value() for access by value with a default value
10343 
10344  @since version 1.1.0
10345  */
10346  template<typename T>
10347  reference operator[](T* key)
10348  {
10349  // implicitly convert null to object
10350  if (is_null())
10351  {
10352  m_type = value_t::object;
10353  m_value = value_t::object;
10354  assert_invariant();
10355  }
10356 
10357  // at only works for objects
10358  if (JSON_LIKELY(is_object()))
10359  {
10360  return m_value.object->operator[](key);
10361  }
10362 
10363  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10364  }
10365 
10366  /*!
10367  @brief read-only access specified object element
10368 
10369  Returns a const reference to the element at with specified key @a key. No
10370  bounds checking is performed.
10371 
10372  @warning If the element with key @a key does not exist, the behavior is
10373  undefined.
10374 
10375  @param[in] key key of the element to access
10376 
10377  @return const reference to the element at key @a key
10378 
10379  @pre The element with key @a key must exist. **This precondition is
10380  enforced with an assertion.**
10381 
10382  @throw type_error.305 if the JSON value is not an object; in that case,
10383  using the [] operator with a key makes no sense.
10384 
10385  @complexity Logarithmic in the size of the container.
10386 
10387  @liveexample{The example below shows how object elements can be read using
10388  the `[]` operator.,operatorarray__key_type_const}
10389 
10390  @sa @ref at(const typename object_t::key_type&) for access by reference
10391  with range checking
10392  @sa @ref value() for access by value with a default value
10393 
10394  @since version 1.1.0
10395  */
10396  template<typename T>
10397  const_reference operator[](T* key) const
10398  {
10399  // at only works for objects
10400  if (JSON_LIKELY(is_object()))
10401  {
10402  assert(m_value.object->find(key) != m_value.object->end());
10403  return m_value.object->find(key)->second;
10404  }
10405 
10406  JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
10407  }
10408 
10409  /*!
10410  @brief access specified object element with default value
10411 
10412  Returns either a copy of an object's element at the specified key @a key
10413  or a given default value if no element with key @a key exists.
10414 
10415  The function is basically equivalent to executing
10416  @code {.cpp}
10417  try {
10418  return at(key);
10419  } catch(out_of_range) {
10420  return default_value;
10421  }
10422  @endcode
10423 
10424  @note Unlike @ref at(const typename object_t::key_type&), this function
10425  does not throw if the given key @a key was not found.
10426 
10427  @note Unlike @ref operator[](const typename object_t::key_type& key), this
10428  function does not implicitly add an element to the position defined by @a
10429  key. This function is furthermore also applicable to const objects.
10430 
10431  @param[in] key key of the element to access
10432  @param[in] default_value the value to return if @a key is not found
10433 
10434  @tparam ValueType type compatible to JSON values, for instance `int` for
10435  JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
10436  JSON arrays. Note the type of the expected value at @a key and the default
10437  value @a default_value must be compatible.
10438 
10439  @return copy of the element at key @a key or @a default_value if @a key
10440  is not found
10441 
10442  @throw type_error.306 if the JSON value is not an object; in that case,
10443  using `value()` with a key makes no sense.
10444 
10445  @complexity Logarithmic in the size of the container.
10446 
10447  @liveexample{The example below shows how object elements can be queried
10448  with a default value.,basic_json__value}
10449 
10450  @sa @ref at(const typename object_t::key_type&) for access by reference
10451  with range checking
10452  @sa @ref operator[](const typename object_t::key_type&) for unchecked
10453  access by reference
10454 
10455  @since version 1.0.0
10456  */
10457  template<class ValueType, typename std::enable_if<
10458  std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
10459  ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
10460  {
10461  // at only works for objects
10462  if (JSON_LIKELY(is_object()))
10463  {
10464  // if key is found, return value and given default value otherwise
10465  const auto it = find(key);
10466  if (it != end())
10467  {
10468  return *it;
10469  }
10470 
10471  return default_value;
10472  }
10473 
10474  JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
10475  }
10476 
10477  /*!
10478  @brief overload for a default value of type const char*
10479  @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
10480  */
10481  string_t value(const typename object_t::key_type& key, const char* default_value) const
10482  {
10483  return value(key, string_t(default_value));
10484  }
10485 
10486  /*!
10487  @brief access specified object element via JSON Pointer with default value
10488 
10489  Returns either a copy of an object's element at the specified key @a key
10490  or a given default value if no element with key @a key exists.
10491 
10492  The function is basically equivalent to executing
10493  @code {.cpp}
10494  try {
10495  return at(ptr);
10496  } catch(out_of_range) {
10497  return default_value;
10498  }
10499  @endcode
10500 
10501  @note Unlike @ref at(const json_pointer&), this function does not throw
10502  if the given key @a key was not found.
10503 
10504  @param[in] ptr a JSON pointer to the element to access
10505  @param[in] default_value the value to return if @a ptr found no value
10506 
10507  @tparam ValueType type compatible to JSON values, for instance `int` for
10508  JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
10509  JSON arrays. Note the type of the expected value at @a key and the default
10510  value @a default_value must be compatible.
10511 
10512  @return copy of the element at key @a key or @a default_value if @a key
10513  is not found
10514 
10515  @throw type_error.306 if the JSON value is not an objec; in that case,
10516  using `value()` with a key makes no sense.
10517 
10518  @complexity Logarithmic in the size of the container.
10519 
10520  @liveexample{The example below shows how object elements can be queried
10521  with a default value.,basic_json__value_ptr}
10522 
10523  @sa @ref operator[](const json_pointer&) for unchecked access by reference
10524 
10525  @since version 2.0.2
10526  */
10527  template<class ValueType, typename std::enable_if<
10528  std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
10529  ValueType value(const json_pointer& ptr, const ValueType& default_value) const
10530  {
10531  // at only works for objects
10532  if (JSON_LIKELY(is_object()))
10533  {
10534  // if pointer resolves a value, return it or use default value
10535  JSON_TRY
10536  {
10537  return ptr.get_checked(this);
10538  }
10539  JSON_CATCH (out_of_range&)
10540  {
10541  return default_value;
10542  }
10543  }
10544 
10545  JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
10546  }
10547 
10548  /*!
10549  @brief overload for a default value of type const char*
10550  @copydoc basic_json::value(const json_pointer&, ValueType) const
10551  */
10552  string_t value(const json_pointer& ptr, const char* default_value) const
10553  {
10554  return value(ptr, string_t(default_value));
10555  }
10556 
10557  /*!
10558  @brief access the first element
10559 
10560  Returns a reference to the first element in the container. For a JSON
10561  container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
10562 
10563  @return In case of a structured type (array or object), a reference to the
10564  first element is returned. In case of number, string, or boolean values, a
10565  reference to the value is returned.
10566 
10567  @complexity Constant.
10568 
10569  @pre The JSON value must not be `null` (would throw `std::out_of_range`)
10570  or an empty array or object (undefined behavior, **guarded by
10571  assertions**).
10572  @post The JSON value remains unchanged.
10573 
10574  @throw invalid_iterator.214 when called on `null` value
10575 
10576  @liveexample{The following code shows an example for `front()`.,front}
10577 
10578  @sa @ref back() -- access the last element
10579 
10580  @since version 1.0.0
10581  */
10582  reference front()
10583  {
10584  return *begin();
10585  }
10586 
10587  /*!
10588  @copydoc basic_json::front()
10589  */
10590  const_reference front() const
10591  {
10592  return *cbegin();
10593  }
10594 
10595  /*!
10596  @brief access the last element
10597 
10598  Returns a reference to the last element in the container. For a JSON
10599  container `c`, the expression `c.back()` is equivalent to
10600  @code {.cpp}
10601  auto tmp = c.end();
10602  --tmp;
10603  return *tmp;
10604  @endcode
10605 
10606  @return In case of a structured type (array or object), a reference to the
10607  last element is returned. In case of number, string, or boolean values, a
10608  reference to the value is returned.
10609 
10610  @complexity Constant.
10611 
10612  @pre The JSON value must not be `null` (would throw `std::out_of_range`)
10613  or an empty array or object (undefined behavior, **guarded by
10614  assertions**).
10615  @post The JSON value remains unchanged.
10616 
10617  @throw invalid_iterator.214 when called on a `null` value. See example
10618  below.
10619 
10620  @liveexample{The following code shows an example for `back()`.,back}
10621 
10622  @sa @ref front() -- access the first element
10623 
10624  @since version 1.0.0
10625  */
10626  reference back()
10627  {
10628  auto tmp = end();
10629  --tmp;
10630  return *tmp;
10631  }
10632 
10633  /*!
10634  @copydoc basic_json::back()
10635  */
10636  const_reference back() const
10637  {
10638  auto tmp = cend();
10639  --tmp;
10640  return *tmp;
10641  }
10642 
10643  /*!
10644  @brief remove element given an iterator
10645 
10646  Removes the element specified by iterator @a pos. The iterator @a pos must
10647  be valid and dereferenceable. Thus the `end()` iterator (which is valid,
10648  but is not dereferenceable) cannot be used as a value for @a pos.
10649 
10650  If called on a primitive type other than `null`, the resulting JSON value
10651  will be `null`.
10652 
10653  @param[in] pos iterator to the element to remove
10654  @return Iterator following the last removed element. If the iterator @a
10655  pos refers to the last element, the `end()` iterator is returned.
10656 
10657  @tparam IteratorType an @ref iterator or @ref const_iterator
10658 
10659  @post Invalidates iterators and references at or after the point of the
10660  erase, including the `end()` iterator.
10661 
10662  @throw type_error.307 if called on a `null` value; example: `"cannot use
10663  erase() with null"`
10664  @throw invalid_iterator.202 if called on an iterator which does not belong
10665  to the current JSON value; example: `"iterator does not fit current
10666  value"`
10667  @throw invalid_iterator.205 if called on a primitive type with invalid
10668  iterator (i.e., any iterator which is not `begin()`); example: `"iterator
10669  out of range"`
10670 
10671  @complexity The complexity depends on the type:
10672  - objects: amortized constant
10673  - arrays: linear in distance between @a pos and the end of the container
10674  - strings: linear in the length of the string
10675  - other types: constant
10676 
10677  @liveexample{The example shows the result of `erase()` for different JSON
10678  types.,erase__IteratorType}
10679 
10680  @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
10681  the given range
10682  @sa @ref erase(const typename object_t::key_type&) -- removes the element
10683  from an object at the given key
10684  @sa @ref erase(const size_type) -- removes the element from an array at
10685  the given index
10686 
10687  @since version 1.0.0
10688  */
10689  template<class IteratorType, typename std::enable_if<
10690  std::is_same<IteratorType, typename basic_json_t::iterator>::value or
10691  std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
10692  = 0>
10693  IteratorType erase(IteratorType pos)
10694  {
10695  // make sure iterator fits the current value
10696  if (JSON_UNLIKELY(this != pos.m_object))
10697  {
10698  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
10699  }
10700 
10701  IteratorType result = end();
10702 
10703  switch (m_type)
10704  {
10705  case value_t::boolean:
10706  case value_t::number_float:
10707  case value_t::number_integer:
10708  case value_t::number_unsigned:
10709  case value_t::string:
10710  {
10711  if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
10712  {
10713  JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
10714  }
10715 
10716  if (is_string())
10717  {
10718  AllocatorType<string_t> alloc;
10719  std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
10720  std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
10721  m_value.string = nullptr;
10722  }
10723 
10724  m_type = value_t::null;
10725  assert_invariant();
10726  break;
10727  }
10728 
10729  case value_t::object:
10730  {
10731  result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
10732  break;
10733  }
10734 
10735  case value_t::array:
10736  {
10737  result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
10738  break;
10739  }
10740 
10741  default:
10742  JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
10743  }
10744 
10745  return result;
10746  }
10747 
10748  /*!
10749  @brief remove elements given an iterator range
10750 
10751  Removes the element specified by the range `[first; last)`. The iterator
10752  @a first does not need to be dereferenceable if `first == last`: erasing
10753  an empty range is a no-op.
10754 
10755  If called on a primitive type other than `null`, the resulting JSON value
10756  will be `null`.
10757 
10758  @param[in] first iterator to the beginning of the range to remove
10759  @param[in] last iterator past the end of the range to remove
10760  @return Iterator following the last removed element. If the iterator @a
10761  second refers to the last element, the `end()` iterator is returned.
10762 
10763  @tparam IteratorType an @ref iterator or @ref const_iterator
10764 
10765  @post Invalidates iterators and references at or after the point of the
10766  erase, including the `end()` iterator.
10767 
10768  @throw type_error.307 if called on a `null` value; example: `"cannot use
10769  erase() with null"`
10770  @throw invalid_iterator.203 if called on iterators which does not belong
10771  to the current JSON value; example: `"iterators do not fit current value"`
10772  @throw invalid_iterator.204 if called on a primitive type with invalid
10773  iterators (i.e., if `first != begin()` and `last != end()`); example:
10774  `"iterators out of range"`
10775 
10776  @complexity The complexity depends on the type:
10777  - objects: `log(size()) + std::distance(first, last)`
10778  - arrays: linear in the distance between @a first and @a last, plus linear
10779  in the distance between @a last and end of the container
10780  - strings: linear in the length of the string
10781  - other types: constant
10782 
10783  @liveexample{The example shows the result of `erase()` for different JSON
10784  types.,erase__IteratorType_IteratorType}
10786  @sa @ref erase(IteratorType) -- removes the element at a given position
10787  @sa @ref erase(const typename object_t::key_type&) -- removes the element
10788  from an object at the given key
10789  @sa @ref erase(const size_type) -- removes the element from an array at
10790  the given index
10791 
10792  @since version 1.0.0
10793  */
10794  template<class IteratorType, typename std::enable_if<
10795  std::is_same<IteratorType, typename basic_json_t::iterator>::value or
10796  std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
10797  = 0>
10798  IteratorType erase(IteratorType first, IteratorType last)
10799  {
10800  // make sure iterator fits the current value
10801  if (JSON_UNLIKELY(this != first.m_object or this != last.m_object))
10802  {
10803  JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
10804  }
10805 
10806  IteratorType result = end();
10807 
10808  switch (m_type)
10809  {
10810  case value_t::boolean:
10811  case value_t::number_float:
10812  case value_t::number_integer:
10813  case value_t::number_unsigned:
10814  case value_t::string:
10815  {
10816  if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin()
10817  or not last.m_it.primitive_iterator.is_end()))
10818  {
10819  JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
10820  }
10821 
10822  if (is_string())
10823  {
10824  AllocatorType<string_t> alloc;
10825  std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
10826  std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
10827  m_value.string = nullptr;
10828  }
10829 
10830  m_type = value_t::null;
10831  assert_invariant();
10832  break;
10833  }
10834 
10835  case value_t::object:
10836  {
10837  result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
10838  last.m_it.object_iterator);
10839  break;
10840  }
10841 
10842  case value_t::array:
10843  {
10844  result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
10845  last.m_it.array_iterator);
10846  break;
10847  }
10848 
10849  default:
10850  JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
10851  }
10852 
10853  return result;
10854  }
10855 
10856  /*!
10857  @brief remove element from a JSON object given a key
10858 
10859  Removes elements from a JSON object with the key value @a key.
10860 
10861  @param[in] key value of the elements to remove
10862 
10863  @return Number of elements removed. If @a ObjectType is the default
10864  `std::map` type, the return value will always be `0` (@a key was not
10865  found) or `1` (@a key was found).
10866 
10867  @post References and iterators to the erased elements are invalidated.
10868  Other references and iterators are not affected.
10869 
10870  @throw type_error.307 when called on a type other than JSON object;
10871  example: `"cannot use erase() with null"`
10872 
10873  @complexity `log(size()) + count(key)`
10874 
10875  @liveexample{The example shows the effect of `erase()`.,erase__key_type}
10876 
10877  @sa @ref erase(IteratorType) -- removes the element at a given position
10878  @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
10879  the given range
10880  @sa @ref erase(const size_type) -- removes the element from an array at
10881  the given index
10882 
10883  @since version 1.0.0
10884  */
10885  size_type erase(const typename object_t::key_type& key)
10886  {
10887  // this erase only works for objects
10888  if (JSON_LIKELY(is_object()))
10889  {
10890  return m_value.object->erase(key);
10891  }
10892 
10893  JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
10894  }
10895 
10896  /*!
10897  @brief remove element from a JSON array given an index
10898 
10899  Removes element from a JSON array at the index @a idx.
10900 
10901  @param[in] idx index of the element to remove
10902 
10903  @throw type_error.307 when called on a type other than JSON object;
10904  example: `"cannot use erase() with null"`
10905  @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
10906  is out of range"`
10907 
10908  @complexity Linear in distance between @a idx and the end of the container.
10909 
10910  @liveexample{The example shows the effect of `erase()`.,erase__size_type}
10911 
10912  @sa @ref erase(IteratorType) -- removes the element at a given position
10913  @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
10914  the given range
10915  @sa @ref erase(const typename object_t::key_type&) -- removes the element
10916  from an object at the given key
10917 
10918  @since version 1.0.0
10919  */
10920  void erase(const size_type idx)
10921  {
10922  // this erase only works for arrays
10923  if (JSON_LIKELY(is_array()))
10924  {
10925  if (JSON_UNLIKELY(idx >= size()))
10926  {
10927  JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
10928  }
10929 
10930  m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
10931  }
10932  else
10933  {
10934  JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
10935  }
10936  }
10937 
10938  /// @}
10939 
10940 
10941  ////////////
10942  // lookup //
10943  ////////////
10944 
10945  /// @name lookup
10946  /// @{
10947 
10948  /*!
10949  @brief find an element in a JSON object
10950 
10951  Finds an element in a JSON object with key equivalent to @a key. If the
10952  element is not found or the JSON value is not an object, end() is
10953  returned.
10954 
10955  @note This method always returns @ref end() when executed on a JSON type
10956  that is not an object.
10957 
10958  @param[in] key key value of the element to search for.
10959 
10960  @return Iterator to an element with key equivalent to @a key. If no such
10961  element is found or the JSON value is not an object, past-the-end (see
10962  @ref end()) iterator is returned.
10963 
10964  @complexity Logarithmic in the size of the JSON object.
10965 
10966  @liveexample{The example shows how `find()` is used.,find__key_type}
10967 
10968  @since version 1.0.0
10969  */
10970  template<typename KeyT>
10971  iterator find(KeyT&& key)
10972  {
10973  auto result = end();
10974 
10975  if (is_object())
10976  {
10977  result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
10978  }
10979 
10980  return result;
10981  }
10982 
10983  /*!
10984  @brief find an element in a JSON object
10985  @copydoc find(KeyT&&)
10986  */
10987  template<typename KeyT>
10988  const_iterator find(KeyT&& key) const
10989  {
10990  auto result = cend();
10991 
10992  if (is_object())
10993  {
10994  result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
10995  }
10996 
10997  return result;
10998  }
10999 
11000  /*!
11001  @brief returns the number of occurrences of a key in a JSON object
11002 
11003  Returns the number of elements with key @a key. If ObjectType is the
11004  default `std::map` type, the return value will always be `0` (@a key was
11005  not found) or `1` (@a key was found).
11006 
11007  @note This method always returns `0` when executed on a JSON type that is
11008  not an object.
11009 
11010  @param[in] key key value of the element to count
11011 
11012  @return Number of elements with key @a key. If the JSON value is not an
11013  object, the return value will be `0`.
11014 
11015  @complexity Logarithmic in the size of the JSON object.
11016 
11017  @liveexample{The example shows how `count()` is used.,count}
11018 
11019  @since version 1.0.0
11020  */
11021  template<typename KeyT>
11022  size_type count(KeyT&& key) const
11023  {
11024  // return 0 for all nonobject types
11025  return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
11026  }
11027 
11028  /// @}
11029 
11030 
11031  ///////////////
11032  // iterators //
11033  ///////////////
11034 
11035  /// @name iterators
11036  /// @{
11037 
11038  /*!
11039  @brief returns an iterator to the first element
11040 
11041  Returns an iterator to the first element.
11042 
11043  @image html range-begin-end.svg "Illustration from cppreference.com"
11044 
11045  @return iterator to the first element
11046 
11047  @complexity Constant.
11048 
11049  @requirement This function helps `basic_json` satisfying the
11050  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11051  requirements:
11052  - The complexity is constant.
11053 
11054  @liveexample{The following code shows an example for `begin()`.,begin}
11055 
11056  @sa @ref cbegin() -- returns a const iterator to the beginning
11057  @sa @ref end() -- returns an iterator to the end
11058  @sa @ref cend() -- returns a const iterator to the end
11059 
11060  @since version 1.0.0
11061  */
11062  iterator begin() noexcept
11063  {
11064  iterator result(this);
11065  result.set_begin();
11066  return result;
11067  }
11068 
11069  /*!
11070  @copydoc basic_json::cbegin()
11071  */
11072  const_iterator begin() const noexcept
11073  {
11074  return cbegin();
11075  }
11076 
11077  /*!
11078  @brief returns a const iterator to the first element
11079 
11080  Returns a const iterator to the first element.
11081 
11082  @image html range-begin-end.svg "Illustration from cppreference.com"
11083 
11084  @return const iterator to the first element
11085 
11086  @complexity Constant.
11087 
11088  @requirement This function helps `basic_json` satisfying the
11089  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11090  requirements:
11091  - The complexity is constant.
11092  - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
11093 
11094  @liveexample{The following code shows an example for `cbegin()`.,cbegin}
11095 
11096  @sa @ref begin() -- returns an iterator to the beginning
11097  @sa @ref end() -- returns an iterator to the end
11098  @sa @ref cend() -- returns a const iterator to the end
11099 
11100  @since version 1.0.0
11101  */
11102  const_iterator cbegin() const noexcept
11103  {
11104  const_iterator result(this);
11105  result.set_begin();
11106  return result;
11107  }
11108 
11109  /*!
11110  @brief returns an iterator to one past the last element
11111 
11112  Returns an iterator to one past the last element.
11113 
11114  @image html range-begin-end.svg "Illustration from cppreference.com"
11115 
11116  @return iterator one past the last element
11117 
11118  @complexity Constant.
11119 
11120  @requirement This function helps `basic_json` satisfying the
11121  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11122  requirements:
11123  - The complexity is constant.
11124 
11125  @liveexample{The following code shows an example for `end()`.,end}
11126 
11127  @sa @ref cend() -- returns a const iterator to the end
11128  @sa @ref begin() -- returns an iterator to the beginning
11129  @sa @ref cbegin() -- returns a const iterator to the beginning
11130 
11131  @since version 1.0.0
11132  */
11133  iterator end() noexcept
11134  {
11135  iterator result(this);
11136  result.set_end();
11137  return result;
11138  }
11139 
11140  /*!
11141  @copydoc basic_json::cend()
11142  */
11143  const_iterator end() const noexcept
11144  {
11145  return cend();
11146  }
11147 
11148  /*!
11149  @brief returns a const iterator to one past the last element
11150 
11151  Returns a const iterator to one past the last element.
11152 
11153  @image html range-begin-end.svg "Illustration from cppreference.com"
11154 
11155  @return const iterator one past the last element
11156 
11157  @complexity Constant.
11158 
11159  @requirement This function helps `basic_json` satisfying the
11160  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11161  requirements:
11162  - The complexity is constant.
11163  - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
11164 
11165  @liveexample{The following code shows an example for `cend()`.,cend}
11166 
11167  @sa @ref end() -- returns an iterator to the end
11168  @sa @ref begin() -- returns an iterator to the beginning
11169  @sa @ref cbegin() -- returns a const iterator to the beginning
11170 
11171  @since version 1.0.0
11172  */
11173  const_iterator cend() const noexcept
11174  {
11175  const_iterator result(this);
11176  result.set_end();
11177  return result;
11178  }
11179 
11180  /*!
11181  @brief returns an iterator to the reverse-beginning
11182 
11183  Returns an iterator to the reverse-beginning; that is, the last element.
11184 
11185  @image html range-rbegin-rend.svg "Illustration from cppreference.com"
11186 
11187  @complexity Constant.
11188 
11189  @requirement This function helps `basic_json` satisfying the
11190  [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
11191  requirements:
11192  - The complexity is constant.
11193  - Has the semantics of `reverse_iterator(end())`.
11194 
11195  @liveexample{The following code shows an example for `rbegin()`.,rbegin}
11196 
11197  @sa @ref crbegin() -- returns a const reverse iterator to the beginning
11198  @sa @ref rend() -- returns a reverse iterator to the end
11199  @sa @ref crend() -- returns a const reverse iterator to the end
11200 
11201  @since version 1.0.0
11202  */
11203  reverse_iterator rbegin() noexcept
11204  {
11205  return reverse_iterator(end());
11206  }
11207 
11208  /*!
11209  @copydoc basic_json::crbegin()
11210  */
11211  const_reverse_iterator rbegin() const noexcept
11212  {
11213  return crbegin();
11214  }
11215 
11216  /*!
11217  @brief returns an iterator to the reverse-end
11218 
11219  Returns an iterator to the reverse-end; that is, one before the first
11220  element.
11221 
11222  @image html range-rbegin-rend.svg "Illustration from cppreference.com"
11223 
11224  @complexity Constant.
11225 
11226  @requirement This function helps `basic_json` satisfying the
11227  [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
11228  requirements:
11229  - The complexity is constant.
11230  - Has the semantics of `reverse_iterator(begin())`.
11231 
11232  @liveexample{The following code shows an example for `rend()`.,rend}
11233 
11234  @sa @ref crend() -- returns a const reverse iterator to the end
11235  @sa @ref rbegin() -- returns a reverse iterator to the beginning
11236  @sa @ref crbegin() -- returns a const reverse iterator to the beginning
11237 
11238  @since version 1.0.0
11239  */
11240  reverse_iterator rend() noexcept
11241  {
11242  return reverse_iterator(begin());
11243  }
11244 
11245  /*!
11246  @copydoc basic_json::crend()
11247  */
11248  const_reverse_iterator rend() const noexcept
11249  {
11250  return crend();
11251  }
11252 
11253  /*!
11254  @brief returns a const reverse iterator to the last element
11255 
11256  Returns a const iterator to the reverse-beginning; that is, the last
11257  element.
11258 
11259  @image html range-rbegin-rend.svg "Illustration from cppreference.com"
11260 
11261  @complexity Constant.
11262 
11263  @requirement This function helps `basic_json` satisfying the
11264  [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
11265  requirements:
11266  - The complexity is constant.
11267  - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
11268 
11269  @liveexample{The following code shows an example for `crbegin()`.,crbegin}
11270 
11271  @sa @ref rbegin() -- returns a reverse iterator to the beginning
11272  @sa @ref rend() -- returns a reverse iterator to the end
11273  @sa @ref crend() -- returns a const reverse iterator to the end
11274 
11275  @since version 1.0.0
11276  */
11277  const_reverse_iterator crbegin() const noexcept
11278  {
11279  return const_reverse_iterator(cend());
11280  }
11281 
11282  /*!
11283  @brief returns a const reverse iterator to one before the first
11284 
11285  Returns a const reverse iterator to the reverse-end; that is, one before
11286  the first element.
11287 
11288  @image html range-rbegin-rend.svg "Illustration from cppreference.com"
11289 
11290  @complexity Constant.
11291 
11292  @requirement This function helps `basic_json` satisfying the
11293  [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
11294  requirements:
11295  - The complexity is constant.
11296  - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
11297 
11298  @liveexample{The following code shows an example for `crend()`.,crend}
11299 
11300  @sa @ref rend() -- returns a reverse iterator to the end
11301  @sa @ref rbegin() -- returns a reverse iterator to the beginning
11302  @sa @ref crbegin() -- returns a const reverse iterator to the beginning
11303 
11304  @since version 1.0.0
11305  */
11306  const_reverse_iterator crend() const noexcept
11307  {
11308  return const_reverse_iterator(cbegin());
11309  }
11310 
11311  public:
11312  /*!
11313  @brief wrapper to access iterator member functions in range-based for
11314 
11315  This function allows to access @ref iterator::key() and @ref
11316  iterator::value() during range-based for loops. In these loops, a
11317  reference to the JSON values is returned, so there is no access to the
11318  underlying iterator.
11319 
11320  For loop without iterator_wrapper:
11321 
11322  @code{cpp}
11323  for (auto it = j_object.begin(); it != j_object.end(); ++it)
11324  {
11325  std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
11326  }
11327  @endcode
11328 
11329  Range-based for loop without iterator proxy:
11330 
11331  @code{cpp}
11332  for (auto it : j_object)
11333  {
11334  // "it" is of type json::reference and has no key() member
11335  std::cout << "value: " << it << '\n';
11336  }
11337  @endcode
11338 
11339  Range-based for loop with iterator proxy:
11340 
11341  @code{cpp}
11342  for (auto it : json::iterator_wrapper(j_object))
11343  {
11344  std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
11345  }
11346  @endcode
11347 
11348  @note When iterating over an array, `key()` will return the index of the
11349  element as string (see example).
11350 
11351  @param[in] ref reference to a JSON value
11352  @return iteration proxy object wrapping @a ref with an interface to use in
11353  range-based for loops
11354 
11355  @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
11356 
11357  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
11358  changes in the JSON value.
11359 
11360  @complexity Constant.
11361 
11362  @note The name of this function is not yet final and may change in the
11363  future.
11364  */
11365  static iteration_proxy<iterator> iterator_wrapper(reference ref)
11366  {
11367  return iteration_proxy<iterator>(ref);
11368  }
11369 
11370  /*!
11371  @copydoc iterator_wrapper(reference)
11372  */
11373  static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref)
11374  {
11375  return iteration_proxy<const_iterator>(ref);
11376  }
11377 
11378  /*!
11379  @brief helper to access iterator member functions in range-based for
11380 
11381  This function allows to access @ref iterator::key() and @ref
11382  iterator::value() during range-based for loops. In these loops, a
11383  reference to the JSON values is returned, so there is no access to the
11384  underlying iterator.
11385 
11386  For loop without `items()` function:
11387 
11388  @code{cpp}
11389  for (auto it = j_object.begin(); it != j_object.end(); ++it)
11390  {
11391  std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
11392  }
11393  @endcode
11394 
11395  Range-based for loop without `items()` function:
11396 
11397  @code{cpp}
11398  for (auto it : j_object)
11399  {
11400  // "it" is of type json::reference and has no key() member
11401  std::cout << "value: " << it << '\n';
11402  }
11403  @endcode
11404 
11405  Range-based for loop with `items()` function:
11406 
11407  @code{cpp}
11408  for (auto it : j_object.items())
11409  {
11410  std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
11411  }
11412  @endcode
11413 
11414  @note When iterating over an array, `key()` will return the index of the
11415  element as string (see example).
11416 
11417  @return iteration proxy object wrapping @a ref with an interface to use in
11418  range-based for loops
11419 
11420  @liveexample{The following code shows how the function is used.,items}
11421 
11422  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
11423  changes in the JSON value.
11424 
11425  @complexity Constant.
11426  */
11427  iteration_proxy<iterator> items()
11428  {
11429  return iteration_proxy<iterator>(*this);
11430  }
11431 
11432  /*!
11433  @copydoc items()
11434  */
11435  iteration_proxy<const_iterator> items() const
11436  {
11437  return iteration_proxy<const_iterator>(*this);
11438  }
11439 
11440  /// @}
11441 
11442 
11443  //////////////
11444  // capacity //
11445  //////////////
11446 
11447  /// @name capacity
11448  /// @{
11449 
11450  /*!
11451  @brief checks whether the container is empty.
11452 
11453  Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
11454 
11455  @return The return value depends on the different types and is
11456  defined as follows:
11457  Value type | return value
11458  ----------- | -------------
11459  null | `true`
11460  boolean | `false`
11461  string | `false`
11462  number | `false`
11463  object | result of function `object_t::empty()`
11464  array | result of function `array_t::empty()`
11465 
11466  @liveexample{The following code uses `empty()` to check if a JSON
11467  object contains any elements.,empty}
11468 
11469  @complexity Constant, as long as @ref array_t and @ref object_t satisfy
11470  the Container concept; that is, their `empty()` functions have constant
11471  complexity.
11472 
11473  @iterators No changes.
11474 
11475  @exceptionsafety No-throw guarantee: this function never throws exceptions.
11476 
11477  @note This function does not return whether a string stored as JSON value
11478  is empty - it returns whether the JSON container itself is empty which is
11479  false in the case of a string.
11480 
11481  @requirement This function helps `basic_json` satisfying the
11482  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11483  requirements:
11484  - The complexity is constant.
11485  - Has the semantics of `begin() == end()`.
11486 
11487  @sa @ref size() -- returns the number of elements
11488 
11489  @since version 1.0.0
11490  */
11491  bool empty() const noexcept
11492  {
11493  switch (m_type)
11494  {
11495  case value_t::null:
11496  {
11497  // null values are empty
11498  return true;
11499  }
11501  case value_t::array:
11502  {
11503  // delegate call to array_t::empty()
11504  return m_value.array->empty();
11505  }
11506 
11507  case value_t::object:
11508  {
11509  // delegate call to object_t::empty()
11510  return m_value.object->empty();
11511  }
11512 
11513  default:
11514  {
11515  // all other types are nonempty
11516  return false;
11517  }
11518  }
11519  }
11520 
11521  /*!
11522  @brief returns the number of elements
11523 
11524  Returns the number of elements in a JSON value.
11525 
11526  @return The return value depends on the different types and is
11527  defined as follows:
11528  Value type | return value
11529  ----------- | -------------
11530  null | `0`
11531  boolean | `1`
11532  string | `1`
11533  number | `1`
11534  object | result of function object_t::size()
11535  array | result of function array_t::size()
11536 
11537  @liveexample{The following code calls `size()` on the different value
11538  types.,size}
11539 
11540  @complexity Constant, as long as @ref array_t and @ref object_t satisfy
11541  the Container concept; that is, their size() functions have constant
11542  complexity.
11543 
11544  @iterators No changes.
11545 
11546  @exceptionsafety No-throw guarantee: this function never throws exceptions.
11547 
11548  @note This function does not return the length of a string stored as JSON
11549  value - it returns the number of elements in the JSON value which is 1 in
11550  the case of a string.
11551 
11552  @requirement This function helps `basic_json` satisfying the
11553  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11554  requirements:
11555  - The complexity is constant.
11556  - Has the semantics of `std::distance(begin(), end())`.
11557 
11558  @sa @ref empty() -- checks whether the container is empty
11559  @sa @ref max_size() -- returns the maximal number of elements
11560 
11561  @since version 1.0.0
11562  */
11563  size_type size() const noexcept
11564  {
11565  switch (m_type)
11566  {
11567  case value_t::null:
11568  {
11569  // null values are empty
11570  return 0;
11571  }
11572 
11573  case value_t::array:
11574  {
11575  // delegate call to array_t::size()
11576  return m_value.array->size();
11577  }
11578 
11579  case value_t::object:
11580  {
11581  // delegate call to object_t::size()
11582  return m_value.object->size();
11583  }
11584 
11585  default:
11586  {
11587  // all other types have size 1
11588  return 1;
11589  }
11590  }
11591  }
11592 
11593  /*!
11594  @brief returns the maximum possible number of elements
11595 
11596  Returns the maximum number of elements a JSON value is able to hold due to
11597  system or library implementation limitations, i.e. `std::distance(begin(),
11598  end())` for the JSON value.
11599 
11600  @return The return value depends on the different types and is
11601  defined as follows:
11602  Value type | return value
11603  ----------- | -------------
11604  null | `0` (same as `size()`)
11605  boolean | `1` (same as `size()`)
11606  string | `1` (same as `size()`)
11607  number | `1` (same as `size()`)
11608  object | result of function `object_t::max_size()`
11609  array | result of function `array_t::max_size()`
11610 
11611  @liveexample{The following code calls `max_size()` on the different value
11612  types. Note the output is implementation specific.,max_size}
11613 
11614  @complexity Constant, as long as @ref array_t and @ref object_t satisfy
11615  the Container concept; that is, their `max_size()` functions have constant
11616  complexity.
11617 
11618  @iterators No changes.
11619 
11620  @exceptionsafety No-throw guarantee: this function never throws exceptions.
11621 
11622  @requirement This function helps `basic_json` satisfying the
11623  [Container](http://en.cppreference.com/w/cpp/concept/Container)
11624  requirements:
11625  - The complexity is constant.
11626  - Has the semantics of returning `b.size()` where `b` is the largest
11627  possible JSON value.
11628 
11629  @sa @ref size() -- returns the number of elements
11630 
11631  @since version 1.0.0
11632  */
11633  size_type max_size() const noexcept
11634  {
11635  switch (m_type)
11636  {
11637  case value_t::array:
11638  {
11639  // delegate call to array_t::max_size()
11640  return m_value.array->max_size();
11641  }
11642 
11643  case value_t::object:
11644  {
11645  // delegate call to object_t::max_size()
11646  return m_value.object->max_size();
11647  }
11648 
11649  default:
11650  {
11651  // all other types have max_size() == size()
11652  return size();
11653  }
11654  }
11655  }
11656 
11657  /// @}
11658 
11659 
11660  ///////////////
11661  // modifiers //
11662  ///////////////
11663 
11664  /// @name modifiers
11665  /// @{
11666 
11667  /*!
11668  @brief clears the contents
11669 
11670  Clears the content of a JSON value and resets it to the default value as
11671  if @ref basic_json(value_t) would have been called with the current value
11672  type from @ref type():
11673 
11674  Value type | initial value
11675  ----------- | -------------
11676  null | `null`
11677  boolean | `false`
11678  string | `""`
11679  number | `0`
11680  object | `{}`
11681  array | `[]`
11682 
11683  @post Has the same effect as calling
11684  @code {.cpp}
11685  *this = basic_json(type());
11686  @endcode
11687 
11688  @liveexample{The example below shows the effect of `clear()` to different
11689  JSON types.,clear}
11690 
11691  @complexity Linear in the size of the JSON value.
11692 
11693  @iterators All iterators, pointers and references related to this container
11694  are invalidated.
11695 
11696  @exceptionsafety No-throw guarantee: this function never throws exceptions.
11697 
11698  @sa @ref basic_json(value_t) -- constructor that creates an object with the
11699  same value than calling `clear()`
11700 
11701  @since version 1.0.0
11702  */
11703  void clear() noexcept
11704  {
11705  switch (m_type)
11706  {
11707  case value_t::number_integer:
11708  {
11709  m_value.number_integer = 0;
11710  break;
11711  }
11712 
11713  case value_t::number_unsigned:
11714  {
11715  m_value.number_unsigned = 0;
11716  break;
11717  }
11718 
11719  case value_t::number_float:
11720  {
11721  m_value.number_float = 0.0;
11722  break;
11723  }
11724 
11725  case value_t::boolean:
11726  {
11727  m_value.boolean = false;
11728  break;
11729  }
11730 
11731  case value_t::string:
11732  {
11733  m_value.string->clear();
11734  break;
11735  }
11736 
11737  case value_t::array:
11738  {
11739  m_value.array->clear();
11740  break;
11741  }
11742 
11743  case value_t::object:
11744  {
11745  m_value.object->clear();
11746  break;
11747  }
11748 
11749  default:
11750  break;
11751  }
11752  }
11753 
11754  /*!
11755  @brief add an object to an array
11756 
11757  Appends the given element @a val to the end of the JSON value. If the
11758  function is called on a JSON null value, an empty array is created before
11759  appending @a val.
11760 
11761  @param[in] val the value to add to the JSON array
11762 
11763  @throw type_error.308 when called on a type other than JSON array or
11764  null; example: `"cannot use push_back() with number"`
11765 
11766  @complexity Amortized constant.
11767 
11768  @liveexample{The example shows how `push_back()` and `+=` can be used to
11769  add elements to a JSON array. Note how the `null` value was silently
11770  converted to a JSON array.,push_back}
11771 
11772  @since version 1.0.0
11773  */
11774  void push_back(basic_json&& val)
11775  {
11776  // push_back only works for null objects or arrays
11777  if (JSON_UNLIKELY(not(is_null() or is_array())))
11778  {
11779  JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
11780  }
11781 
11782  // transform null object into an array
11783  if (is_null())
11784  {
11785  m_type = value_t::array;
11786  m_value = value_t::array;
11787  assert_invariant();
11788  }
11789 
11790  // add element to array (move semantics)
11791  m_value.array->push_back(std::move(val));
11792  // invalidate object
11793  val.m_type = value_t::null;
11794  }
11795 
11796  /*!
11797  @brief add an object to an array
11798  @copydoc push_back(basic_json&&)
11799  */
11800  reference operator+=(basic_json&& val)
11801  {
11802  push_back(std::move(val));
11803  return *this;
11804  }
11805 
11806  /*!
11807  @brief add an object to an array
11808  @copydoc push_back(basic_json&&)
11809  */
11810  void push_back(const basic_json& val)
11811  {
11812  // push_back only works for null objects or arrays
11813  if (JSON_UNLIKELY(not(is_null() or is_array())))
11814  {
11815  JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
11816  }
11817 
11818  // transform null object into an array
11819  if (is_null())
11820  {
11821  m_type = value_t::array;
11822  m_value = value_t::array;
11823  assert_invariant();
11824  }
11825 
11826  // add element to array
11827  m_value.array->push_back(val);
11828  }
11829 
11830  /*!
11831  @brief add an object to an array
11832  @copydoc push_back(basic_json&&)
11833  */
11834  reference operator+=(const basic_json& val)
11835  {
11836  push_back(val);
11837  return *this;
11838  }
11839 
11840  /*!
11841  @brief add an object to an object
11842 
11843  Inserts the given element @a val to the JSON object. If the function is
11844  called on a JSON null value, an empty object is created before inserting
11845  @a val.
11846 
11847  @param[in] val the value to add to the JSON object
11848 
11849  @throw type_error.308 when called on a type other than JSON object or
11850  null; example: `"cannot use push_back() with number"`
11851 
11852  @complexity Logarithmic in the size of the container, O(log(`size()`)).
11853 
11854  @liveexample{The example shows how `push_back()` and `+=` can be used to
11855  add elements to a JSON object. Note how the `null` value was silently
11856  converted to a JSON object.,push_back__object_t__value}
11857 
11858  @since version 1.0.0
11859  */
11860  void push_back(const typename object_t::value_type& val)
11861  {
11862  // push_back only works for null objects or objects
11863  if (JSON_UNLIKELY(not(is_null() or is_object())))
11864  {
11865  JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
11866  }
11867 
11868  // transform null object into an object
11869  if (is_null())
11870  {
11871  m_type = value_t::object;
11872  m_value = value_t::object;
11873  assert_invariant();
11874  }
11875 
11876  // add element to array
11877  m_value.object->insert(val);
11878  }
11879 
11880  /*!
11881  @brief add an object to an object
11882  @copydoc push_back(const typename object_t::value_type&)
11883  */
11884  reference operator+=(const typename object_t::value_type& val)
11885  {
11886  push_back(val);
11887  return *this;
11888  }
11889 
11890  /*!
11891  @brief add an object to an object
11892 
11893  This function allows to use `push_back` with an initializer list. In case
11894 
11895  1. the current value is an object,
11896  2. the initializer list @a init contains only two elements, and
11897  3. the first element of @a init is a string,
11898 
11899  @a init is converted into an object element and added using
11900  @ref push_back(const typename object_t::value_type&). Otherwise, @a init
11901  is converted to a JSON value and added using @ref push_back(basic_json&&).
11902 
11903  @param[in] init an initializer list
11904 
11905  @complexity Linear in the size of the initializer list @a init.
11906 
11907  @note This function is required to resolve an ambiguous overload error,
11908  because pairs like `{"key", "value"}` can be both interpreted as
11909  `object_t::value_type` or `std::initializer_list<basic_json>`, see
11910  https://github.com/nlohmann/json/issues/235 for more information.
11911 
11912  @liveexample{The example shows how initializer lists are treated as
11913  objects when possible.,push_back__initializer_list}
11914  */
11915  void push_back(initializer_list_t init)
11916  {
11917  if (is_object() and init.size() == 2 and (*init.begin())->is_string())
11918  {
11919  basic_json&& key = init.begin()->moved_or_copied();
11920  push_back(typename object_t::value_type(
11921  std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
11922  }
11923  else
11924  {
11925  push_back(basic_json(init));
11926  }
11927  }
11928 
11929  /*!
11930  @brief add an object to an object
11931  @copydoc push_back(initializer_list_t)
11932  */
11933  reference operator+=(initializer_list_t init)
11934  {
11935  push_back(init);
11936  return *this;
11937  }
11938 
11939  /*!
11940  @brief add an object to an array
11941 
11942  Creates a JSON value from the passed parameters @a args to the end of the
11943  JSON value. If the function is called on a JSON null value, an empty array
11944  is created before appending the value created from @a args.
11945 
11946  @param[in] args arguments to forward to a constructor of @ref basic_json
11947  @tparam Args compatible types to create a @ref basic_json object
11948 
11949  @throw type_error.311 when called on a type other than JSON array or
11950  null; example: `"cannot use emplace_back() with number"`
11951 
11952  @complexity Amortized constant.
11953 
11954  @liveexample{The example shows how `push_back()` can be used to add
11955  elements to a JSON array. Note how the `null` value was silently converted
11956  to a JSON array.,emplace_back}
11957 
11958  @since version 2.0.8
11959  */
11960  template<class... Args>
11961  void emplace_back(Args&& ... args)
11962  {
11963  // emplace_back only works for null objects or arrays
11964  if (JSON_UNLIKELY(not(is_null() or is_array())))
11965  {
11966  JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
11967  }
11968 
11969  // transform null object into an array
11970  if (is_null())
11971  {
11972  m_type = value_t::array;
11973  m_value = value_t::array;
11974  assert_invariant();
11975  }
11976 
11977  // add element to array (perfect forwarding)
11978  m_value.array->emplace_back(std::forward<Args>(args)...);
11979  }
11980 
11981  /*!
11982  @brief add an object to an object if key does not exist
11983 
11984  Inserts a new element into a JSON object constructed in-place with the
11985  given @a args if there is no element with the key in the container. If the
11986  function is called on a JSON null value, an empty object is created before
11987  appending the value created from @a args.
11989  @param[in] args arguments to forward to a constructor of @ref basic_json
11990  @tparam Args compatible types to create a @ref basic_json object
11991 
11992  @return a pair consisting of an iterator to the inserted element, or the
11993  already-existing element if no insertion happened, and a bool
11994  denoting whether the insertion took place.
11995 
11996  @throw type_error.311 when called on a type other than JSON object or
11997  null; example: `"cannot use emplace() with number"`
11998 
11999  @complexity Logarithmic in the size of the container, O(log(`size()`)).
12000 
12001  @liveexample{The example shows how `emplace()` can be used to add elements
12002  to a JSON object. Note how the `null` value was silently converted to a
12003  JSON object. Further note how no value is added if there was already one
12004  value stored with the same key.,emplace}
12005 
12006  @since version 2.0.8
12007  */
12008  template<class... Args>
12009  std::pair<iterator, bool> emplace(Args&& ... args)
12010  {
12011  // emplace only works for null objects or arrays
12012  if (JSON_UNLIKELY(not(is_null() or is_object())))
12013  {
12014  JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
12015  }
12016 
12017  // transform null object into an object
12018  if (is_null())
12019  {
12020  m_type = value_t::object;
12021  m_value = value_t::object;
12022  assert_invariant();
12023  }
12024 
12025  // add element to array (perfect forwarding)
12026  auto res = m_value.object->emplace(std::forward<Args>(args)...);
12027  // create result iterator and set iterator to the result of emplace
12028  auto it = begin();
12029  it.m_it.object_iterator = res.first;
12030 
12031  // return pair of iterator and boolean
12032  return {it, res.second};
12033  }
12034 
12035  /*!
12036  @brief inserts element
12037 
12038  Inserts element @a val before iterator @a pos.
12039 
12040  @param[in] pos iterator before which the content will be inserted; may be
12041  the end() iterator
12042  @param[in] val element to insert
12043  @return iterator pointing to the inserted @a val.
12044 
12045  @throw type_error.309 if called on JSON values other than arrays;
12046  example: `"cannot use insert() with string"`
12047  @throw invalid_iterator.202 if @a pos is not an iterator of *this;
12048  example: `"iterator does not fit current value"`
12049 
12050  @complexity Constant plus linear in the distance between @a pos and end of
12051  the container.
12052 
12053  @liveexample{The example shows how `insert()` is used.,insert}
12054 
12055  @since version 1.0.0
12056  */
12057  iterator insert(const_iterator pos, const basic_json& val)
12058  {
12059  // insert only works for arrays
12060  if (JSON_LIKELY(is_array()))
12061  {
12062  // check if iterator pos fits to this JSON value
12063  if (JSON_UNLIKELY(pos.m_object != this))
12064  {
12065  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
12066  }
12067 
12068  // insert to array and return iterator
12069  iterator result(this);
12070  result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
12071  return result;
12072  }
12073 
12074  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12075  }
12076 
12077  /*!
12078  @brief inserts element
12079  @copydoc insert(const_iterator, const basic_json&)
12080  */
12081  iterator insert(const_iterator pos, basic_json&& val)
12082  {
12083  return insert(pos, val);
12084  }
12085 
12086  /*!
12087  @brief inserts elements
12088 
12089  Inserts @a cnt copies of @a val before iterator @a pos.
12090 
12091  @param[in] pos iterator before which the content will be inserted; may be
12092  the end() iterator
12093  @param[in] cnt number of copies of @a val to insert
12094  @param[in] val element to insert
12095  @return iterator pointing to the first element inserted, or @a pos if
12096  `cnt==0`
12097 
12098  @throw type_error.309 if called on JSON values other than arrays; example:
12099  `"cannot use insert() with string"`
12100  @throw invalid_iterator.202 if @a pos is not an iterator of *this;
12101  example: `"iterator does not fit current value"`
12102 
12103  @complexity Linear in @a cnt plus linear in the distance between @a pos
12104  and end of the container.
12105 
12106  @liveexample{The example shows how `insert()` is used.,insert__count}
12107 
12108  @since version 1.0.0
12109  */
12110  iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
12111  {
12112  // insert only works for arrays
12113  if (JSON_LIKELY(is_array()))
12114  {
12115  // check if iterator pos fits to this JSON value
12116  if (JSON_UNLIKELY(pos.m_object != this))
12117  {
12118  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
12119  }
12120 
12121  // insert to array and return iterator
12122  iterator result(this);
12123  result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
12124  return result;
12125  }
12126 
12127  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12128  }
12129 
12130  /*!
12131  @brief inserts elements
12132 
12133  Inserts elements from range `[first, last)` before iterator @a pos.
12134 
12135  @param[in] pos iterator before which the content will be inserted; may be
12136  the end() iterator
12137  @param[in] first begin of the range of elements to insert
12138  @param[in] last end of the range of elements to insert
12139 
12140  @throw type_error.309 if called on JSON values other than arrays; example:
12141  `"cannot use insert() with string"`
12142  @throw invalid_iterator.202 if @a pos is not an iterator of *this;
12143  example: `"iterator does not fit current value"`
12144  @throw invalid_iterator.210 if @a first and @a last do not belong to the
12145  same JSON value; example: `"iterators do not fit"`
12146  @throw invalid_iterator.211 if @a first or @a last are iterators into
12147  container for which insert is called; example: `"passed iterators may not
12148  belong to container"`
12149 
12150  @return iterator pointing to the first element inserted, or @a pos if
12151  `first==last`
12152 
12153  @complexity Linear in `std::distance(first, last)` plus linear in the
12154  distance between @a pos and end of the container.
12155 
12156  @liveexample{The example shows how `insert()` is used.,insert__range}
12157 
12158  @since version 1.0.0
12159  */
12160  iterator insert(const_iterator pos, const_iterator first, const_iterator last)
12161  {
12162  // insert only works for arrays
12163  if (JSON_UNLIKELY(not is_array()))
12164  {
12165  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12166  }
12167 
12168  // check if iterator pos fits to this JSON value
12169  if (JSON_UNLIKELY(pos.m_object != this))
12170  {
12171  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
12172  }
12173 
12174  // check if range iterators belong to the same JSON object
12175  if (JSON_UNLIKELY(first.m_object != last.m_object))
12176  {
12177  JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
12178  }
12179 
12180  if (JSON_UNLIKELY(first.m_object == this))
12181  {
12182  JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
12183  }
12184 
12185  // insert to array and return iterator
12186  iterator result(this);
12187  result.m_it.array_iterator = m_value.array->insert(
12188  pos.m_it.array_iterator,
12189  first.m_it.array_iterator,
12190  last.m_it.array_iterator);
12191  return result;
12192  }
12193 
12194  /*!
12195  @brief inserts elements
12196 
12197  Inserts elements from initializer list @a ilist before iterator @a pos.
12198 
12199  @param[in] pos iterator before which the content will be inserted; may be
12200  the end() iterator
12201  @param[in] ilist initializer list to insert the values from
12202 
12203  @throw type_error.309 if called on JSON values other than arrays; example:
12204  `"cannot use insert() with string"`
12205  @throw invalid_iterator.202 if @a pos is not an iterator of *this;
12206  example: `"iterator does not fit current value"`
12207 
12208  @return iterator pointing to the first element inserted, or @a pos if
12209  `ilist` is empty
12210 
12211  @complexity Linear in `ilist.size()` plus linear in the distance between
12212  @a pos and end of the container.
12213 
12214  @liveexample{The example shows how `insert()` is used.,insert__ilist}
12215 
12216  @since version 1.0.0
12217  */
12218  iterator insert(const_iterator pos, initializer_list_t ilist)
12219  {
12220  // insert only works for arrays
12221  if (JSON_UNLIKELY(not is_array()))
12222  {
12223  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12224  }
12225 
12226  // check if iterator pos fits to this JSON value
12227  if (JSON_UNLIKELY(pos.m_object != this))
12228  {
12229  JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
12230  }
12231 
12232  // insert to array and return iterator
12233  iterator result(this);
12234  result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end());
12235  return result;
12236  }
12237 
12238  /*!
12239  @brief inserts elements
12240 
12241  Inserts elements from range `[first, last)`.
12242 
12243  @param[in] first begin of the range of elements to insert
12244  @param[in] last end of the range of elements to insert
12246  @throw type_error.309 if called on JSON values other than objects; example:
12247  `"cannot use insert() with string"`
12248  @throw invalid_iterator.202 if iterator @a first or @a last does does not
12249  point to an object; example: `"iterators first and last must point to
12250  objects"`
12251  @throw invalid_iterator.210 if @a first and @a last do not belong to the
12252  same JSON value; example: `"iterators do not fit"`
12253 
12254  @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
12255  of elements to insert.
12256 
12257  @liveexample{The example shows how `insert()` is used.,insert__range_object}
12258 
12259  @since version 3.0.0
12260  */
12261  void insert(const_iterator first, const_iterator last)
12262  {
12263  // insert only works for objects
12264  if (JSON_UNLIKELY(not is_object()))
12265  {
12266  JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
12267  }
12268 
12269  // check if range iterators belong to the same JSON object
12270  if (JSON_UNLIKELY(first.m_object != last.m_object))
12271  {
12272  JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
12273  }
12274 
12275  // passed iterators must belong to objects
12276  if (JSON_UNLIKELY(not first.m_object->is_object()))
12277  {
12278  JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
12279  }
12280 
12281  m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
12282  }
12283 
12284  /*!
12285  @brief updates a JSON object from another object, overwriting existing keys
12286 
12287  Inserts all values from JSON object @a j and overwrites existing keys.
12288 
12289  @param[in] j JSON object to read values from
12290 
12291  @throw type_error.312 if called on JSON values other than objects; example:
12292  `"cannot use update() with string"`
12293 
12294  @complexity O(N*log(size() + N)), where N is the number of elements to
12295  insert.
12296 
12297  @liveexample{The example shows how `update()` is used.,update}
12298 
12299  @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
12300 
12301  @since version 3.0.0
12302  */
12303  void update(const_reference j)
12304  {
12305  // implicitly convert null value to an empty object
12306  if (is_null())
12307  {
12308  m_type = value_t::object;
12309  m_value.object = create<object_t>();
12310  assert_invariant();
12311  }
12312 
12313  if (JSON_UNLIKELY(not is_object()))
12314  {
12315  JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
12316  }
12317  if (JSON_UNLIKELY(not j.is_object()))
12318  {
12319  JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
12320  }
12321 
12322  for (auto it = j.cbegin(); it != j.cend(); ++it)
12323  {
12324  m_value.object->operator[](it.key()) = it.value();
12325  }
12326  }
12327 
12328  /*!
12329  @brief updates a JSON object from another object, overwriting existing keys
12330 
12331  Inserts all values from from range `[first, last)` and overwrites existing
12332  keys.
12333 
12334  @param[in] first begin of the range of elements to insert
12335  @param[in] last end of the range of elements to insert
12336 
12337  @throw type_error.312 if called on JSON values other than objects; example:
12338  `"cannot use update() with string"`
12339  @throw invalid_iterator.202 if iterator @a first or @a last does does not
12340  point to an object; example: `"iterators first and last must point to
12341  objects"`
12342  @throw invalid_iterator.210 if @a first and @a last do not belong to the
12343  same JSON value; example: `"iterators do not fit"`
12344 
12345  @complexity O(N*log(size() + N)), where N is the number of elements to
12346  insert.
12347 
12348  @liveexample{The example shows how `update()` is used__range.,update}
12349 
12350  @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
12351 
12352  @since version 3.0.0
12353  */
12354  void update(const_iterator first, const_iterator last)
12355  {
12356  // implicitly convert null value to an empty object
12357  if (is_null())
12358  {
12359  m_type = value_t::object;
12360  m_value.object = create<object_t>();
12361  assert_invariant();
12362  }
12363 
12364  if (JSON_UNLIKELY(not is_object()))
12365  {
12366  JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
12367  }
12368 
12369  // check if range iterators belong to the same JSON object
12370  if (JSON_UNLIKELY(first.m_object != last.m_object))
12371  {
12372  JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
12373  }
12374 
12375  // passed iterators must belong to objects
12376  if (JSON_UNLIKELY(not first.m_object->is_object()
12377  or not first.m_object->is_object()))
12378  {
12379  JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
12380  }
12381 
12382  for (auto it = first; it != last; ++it)
12383  {
12384  m_value.object->operator[](it.key()) = it.value();
12385  }
12386  }
12387 
12388  /*!
12389  @brief exchanges the values
12390 
12391  Exchanges the contents of the JSON value with those of @a other. Does not
12392  invoke any move, copy, or swap operations on individual elements. All
12393  iterators and references remain valid. The past-the-end iterator is
12394  invalidated.
12395 
12396  @param[in,out] other JSON value to exchange the contents with
12397 
12398  @complexity Constant.
12399 
12400  @liveexample{The example below shows how JSON values can be swapped with
12401  `swap()`.,swap__reference}
12402 
12403  @since version 1.0.0
12404  */
12405  void swap(reference other) noexcept (
12406  std::is_nothrow_move_constructible<value_t>::value and
12407  std::is_nothrow_move_assignable<value_t>::value and
12408  std::is_nothrow_move_constructible<json_value>::value and
12409  std::is_nothrow_move_assignable<json_value>::value
12410  )
12411  {
12412  std::swap(m_type, other.m_type);
12413  std::swap(m_value, other.m_value);
12414  assert_invariant();
12415  }
12416 
12417  /*!
12418  @brief exchanges the values
12419 
12420  Exchanges the contents of a JSON array with those of @a other. Does not
12421  invoke any move, copy, or swap operations on individual elements. All
12422  iterators and references remain valid. The past-the-end iterator is
12423  invalidated.
12424 
12425  @param[in,out] other array to exchange the contents with
12426 
12427  @throw type_error.310 when JSON value is not an array; example: `"cannot
12428  use swap() with string"`
12429 
12430  @complexity Constant.
12431 
12432  @liveexample{The example below shows how arrays can be swapped with
12433  `swap()`.,swap__array_t}
12434 
12435  @since version 1.0.0
12436  */
12437  void swap(array_t& other)
12438  {
12439  // swap only works for arrays
12440  if (JSON_LIKELY(is_array()))
12441  {
12442  std::swap(*(m_value.array), other);
12443  }
12444  else
12445  {
12446  JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
12447  }
12448  }
12449 
12450  /*!
12451  @brief exchanges the values
12452 
12453  Exchanges the contents of a JSON object with those of @a other. Does not
12454  invoke any move, copy, or swap operations on individual elements. All
12455  iterators and references remain valid. The past-the-end iterator is
12456  invalidated.
12457 
12458  @param[in,out] other object to exchange the contents with
12459 
12460  @throw type_error.310 when JSON value is not an object; example:
12461  `"cannot use swap() with string"`
12462 
12463  @complexity Constant.
12464 
12465  @liveexample{The example below shows how objects can be swapped with
12466  `swap()`.,swap__object_t}
12467 
12468  @since version 1.0.0
12469  */
12470  void swap(object_t& other)
12471  {
12472  // swap only works for objects
12473  if (JSON_LIKELY(is_object()))
12474  {
12475  std::swap(*(m_value.object), other);
12476  }
12477  else
12478  {
12479  JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
12480  }
12481  }
12482 
12483  /*!
12484  @brief exchanges the values
12485 
12486  Exchanges the contents of a JSON string with those of @a other. Does not
12487  invoke any move, copy, or swap operations on individual elements. All
12488  iterators and references remain valid. The past-the-end iterator is
12489  invalidated.
12490 
12491  @param[in,out] other string to exchange the contents with
12492 
12493  @throw type_error.310 when JSON value is not a string; example: `"cannot
12494  use swap() with boolean"`
12495 
12496  @complexity Constant.
12497 
12498  @liveexample{The example below shows how strings can be swapped with
12499  `swap()`.,swap__string_t}
12500 
12501  @since version 1.0.0
12502  */
12503  void swap(string_t& other)
12504  {
12505  // swap only works for strings
12506  if (JSON_LIKELY(is_string()))
12507  {
12508  std::swap(*(m_value.string), other);
12509  }
12510  else
12511  {
12512  JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
12513  }
12514  }
12515 
12516  /// @}
12517 
12518  public:
12519  //////////////////////////////////////////
12520  // lexicographical comparison operators //
12521  //////////////////////////////////////////
12522 
12523  /// @name lexicographical comparison operators
12524  /// @{
12525 
12526  /*!
12527  @brief comparison: equal
12528 
12529  Compares two JSON values for equality according to the following rules:
12530  - Two JSON values are equal if (1) they are from the same type and (2)
12531  their stored values are the same according to their respective
12532  `operator==`.
12533  - Integer and floating-point numbers are automatically converted before
12534  comparison. Note than two NaN values are always treated as unequal.
12535  - Two JSON null values are equal.
12536 
12537  @note Floating-point inside JSON values numbers are compared with
12538  `json::number_float_t::operator==` which is `double::operator==` by
12539  default. To compare floating-point while respecting an epsilon, an alternative
12540  [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
12541  could be used, for instance
12542  @code {.cpp}
12543  template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
12544  inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
12545  {
12546  return std::abs(a - b) <= epsilon;
12547  }
12548  @endcode
12549 
12550  @note NaN values never compare equal to themselves or to other NaN values.
12552  @param[in] lhs first JSON value to consider
12553  @param[in] rhs second JSON value to consider
12554  @return whether the values @a lhs and @a rhs are equal
12555 
12556  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12557 
12558  @complexity Linear.
12559 
12560  @liveexample{The example demonstrates comparing several JSON
12561  types.,operator__equal}
12562 
12563  @since version 1.0.0
12564  */
12565  friend bool operator==(const_reference lhs, const_reference rhs) noexcept
12566  {
12567  const auto lhs_type = lhs.type();
12568  const auto rhs_type = rhs.type();
12569 
12570  if (lhs_type == rhs_type)
12571  {
12572  switch (lhs_type)
12573  {
12574  case value_t::array:
12575  return (*lhs.m_value.array == *rhs.m_value.array);
12576 
12577  case value_t::object:
12578  return (*lhs.m_value.object == *rhs.m_value.object);
12579 
12580  case value_t::null:
12581  return true;
12582 
12583  case value_t::string:
12584  return (*lhs.m_value.string == *rhs.m_value.string);
12586  case value_t::boolean:
12587  return (lhs.m_value.boolean == rhs.m_value.boolean);
12588 
12589  case value_t::number_integer:
12590  return (lhs.m_value.number_integer == rhs.m_value.number_integer);
12591 
12592  case value_t::number_unsigned:
12593  return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned);
12594 
12595  case value_t::number_float:
12596  return (lhs.m_value.number_float == rhs.m_value.number_float);
12597 
12598  default:
12599  return false;
12600  }
12601  }
12602  else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
12603  {
12604  return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float);
12605  }
12606  else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
12607  {
12608  return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer));
12609  }
12610  else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
12611  {
12612  return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float);
12613  }
12614  else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
12615  {
12616  return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned));
12617  }
12618  else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
12619  {
12620  return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer);
12621  }
12622  else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
12623  {
12624  return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned));
12625  }
12626 
12627  return false;
12628  }
12629 
12630  /*!
12631  @brief comparison: equal
12632  @copydoc operator==(const_reference, const_reference)
12633  */
12634  template<typename ScalarType, typename std::enable_if<
12635  std::is_scalar<ScalarType>::value, int>::type = 0>
12636  friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
12637  {
12638  return (lhs == basic_json(rhs));
12639  }
12641  /*!
12642  @brief comparison: equal
12643  @copydoc operator==(const_reference, const_reference)
12644  */
12645  template<typename ScalarType, typename std::enable_if<
12646  std::is_scalar<ScalarType>::value, int>::type = 0>
12647  friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
12648  {
12649  return (basic_json(lhs) == rhs);
12650  }
12651 
12652  /*!
12653  @brief comparison: not equal
12654 
12655  Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
12656 
12657  @param[in] lhs first JSON value to consider
12658  @param[in] rhs second JSON value to consider
12659  @return whether the values @a lhs and @a rhs are not equal
12660 
12661  @complexity Linear.
12662 
12663  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12664 
12665  @liveexample{The example demonstrates comparing several JSON
12666  types.,operator__notequal}
12667 
12668  @since version 1.0.0
12669  */
12670  friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
12671  {
12672  return not (lhs == rhs);
12673  }
12674 
12675  /*!
12676  @brief comparison: not equal
12677  @copydoc operator!=(const_reference, const_reference)
12678  */
12679  template<typename ScalarType, typename std::enable_if<
12680  std::is_scalar<ScalarType>::value, int>::type = 0>
12681  friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
12682  {
12683  return (lhs != basic_json(rhs));
12684  }
12685 
12686  /*!
12687  @brief comparison: not equal
12688  @copydoc operator!=(const_reference, const_reference)
12689  */
12690  template<typename ScalarType, typename std::enable_if<
12691  std::is_scalar<ScalarType>::value, int>::type = 0>
12692  friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
12693  {
12694  return (basic_json(lhs) != rhs);
12695  }
12696 
12697  /*!
12698  @brief comparison: less than
12699 
12700  Compares whether one JSON value @a lhs is less than another JSON value @a
12701  rhs according to the following rules:
12702  - If @a lhs and @a rhs have the same type, the values are compared using
12703  the default `<` operator.
12704  - Integer and floating-point numbers are automatically converted before
12705  comparison
12706  - In case @a lhs and @a rhs have different types, the values are ignored
12707  and the order of the types is considered, see
12708  @ref operator<(const value_t, const value_t).
12709 
12710  @param[in] lhs first JSON value to consider
12711  @param[in] rhs second JSON value to consider
12712  @return whether @a lhs is less than @a rhs
12713 
12714  @complexity Linear.
12715 
12716  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12717 
12718  @liveexample{The example demonstrates comparing several JSON
12719  types.,operator__less}
12720 
12721  @since version 1.0.0
12722  */
12723  friend bool operator<(const_reference lhs, const_reference rhs) noexcept
12724  {
12725  const auto lhs_type = lhs.type();
12726  const auto rhs_type = rhs.type();
12727 
12728  if (lhs_type == rhs_type)
12729  {
12730  switch (lhs_type)
12731  {
12732  case value_t::array:
12733  return (*lhs.m_value.array) < (*rhs.m_value.array);
12734 
12735  case value_t::object:
12736  return *lhs.m_value.object < *rhs.m_value.object;
12737 
12738  case value_t::null:
12739  return false;
12740 
12741  case value_t::string:
12742  return *lhs.m_value.string < *rhs.m_value.string;
12743 
12744  case value_t::boolean:
12745  return lhs.m_value.boolean < rhs.m_value.boolean;
12746 
12747  case value_t::number_integer:
12748  return lhs.m_value.number_integer < rhs.m_value.number_integer;
12749 
12750  case value_t::number_unsigned:
12751  return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
12752 
12753  case value_t::number_float:
12754  return lhs.m_value.number_float < rhs.m_value.number_float;
12755 
12756  default:
12757  return false;
12758  }
12759  }
12760  else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
12761  {
12762  return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
12763  }
12764  else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
12765  {
12766  return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
12767  }
12768  else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
12769  {
12770  return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
12771  }
12772  else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
12773  {
12774  return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
12775  }
12776  else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
12777  {
12778  return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
12779  }
12780  else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
12781  {
12782  return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
12783  }
12784 
12785  // We only reach this line if we cannot compare values. In that case,
12786  // we compare types. Note we have to call the operator explicitly,
12787  // because MSVC has problems otherwise.
12788  return operator<(lhs_type, rhs_type);
12789  }
12790 
12791  /*!
12792  @brief comparison: less than
12793  @copydoc operator<(const_reference, const_reference)
12794  */
12795  template<typename ScalarType, typename std::enable_if<
12796  std::is_scalar<ScalarType>::value, int>::type = 0>
12797  friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
12798  {
12799  return (lhs < basic_json(rhs));
12800  }
12801 
12802  /*!
12803  @brief comparison: less than
12804  @copydoc operator<(const_reference, const_reference)
12805  */
12806  template<typename ScalarType, typename std::enable_if<
12807  std::is_scalar<ScalarType>::value, int>::type = 0>
12808  friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
12809  {
12810  return (basic_json(lhs) < rhs);
12811  }
12812 
12813  /*!
12814  @brief comparison: less than or equal
12815 
12816  Compares whether one JSON value @a lhs is less than or equal to another
12817  JSON value by calculating `not (rhs < lhs)`.
12818 
12819  @param[in] lhs first JSON value to consider
12820  @param[in] rhs second JSON value to consider
12821  @return whether @a lhs is less than or equal to @a rhs
12822 
12823  @complexity Linear.
12824 
12825  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12826 
12827  @liveexample{The example demonstrates comparing several JSON
12828  types.,operator__greater}
12829 
12830  @since version 1.0.0
12831  */
12832  friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
12833  {
12834  return not (rhs < lhs);
12835  }
12836 
12837  /*!
12838  @brief comparison: less than or equal
12839  @copydoc operator<=(const_reference, const_reference)
12840  */
12841  template<typename ScalarType, typename std::enable_if<
12842  std::is_scalar<ScalarType>::value, int>::type = 0>
12843  friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
12844  {
12845  return (lhs <= basic_json(rhs));
12846  }
12847 
12848  /*!
12849  @brief comparison: less than or equal
12850  @copydoc operator<=(const_reference, const_reference)
12851  */
12852  template<typename ScalarType, typename std::enable_if<
12853  std::is_scalar<ScalarType>::value, int>::type = 0>
12854  friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
12855  {
12856  return (basic_json(lhs) <= rhs);
12857  }
12858 
12859  /*!
12860  @brief comparison: greater than
12861 
12862  Compares whether one JSON value @a lhs is greater than another
12863  JSON value by calculating `not (lhs <= rhs)`.
12864 
12865  @param[in] lhs first JSON value to consider
12866  @param[in] rhs second JSON value to consider
12867  @return whether @a lhs is greater than to @a rhs
12868 
12869  @complexity Linear.
12870 
12871  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12872 
12873  @liveexample{The example demonstrates comparing several JSON
12874  types.,operator__lessequal}
12875 
12876  @since version 1.0.0
12877  */
12878  friend bool operator>(const_reference lhs, const_reference rhs) noexcept
12879  {
12880  return not (lhs <= rhs);
12881  }
12882 
12883  /*!
12884  @brief comparison: greater than
12885  @copydoc operator>(const_reference, const_reference)
12886  */
12887  template<typename ScalarType, typename std::enable_if<
12888  std::is_scalar<ScalarType>::value, int>::type = 0>
12889  friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
12890  {
12891  return (lhs > basic_json(rhs));
12892  }
12893 
12894  /*!
12895  @brief comparison: greater than
12896  @copydoc operator>(const_reference, const_reference)
12897  */
12898  template<typename ScalarType, typename std::enable_if<
12899  std::is_scalar<ScalarType>::value, int>::type = 0>
12900  friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
12901  {
12902  return (basic_json(lhs) > rhs);
12903  }
12904 
12905  /*!
12906  @brief comparison: greater than or equal
12907 
12908  Compares whether one JSON value @a lhs is greater than or equal to another
12909  JSON value by calculating `not (lhs < rhs)`.
12911  @param[in] lhs first JSON value to consider
12912  @param[in] rhs second JSON value to consider
12913  @return whether @a lhs is greater than or equal to @a rhs
12914 
12915  @complexity Linear.
12916 
12917  @exceptionsafety No-throw guarantee: this function never throws exceptions.
12918 
12919  @liveexample{The example demonstrates comparing several JSON
12920  types.,operator__greaterequal}
12921 
12922  @since version 1.0.0
12923  */
12924  friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
12925  {
12926  return not (lhs < rhs);
12927  }
12928 
12929  /*!
12930  @brief comparison: greater than or equal
12931  @copydoc operator>=(const_reference, const_reference)
12932  */
12933  template<typename ScalarType, typename std::enable_if<
12934  std::is_scalar<ScalarType>::value, int>::type = 0>
12935  friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
12936  {
12937  return (lhs >= basic_json(rhs));
12938  }
12939 
12940  /*!
12941  @brief comparison: greater than or equal
12942  @copydoc operator>=(const_reference, const_reference)
12943  */
12944  template<typename ScalarType, typename std::enable_if<
12945  std::is_scalar<ScalarType>::value, int>::type = 0>
12946  friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
12947  {
12948  return (basic_json(lhs) >= rhs);
12949  }
12950 
12951  /// @}
12952 
12953  ///////////////////
12954  // serialization //
12955  ///////////////////
12956 
12957  /// @name serialization
12958  /// @{
12959 
12960  /*!
12961  @brief serialize to stream
12962 
12963  Serialize the given JSON value @a j to the output stream @a o. The JSON
12964  value will be serialized using the @ref dump member function.
12965 
12966  - The indentation of the output can be controlled with the member variable
12967  `width` of the output stream @a o. For instance, using the manipulator
12968  `std::setw(4)` on @a o sets the indentation level to `4` and the
12969  serialization result is the same as calling `dump(4)`.
12970 
12971  - The indentation character can be controlled with the member variable
12972  `fill` of the output stream @a o. For instance, the manipulator
12973  `std::setfill('\\t')` sets indentation to use a tab character rather than
12974  the default space character.
12975 
12976  @param[in,out] o stream to serialize to
12977  @param[in] j JSON value to serialize
12978 
12979  @return the stream @a o
12980 
12981  @throw type_error.316 if a string stored inside the JSON value is not
12982  UTF-8 encoded
12983 
12984  @complexity Linear.
12986  @liveexample{The example below shows the serialization with different
12987  parameters to `width` to adjust the indentation level.,operator_serialize}
12988 
12989  @since version 1.0.0; indentation character added in version 3.0.0
12990  */
12991  friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
12992  {
12993  // read width member and use it as indentation parameter if nonzero
12994  const bool pretty_print = (o.width() > 0);
12995  const auto indentation = (pretty_print ? o.width() : 0);
12996 
12997  // reset width to 0 for subsequent calls to this stream
12998  o.width(0);
12999 
13000  // do the actual serialization
13001  serializer s(detail::output_adapter<char>(o), o.fill());
13002  s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
13003  return o;
13004  }
13005 
13006  /*!
13007  @brief serialize to stream
13008  @deprecated This stream operator is deprecated and will be removed in a
13009  future version of the library. Please use
13010  @ref operator<<(std::ostream&, const basic_json&)
13011  instead; that is, replace calls like `j >> o;` with `o << j;`.
13012  @since version 1.0.0; deprecated since version 3.0.0
13013  */
13015  friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
13016  {
13017  return o << j;
13018  }
13019 
13020  /// @}
13021 
13022 
13023  /////////////////////
13024  // deserialization //
13025  /////////////////////
13026 
13027  /// @name deserialization
13028  /// @{
13029 
13030  /*!
13031  @brief deserialize from a compatible input
13032 
13033  This function reads from a compatible input. Examples are:
13034  - an array of 1-byte values
13035  - strings with character/literal type with size of 1 byte
13036  - input streams
13037  - container with contiguous storage of 1-byte values. Compatible container
13038  types include `std::vector`, `std::string`, `std::array`,
13039  `std::valarray`, and `std::initializer_list`. Furthermore, C-style
13040  arrays can be used with `std::begin()`/`std::end()`. User-defined
13041  containers can be used as long as they implement random-access iterators
13042  and a contiguous storage.
13043 
13044  @pre Each element of the container has a size of 1 byte. Violating this
13045  precondition yields undefined behavior. **This precondition is enforced
13046  with a static assertion.**
13047 
13048  @pre The container storage is contiguous. Violating this precondition
13049  yields undefined behavior. **This precondition is enforced with an
13050  assertion.**
13051  @pre Each element of the container has a size of 1 byte. Violating this
13052  precondition yields undefined behavior. **This precondition is enforced
13053  with a static assertion.**
13054 
13055  @warning There is no way to enforce all preconditions at compile-time. If
13056  the function is called with a noncompliant container and with
13057  assertions switched off, the behavior is undefined and will most
13058  likely yield segmentation violation.
13059 
13060  @param[in] i input to read from
13061  @param[in] cb a parser callback function of type @ref parser_callback_t
13062  which is used to control the deserialization by filtering unwanted values
13063  (optional)
13064 
13065  @return result of the deserialization
13066 
13067  @throw parse_error.101 if a parse error occurs; example: `""unexpected end
13068  of input; expected string literal""`
13069  @throw parse_error.102 if to_unicode fails or surrogate error
13070  @throw parse_error.103 if to_unicode fails
13071 
13072  @complexity Linear in the length of the input. The parser is a predictive
13073  LL(1) parser. The complexity can be higher if the parser callback function
13074  @a cb has a super-linear complexity.
13075 
13076  @note A UTF-8 byte order mark is silently ignored.
13077 
13078  @liveexample{The example below demonstrates the `parse()` function reading
13079  from an array.,parse__array__parser_callback_t}
13080 
13081  @liveexample{The example below demonstrates the `parse()` function with
13082  and without callback function.,parse__string__parser_callback_t}
13083 
13084  @liveexample{The example below demonstrates the `parse()` function with
13085  and without callback function.,parse__istream__parser_callback_t}
13086 
13087  @liveexample{The example below demonstrates the `parse()` function reading
13088  from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
13089 
13090  @since version 2.0.3 (contiguous containers)
13091  */
13092  static basic_json parse(detail::input_adapter i,
13093  const parser_callback_t cb = nullptr,
13094  const bool allow_exceptions = true)
13095  {
13096  basic_json result;
13097  parser(i, cb, allow_exceptions).parse(true, result);
13098  return result;
13099  }
13100 
13101  /*!
13102  @copydoc basic_json parse(detail::input_adapter, const parser_callback_t)
13103  */
13104  static basic_json parse(detail::input_adapter& i,
13105  const parser_callback_t cb = nullptr,
13106  const bool allow_exceptions = true)
13107  {
13108  basic_json result;
13109  parser(i, cb, allow_exceptions).parse(true, result);
13110  return result;
13111  }
13112 
13113  static bool accept(detail::input_adapter i)
13114  {
13115  return parser(i).accept(true);
13116  }
13117 
13118  static bool accept(detail::input_adapter& i)
13119  {
13120  return parser(i).accept(true);
13121  }
13122 
13123  /*!
13124  @brief deserialize from an iterator range with contiguous storage
13125 
13126  This function reads from an iterator range of a container with contiguous
13127  storage of 1-byte values. Compatible container types include
13128  `std::vector`, `std::string`, `std::array`, `std::valarray`, and
13129  `std::initializer_list`. Furthermore, C-style arrays can be used with
13130  `std::begin()`/`std::end()`. User-defined containers can be used as long
13131  as they implement random-access iterators and a contiguous storage.
13132 
13133  @pre The iterator range is contiguous. Violating this precondition yields
13134  undefined behavior. **This precondition is enforced with an assertion.**
13135  @pre Each element in the range has a size of 1 byte. Violating this
13136  precondition yields undefined behavior. **This precondition is enforced
13137  with a static assertion.**
13138 
13139  @warning There is no way to enforce all preconditions at compile-time. If
13140  the function is called with noncompliant iterators and with
13141  assertions switched off, the behavior is undefined and will most
13142  likely yield segmentation violation.
13143 
13144  @tparam IteratorType iterator of container with contiguous storage
13145  @param[in] first begin of the range to parse (included)
13146  @param[in] last end of the range to parse (excluded)
13147  @param[in] cb a parser callback function of type @ref parser_callback_t
13148  which is used to control the deserialization by filtering unwanted values
13149  (optional)
13150  @param[in] allow_exceptions whether to throw exceptions in case of a
13151  parse error (optional, true by default)
13152 
13153  @return result of the deserialization
13154 
13155  @throw parse_error.101 in case of an unexpected token
13156  @throw parse_error.102 if to_unicode fails or surrogate error
13157  @throw parse_error.103 if to_unicode fails
13158 
13159  @complexity Linear in the length of the input. The parser is a predictive
13160  LL(1) parser. The complexity can be higher if the parser callback function
13161  @a cb has a super-linear complexity.
13163  @note A UTF-8 byte order mark is silently ignored.
13164 
13165  @liveexample{The example below demonstrates the `parse()` function reading
13166  from an iterator range.,parse__iteratortype__parser_callback_t}
13167 
13168  @since version 2.0.3
13169  */
13170  template<class IteratorType, typename std::enable_if<
13171  std::is_base_of<
13172  std::random_access_iterator_tag,
13173  typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
13174  static basic_json parse(IteratorType first, IteratorType last,
13175  const parser_callback_t cb = nullptr,
13176  const bool allow_exceptions = true)
13177  {
13178  basic_json result;
13179  parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
13180  return result;
13181  }
13182 
13183  template<class IteratorType, typename std::enable_if<
13184  std::is_base_of<
13185  std::random_access_iterator_tag,
13186  typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
13187  static bool accept(IteratorType first, IteratorType last)
13188  {
13189  return parser(detail::input_adapter(first, last)).accept(true);
13190  }
13191 
13192  /*!
13193  @brief deserialize from stream
13194  @deprecated This stream operator is deprecated and will be removed in a
13195  future version of the library. Please use
13196  @ref operator>>(std::istream&, basic_json&)
13197  instead; that is, replace calls like `j << i;` with `i >> j;`.
13198  @since version 1.0.0; deprecated since version 3.0.0
13199  */
13201  friend std::istream& operator<<(basic_json& j, std::istream& i)
13202  {
13203  return operator>>(i, j);
13204  }
13205 
13206  /*!
13207  @brief deserialize from stream
13208 
13209  Deserializes an input stream to a JSON value.
13210 
13211  @param[in,out] i input stream to read a serialized JSON value from
13212  @param[in,out] j JSON value to write the deserialized input to
13214  @throw parse_error.101 in case of an unexpected token
13215  @throw parse_error.102 if to_unicode fails or surrogate error
13216  @throw parse_error.103 if to_unicode fails
13217 
13218  @complexity Linear in the length of the input. The parser is a predictive
13219  LL(1) parser.
13220 
13221  @note A UTF-8 byte order mark is silently ignored.
13222 
13223  @liveexample{The example below shows how a JSON value is constructed by
13224  reading a serialization from a stream.,operator_deserialize}
13225 
13226  @sa parse(std::istream&, const parser_callback_t) for a variant with a
13227  parser callback function to filter values while parsing
13228 
13229  @since version 1.0.0
13230  */
13231  friend std::istream& operator>>(std::istream& i, basic_json& j)
13232  {
13233  parser(detail::input_adapter(i)).parse(false, j);
13234  return i;
13235  }
13236 
13237  /// @}
13238 
13239  ///////////////////////////
13240  // convenience functions //
13241  ///////////////////////////
13242 
13243  /*!
13244  @brief return the type as string
13245 
13246  Returns the type name as string to be used in error messages - usually to
13247  indicate that a function was called on a wrong JSON type.
13248 
13249  @return a string representation of a the @a m_type member:
13250  Value type | return value
13251  ----------- | -------------
13252  null | `"null"`
13253  boolean | `"boolean"`
13254  string | `"string"`
13255  number | `"number"` (for all number types)
13256  object | `"object"`
13257  array | `"array"`
13258  discarded | `"discarded"`
13259 
13260  @exceptionsafety No-throw guarantee: this function never throws exceptions.
13262  @complexity Constant.
13263 
13264  @liveexample{The following code exemplifies `type_name()` for all JSON
13265  types.,type_name}
13266 
13267  @sa @ref type() -- return the type of the JSON value
13268  @sa @ref operator value_t() -- return the type of the JSON value (implicit)
13269 
13270  @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
13271  since 3.0.0
13272  */
13273  const char* type_name() const noexcept
13274  {
13275  {
13276  switch (m_type)
13277  {
13278  case value_t::null:
13279  return "null";
13280  case value_t::object:
13281  return "object";
13282  case value_t::array:
13283  return "array";
13284  case value_t::string:
13285  return "string";
13286  case value_t::boolean:
13287  return "boolean";
13288  case value_t::discarded:
13289  return "discarded";
13290  default:
13291  return "number";
13292  }
13293  }
13294  }
13295 
13296 
13297  private:
13298  //////////////////////
13299  // member variables //
13300  //////////////////////
13301 
13302  /// the type of the current element
13303  value_t m_type = value_t::null;
13304 
13305  /// the value of the current element
13306  json_value m_value = {};
13307 
13308  //////////////////////////////////////////
13309  // binary serialization/deserialization //
13310  //////////////////////////////////////////
13311 
13312  /// @name binary serialization/deserialization support
13313  /// @{
13314 
13315  public:
13316  /*!
13317  @brief create a CBOR serialization of a given JSON value
13318 
13319  Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
13320  Binary Object Representation) serialization format. CBOR is a binary
13321  serialization format which aims to be more compact than JSON itself, yet
13322  more efficient to parse.
13323 
13324  The library uses the following mapping from JSON values types to
13325  CBOR types according to the CBOR specification (RFC 7049):
13326 
13327  JSON value type | value/range | CBOR type | first byte
13328  --------------- | ------------------------------------------ | ---------------------------------- | ---------------
13329  null | `null` | Null | 0xF6
13330  boolean | `true` | True | 0xF5
13331  boolean | `false` | False | 0xF4
13332  number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
13333  number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
13334  number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
13335  number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
13336  number_integer | -24..-1 | Negative integer | 0x20..0x37
13337  number_integer | 0..23 | Integer | 0x00..0x17
13338  number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
13339  number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
13340  number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
13341  number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
13342  number_unsigned | 0..23 | Integer | 0x00..0x17
13343  number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
13344  number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
13345  number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
13346  number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
13347  number_float | *any value* | Double-Precision Float | 0xFB
13348  string | *length*: 0..23 | UTF-8 string | 0x60..0x77
13349  string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
13350  string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
13351  string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
13352  string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
13353  array | *size*: 0..23 | array | 0x80..0x97
13354  array | *size*: 23..255 | array (1 byte follow) | 0x98
13355  array | *size*: 256..65535 | array (2 bytes follow) | 0x99
13356  array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
13357  array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
13358  object | *size*: 0..23 | map | 0xA0..0xB7
13359  object | *size*: 23..255 | map (1 byte follow) | 0xB8
13360  object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
13361  object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
13362  object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
13363 
13364  @note The mapping is **complete** in the sense that any JSON value type
13365  can be converted to a CBOR value.
13366 
13367  @note If NaN or Infinity are stored inside a JSON number, they are
13368  serialized properly. This behavior differs from the @ref dump()
13369  function which serializes NaN or Infinity to `null`.
13370 
13371  @note The following CBOR types are not used in the conversion:
13372  - byte strings (0x40..0x5F)
13373  - UTF-8 strings terminated by "break" (0x7F)
13374  - arrays terminated by "break" (0x9F)
13375  - maps terminated by "break" (0xBF)
13376  - date/time (0xC0..0xC1)
13377  - bignum (0xC2..0xC3)
13378  - decimal fraction (0xC4)
13379  - bigfloat (0xC5)
13380  - tagged items (0xC6..0xD4, 0xD8..0xDB)
13381  - expected conversions (0xD5..0xD7)
13382  - simple values (0xE0..0xF3, 0xF8)
13383  - undefined (0xF7)
13384  - half and single-precision floats (0xF9-0xFA)
13385  - break (0xFF)
13386 
13387  @param[in] j JSON value to serialize
13388  @return MessagePack serialization as byte vector
13389 
13390  @complexity Linear in the size of the JSON value @a j.
13391 
13392  @liveexample{The example shows the serialization of a JSON value to a byte
13393  vector in CBOR format.,to_cbor}
13394 
13395  @sa http://cbor.io
13396  @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the
13397  analogous deserialization
13398  @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
13399 
13400  @since version 2.0.9
13401  */
13402  static std::vector<uint8_t> to_cbor(const basic_json& j)
13403  {
13404  std::vector<uint8_t> result;
13405  to_cbor(j, result);
13406  return result;
13407  }
13408 
13409  static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
13410  {
13411  binary_writer<uint8_t>(o).write_cbor(j);
13412  }
13413 
13414  static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
13415  {
13416  binary_writer<char>(o).write_cbor(j);
13417  }
13418 
13419  /*!
13420  @brief create a MessagePack serialization of a given JSON value
13421 
13422  Serializes a given JSON value @a j to a byte vector using the MessagePack
13423  serialization format. MessagePack is a binary serialization format which
13424  aims to be more compact than JSON itself, yet more efficient to parse.
13425 
13426  The library uses the following mapping from JSON values types to
13427  MessagePack types according to the MessagePack specification:
13429  JSON value type | value/range | MessagePack type | first byte
13430  --------------- | --------------------------------- | ---------------- | ----------
13431  null | `null` | nil | 0xC0
13432  boolean | `true` | true | 0xC3
13433  boolean | `false` | false | 0xC2
13434  number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
13435  number_integer | -2147483648..-32769 | int32 | 0xD2
13436  number_integer | -32768..-129 | int16 | 0xD1
13437  number_integer | -128..-33 | int8 | 0xD0
13438  number_integer | -32..-1 | negative fixint | 0xE0..0xFF
13439  number_integer | 0..127 | positive fixint | 0x00..0x7F
13440  number_integer | 128..255 | uint 8 | 0xCC
13441  number_integer | 256..65535 | uint 16 | 0xCD
13442  number_integer | 65536..4294967295 | uint 32 | 0xCE
13443  number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
13444  number_unsigned | 0..127 | positive fixint | 0x00..0x7F
13445  number_unsigned | 128..255 | uint 8 | 0xCC
13446  number_unsigned | 256..65535 | uint 16 | 0xCD
13447  number_unsigned | 65536..4294967295 | uint 32 | 0xCE
13448  number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
13449  number_float | *any value* | float 64 | 0xCB
13450  string | *length*: 0..31 | fixstr | 0xA0..0xBF
13451  string | *length*: 32..255 | str 8 | 0xD9
13452  string | *length*: 256..65535 | str 16 | 0xDA
13453  string | *length*: 65536..4294967295 | str 32 | 0xDB
13454  array | *size*: 0..15 | fixarray | 0x90..0x9F
13455  array | *size*: 16..65535 | array 16 | 0xDC
13456  array | *size*: 65536..4294967295 | array 32 | 0xDD
13457  object | *size*: 0..15 | fix map | 0x80..0x8F
13458  object | *size*: 16..65535 | map 16 | 0xDE
13459  object | *size*: 65536..4294967295 | map 32 | 0xDF
13460 
13461  @note The mapping is **complete** in the sense that any JSON value type
13462  can be converted to a MessagePack value.
13463 
13464  @note The following values can **not** be converted to a MessagePack value:
13465  - strings with more than 4294967295 bytes
13466  - arrays with more than 4294967295 elements
13467  - objects with more than 4294967295 elements
13468 
13469  @note The following MessagePack types are not used in the conversion:
13470  - bin 8 - bin 32 (0xC4..0xC6)
13471  - ext 8 - ext 32 (0xC7..0xC9)
13472  - float 32 (0xCA)
13473  - fixext 1 - fixext 16 (0xD4..0xD8)
13474 
13475  @note Any MessagePack output created @ref to_msgpack can be successfully
13476  parsed by @ref from_msgpack.
13477 
13478  @note If NaN or Infinity are stored inside a JSON number, they are
13479  serialized properly. This behavior differs from the @ref dump()
13480  function which serializes NaN or Infinity to `null`.
13481 
13482  @param[in] j JSON value to serialize
13483  @return MessagePack serialization as byte vector
13484 
13485  @complexity Linear in the size of the JSON value @a j.
13486 
13487  @liveexample{The example shows the serialization of a JSON value to a byte
13488  vector in MessagePack format.,to_msgpack}
13489 
13490  @sa http://msgpack.org
13491  @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
13492  analogous deserialization
13493  @sa @ref to_cbor(const basic_json& for the related CBOR format
13494 
13495  @since version 2.0.9
13496  */
13497  static std::vector<uint8_t> to_msgpack(const basic_json& j)
13498  {
13499  std::vector<uint8_t> result;
13500  to_msgpack(j, result);
13501  return result;
13502  }
13503 
13504  static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
13505  {
13506  binary_writer<uint8_t>(o).write_msgpack(j);
13507  }
13508 
13509  static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
13510  {
13511  binary_writer<char>(o).write_msgpack(j);
13512  }
13513 
13514  /*!
13515  @brief create a JSON value from an input in CBOR format
13516 
13517  Deserializes a given input @a i to a JSON value using the CBOR (Concise
13518  Binary Object Representation) serialization format.
13519 
13520  The library maps CBOR types to JSON value types as follows:
13521 
13522  CBOR type | JSON value type | first byte
13523  ---------------------- | --------------- | ----------
13524  Integer | number_unsigned | 0x00..0x17
13525  Unsigned integer | number_unsigned | 0x18
13526  Unsigned integer | number_unsigned | 0x19
13527  Unsigned integer | number_unsigned | 0x1A
13528  Unsigned integer | number_unsigned | 0x1B
13529  Negative integer | number_integer | 0x20..0x37
13530  Negative integer | number_integer | 0x38
13531  Negative integer | number_integer | 0x39
13532  Negative integer | number_integer | 0x3A
13533  Negative integer | number_integer | 0x3B
13534  Negative integer | number_integer | 0x40..0x57
13535  UTF-8 string | string | 0x60..0x77
13536  UTF-8 string | string | 0x78
13537  UTF-8 string | string | 0x79
13538  UTF-8 string | string | 0x7A
13539  UTF-8 string | string | 0x7B
13540  UTF-8 string | string | 0x7F
13541  array | array | 0x80..0x97
13542  array | array | 0x98
13543  array | array | 0x99
13544  array | array | 0x9A
13545  array | array | 0x9B
13546  array | array | 0x9F
13547  map | object | 0xA0..0xB7
13548  map | object | 0xB8
13549  map | object | 0xB9
13550  map | object | 0xBA
13551  map | object | 0xBB
13552  map | object | 0xBF
13553  False | `false` | 0xF4
13554  True | `true` | 0xF5
13555  Nill | `null` | 0xF6
13556  Half-Precision Float | number_float | 0xF9
13557  Single-Precision Float | number_float | 0xFA
13558  Double-Precision Float | number_float | 0xFB
13559 
13560  @warning The mapping is **incomplete** in the sense that not all CBOR
13561  types can be converted to a JSON value. The following CBOR types
13562  are not supported and will yield parse errors (parse_error.112):
13563  - byte strings (0x40..0x5F)
13564  - date/time (0xC0..0xC1)
13565  - bignum (0xC2..0xC3)
13566  - decimal fraction (0xC4)
13567  - bigfloat (0xC5)
13568  - tagged items (0xC6..0xD4, 0xD8..0xDB)
13569  - expected conversions (0xD5..0xD7)
13570  - simple values (0xE0..0xF3, 0xF8)
13571  - undefined (0xF7)
13572 
13573  @warning CBOR allows map keys of any type, whereas JSON only allows
13574  strings as keys in object values. Therefore, CBOR maps with keys
13575  other than UTF-8 strings are rejected (parse_error.113).
13577  @note Any CBOR output created @ref to_cbor can be successfully parsed by
13578  @ref from_cbor.
13579 
13580  @param[in] i an input in CBOR format convertible to an input adapter
13581  @param[in] strict whether to expect the input to be consumed until EOF
13582  (true by default)
13583  @return deserialized JSON value
13584 
13585  @throw parse_error.110 if the given input ends prematurely or the end of
13586  file was not reached when @a strict was set to true
13587  @throw parse_error.112 if unsupported features from CBOR were
13588  used in the given input @a v or if the input is not valid CBOR
13589  @throw parse_error.113 if a string was expected as map key, but not found
13590 
13591  @complexity Linear in the size of the input @a i.
13592 
13593  @liveexample{The example shows the deserialization of a byte vector in CBOR
13594  format to a JSON value.,from_cbor}
13595 
13596  @sa http://cbor.io
13597  @sa @ref to_cbor(const basic_json&) for the analogous serialization
13598  @sa @ref from_msgpack(detail::input_adapter, const bool) for the
13599  related MessagePack format
13600 
13601  @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
13602  consume input adapters, removed start_index parameter, and added
13603  @a strict parameter since 3.0.0
13604  */
13605  static basic_json from_cbor(detail::input_adapter i,
13606  const bool strict = true)
13607  {
13608  return binary_reader(i).parse_cbor(strict);
13609  }
13610 
13611  /*!
13612  @copydoc from_cbor(detail::input_adapter, const bool)
13613  */
13614  template<typename A1, typename A2,
13615  detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
13616  static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true)
13617  {
13618  return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_cbor(strict);
13619  }
13620 
13621  /*!
13622  @brief create a JSON value from an input in MessagePack format
13623 
13624  Deserializes a given input @a i to a JSON value using the MessagePack
13625  serialization format.
13626 
13627  The library maps MessagePack types to JSON value types as follows:
13628 
13629  MessagePack type | JSON value type | first byte
13630  ---------------- | --------------- | ----------
13631  positive fixint | number_unsigned | 0x00..0x7F
13632  fixmap | object | 0x80..0x8F
13633  fixarray | array | 0x90..0x9F
13634  fixstr | string | 0xA0..0xBF
13635  nil | `null` | 0xC0
13636  false | `false` | 0xC2
13637  true | `true` | 0xC3
13638  float 32 | number_float | 0xCA
13639  float 64 | number_float | 0xCB
13640  uint 8 | number_unsigned | 0xCC
13641  uint 16 | number_unsigned | 0xCD
13642  uint 32 | number_unsigned | 0xCE
13643  uint 64 | number_unsigned | 0xCF
13644  int 8 | number_integer | 0xD0
13645  int 16 | number_integer | 0xD1
13646  int 32 | number_integer | 0xD2
13647  int 64 | number_integer | 0xD3
13648  str 8 | string | 0xD9
13649  str 16 | string | 0xDA
13650  str 32 | string | 0xDB
13651  array 16 | array | 0xDC
13652  array 32 | array | 0xDD
13653  map 16 | object | 0xDE
13654  map 32 | object | 0xDF
13655  negative fixint | number_integer | 0xE0-0xFF
13656 
13657  @warning The mapping is **incomplete** in the sense that not all
13658  MessagePack types can be converted to a JSON value. The following
13659  MessagePack types are not supported and will yield parse errors:
13660  - bin 8 - bin 32 (0xC4..0xC6)
13661  - ext 8 - ext 32 (0xC7..0xC9)
13662  - fixext 1 - fixext 16 (0xD4..0xD8)
13663 
13664  @note Any MessagePack output created @ref to_msgpack can be successfully
13665  parsed by @ref from_msgpack.
13666 
13667  @param[in] i an input in MessagePack format convertible to an input
13668  adapter
13669  @param[in] strict whether to expect the input to be consumed until EOF
13670  (true by default)
13671 
13672  @throw parse_error.110 if the given input ends prematurely or the end of
13673  file was not reached when @a strict was set to true
13674  @throw parse_error.112 if unsupported features from MessagePack were
13675  used in the given input @a i or if the input is not valid MessagePack
13676  @throw parse_error.113 if a string was expected as map key, but not found
13677 
13678  @complexity Linear in the size of the input @a i.
13679 
13680  @liveexample{The example shows the deserialization of a byte vector in
13681  MessagePack format to a JSON value.,from_msgpack}
13683  @sa http://msgpack.org
13684  @sa @ref to_msgpack(const basic_json&) for the analogous serialization
13685  @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR
13686  format
13687 
13688  @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
13689  consume input adapters, removed start_index parameter, and added
13690  @a strict parameter since 3.0.0
13691  */
13692  static basic_json from_msgpack(detail::input_adapter i,
13693  const bool strict = true)
13694  {
13695  return binary_reader(i).parse_msgpack(strict);
13696  }
13697 
13698  /*!
13699  @copydoc from_msgpack(detail::input_adapter, const bool)
13700  */
13701  template<typename A1, typename A2,
13702  detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
13703  static basic_json from_msgpack(A1 && a1, A2 && a2, const bool strict = true)
13704  {
13705  return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_msgpack(strict);
13706  }
13707 
13708  /// @}
13709 
13710  //////////////////////////
13711  // JSON Pointer support //
13712  //////////////////////////
13713 
13714  /// @name JSON Pointer functions
13715  /// @{
13716 
13717  /*!
13718  @brief access specified element via JSON Pointer
13719 
13720  Uses a JSON pointer to retrieve a reference to the respective JSON value.
13721  No bound checking is performed. Similar to @ref operator[](const typename
13722  object_t::key_type&), `null` values are created in arrays and objects if
13723  necessary.
13724 
13725  In particular:
13726  - If the JSON pointer points to an object key that does not exist, it
13727  is created an filled with a `null` value before a reference to it
13728  is returned.
13729  - If the JSON pointer points to an array index that does not exist, it
13730  is created an filled with a `null` value before a reference to it
13731  is returned. All indices between the current maximum and the given
13732  index are also filled with `null`.
13733  - The special value `-` is treated as a synonym for the index past the
13734  end.
13735 
13736  @param[in] ptr a JSON pointer
13737 
13738  @return reference to the element pointed to by @a ptr
13739 
13740  @complexity Constant.
13741 
13742  @throw parse_error.106 if an array index begins with '0'
13743  @throw parse_error.109 if an array index was not a number
13744  @throw out_of_range.404 if the JSON pointer can not be resolved
13745 
13746  @liveexample{The behavior is shown in the example.,operatorjson_pointer}
13747 
13748  @since version 2.0.0
13749  */
13750  reference operator[](const json_pointer& ptr)
13751  {
13752  return ptr.get_unchecked(this);
13753  }
13754 
13755  /*!
13756  @brief access specified element via JSON Pointer
13758  Uses a JSON pointer to retrieve a reference to the respective JSON value.
13759  No bound checking is performed. The function does not change the JSON
13760  value; no `null` values are created. In particular, the the special value
13761  `-` yields an exception.
13762 
13763  @param[in] ptr JSON pointer to the desired element
13764 
13765  @return const reference to the element pointed to by @a ptr
13766 
13767  @complexity Constant.
13768 
13769  @throw parse_error.106 if an array index begins with '0'
13770  @throw parse_error.109 if an array index was not a number
13771  @throw out_of_range.402 if the array index '-' is used
13772  @throw out_of_range.404 if the JSON pointer can not be resolved
13773 
13774  @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
13775 
13776  @since version 2.0.0
13777  */
13778  const_reference operator[](const json_pointer& ptr) const
13779  {
13780  return ptr.get_unchecked(this);
13781  }
13782 
13783  /*!
13784  @brief access specified element via JSON Pointer
13785 
13786  Returns a reference to the element at with specified JSON pointer @a ptr,
13787  with bounds checking.
13788 
13789  @param[in] ptr JSON pointer to the desired element
13790 
13791  @return reference to the element pointed to by @a ptr
13792 
13793  @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
13794  begins with '0'. See example below.
13795 
13796  @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
13797  is not a number. See example below.
13798 
13799  @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
13800  is out of range. See example below.
13801 
13802  @throw out_of_range.402 if the array index '-' is used in the passed JSON
13803  pointer @a ptr. As `at` provides checked access (and no elements are
13804  implicitly inserted), the index '-' is always invalid. See example below.
13805 
13806  @throw out_of_range.403 if the JSON pointer describes a key of an object
13807  which cannot be found. See example below.
13808 
13809  @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
13810  See example below.
13811 
13812  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
13813  changes in the JSON value.
13814 
13815  @complexity Constant.
13816 
13817  @since version 2.0.0
13818 
13819  @liveexample{The behavior is shown in the example.,at_json_pointer}
13820  */
13821  reference at(const json_pointer& ptr)
13822  {
13823  return ptr.get_checked(this);
13824  }
13825 
13826  /*!
13827  @brief access specified element via JSON Pointer
13828 
13829  Returns a const reference to the element at with specified JSON pointer @a
13830  ptr, with bounds checking.
13831 
13832  @param[in] ptr JSON pointer to the desired element
13833 
13834  @return reference to the element pointed to by @a ptr
13835 
13836  @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
13837  begins with '0'. See example below.
13838 
13839  @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
13840  is not a number. See example below.
13841 
13842  @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
13843  is out of range. See example below.
13844 
13845  @throw out_of_range.402 if the array index '-' is used in the passed JSON
13846  pointer @a ptr. As `at` provides checked access (and no elements are
13847  implicitly inserted), the index '-' is always invalid. See example below.
13848 
13849  @throw out_of_range.403 if the JSON pointer describes a key of an object
13850  which cannot be found. See example below.
13851 
13852  @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
13853  See example below.
13854 
13855  @exceptionsafety Strong guarantee: if an exception is thrown, there are no
13856  changes in the JSON value.
13857 
13858  @complexity Constant.
13859 
13860  @since version 2.0.0
13861 
13862  @liveexample{The behavior is shown in the example.,at_json_pointer_const}
13863  */
13864  const_reference at(const json_pointer& ptr) const
13865  {
13866  return ptr.get_checked(this);
13867  }
13868 
13869  /*!
13870  @brief return flattened JSON value
13871 
13872  The function creates a JSON object whose keys are JSON pointers (see [RFC
13873  6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
13874  primitive. The original JSON value can be restored using the @ref
13875  unflatten() function.
13876 
13877  @return an object that maps JSON pointers to primitive values
13878 
13879  @note Empty objects and arrays are flattened to `null` and will not be
13880  reconstructed correctly by the @ref unflatten() function.
13881 
13882  @complexity Linear in the size the JSON value.
13883 
13884  @liveexample{The following code shows how a JSON object is flattened to an
13885  object whose keys consist of JSON pointers.,flatten}
13886 
13887  @sa @ref unflatten() for the reverse function
13888 
13889  @since version 2.0.0
13890  */
13891  basic_json flatten() const
13892  {
13893  basic_json result(value_t::object);
13894  json_pointer::flatten("", *this, result);
13895  return result;
13896  }
13897 
13898  /*!
13899  @brief unflatten a previously flattened JSON value
13900 
13901  The function restores the arbitrary nesting of a JSON value that has been
13902  flattened before using the @ref flatten() function. The JSON value must
13903  meet certain constraints:
13904  1. The value must be an object.
13905  2. The keys must be JSON pointers (see
13906  [RFC 6901](https://tools.ietf.org/html/rfc6901))
13907  3. The mapped values must be primitive JSON types.
13908 
13909  @return the original JSON from a flattened version
13910 
13911  @note Empty objects and arrays are flattened by @ref flatten() to `null`
13912  values and can not unflattened to their original type. Apart from
13913  this example, for a JSON value `j`, the following is always true:
13914  `j == j.flatten().unflatten()`.
13915 
13916  @complexity Linear in the size the JSON value.
13917 
13918  @throw type_error.314 if value is not an object
13919  @throw type_error.315 if object values are not primitive
13920 
13921  @liveexample{The following code shows how a flattened JSON object is
13922  unflattened into the original nested JSON object.,unflatten}
13923 
13924  @sa @ref flatten() for the reverse function
13925 
13926  @since version 2.0.0
13927  */
13928  basic_json unflatten() const
13929  {
13930  return json_pointer::unflatten(*this);
13931  }
13932 
13933  /// @}
13934 
13935  //////////////////////////
13936  // JSON Patch functions //
13937  //////////////////////////
13938 
13939  /// @name JSON Patch functions
13940  /// @{
13941 
13942  /*!
13943  @brief applies a JSON patch
13944 
13945  [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
13946  expressing a sequence of operations to apply to a JSON) document. With
13947  this function, a JSON Patch is applied to the current JSON value by
13948  executing all operations from the patch.
13949 
13950  @param[in] json_patch JSON patch document
13951  @return patched document
13952 
13953  @note The application of a patch is atomic: Either all operations succeed
13954  and the patched document is returned or an exception is thrown. In
13955  any case, the original value is not changed: the patch is applied
13956  to a copy of the value.
13957 
13958  @throw parse_error.104 if the JSON patch does not consist of an array of
13959  objects
13960 
13961  @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
13962  attributes are missing); example: `"operation add must have member path"`
13963 
13964  @throw out_of_range.401 if an array index is out of range.
13965 
13966  @throw out_of_range.403 if a JSON pointer inside the patch could not be
13967  resolved successfully in the current JSON value; example: `"key baz not
13968  found"`
13969 
13970  @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
13971  "move")
13972 
13973  @throw other_error.501 if "test" operation was unsuccessful
13974 
13975  @complexity Linear in the size of the JSON value and the length of the
13976  JSON patch. As usually only a fraction of the JSON value is affected by
13977  the patch, the complexity can usually be neglected.
13978 
13979  @liveexample{The following code shows how a JSON patch is applied to a
13980  value.,patch}
13981 
13982  @sa @ref diff -- create a JSON patch by comparing two JSON values
13983 
13984  @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
13985  @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
13986 
13987  @since version 2.0.0
13988  */
13989  basic_json patch(const basic_json& json_patch) const
13990  {
13991  // make a working copy to apply the patch to
13992  basic_json result = *this;
13993 
13994  // the valid JSON Patch operations
13995  enum class patch_operations {add, remove, replace, move, copy, test, invalid};
13996 
13997  const auto get_op = [](const std::string & op)
13998  {
13999  if (op == "add")
14000  {
14001  return patch_operations::add;
14002  }
14003  if (op == "remove")
14004  {
14005  return patch_operations::remove;
14006  }
14007  if (op == "replace")
14008  {
14009  return patch_operations::replace;
14010  }
14011  if (op == "move")
14012  {
14013  return patch_operations::move;
14014  }
14015  if (op == "copy")
14016  {
14017  return patch_operations::copy;
14018  }
14019  if (op == "test")
14020  {
14021  return patch_operations::test;
14022  }
14023 
14024  return patch_operations::invalid;
14025  };
14026 
14027  // wrapper for "add" operation; add value at ptr
14028  const auto operation_add = [&result](json_pointer & ptr, basic_json val)
14029  {
14030  // adding to the root of the target document means replacing it
14031  if (ptr.is_root())
14032  {
14033  result = val;
14034  }
14035  else
14036  {
14037  // make sure the top element of the pointer exists
14038  json_pointer top_pointer = ptr.top();
14039  if (top_pointer != ptr)
14040  {
14041  result.at(top_pointer);
14042  }
14043 
14044  // get reference to parent of JSON pointer ptr
14045  const auto last_path = ptr.pop_back();
14046  basic_json& parent = result[ptr];
14047 
14048  switch (parent.m_type)
14049  {
14050  case value_t::null:
14051  case value_t::object:
14052  {
14053  // use operator[] to add value
14054  parent[last_path] = val;
14055  break;
14056  }
14057 
14058  case value_t::array:
14059  {
14060  if (last_path == "-")
14061  {
14062  // special case: append to back
14063  parent.push_back(val);
14064  }
14065  else
14066  {
14067  const auto idx = json_pointer::array_index(last_path);
14068  if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
14069  {
14070  // avoid undefined behavior
14071  JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
14072  }
14073  else
14074  {
14075  // default case: insert add offset
14076  parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
14077  }
14078  }
14079  break;
14080  }
14081 
14082  default:
14083  {
14084  // if there exists a parent it cannot be primitive
14085  assert(false); // LCOV_EXCL_LINE
14086  }
14087  }
14088  }
14089  };
14090 
14091  // wrapper for "remove" operation; remove value at ptr
14092  const auto operation_remove = [&result](json_pointer & ptr)
14093  {
14094  // get reference to parent of JSON pointer ptr
14095  const auto last_path = ptr.pop_back();
14096  basic_json& parent = result.at(ptr);
14097 
14098  // remove child
14099  if (parent.is_object())
14100  {
14101  // perform range check
14102  auto it = parent.find(last_path);
14103  if (JSON_LIKELY(it != parent.end()))
14104  {
14105  parent.erase(it);
14106  }
14107  else
14108  {
14109  JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
14110  }
14111  }
14112  else if (parent.is_array())
14113  {
14114  // note erase performs range check
14115  parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
14116  }
14117  };
14118 
14119  // type check: top level value must be an array
14120  if (JSON_UNLIKELY(not json_patch.is_array()))
14121  {
14122  JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
14123  }
14124 
14125  // iterate and apply the operations
14126  for (const auto& val : json_patch)
14127  {
14128  // wrapper to get a value for an operation
14129  const auto get_value = [&val](const std::string & op,
14130  const std::string & member,
14131  bool string_type) -> basic_json&
14132  {
14133  // find value
14134  auto it = val.m_value.object->find(member);
14135 
14136  // context-sensitive error message
14137  const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
14138 
14139  // check if desired value is present
14140  if (JSON_UNLIKELY(it == val.m_value.object->end()))
14141  {
14142  JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
14143  }
14144 
14145  // check if result is of type string
14146  if (JSON_UNLIKELY(string_type and not it->second.is_string()))
14147  {
14148  JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
14149  }
14150 
14151  // no error: return value
14152  return it->second;
14153  };
14154 
14155  // type check: every element of the array must be an object
14156  if (JSON_UNLIKELY(not val.is_object()))
14157  {
14158  JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
14159  }
14160 
14161  // collect mandatory members
14162  const std::string op = get_value("op", "op", true);
14163  const std::string path = get_value(op, "path", true);
14164  json_pointer ptr(path);
14165 
14166  switch (get_op(op))
14167  {
14168  case patch_operations::add:
14169  {
14170  operation_add(ptr, get_value("add", "value", false));
14171  break;
14172  }
14173 
14174  case patch_operations::remove:
14175  {
14176  operation_remove(ptr);
14177  break;
14178  }
14179 
14180  case patch_operations::replace:
14181  {
14182  // the "path" location must exist - use at()
14183  result.at(ptr) = get_value("replace", "value", false);
14184  break;
14185  }
14186 
14187  case patch_operations::move:
14188  {
14189  const std::string from_path = get_value("move", "from", true);
14190  json_pointer from_ptr(from_path);
14191 
14192  // the "from" location must exist - use at()
14193  basic_json v = result.at(from_ptr);
14194 
14195  // The move operation is functionally identical to a
14196  // "remove" operation on the "from" location, followed
14197  // immediately by an "add" operation at the target
14198  // location with the value that was just removed.
14199  operation_remove(from_ptr);
14200  operation_add(ptr, v);
14201  break;
14202  }
14203 
14204  case patch_operations::copy:
14205  {
14206  const std::string from_path = get_value("copy", "from", true);
14207  const json_pointer from_ptr(from_path);
14208 
14209  // the "from" location must exist - use at()
14210  basic_json v = result.at(from_ptr);
14211 
14212  // The copy is functionally identical to an "add"
14213  // operation at the target location using the value
14214  // specified in the "from" member.
14215  operation_add(ptr, v);
14216  break;
14217  }
14218 
14219  case patch_operations::test:
14220  {
14221  bool success = false;
14222  JSON_TRY
14223  {
14224  // check if "value" matches the one at "path"
14225  // the "path" location must exist - use at()
14226  success = (result.at(ptr) == get_value("test", "value", false));
14227  }
14228  JSON_CATCH (out_of_range&)
14229  {
14230  // ignore out of range errors: success remains false
14231  }
14232 
14233  // throw an exception if test fails
14234  if (JSON_UNLIKELY(not success))
14235  {
14236  JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
14237  }
14238 
14239  break;
14240  }
14241 
14242  case patch_operations::invalid:
14243  {
14244  // op must be "add", "remove", "replace", "move", "copy", or
14245  // "test"
14246  JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
14247  }
14248  }
14249  }
14250 
14251  return result;
14252  }
14253 
14254  /*!
14255  @brief creates a diff as a JSON patch
14256 
14257  Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
14258  be changed into the value @a target by calling @ref patch function.
14259 
14260  @invariant For two JSON values @a source and @a target, the following code
14261  yields always `true`:
14262  @code {.cpp}
14263  source.patch(diff(source, target)) == target;
14264  @endcode
14265 
14266  @note Currently, only `remove`, `add`, and `replace` operations are
14267  generated.
14268 
14269  @param[in] source JSON value to compare from
14270  @param[in] target JSON value to compare against
14271  @param[in] path helper value to create JSON pointers
14272 
14273  @return a JSON patch to convert the @a source to @a target
14274 
14275  @complexity Linear in the lengths of @a source and @a target.
14276 
14277  @liveexample{The following code shows how a JSON patch is created as a
14278  diff for two JSON values.,diff}
14279 
14280  @sa @ref patch -- apply a JSON patch
14281 
14282  @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
14283 
14284  @since version 2.0.0
14285  */
14286  static basic_json diff(const basic_json& source, const basic_json& target,
14287  const std::string& path = "")
14288  {
14289  // the patch
14290  basic_json result(value_t::array);
14291 
14292  // if the values are the same, return empty patch
14293  if (source == target)
14294  {
14295  return result;
14296  }
14297 
14298  if (source.type() != target.type())
14299  {
14300  // different types: replace value
14301  result.push_back(
14302  {
14303  {"op", "replace"}, {"path", path}, {"value", target}
14304  });
14305  }
14306  else
14307  {
14308  switch (source.type())
14309  {
14310  case value_t::array:
14311  {
14312  // first pass: traverse common elements
14313  std::size_t i = 0;
14314  while (i < source.size() and i < target.size())
14315  {
14316  // recursive call to compare array values at index i
14317  auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
14318  result.insert(result.end(), temp_diff.begin(), temp_diff.end());
14319  ++i;
14320  }
14321 
14322  // i now reached the end of at least one array
14323  // in a second pass, traverse the remaining elements
14324 
14325  // remove my remaining elements
14326  const auto end_index = static_cast<difference_type>(result.size());
14327  while (i < source.size())
14328  {
14329  // add operations in reverse order to avoid invalid
14330  // indices
14331  result.insert(result.begin() + end_index, object(
14332  {
14333  {"op", "remove"},
14334  {"path", path + "/" + std::to_string(i)}
14335  }));
14336  ++i;
14337  }
14338 
14339  // add other remaining elements
14340  while (i < target.size())
14341  {
14342  result.push_back(
14343  {
14344  {"op", "add"},
14345  {"path", path + "/" + std::to_string(i)},
14346  {"value", target[i]}
14347  });
14348  ++i;
14349  }
14350 
14351  break;
14352  }
14353 
14354  case value_t::object:
14355  {
14356  // first pass: traverse this object's elements
14357  for (auto it = source.cbegin(); it != source.cend(); ++it)
14358  {
14359  // escape the key name to be used in a JSON patch
14360  const auto key = json_pointer::escape(it.key());
14361 
14362  if (target.find(it.key()) != target.end())
14363  {
14364  // recursive call to compare object values at key it
14365  auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
14366  result.insert(result.end(), temp_diff.begin(), temp_diff.end());
14367  }
14368  else
14369  {
14370  // found a key that is not in o -> remove it
14371  result.push_back(object(
14372  {
14373  {"op", "remove"}, {"path", path + "/" + key}
14374  }));
14375  }
14376  }
14377 
14378  // second pass: traverse other object's elements
14379  for (auto it = target.cbegin(); it != target.cend(); ++it)
14380  {
14381  if (source.find(it.key()) == source.end())
14382  {
14383  // found a key that is not in this -> add it
14384  const auto key = json_pointer::escape(it.key());
14385  result.push_back(
14386  {
14387  {"op", "add"}, {"path", path + "/" + key},
14388  {"value", it.value()}
14389  });
14390  }
14391  }
14392 
14393  break;
14394  }
14395 
14396  default:
14397  {
14398  // both primitive type: replace value
14399  result.push_back(
14400  {
14401  {"op", "replace"}, {"path", path}, {"value", target}
14402  });
14403  break;
14404  }
14405  }
14406  }
14407 
14408  return result;
14409  }
14410 
14411  /// @}
14412 };
14413 
14414 /////////////
14415 // presets //
14416 /////////////
14417 
14418 /*!
14419 @brief default JSON class
14420 
14421 This type is the default specialization of the @ref basic_json class which
14422 uses the standard template types.
14423 
14424 @since version 1.0.0
14425 */
14426 using json = basic_json<>;
14427 
14428 //////////////////
14429 // json_pointer //
14430 //////////////////
14431 
14434 json_pointer::get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const
14435 {
14436  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14437  auto result = &j;
14438 
14439  // in case no reference tokens exist, return a reference to the JSON value
14440  // j which will be overwritten by a primitive value
14441  for (const auto& reference_token : reference_tokens)
14442  {
14443  switch (result->m_type)
14444  {
14445  case detail::value_t::null:
14446  {
14447  if (reference_token == "0")
14448  {
14449  // start a new array if reference token is 0
14450  result = &result->operator[](0);
14451  }
14452  else
14453  {
14454  // start a new object otherwise
14455  result = &result->operator[](reference_token);
14456  }
14457  break;
14458  }
14459 
14460  case detail::value_t::object:
14461  {
14462  // create an entry in the object
14463  result = &result->operator[](reference_token);
14464  break;
14465  }
14466 
14467  case detail::value_t::array:
14468  {
14469  // create an entry in the array
14470  JSON_TRY
14471  {
14472  result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
14473  }
14474  JSON_CATCH(std::invalid_argument&)
14475  {
14476  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14477  }
14478  break;
14479  }
14480 
14481  /*
14482  The following code is only reached if there exists a reference
14483  token _and_ the current value is primitive. In this case, we have
14484  an error situation, because primitive values may only occur as
14485  single value; that is, with an empty list of reference tokens.
14486  */
14487  default:
14488  JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
14489  }
14490  }
14491 
14492  return *result;
14493 }
14494 
14497 json_pointer::get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const
14498 {
14499  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14500  for (const auto& reference_token : reference_tokens)
14501  {
14502  // convert null values to arrays or objects before continuing
14503  if (ptr->m_type == detail::value_t::null)
14504  {
14505  // check if reference token is a number
14506  const bool nums =
14507  std::all_of(reference_token.begin(), reference_token.end(),
14508  [](const char x)
14509  {
14510  return (x >= '0' and x <= '9');
14511  });
14512 
14513  // change value to array for numbers or "-" or to object otherwise
14514  *ptr = (nums or reference_token == "-")
14515  ? detail::value_t::array
14516  : detail::value_t::object;
14517  }
14518 
14519  switch (ptr->m_type)
14520  {
14521  case detail::value_t::object:
14522  {
14523  // use unchecked object access
14524  ptr = &ptr->operator[](reference_token);
14525  break;
14526  }
14527 
14528  case detail::value_t::array:
14529  {
14530  // error condition (cf. RFC 6901, Sect. 4)
14531  if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
14532  {
14533  JSON_THROW(detail::parse_error::create(106, 0,
14534  "array index '" + reference_token +
14535  "' must not begin with '0'"));
14536  }
14537 
14538  if (reference_token == "-")
14539  {
14540  // explicitly treat "-" as index beyond the end
14541  ptr = &ptr->operator[](ptr->m_value.array->size());
14542  }
14543  else
14544  {
14545  // convert array index to number; unchecked access
14546  JSON_TRY
14547  {
14548  ptr = &ptr->operator[](
14549  static_cast<size_type>(array_index(reference_token)));
14550  }
14551  JSON_CATCH(std::invalid_argument&)
14552  {
14553  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14554  }
14555  }
14556  break;
14557  }
14558 
14559  default:
14560  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
14561  }
14562  }
14563 
14564  return *ptr;
14565 }
14566 
14569 json_pointer::get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const
14570 {
14571  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14572  for (const auto& reference_token : reference_tokens)
14573  {
14574  switch (ptr->m_type)
14575  {
14576  case detail::value_t::object:
14577  {
14578  // note: at performs range check
14579  ptr = &ptr->at(reference_token);
14580  break;
14581  }
14582 
14583  case detail::value_t::array:
14584  {
14585  if (JSON_UNLIKELY(reference_token == "-"))
14586  {
14587  // "-" always fails the range check
14588  JSON_THROW(detail::out_of_range::create(402,
14589  "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
14590  ") is out of range"));
14591  }
14592 
14593  // error condition (cf. RFC 6901, Sect. 4)
14594  if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
14595  {
14596  JSON_THROW(detail::parse_error::create(106, 0,
14597  "array index '" + reference_token +
14598  "' must not begin with '0'"));
14599  }
14600 
14601  // note: at performs range check
14602  JSON_TRY
14603  {
14604  ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
14605  }
14606  JSON_CATCH(std::invalid_argument&)
14607  {
14608  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14609  }
14610  break;
14611  }
14612 
14613  default:
14614  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
14615  }
14616  }
14617 
14618  return *ptr;
14619 }
14620 
14623 json_pointer::get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const
14624 {
14625  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14626  for (const auto& reference_token : reference_tokens)
14627  {
14628  switch (ptr->m_type)
14629  {
14630  case detail::value_t::object:
14631  {
14632  // use unchecked object access
14633  ptr = &ptr->operator[](reference_token);
14634  break;
14635  }
14636 
14637  case detail::value_t::array:
14638  {
14639  if (JSON_UNLIKELY(reference_token == "-"))
14640  {
14641  // "-" cannot be used for const access
14642  JSON_THROW(detail::out_of_range::create(402,
14643  "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
14644  ") is out of range"));
14645  }
14646 
14647  // error condition (cf. RFC 6901, Sect. 4)
14648  if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
14649  {
14650  JSON_THROW(detail::parse_error::create(106, 0,
14651  "array index '" + reference_token +
14652  "' must not begin with '0'"));
14653  }
14654 
14655  // use unchecked array access
14656  JSON_TRY
14657  {
14658  ptr = &ptr->operator[](
14659  static_cast<size_type>(array_index(reference_token)));
14660  }
14661  JSON_CATCH(std::invalid_argument&)
14662  {
14663  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14664  }
14665  break;
14666  }
14667 
14668  default:
14669  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
14670  }
14671  }
14672 
14673  return *ptr;
14674 }
14675 
14678 json_pointer::get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const
14679 {
14680  using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
14681  for (const auto& reference_token : reference_tokens)
14682  {
14683  switch (ptr->m_type)
14684  {
14685  case detail::value_t::object:
14686  {
14687  // note: at performs range check
14688  ptr = &ptr->at(reference_token);
14689  break;
14690  }
14691 
14692  case detail::value_t::array:
14693  {
14694  if (JSON_UNLIKELY(reference_token == "-"))
14695  {
14696  // "-" always fails the range check
14697  JSON_THROW(detail::out_of_range::create(402,
14698  "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
14699  ") is out of range"));
14700  }
14701 
14702  // error condition (cf. RFC 6901, Sect. 4)
14703  if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
14704  {
14705  JSON_THROW(detail::parse_error::create(106, 0,
14706  "array index '" + reference_token +
14707  "' must not begin with '0'"));
14708  }
14709 
14710  // note: at performs range check
14711  JSON_TRY
14712  {
14713  ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
14714  }
14715  JSON_CATCH(std::invalid_argument&)
14716  {
14717  JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
14718  }
14719  break;
14720  }
14721 
14722  default:
14723  JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
14724  }
14725  }
14726 
14727  return *ptr;
14728 }
14729 
14731 void json_pointer::flatten(const std::string& reference_string,
14732  const NLOHMANN_BASIC_JSON_TPL& value,
14733  NLOHMANN_BASIC_JSON_TPL& result)
14734 {
14735  switch (value.m_type)
14736  {
14737  case detail::value_t::array:
14738  {
14739  if (value.m_value.array->empty())
14740  {
14741  // flatten empty array as null
14742  result[reference_string] = nullptr;
14743  }
14744  else
14745  {
14746  // iterate array and use index as reference string
14747  for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
14748  {
14749  flatten(reference_string + "/" + std::to_string(i),
14750  value.m_value.array->operator[](i), result);
14751  }
14752  }
14753  break;
14754  }
14755 
14756  case detail::value_t::object:
14757  {
14758  if (value.m_value.object->empty())
14759  {
14760  // flatten empty object as null
14761  result[reference_string] = nullptr;
14762  }
14763  else
14764  {
14765  // iterate object and use keys as reference string
14766  for (const auto& element : *value.m_value.object)
14767  {
14768  flatten(reference_string + "/" + escape(element.first), element.second, result);
14769  }
14770  }
14771  break;
14772  }
14773 
14774  default:
14775  {
14776  // add primitive value with its reference string
14777  result[reference_string] = value;
14778  break;
14779  }
14780  }
14781 }
14782 
14785 json_pointer::unflatten(const NLOHMANN_BASIC_JSON_TPL& value)
14786 {
14787  if (JSON_UNLIKELY(not value.is_object()))
14788  {
14789  JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
14790  }
14791 
14792  NLOHMANN_BASIC_JSON_TPL result;
14793 
14794  // iterate the JSON object values
14795  for (const auto& element : *value.m_value.object)
14796  {
14797  if (JSON_UNLIKELY(not element.second.is_primitive()))
14798  {
14799  JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
14800  }
14801 
14802  // assign value to reference pointed to by JSON pointer; Note that if
14803  // the JSON pointer is "" (i.e., points to the whole value), function
14804  // get_and_create returns a reference to result itself. An assignment
14805  // will then create a primitive value.
14806  json_pointer(element.first).get_and_create(result) = element.second;
14807  }
14808 
14809  return result;
14810 }
14811 
14812 inline bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept
14813 {
14814  return (lhs.reference_tokens == rhs.reference_tokens);
14815 }
14816 
14817 inline bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept
14818 {
14819  return not (lhs == rhs);
14820 }
14821 } // namespace nlohmann
14822 
14823 
14824 ///////////////////////
14825 // nonmember support //
14826 ///////////////////////
14827 
14828 // specialization of std::swap, and std::hash
14829 namespace std
14830 {
14831 /*!
14832 @brief exchanges the values of two JSON objects
14833 
14834 @since version 1.0.0
14835 */
14836 template<>
14837 inline void swap(nlohmann::json& j1,
14838  nlohmann::json& j2) noexcept(
14839  is_nothrow_move_constructible<nlohmann::json>::value and
14840  is_nothrow_move_assignable<nlohmann::json>::value
14841  )
14842 {
14843  j1.swap(j2);
14844 }
14845 
14846 /// hash value for JSON objects
14847 template<>
14848 struct hash<nlohmann::json>
14849 {
14850  /*!
14851  @brief return a hash value for a JSON object
14852 
14853  @since version 1.0.0
14854  */
14855  std::size_t operator()(const nlohmann::json& j) const
14856  {
14857  // a naive hashing via the string representation
14858  const auto& h = hash<nlohmann::json::string_t>();
14859  return h(j.dump());
14860  }
14861 };
14862 
14863 /// specialization for std::less<value_t>
14864 /// @note: do not remove the space after '<',
14865 /// see https://github.com/nlohmann/json/pull/679
14866 template<>
14867 struct less< ::nlohmann::detail::value_t>
14868 {
14869  /*!
14870  @brief compare two value_t enum values
14871  @since version 3.0.0
14872  */
14873  bool operator()(nlohmann::detail::value_t lhs,
14874  nlohmann::detail::value_t rhs) const noexcept
14875  {
14876  return nlohmann::detail::operator<(lhs, rhs);
14877  }
14878 };
14879 
14880 } // namespace std
14881 
14882 /*!
14883 @brief user-defined string literal for JSON values
14884 
14885 This operator implements a user-defined string literal for JSON objects. It
14886 can be used by adding `"_json"` to a string literal and returns a JSON object
14887 if no parse error occurred.
14888 
14889 @param[in] s a string representation of a JSON object
14890 @param[in] n the length of string @a s
14891 @return a JSON object
14892 
14893 @since version 1.0.0
14894 */
14895 inline nlohmann::json operator "" _json(const char* s, std::size_t n)
14896 {
14897  return nlohmann::json::parse(s, s + n);
14898 }
14899 
14900 /*!
14901 @brief user-defined string literal for JSON pointer
14902 
14903 This operator implements a user-defined string literal for JSON Pointers. It
14904 can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
14905 object if no parse error occurred.
14906 
14907 @param[in] s a string representation of a JSON Pointer
14908 @param[in] n the length of string @a s
14909 @return a JSON pointer object
14910 
14911 @since version 2.0.0
14912 */
14913 inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
14914 {
14915  return nlohmann::json::json_pointer(std::string(s, n));
14916 }
14917 
14918 // restore GCC/clang diagnostic settings
14919 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
14920  #pragma GCC diagnostic pop
14921 #endif
14922 #if defined(__clang__)
14923  #pragma GCC diagnostic pop
14924 #endif
14925 
14926 // clean up
14927 #undef JSON_CATCH
14928 #undef JSON_THROW
14929 #undef JSON_TRY
14930 #undef JSON_LIKELY
14931 #undef JSON_UNLIKELY
14932 #undef JSON_DEPRECATED
14933 #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
14934 #undef NLOHMANN_BASIC_JSON_TPL
14935 
14936 #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:825
#define JSON_UNLIKELY(x)
Definition: json.hpp:109
#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
#define JSON_TRY
Definition: json.hpp:99
#define JSON_THROW(exception)
Definition: json.hpp:98
JSON Pointer.
Definition: json.hpp:6982