Switch to unified view

a b/src/json.hpp
1
/*
2
    __ _____ _____ _____
3
 __|  |   __|     |   | |  JSON for Modern C++
4
|  |  |__   |  |  | | | |  version 2.0.2
5
|_____|_____|_____|_|___|  https://github.com/nlohmann/json
6
7
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
8
Copyright (c) 2013-2016 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>
33
#include <array>
34
#include <cassert>
35
#include <ciso646>
36
#include <cmath>
37
#include <cstddef>
38
#include <cstdint>
39
#include <cstdlib>
40
#include <functional>
41
#include <initializer_list>
42
#include <iomanip>
43
#include <iostream>
44
#include <iterator>
45
#include <limits>
46
#include <locale>
47
#include <map>
48
#include <memory>
49
#include <numeric>
50
#include <sstream>
51
#include <stdexcept>
52
#include <string>
53
#include <type_traits>
54
#include <utility>
55
#include <vector>
56
57
// exclude unsupported compilers
58
#if defined(__clang__)
59
    #define CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
60
    #if CLANG_VERSION < 30400
61
        #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
62
    #endif
63
#elif defined(__GNUC__)
64
    #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
65
    #if GCC_VERSION < 40900
66
        #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
67
    #endif
68
#endif
69
70
// disable float-equal warnings on GCC/clang
71
#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
72
    #pragma GCC diagnostic push
73
    #pragma GCC diagnostic ignored "-Wfloat-equal"
74
#endif
75
76
/*!
77
@brief namespace for Niels Lohmann
78
@see https://github.com/nlohmann
79
@since version 1.0.0
80
*/
81
namespace nlohmann
82
{
83
84
85
/*!
86
@brief unnamed namespace with internal helper functions
87
@since version 1.0.0
88
*/
89
namespace
90
{
91
/*!
92
@brief Helper to determine whether there's a key_type for T.
93
94
Thus helper is used to tell associative containers apart from other containers
95
such as sequence containers. For instance, `std::map` passes the test as it
96
contains a `mapped_type`, whereas `std::vector` fails the test.
97
98
@sa http://stackoverflow.com/a/7728728/266378
99
@since version 1.0.0
100
*/
101
template<typename T>
102
struct has_mapped_type
103
{
104
  private:
105
    template<typename C> static char test(typename C::mapped_type*);
106
    template<typename C> static char (&test(...))[2];
107
  public:
108
    static constexpr bool value = sizeof(test<T>(0)) == 1;
109
};
110
111
/*!
112
@brief helper class to create locales with decimal point
113
114
This struct is used a default locale during the JSON serialization. JSON
115
requires the decimal point to be `.`, so this function overloads the
116
`do_decimal_point()` function to return `.`. This function is called by
117
float-to-string conversions to retrieve the decimal separator between integer
118
and fractional parts.
119
120
@sa https://github.com/nlohmann/json/issues/51#issuecomment-86869315
121
@since version 2.0.0
122
*/
123
struct DecimalSeparator : std::numpunct<char>
124
{
125
    char do_decimal_point() const
126
    {
127
        return '.';
128
    }
129
};
130
131
}
132
133
/*!
134
@brief a class to store JSON values
135
136
@tparam ObjectType type for JSON objects (`std::map` by default; will be used
137
in @ref object_t)
138
@tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
139
in @ref array_t)
140
@tparam StringType type for JSON strings and object keys (`std::string` by
141
default; will be used in @ref string_t)
142
@tparam BooleanType type for JSON booleans (`bool` by default; will be used
143
in @ref boolean_t)
144
@tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
145
default; will be used in @ref number_integer_t)
146
@tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
147
`uint64_t` by default; will be used in @ref number_unsigned_t)
148
@tparam NumberFloatType type for JSON floating-point numbers (`double` by
149
default; will be used in @ref number_float_t)
150
@tparam AllocatorType type of the allocator to use (`std::allocator` by
151
default)
152
153
@requirement The class satisfies the following concept requirements:
154
- Basic
155
 - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
156
   JSON values can be default constructed. The result will be a JSON null value.
157
 - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
158
   A JSON value can be constructed from an rvalue argument.
159
 - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
160
   A JSON value can be copy-constructed from an lvalue expression.
161
 - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
162
   A JSON value van be assigned from an rvalue argument.
163
 - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
164
   A JSON value can be copy-assigned from an lvalue expression.
165
 - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
166
   JSON values can be destructed.
167
- Layout
168
 - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
169
   JSON values have
170
   [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
171
   All non-static data members are private and standard layout types, the class
172
   has no virtual functions or (virtual) base classes.
173
- Library-wide
174
 - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
175
   JSON values can be compared with `==`, see @ref
176
   operator==(const_reference,const_reference).
177
 - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
178
   JSON values can be compared with `<`, see @ref
179
   operator<(const_reference,const_reference).
180
 - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
181
   Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
182
   other compatible types, using unqualified function call @ref swap().
183
 - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
184
   JSON values can be compared against `std::nullptr_t` objects which are used
185
   to model the `null` value.
186
- Container
187
 - [Container](http://en.cppreference.com/w/cpp/concept/Container):
188
   JSON values can be used like STL containers and provide iterator access.
189
 - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
190
   JSON values can be used like STL containers and provide reverse iterator
191
   access.
192
193
@invariant The member variables @a m_value and @a m_type have the following
194
relationship:
195
- If `m_type == value_t::object`, then `m_value.object != nullptr`.
196
- If `m_type == value_t::array`, then `m_value.array != nullptr`.
197
- If `m_type == value_t::string`, then `m_value.string != nullptr`.
198
The invariants are checked by member function assert_invariant().
199
200
@internal
201
@note ObjectType trick from http://stackoverflow.com/a/9860911
202
@endinternal
203
204
@see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
205
Format](http://rfc7159.net/rfc7159)
206
207
@since version 1.0.0
208
209
@nosubgrouping
210
*/
211
template <
212
    template<typename U, typename V, typename... Args> class ObjectType = std::map,
213
    template<typename U, typename... Args> class ArrayType = std::vector,
214
    class StringType = std::string,
215
    class BooleanType = bool,
216
    class NumberIntegerType = std::int64_t,
217
    class NumberUnsignedType = std::uint64_t,
218
    class NumberFloatType = double,
219
    template<typename U> class AllocatorType = std::allocator
220
    >
221
class basic_json
222
{
223
  private:
224
    /// workaround type for MSVC
225
    using basic_json_t = basic_json<ObjectType, ArrayType, StringType,
226
          BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType,
227
          AllocatorType>;
228
229
  public:
230
    // forward declarations
231
    template<typename Base> class json_reverse_iterator;
232
    class json_pointer;
233
234
    /////////////////////
235
    // container types //
236
    /////////////////////
237
238
    /// @name container types
239
    /// The canonic container types to use @ref basic_json like any other STL
240
    /// container.
241
    /// @{
242
243
    /// the type of elements in a basic_json container
244
    using value_type = basic_json;
245
246
    /// the type of an element reference
247
    using reference = value_type&;
248
    /// the type of an element const reference
249
    using const_reference = const value_type&;
250
251
    /// a type to represent differences between iterators
252
    using difference_type = std::ptrdiff_t;
253
    /// a type to represent container sizes
254
    using size_type = std::size_t;
255
256
    /// the allocator type
257
    using allocator_type = AllocatorType<basic_json>;
258
259
    /// the type of an element pointer
260
    using pointer = typename std::allocator_traits<allocator_type>::pointer;
261
    /// the type of an element const pointer
262
    using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
263
264
    /// an iterator for a basic_json container
265
    class iterator;
266
    /// a const iterator for a basic_json container
267
    class const_iterator;
268
    /// a reverse iterator for a basic_json container
269
    using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
270
    /// a const reverse iterator for a basic_json container
271
    using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
272
273
    /// @}
274
275
276
    /*!
277
    @brief returns the allocator associated with the container
278
    */
279
    static allocator_type get_allocator()
280
    {
281
        return allocator_type();
282
    }
283
284
285
    ///////////////////////////
286
    // JSON value data types //
287
    ///////////////////////////
288
289
    /// @name JSON value data types
290
    /// The data types to store a JSON value. These types are derived from
291
    /// the template arguments passed to class @ref basic_json.
292
    /// @{
293
294
    /*!
295
    @brief a type for an object
296
297
    [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
298
    > An object is an unordered collection of zero or more name/value pairs,
299
    > where a name is a string and a value is a string, number, boolean, null,
300
    > object, or array.
301
302
    To store objects in C++, a type is defined by the template parameters
303
    described below.
304
305
    @tparam ObjectType  the container to store objects (e.g., `std::map` or
306
    `std::unordered_map`)
307
    @tparam StringType the type of the keys or names (e.g., `std::string`).
308
    The comparison function `std::less<StringType>` is used to order elements
309
    inside the container.
310
    @tparam AllocatorType the allocator to use for objects (e.g.,
311
    `std::allocator`)
312
313
    #### Default type
314
315
    With the default values for @a ObjectType (`std::map`), @a StringType
316
    (`std::string`), and @a AllocatorType (`std::allocator`), the default
317
    value for @a object_t is:
318
319
    @code {.cpp}
320
    std::map<
321
      std::string, // key_type
322
      basic_json, // value_type
323
      std::less<std::string>, // key_compare
324
      std::allocator<std::pair<const std::string, basic_json>> // allocator_type
325
    >
326
    @endcode
327
328
    #### Behavior
329
330
    The choice of @a object_t influences the behavior of the JSON class. With
331
    the default type, objects have the following behavior:
332
333
    - When all names are unique, objects will be interoperable in the sense
334
      that all software implementations receiving that object will agree on
335
      the name-value mappings.
336
    - When the names within an object are not unique, later stored name/value
337
      pairs overwrite previously stored name/value pairs, leaving the used
338
      names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will
339
      be treated as equal and both stored as `{"key": 1}`.
340
    - Internally, name/value pairs are stored in lexicographical order of the
341
      names. Objects will also be serialized (see @ref dump) in this order.
342
      For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
343
      and serialized as `{"a": 2, "b": 1}`.
344
    - When comparing objects, the order of the name/value pairs is irrelevant.
345
      This makes objects interoperable in the sense that they will not be
346
      affected by these differences. For instance, `{"b": 1, "a": 2}` and
347
      `{"a": 2, "b": 1}` will be treated as equal.
348
349
    #### Limits
350
351
    [RFC 7159](http://rfc7159.net/rfc7159) specifies:
352
    > An implementation may set limits on the maximum depth of nesting.
353
354
    In this class, the object's limit of nesting is not constraint explicitly.
355
    However, a maximum depth of nesting may be introduced by the compiler or
356
    runtime environment. A theoretical limit can be queried by calling the
357
    @ref max_size function of a JSON object.
358
359
    #### Storage
360
361
    Objects are stored as pointers in a @ref basic_json type. That is, for any
362
    access to object values, a pointer of type `object_t*` must be
363
    dereferenced.
364
365
    @sa @ref array_t -- type for an array value
366
367
    @since version 1.0.0
368
369
    @note The order name/value pairs are added to the object is *not*
370
    preserved by the library. Therefore, iterating an object may return
371
    name/value pairs in a different order than they were originally stored. In
372
    fact, keys will be traversed in alphabetical order as `std::map` with
373
    `std::less` is used by default. Please note this behavior conforms to [RFC
374
    7159](http://rfc7159.net/rfc7159), because any order implements the
375
    specified "unordered" nature of JSON objects.
376
    */
377
    using object_t = ObjectType<StringType,
378
          basic_json,
379
          std::less<StringType>,
380
          AllocatorType<std::pair<const StringType,
381
          basic_json>>>;
382
383
    /*!
384
    @brief a type for an array
385
386
    [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
387
    > An array is an ordered sequence of zero or more values.
388
389
    To store objects in C++, a type is defined by the template parameters
390
    explained below.
391
392
    @tparam ArrayType  container type to store arrays (e.g., `std::vector` or
393
    `std::list`)
394
    @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
395
396
    #### Default type
397
398
    With the default values for @a ArrayType (`std::vector`) and @a
399
    AllocatorType (`std::allocator`), the default value for @a array_t is:
400
401
    @code {.cpp}
402
    std::vector<
403
      basic_json, // value_type
404
      std::allocator<basic_json> // allocator_type
405
    >
406
    @endcode
407
408
    #### Limits
409
410
    [RFC 7159](http://rfc7159.net/rfc7159) specifies:
411
    > An implementation may set limits on the maximum depth of nesting.
412
413
    In this class, the array's limit of nesting is not constraint explicitly.
414
    However, a maximum depth of nesting may be introduced by the compiler or
415
    runtime environment. A theoretical limit can be queried by calling the
416
    @ref max_size function of a JSON array.
417
418
    #### Storage
419
420
    Arrays are stored as pointers in a @ref basic_json type. That is, for any
421
    access to array values, a pointer of type `array_t*` must be dereferenced.
422
423
    @sa @ref object_t -- type for an object value
424
425
    @since version 1.0.0
426
    */
427
    using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
428
429
    /*!
430
    @brief a type for a string
431
432
    [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
433
    > A string is a sequence of zero or more Unicode characters.
434
435
    To store objects in C++, a type is defined by the template parameter
436
    described below. Unicode values are split by the JSON class into
437
    byte-sized characters during deserialization.
438
439
    @tparam StringType  the container to store strings (e.g., `std::string`).
440
    Note this container is used for keys/names in objects, see @ref object_t.
441
442
    #### Default type
443
444
    With the default values for @a StringType (`std::string`), the default
445
    value for @a string_t is:
446
447
    @code {.cpp}
448
    std::string
449
    @endcode
450
451
    #### String comparison
452
453
    [RFC 7159](http://rfc7159.net/rfc7159) states:
454
    > Software implementations are typically required to test names of object
455
    > members for equality. Implementations that transform the textual
456
    > representation into sequences of Unicode code units and then perform the
457
    > comparison numerically, code unit by code unit, are interoperable in the
458
    > sense that implementations will agree in all cases on equality or
459
    > inequality of two strings. For example, implementations that compare
460
    > strings with escaped characters unconverted may incorrectly find that
461
    > `"a\\b"` and `"a\u005Cb"` are not equal.
462
463
    This implementation is interoperable as it does compare strings code unit
464
    by code unit.
465
466
    #### Storage
467
468
    String values are stored as pointers in a @ref basic_json type. That is,
469
    for any access to string values, a pointer of type `string_t*` must be
470
    dereferenced.
471
472
    @since version 1.0.0
473
    */
474
    using string_t = StringType;
475
476
    /*!
477
    @brief a type for a boolean
478
479
    [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
480
    type which differentiates the two literals `true` and `false`.
481
482
    To store objects in C++, a type is defined by the template parameter @a
483
    BooleanType which chooses the type to use.
484
485
    #### Default type
486
487
    With the default values for @a BooleanType (`bool`), the default value for
488
    @a boolean_t is:
489
490
    @code {.cpp}
491
    bool
492
    @endcode
493
494
    #### Storage
495
496
    Boolean values are stored directly inside a @ref basic_json type.
497
498
    @since version 1.0.0
499
    */
500
    using boolean_t = BooleanType;
501
502
    /*!
503
    @brief a type for a number (integer)
504
505
    [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
506
    > The representation of numbers is similar to that used in most
507
    > programming languages. A number is represented in base 10 using decimal
508
    > digits. It contains an integer component that may be prefixed with an
509
    > optional minus sign, which may be followed by a fraction part and/or an
510
    > exponent part. Leading zeros are not allowed. (...) Numeric values that
511
    > cannot be represented in the grammar below (such as Infinity and NaN)
512
    > are not permitted.
513
514
    This description includes both integer and floating-point numbers.
515
    However, C++ allows more precise storage if it is known whether the number
516
    is a signed integer, an unsigned integer or a floating-point number.
517
    Therefore, three different types, @ref number_integer_t, @ref
518
    number_unsigned_t and @ref number_float_t are used.
519
520
    To store integer numbers in C++, a type is defined by the template
521
    parameter @a NumberIntegerType which chooses the type to use.
522
523
    #### Default type
524
525
    With the default values for @a NumberIntegerType (`int64_t`), the default
526
    value for @a number_integer_t is:
527
528
    @code {.cpp}
529
    int64_t
530
    @endcode
531
532
    #### Default behavior
533
534
    - The restrictions about leading zeros is not enforced in C++. Instead,
535
      leading zeros in integer literals lead to an interpretation as octal
536
      number. Internally, the value will be stored as decimal number. For
537
      instance, the C++ integer literal `010` will be serialized to `8`.
538
      During deserialization, leading zeros yield an error.
539
    - Not-a-number (NaN) values will be serialized to `null`.
540
541
    #### Limits
542
543
    [RFC 7159](http://rfc7159.net/rfc7159) specifies:
544
    > An implementation may set limits on the range and precision of numbers.
545
546
    When the default type is used, the maximal integer number that can be
547
    stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
548
    that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
549
    that are out of range will yield over/underflow when used in a
550
    constructor. During deserialization, too large or small integer numbers
551
    will be automatically be stored as @ref number_unsigned_t or @ref
552
    number_float_t.
553
554
    [RFC 7159](http://rfc7159.net/rfc7159) further states:
555
    > Note that when such software is used, numbers that are integers and are
556
    > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
557
    > that implementations will agree exactly on their numeric values.
558
559
    As this range is a subrange of the exactly supported range [INT64_MIN,
560
    INT64_MAX], this class's integer type is interoperable.
561
562
    #### Storage
563
564
    Integer number values are stored directly inside a @ref basic_json type.
565
566
    @sa @ref number_float_t -- type for number values (floating-point)
567
568
    @sa @ref number_unsigned_t -- type for number values (unsigned integer)
569
570
    @since version 1.0.0
571
    */
572
    using number_integer_t = NumberIntegerType;
573
574
    /*!
575
    @brief a type for a number (unsigned)
576
577
    [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
578
    > The representation of numbers is similar to that used in most
579
    > programming languages. A number is represented in base 10 using decimal
580
    > digits. It contains an integer component that may be prefixed with an
581
    > optional minus sign, which may be followed by a fraction part and/or an
582
    > exponent part. Leading zeros are not allowed. (...) Numeric values that
583
    > cannot be represented in the grammar below (such as Infinity and NaN)
584
    > are not permitted.
585
586
    This description includes both integer and floating-point numbers.
587
    However, C++ allows more precise storage if it is known whether the number
588
    is a signed integer, an unsigned integer or a floating-point number.
589
    Therefore, three different types, @ref number_integer_t, @ref
590
    number_unsigned_t and @ref number_float_t are used.
591
592
    To store unsigned integer numbers in C++, a type is defined by the
593
    template parameter @a NumberUnsignedType which chooses the type to use.
594
595
    #### Default type
596
597
    With the default values for @a NumberUnsignedType (`uint64_t`), the
598
    default value for @a number_unsigned_t is:
599
600
    @code {.cpp}
601
    uint64_t
602
    @endcode
603
604
    #### Default behavior
605
606
    - The restrictions about leading zeros is not enforced in C++. Instead,
607
      leading zeros in integer literals lead to an interpretation as octal
608
      number. Internally, the value will be stored as decimal number. For
609
      instance, the C++ integer literal `010` will be serialized to `8`.
610
      During deserialization, leading zeros yield an error.
611
    - Not-a-number (NaN) values will be serialized to `null`.
612
613
    #### Limits
614
615
    [RFC 7159](http://rfc7159.net/rfc7159) specifies:
616
    > An implementation may set limits on the range and precision of numbers.
617
618
    When the default type is used, the maximal integer number that can be
619
    stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
620
    number that can be stored is `0`. Integer numbers that are out of range
621
    will yield over/underflow when used in a constructor. During
622
    deserialization, too large or small integer numbers will be automatically
623
    be stored as @ref number_integer_t or @ref number_float_t.
624
625
    [RFC 7159](http://rfc7159.net/rfc7159) further states:
626
    > Note that when such software is used, numbers that are integers and are
627
    > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
628
    > that implementations will agree exactly on their numeric values.
629
630
    As this range is a subrange (when considered in conjunction with the
631
    number_integer_t type) of the exactly supported range [0, UINT64_MAX],
632
    this class's integer type is interoperable.
633
634
    #### Storage
635
636
    Integer number values are stored directly inside a @ref basic_json type.
637
638
    @sa @ref number_float_t -- type for number values (floating-point)
639
    @sa @ref number_integer_t -- type for number values (integer)
640
641
    @since version 2.0.0
642
    */
643
    using number_unsigned_t = NumberUnsignedType;
644
645
    /*!
646
    @brief a type for a number (floating-point)
647
648
    [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
649
    > The representation of numbers is similar to that used in most
650
    > programming languages. A number is represented in base 10 using decimal
651
    > digits. It contains an integer component that may be prefixed with an
652
    > optional minus sign, which may be followed by a fraction part and/or an
653
    > exponent part. Leading zeros are not allowed. (...) Numeric values that
654
    > cannot be represented in the grammar below (such as Infinity and NaN)
655
    > are not permitted.
656
657
    This description includes both integer and floating-point numbers.
658
    However, C++ allows more precise storage if it is known whether the number
659
    is a signed integer, an unsigned integer or a floating-point number.
660
    Therefore, three different types, @ref number_integer_t, @ref
661
    number_unsigned_t and @ref number_float_t are used.
662
663
    To store floating-point numbers in C++, a type is defined by the template
664
    parameter @a NumberFloatType which chooses the type to use.
665
666
    #### Default type
667
668
    With the default values for @a NumberFloatType (`double`), the default
669
    value for @a number_float_t is:
670
671
    @code {.cpp}
672
    double
673
    @endcode
674
675
    #### Default behavior
676
677
    - The restrictions about leading zeros is not enforced in C++. Instead,
678
      leading zeros in floating-point literals will be ignored. Internally,
679
      the value will be stored as decimal number. For instance, the C++
680
      floating-point literal `01.2` will be serialized to `1.2`. During
681
      deserialization, leading zeros yield an error.
682
    - Not-a-number (NaN) values will be serialized to `null`.
683
684
    #### Limits
685
686
    [RFC 7159](http://rfc7159.net/rfc7159) states:
687
    > This specification allows implementations to set limits on the range and
688
    > precision of numbers accepted. Since software that implements IEEE
689
    > 754-2008 binary64 (double precision) numbers is generally available and
690
    > widely used, good interoperability can be achieved by implementations
691
    > that expect no more precision or range than these provide, in the sense
692
    > that implementations will approximate JSON numbers within the expected
693
    > precision.
694
695
    This implementation does exactly follow this approach, as it uses double
696
    precision floating-point numbers. Note values smaller than
697
    `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
698
    will be stored as NaN internally and be serialized to `null`.
699
700
    #### Storage
701
702
    Floating-point number values are stored directly inside a @ref basic_json
703
    type.
704
705
    @sa @ref number_integer_t -- type for number values (integer)
706
707
    @sa @ref number_unsigned_t -- type for number values (unsigned integer)
708
709
    @since version 1.0.0
710
    */
711
    using number_float_t = NumberFloatType;
712
713
    /// @}
714
715
716
    ///////////////////////////
717
    // JSON type enumeration //
718
    ///////////////////////////
719
720
    /*!
721
    @brief the JSON type enumeration
722
723
    This enumeration collects the different JSON types. It is internally used
724
    to distinguish the stored values, and the functions @ref is_null(), @ref
725
    is_object(), @ref is_array(), @ref is_string(), @ref is_boolean(), @ref
726
    is_number() (with @ref is_number_integer(), @ref is_number_unsigned(), and
727
    @ref is_number_float()), @ref is_discarded(), @ref is_primitive(), and
728
    @ref is_structured() rely on it.
729
730
    @note There are three enumeration entries (number_integer,
731
    number_unsigned, and number_float), because the library distinguishes
732
    these three types for numbers: @ref number_unsigned_t is used for unsigned
733
    integers, @ref number_integer_t is used for signed integers, and @ref
734
    number_float_t is used for floating-point numbers or to approximate
735
    integers which do not fit in the limits of their respective type.
736
737
    @sa @ref basic_json(const value_t value_type) -- create a JSON value with
738
    the default value for a given type
739
740
    @since version 1.0.0
741
    */
742
    enum class value_t : uint8_t
743
    {
744
        null,            ///< null value
745
        object,          ///< object (unordered set of name/value pairs)
746
        array,           ///< array (ordered collection of values)
747
        string,          ///< string value
748
        boolean,         ///< boolean value
749
        number_integer,  ///< number value (signed integer)
750
        number_unsigned, ///< number value (unsigned integer)
751
        number_float,    ///< number value (floating-point)
752
        discarded        ///< discarded by the the parser callback function
753
    };
754
755
756
  private:
757
758
    /// helper for exception-safe object creation
759
    template<typename T, typename... Args>
760
    static T* create(Args&& ... args)
761
    {
762
        AllocatorType<T> alloc;
763
        auto deleter = [&](T * object)
764
        {
765
            alloc.deallocate(object, 1);
766
        };
767
        std::unique_ptr<T, decltype(deleter)> object(alloc.allocate(1), deleter);
768
        alloc.construct(object.get(), std::forward<Args>(args)...);
769
        assert(object.get() != nullptr);
770
        return object.release();
771
    }
772
773
    ////////////////////////
774
    // JSON value storage //
775
    ////////////////////////
776
777
    /*!
778
    @brief a JSON value
779
780
    The actual storage for a JSON value of the @ref basic_json class. This
781
    union combines the different storage types for the JSON value types
782
    defined in @ref value_t.
783
784
    JSON type | value_t type    | used type
785
    --------- | --------------- | ------------------------
786
    object    | object          | pointer to @ref object_t
787
    array     | array           | pointer to @ref array_t
788
    string    | string          | pointer to @ref string_t
789
    boolean   | boolean         | @ref boolean_t
790
    number    | number_integer  | @ref number_integer_t
791
    number    | number_unsigned | @ref number_unsigned_t
792
    number    | number_float    | @ref number_float_t
793
    null      | null            | *no value is stored*
794
795
    @note Variable-length types (objects, arrays, and strings) are stored as
796
    pointers. The size of the union should not exceed 64 bits if the default
797
    value types are used.
798
799
    @since version 1.0.0
800
    */
801
    union json_value
802
    {
803
        /// object (stored with pointer to save storage)
804
        object_t* object;
805
        /// array (stored with pointer to save storage)
806
        array_t* array;
807
        /// string (stored with pointer to save storage)
808
        string_t* string;
809
        /// boolean
810
        boolean_t boolean;
811
        /// number (integer)
812
        number_integer_t number_integer;
813
        /// number (unsigned integer)
814
        number_unsigned_t number_unsigned;
815
        /// number (floating-point)
816
        number_float_t number_float;
817
818
        /// default constructor (for null values)
819
        json_value() = default;
820
        /// constructor for booleans
821
        json_value(boolean_t v) noexcept : boolean(v) {}
822
        /// constructor for numbers (integer)
823
        json_value(number_integer_t v) noexcept : number_integer(v) {}
824
        /// constructor for numbers (unsigned)
825
        json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
826
        /// constructor for numbers (floating-point)
827
        json_value(number_float_t v) noexcept : number_float(v) {}
828
        /// constructor for empty values of a given type
829
        json_value(value_t t)
830
        {
831
            switch (t)
832
            {
833
                case value_t::object:
834
                {
835
                    object = create<object_t>();
836
                    break;
837
                }
838
839
                case value_t::array:
840
                {
841
                    array = create<array_t>();
842
                    break;
843
                }
844
845
                case value_t::string:
846
                {
847
                    string = create<string_t>("");
848
                    break;
849
                }
850
851
                case value_t::boolean:
852
                {
853
                    boolean = boolean_t(false);
854
                    break;
855
                }
856
857
                case value_t::number_integer:
858
                {
859
                    number_integer = number_integer_t(0);
860
                    break;
861
                }
862
863
                case value_t::number_unsigned:
864
                {
865
                    number_unsigned = number_unsigned_t(0);
866
                    break;
867
                }
868
869
                case value_t::number_float:
870
                {
871
                    number_float = number_float_t(0.0);
872
                    break;
873
                }
874
875
                default:
876
                {
877
                    break;
878
                }
879
            }
880
        }
881
882
        /// constructor for strings
883
        json_value(const string_t& value)
884
        {
885
            string = create<string_t>(value);
886
        }
887
888
        /// constructor for objects
889
        json_value(const object_t& value)
890
        {
891
            object = create<object_t>(value);
892
        }
893
894
        /// constructor for arrays
895
        json_value(const array_t& value)
896
        {
897
            array = create<array_t>(value);
898
        }
899
    };
900
901
    /*!
902
    @brief checks the class invariants
903
904
    This function asserts the class invariants. It needs to be called at the
905
    end of every constructor to make sure that created objects respect the
906
    invariant. Furthermore, it has to be called each time the type of a JSON
907
    value is changed, because the invariant expresses a relationship between
908
    @a m_type and @a m_value.
909
    */
910
    void assert_invariant() const
911
    {
912
        assert(m_type != value_t::object or m_value.object != nullptr);
913
        assert(m_type != value_t::array or m_value.array != nullptr);
914
        assert(m_type != value_t::string or m_value.string != nullptr);
915
    }
916
917
  public:
918
    //////////////////////////
919
    // JSON parser callback //
920
    //////////////////////////
921
922
    /*!
923
    @brief JSON callback events
924
925
    This enumeration lists the parser events that can trigger calling a
926
    callback function of type @ref parser_callback_t during parsing.
927
928
    @image html callback_events.png "Example when certain parse events are triggered"
929
930
    @since version 1.0.0
931
    */
932
    enum class parse_event_t : uint8_t
933
    {
934
        /// the parser read `{` and started to process a JSON object
935
        object_start,
936
        /// the parser read `}` and finished processing a JSON object
937
        object_end,
938
        /// the parser read `[` and started to process a JSON array
939
        array_start,
940
        /// the parser read `]` and finished processing a JSON array
941
        array_end,
942
        /// the parser read a key of a value in an object
943
        key,
944
        /// the parser finished reading a JSON value
945
        value
946
    };
947
948
    /*!
949
    @brief per-element parser callback type
950
951
    With a parser callback function, the result of parsing a JSON text can be
952
    influenced. When passed to @ref parse(std::istream&, const
953
    parser_callback_t) or @ref parse(const string_t&, const parser_callback_t),
954
    it is called on certain events (passed as @ref parse_event_t via parameter
955
    @a event) with a set recursion depth @a depth and context JSON value
956
    @a parsed. The return value of the callback function is a boolean
957
    indicating whether the element that emitted the callback shall be kept or
958
    not.
959
960
    We distinguish six scenarios (determined by the event type) in which the
961
    callback function can be called. The following table describes the values
962
    of the parameters @a depth, @a event, and @a parsed.
963
964
    parameter @a event | description | parameter @a depth | parameter @a parsed
965
    ------------------ | ----------- | ------------------ | -------------------
966
    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
967
    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
968
    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
969
    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
970
    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
971
    parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
972
973
    @image html callback_events.png "Example when certain parse events are triggered"
974
975
    Discarding a value (i.e., returning `false`) has different effects
976
    depending on the context in which function was called:
977
978
    - Discarded values in structured types are skipped. That is, the parser
979
      will behave as if the discarded value was never read.
980
    - In case a value outside a structured type is skipped, it is replaced
981
      with `null`. This case happens if the top-level element is skipped.
982
983
    @param[in] depth  the depth of the recursion during parsing
984
985
    @param[in] event  an event of type parse_event_t indicating the context in
986
    the callback function has been called
987
988
    @param[in,out] parsed  the current intermediate parse result; note that
989
    writing to this value has no effect for parse_event_t::key events
990
991
    @return Whether the JSON value which called the function during parsing
992
    should be kept (`true`) or not (`false`). In the latter case, it is either
993
    skipped completely or replaced by an empty discarded object.
994
995
    @sa @ref parse(std::istream&, parser_callback_t) or
996
    @ref parse(const string_t&, parser_callback_t) for examples
997
998
    @since version 1.0.0
999
    */
1000
    using parser_callback_t = std::function<bool(int depth,
1001
                              parse_event_t event,
1002
                              basic_json& parsed)>;
1003
1004
1005
    //////////////////
1006
    // constructors //
1007
    //////////////////
1008
1009
    /// @name constructors and destructors
1010
    /// Constructors of class @ref basic_json, copy/move constructor, copy
1011
    /// assignment, static functions creating objects, and the destructor.
1012
    /// @{
1013
1014
    /*!
1015
    @brief create an empty value with a given type
1016
1017
    Create an empty JSON value with a given type. The value will be default
1018
    initialized with an empty value which depends on the type:
1019
1020
    Value type  | initial value
1021
    ----------- | -------------
1022
    null        | `null`
1023
    boolean     | `false`
1024
    string      | `""`
1025
    number      | `0`
1026
    object      | `{}`
1027
    array       | `[]`
1028
1029
    @param[in] value_type  the type of the value to create
1030
1031
    @complexity Constant.
1032
1033
    @throw std::bad_alloc if allocation for object, array, or string value
1034
    fails
1035
1036
    @liveexample{The following code shows the constructor for different @ref
1037
    value_t values,basic_json__value_t}
1038
1039
    @sa @ref basic_json(std::nullptr_t) -- create a `null` value
1040
    @sa @ref basic_json(boolean_t value) -- create a boolean value
1041
    @sa @ref basic_json(const string_t&) -- create a string value
1042
    @sa @ref basic_json(const object_t&) -- create a object value
1043
    @sa @ref basic_json(const array_t&) -- create a array value
1044
    @sa @ref basic_json(const number_float_t) -- create a number
1045
    (floating-point) value
1046
    @sa @ref basic_json(const number_integer_t) -- create a number (integer)
1047
    value
1048
    @sa @ref basic_json(const number_unsigned_t) -- create a number (unsigned)
1049
    value
1050
1051
    @since version 1.0.0
1052
    */
1053
    basic_json(const value_t value_type)
1054
        : m_type(value_type), m_value(value_type)
1055
    {
1056
        assert_invariant();
1057
    }
1058
1059
    /*!
1060
    @brief create a null object (implicitly)
1061
1062
    Create a `null` JSON value. This is the implicit version of the `null`
1063
    value constructor as it takes no parameters.
1064
1065
    @note The class invariant is satisfied, because it poses no requirements
1066
    for null values.
1067
1068
    @complexity Constant.
1069
1070
    @exceptionsafety No-throw guarantee: this constructor never throws
1071
    exceptions.
1072
1073
    @requirement This function helps `basic_json` satisfying the
1074
    [Container](http://en.cppreference.com/w/cpp/concept/Container)
1075
    requirements:
1076
    - The complexity is constant.
1077
    - As postcondition, it holds: `basic_json().empty() == true`.
1078
1079
    @liveexample{The following code shows the constructor for a `null` JSON
1080
    value.,basic_json}
1081
1082
    @sa @ref basic_json(std::nullptr_t) -- create a `null` value
1083
1084
    @since version 1.0.0
1085
    */
1086
    basic_json() = default;
1087
1088
    /*!
1089
    @brief create a null object (explicitly)
1090
1091
    Create a `null` JSON value. This is the explicitly version of the `null`
1092
    value constructor as it takes a null pointer as parameter. It allows to
1093
    create `null` values by explicitly assigning a `nullptr` to a JSON value.
1094
    The passed null pointer itself is not read -- it is only used to choose
1095
    the right constructor.
1096
1097
    @complexity Constant.
1098
1099
    @exceptionsafety No-throw guarantee: this constructor never throws
1100
    exceptions.
1101
1102
    @liveexample{The following code shows the constructor with null pointer
1103
    parameter.,basic_json__nullptr_t}
1104
1105
    @sa @ref basic_json() -- default constructor (implicitly creating a `null`
1106
    value)
1107
1108
    @since version 1.0.0
1109
    */
1110
    basic_json(std::nullptr_t) noexcept
1111
        : basic_json(value_t::null)
1112
    {
1113
        assert_invariant();
1114
    }
1115
1116
    /*!
1117
    @brief create an object (explicit)
1118
1119
    Create an object JSON value with a given content.
1120
1121
    @param[in] val  a value for the object
1122
1123
    @complexity Linear in the size of the passed @a val.
1124
1125
    @throw std::bad_alloc if allocation for object value fails
1126
1127
    @liveexample{The following code shows the constructor with an @ref
1128
    object_t parameter.,basic_json__object_t}
1129
1130
    @sa @ref basic_json(const CompatibleObjectType&) -- create an object value
1131
    from a compatible STL container
1132
1133
    @since version 1.0.0
1134
    */
1135
    basic_json(const object_t& val)
1136
        : m_type(value_t::object), m_value(val)
1137
    {
1138
        assert_invariant();
1139
    }
1140
1141
    /*!
1142
    @brief create an object (implicit)
1143
1144
    Create an object JSON value with a given content. This constructor allows
1145
    any type @a CompatibleObjectType that can be used to construct values of
1146
    type @ref object_t.
1147
1148
    @tparam CompatibleObjectType An object type whose `key_type` and
1149
    `value_type` is compatible to @ref object_t. Examples include `std::map`,
1150
    `std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with
1151
    a `key_type` of `std::string`, and a `value_type` from which a @ref
1152
    basic_json value can be constructed.
1153
1154
    @param[in] val  a value for the object
1155
1156
    @complexity Linear in the size of the passed @a val.
1157
1158
    @throw std::bad_alloc if allocation for object value fails
1159
1160
    @liveexample{The following code shows the constructor with several
1161
    compatible object type parameters.,basic_json__CompatibleObjectType}
1162
1163
    @sa @ref basic_json(const object_t&) -- create an object value
1164
1165
    @since version 1.0.0
1166
    */
1167
    template <class CompatibleObjectType, typename
1168
              std::enable_if<
1169
                  std::is_constructible<typename object_t::key_type, typename CompatibleObjectType::key_type>::value and
1170
                  std::is_constructible<basic_json, typename CompatibleObjectType::mapped_type>::value, int>::type
1171
              = 0>
1172
    basic_json(const CompatibleObjectType& val)
1173
        : m_type(value_t::object)
1174
    {
1175
        using std::begin;
1176
        using std::end;
1177
        m_value.object = create<object_t>(begin(val), end(val));
1178
        assert_invariant();
1179
    }
1180
1181
    /*!
1182
    @brief create an array (explicit)
1183
1184
    Create an array JSON value with a given content.
1185
1186
    @param[in] val  a value for the array
1187
1188
    @complexity Linear in the size of the passed @a val.
1189
1190
    @throw std::bad_alloc if allocation for array value fails
1191
1192
    @liveexample{The following code shows the constructor with an @ref array_t
1193
    parameter.,basic_json__array_t}
1194
1195
    @sa @ref basic_json(const CompatibleArrayType&) -- create an array value
1196
    from a compatible STL containers
1197
1198
    @since version 1.0.0
1199
    */
1200
    basic_json(const array_t& val)
1201
        : m_type(value_t::array), m_value(val)
1202
    {
1203
        assert_invariant();
1204
    }
1205
1206
    /*!
1207
    @brief create an array (implicit)
1208
1209
    Create an array JSON value with a given content. This constructor allows
1210
    any type @a CompatibleArrayType that can be used to construct values of
1211
    type @ref array_t.
1212
1213
    @tparam CompatibleArrayType An object type whose `value_type` is
1214
    compatible to @ref array_t. Examples include `std::vector`, `std::deque`,
1215
    `std::list`, `std::forward_list`, `std::array`, `std::set`,
1216
    `std::unordered_set`, `std::multiset`, and `unordered_multiset` with a
1217
    `value_type` from which a @ref basic_json value can be constructed.
1218
1219
    @param[in] val  a value for the array
1220
1221
    @complexity Linear in the size of the passed @a val.
1222
1223
    @throw std::bad_alloc if allocation for array value fails
1224
1225
    @liveexample{The following code shows the constructor with several
1226
    compatible array type parameters.,basic_json__CompatibleArrayType}
1227
1228
    @sa @ref basic_json(const array_t&) -- create an array value
1229
1230
    @since version 1.0.0
1231
    */
1232
    template <class CompatibleArrayType, typename
1233
              std::enable_if<
1234
                  not std::is_same<CompatibleArrayType, typename basic_json_t::iterator>::value and
1235
                  not std::is_same<CompatibleArrayType, typename basic_json_t::const_iterator>::value and
1236
                  not std::is_same<CompatibleArrayType, typename basic_json_t::reverse_iterator>::value and
1237
                  not std::is_same<CompatibleArrayType, typename basic_json_t::const_reverse_iterator>::value and
1238
                  not std::is_same<CompatibleArrayType, typename array_t::iterator>::value and
1239
                  not std::is_same<CompatibleArrayType, typename array_t::const_iterator>::value and
1240
                  std::is_constructible<basic_json, typename CompatibleArrayType::value_type>::value, int>::type
1241
              = 0>
1242
    basic_json(const CompatibleArrayType& val)
1243
        : m_type(value_t::array)
1244
    {
1245
        using std::begin;
1246
        using std::end;
1247
        m_value.array = create<array_t>(begin(val), end(val));
1248
        assert_invariant();
1249
    }
1250
1251
    /*!
1252
    @brief create a string (explicit)
1253
1254
    Create an string JSON value with a given content.
1255
1256
    @param[in] val  a value for the string
1257
1258
    @complexity Linear in the size of the passed @a val.
1259
1260
    @throw std::bad_alloc if allocation for string value fails
1261
1262
    @liveexample{The following code shows the constructor with an @ref
1263
    string_t parameter.,basic_json__string_t}
1264
1265
    @sa @ref basic_json(const typename string_t::value_type*) -- create a
1266
    string value from a character pointer
1267
    @sa @ref basic_json(const CompatibleStringType&) -- create a string value
1268
    from a compatible string container
1269
1270
    @since version 1.0.0
1271
    */
1272
    basic_json(const string_t& val)
1273
        : m_type(value_t::string), m_value(val)
1274
    {
1275
        assert_invariant();
1276
    }
1277
1278
    /*!
1279
    @brief create a string (explicit)
1280
1281
    Create a string JSON value with a given content.
1282
1283
    @param[in] val  a literal value for the string
1284
1285
    @complexity Linear in the size of the passed @a val.
1286
1287
    @throw std::bad_alloc if allocation for string value fails
1288
1289
    @liveexample{The following code shows the constructor with string literal
1290
    parameter.,basic_json__string_t_value_type}
1291
1292
    @sa @ref basic_json(const string_t&) -- create a string value
1293
    @sa @ref basic_json(const CompatibleStringType&) -- create a string value
1294
    from a compatible string container
1295
1296
    @since version 1.0.0
1297
    */
1298
    basic_json(const typename string_t::value_type* val)
1299
        : basic_json(string_t(val))
1300
    {
1301
        assert_invariant();
1302
    }
1303
1304
    /*!
1305
    @brief create a string (implicit)
1306
1307
    Create a string JSON value with a given content.
1308
1309
    @param[in] val  a value for the string
1310
1311
    @tparam CompatibleStringType an string type which is compatible to @ref
1312
    string_t, for instance `std::string`.
1313
1314
    @complexity Linear in the size of the passed @a val.
1315
1316
    @throw std::bad_alloc if allocation for string value fails
1317
1318
    @liveexample{The following code shows the construction of a string value
1319
    from a compatible type.,basic_json__CompatibleStringType}
1320
1321
    @sa @ref basic_json(const string_t&) -- create a string value
1322
    @sa @ref basic_json(const typename string_t::value_type*) -- create a
1323
    string value from a character pointer
1324
1325
    @since version 1.0.0
1326
    */
1327
    template <class CompatibleStringType, typename
1328
              std::enable_if<
1329
                  std::is_constructible<string_t, CompatibleStringType>::value, int>::type
1330
              = 0>
1331
    basic_json(const CompatibleStringType& val)
1332
        : basic_json(string_t(val))
1333
    {
1334
        assert_invariant();
1335
    }
1336
1337
    /*!
1338
    @brief create a boolean (explicit)
1339
1340
    Creates a JSON boolean type from a given value.
1341
1342
    @param[in] val  a boolean value to store
1343
1344
    @complexity Constant.
1345
1346
    @liveexample{The example below demonstrates boolean
1347
    values.,basic_json__boolean_t}
1348
1349
    @since version 1.0.0
1350
    */
1351
    basic_json(boolean_t val) noexcept
1352
        : m_type(value_t::boolean), m_value(val)
1353
    {
1354
        assert_invariant();
1355
    }
1356
1357
    /*!
1358
    @brief create an integer number (explicit)
1359
1360
    Create an integer number JSON value with a given content.
1361
1362
    @tparam T A helper type to remove this function via SFINAE in case @ref
1363
    number_integer_t is the same as `int`. In this case, this constructor
1364
    would have the same signature as @ref basic_json(const int value). Note
1365
    the helper type @a T is not visible in this constructor's interface.
1366
1367
    @param[in] val  an integer to create a JSON number from
1368
1369
    @complexity Constant.
1370
1371
    @liveexample{The example below shows the construction of an integer
1372
    number value.,basic_json__number_integer_t}
1373
1374
    @sa @ref basic_json(const int) -- create a number value (integer)
1375
    @sa @ref basic_json(const CompatibleNumberIntegerType) -- create a number
1376
    value (integer) from a compatible number type
1377
1378
    @since version 1.0.0
1379
    */
1380
    template<typename T,
1381
             typename std::enable_if<
1382
                 not (std::is_same<T, int>::value)
1383
                 and std::is_same<T, number_integer_t>::value
1384
                 , int>::type
1385
             = 0>
1386
    basic_json(const number_integer_t val) noexcept
1387
        : m_type(value_t::number_integer), m_value(val)
1388
    {
1389
        assert_invariant();
1390
    }
1391
1392
    /*!
1393
    @brief create an integer number from an enum type (explicit)
1394
1395
    Create an integer number JSON value with a given content.
1396
1397
    @param[in] val  an integer to create a JSON number from
1398
1399
    @note This constructor allows to pass enums directly to a constructor. As
1400
    C++ has no way of specifying the type of an anonymous enum explicitly, we
1401
    can only rely on the fact that such values implicitly convert to int. As
1402
    int may already be the same type of number_integer_t, we may need to
1403
    switch off the constructor @ref basic_json(const number_integer_t).
1404
1405
    @complexity Constant.
1406
1407
    @liveexample{The example below shows the construction of an integer
1408
    number value from an anonymous enum.,basic_json__const_int}
1409
1410
    @sa @ref basic_json(const number_integer_t) -- create a number value
1411
    (integer)
1412
    @sa @ref basic_json(const CompatibleNumberIntegerType) -- create a number
1413
    value (integer) from a compatible number type
1414
1415
    @since version 1.0.0
1416
    */
1417
    basic_json(const int val) noexcept
1418
        : m_type(value_t::number_integer),
1419
          m_value(static_cast<number_integer_t>(val))
1420
    {
1421
        assert_invariant();
1422
    }
1423
1424
    /*!
1425
    @brief create an integer number (implicit)
1426
1427
    Create an integer number JSON value with a given content. This constructor
1428
    allows any type @a CompatibleNumberIntegerType that can be used to
1429
    construct values of type @ref number_integer_t.
1430
1431
    @tparam CompatibleNumberIntegerType An integer type which is compatible to
1432
    @ref number_integer_t. Examples include the types `int`, `int32_t`,
1433
    `long`, and `short`.
1434
1435
    @param[in] val  an integer to create a JSON number from
1436
1437
    @complexity Constant.
1438
1439
    @liveexample{The example below shows the construction of several integer
1440
    number values from compatible
1441
    types.,basic_json__CompatibleIntegerNumberType}
1442
1443
    @sa @ref basic_json(const number_integer_t) -- create a number value
1444
    (integer)
1445
    @sa @ref basic_json(const int) -- create a number value (integer)
1446
1447
    @since version 1.0.0
1448
    */
1449
    template<typename CompatibleNumberIntegerType, typename
1450
             std::enable_if<
1451
                 std::is_constructible<number_integer_t, CompatibleNumberIntegerType>::value and
1452
                 std::numeric_limits<CompatibleNumberIntegerType>::is_integer and
1453
                 std::numeric_limits<CompatibleNumberIntegerType>::is_signed,
1454
                 CompatibleNumberIntegerType>::type
1455
             = 0>
1456
    basic_json(const CompatibleNumberIntegerType val) noexcept
1457
        : m_type(value_t::number_integer),
1458
          m_value(static_cast<number_integer_t>(val))
1459
    {
1460
        assert_invariant();
1461
    }
1462
1463
    /*!
1464
    @brief create an unsigned integer number (explicit)
1465
1466
    Create an unsigned integer number JSON value with a given content.
1467
1468
    @tparam T  helper type to compare number_unsigned_t and unsigned int (not
1469
    visible in) the interface.
1470
1471
    @param[in] val  an integer to create a JSON number from
1472
1473
    @complexity Constant.
1474
1475
    @sa @ref basic_json(const CompatibleNumberUnsignedType) -- create a number
1476
    value (unsigned integer) from a compatible number type
1477
1478
    @since version 2.0.0
1479
    */
1480
    template<typename T,
1481
             typename std::enable_if<
1482
                 not (std::is_same<T, int>::value)
1483
                 and std::is_same<T, number_unsigned_t>::value
1484
                 , int>::type
1485
             = 0>
1486
    basic_json(const number_unsigned_t val) noexcept
1487
        : m_type(value_t::number_unsigned), m_value(val)
1488
    {
1489
        assert_invariant();
1490
    }
1491
1492
    /*!
1493
    @brief create an unsigned number (implicit)
1494
1495
    Create an unsigned number JSON value with a given content. This
1496
    constructor allows any type @a CompatibleNumberUnsignedType that can be
1497
    used to construct values of type @ref number_unsigned_t.
1498
1499
    @tparam CompatibleNumberUnsignedType An integer type which is compatible
1500
    to @ref number_unsigned_t. Examples may include the types `unsigned int`,
1501
    `uint32_t`, or `unsigned short`.
1502
1503
    @param[in] val  an unsigned integer to create a JSON number from
1504
1505
    @complexity Constant.
1506
1507
    @sa @ref basic_json(const number_unsigned_t) -- create a number value
1508
    (unsigned)
1509
1510
    @since version 2.0.0
1511
    */
1512
    template <typename CompatibleNumberUnsignedType, typename
1513
              std::enable_if <
1514
                  std::is_constructible<number_unsigned_t, CompatibleNumberUnsignedType>::value and
1515
                  std::numeric_limits<CompatibleNumberUnsignedType>::is_integer and
1516
                  not std::numeric_limits<CompatibleNumberUnsignedType>::is_signed,
1517
                  CompatibleNumberUnsignedType>::type
1518
              = 0>
1519
    basic_json(const CompatibleNumberUnsignedType val) noexcept
1520
        : m_type(value_t::number_unsigned),
1521
          m_value(static_cast<number_unsigned_t>(val))
1522
    {
1523
        assert_invariant();
1524
    }
1525
1526
    /*!
1527
    @brief create a floating-point number (explicit)
1528
1529
    Create a floating-point number JSON value with a given content.
1530
1531
    @param[in] val  a floating-point value to create a JSON number from
1532
1533
    @note [RFC 7159](http://www.rfc-editor.org/rfc/rfc7159.txt), section 6
1534
    disallows NaN values:
1535
    > Numeric values that cannot be represented in the grammar below (such as
1536
    > Infinity and NaN) are not permitted.
1537
    In case the parameter @a val is not a number, a JSON null value is created
1538
    instead.
1539
1540
    @complexity Constant.
1541
1542
    @liveexample{The following example creates several floating-point
1543
    values.,basic_json__number_float_t}
1544
1545
    @sa @ref basic_json(const CompatibleNumberFloatType) -- create a number
1546
    value (floating-point) from a compatible number type
1547
1548
    @since version 1.0.0
1549
    */
1550
    basic_json(const number_float_t val) noexcept
1551
        : m_type(value_t::number_float), m_value(val)
1552
    {
1553
        // replace infinity and NAN by null
1554
        if (not std::isfinite(val))
1555
        {
1556
            m_type = value_t::null;
1557
            m_value = json_value();
1558
        }
1559
1560
        assert_invariant();
1561
    }
1562
1563
    /*!
1564
    @brief create an floating-point number (implicit)
1565
1566
    Create an floating-point number JSON value with a given content. This
1567
    constructor allows any type @a CompatibleNumberFloatType that can be used
1568
    to construct values of type @ref number_float_t.
1569
1570
    @tparam CompatibleNumberFloatType A floating-point type which is
1571
    compatible to @ref number_float_t. Examples may include the types `float`
1572
    or `double`.
1573
1574
    @param[in] val  a floating-point to create a JSON number from
1575
1576
    @note [RFC 7159](http://www.rfc-editor.org/rfc/rfc7159.txt), section 6
1577
    disallows NaN values:
1578
    > Numeric values that cannot be represented in the grammar below (such as
1579
    > Infinity and NaN) are not permitted.
1580
    In case the parameter @a val is not a number, a JSON null value is
1581
    created instead.
1582
1583
    @complexity Constant.
1584
1585
    @liveexample{The example below shows the construction of several
1586
    floating-point number values from compatible
1587
    types.,basic_json__CompatibleNumberFloatType}
1588
1589
    @sa @ref basic_json(const number_float_t) -- create a number value
1590
    (floating-point)
1591
1592
    @since version 1.0.0
1593
    */
1594
    template<typename CompatibleNumberFloatType, typename = typename
1595
             std::enable_if<
1596
                 std::is_constructible<number_float_t, CompatibleNumberFloatType>::value and
1597
                 std::is_floating_point<CompatibleNumberFloatType>::value>::type
1598
             >
1599
    basic_json(const CompatibleNumberFloatType val) noexcept
1600
        : basic_json(number_float_t(val))
1601
    {
1602
        assert_invariant();
1603
    }
1604
1605
    /*!
1606
    @brief create a container (array or object) from an initializer list
1607
1608
    Creates a JSON value of type array or object from the passed initializer
1609
    list @a init. In case @a type_deduction is `true` (default), the type of
1610
    the JSON value to be created is deducted from the initializer list @a init
1611
    according to the following rules:
1612
1613
    1. If the list is empty, an empty JSON object value `{}` is created.
1614
    2. If the list consists of pairs whose first element is a string, a JSON
1615
       object value is created where the first elements of the pairs are
1616
       treated as keys and the second elements are as values.
1617
    3. In all other cases, an array is created.
1618
1619
    The rules aim to create the best fit between a C++ initializer list and
1620
    JSON values. The rationale is as follows:
1621
1622
    1. The empty initializer list is written as `{}` which is exactly an empty
1623
       JSON object.
1624
    2. C++ has now way of describing mapped types other than to list a list of
1625
       pairs. As JSON requires that keys must be of type string, rule 2 is the
1626
       weakest constraint one can pose on initializer lists to interpret them
1627
       as an object.
1628
    3. In all other cases, the initializer list could not be interpreted as
1629
       JSON object type, so interpreting it as JSON array type is safe.
1630
1631
    With the rules described above, the following JSON values cannot be
1632
    expressed by an initializer list:
1633
1634
    - the empty array (`[]`): use @ref array(std::initializer_list<basic_json>)
1635
      with an empty initializer list in this case
1636
    - arrays whose elements satisfy rule 2: use @ref
1637
      array(std::initializer_list<basic_json>) with the same initializer list
1638
      in this case
1639
1640
    @note When used without parentheses around an empty initializer list, @ref
1641
    basic_json() is called instead of this function, yielding the JSON null
1642
    value.
1643
1644
    @param[in] init  initializer list with JSON values
1645
1646
    @param[in] type_deduction internal parameter; when set to `true`, the type
1647
    of the JSON value is deducted from the initializer list @a init; when set
1648
    to `false`, the type provided via @a manual_type is forced. This mode is
1649
    used by the functions @ref array(std::initializer_list<basic_json>) and
1650
    @ref object(std::initializer_list<basic_json>).
1651
1652
    @param[in] manual_type internal parameter; when @a type_deduction is set
1653
    to `false`, the created JSON value will use the provided type (only @ref
1654
    value_t::array and @ref value_t::object are valid); when @a type_deduction
1655
    is set to `true`, this parameter has no effect
1656
1657
    @throw std::domain_error if @a type_deduction is `false`, @a manual_type
1658
    is `value_t::object`, but @a init contains an element which is not a pair
1659
    whose first element is a string; example: `"cannot create object from
1660
    initializer list"`
1661
1662
    @complexity Linear in the size of the initializer list @a init.
1663
1664
    @liveexample{The example below shows how JSON values are created from
1665
    initializer lists.,basic_json__list_init_t}
1666
1667
    @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
1668
    value from an initializer list
1669
    @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
1670
    value from an initializer list
1671
1672
    @since version 1.0.0
1673
    */
1674
    basic_json(std::initializer_list<basic_json> init,
1675
               bool type_deduction = true,
1676
               value_t manual_type = value_t::array)
1677
    {
1678
        // check if each element is an array with two elements whose first
1679
        // element is a string
1680
        bool is_an_object = std::all_of(init.begin(), init.end(),
1681
                                        [](const basic_json & element)
1682
        {
1683
            return element.is_array() and element.size() == 2 and element[0].is_string();
1684
        });
1685
1686
        // adjust type if type deduction is not wanted
1687
        if (not type_deduction)
1688
        {
1689
            // if array is wanted, do not create an object though possible
1690
            if (manual_type == value_t::array)
1691
            {
1692
                is_an_object = false;
1693
            }
1694
1695
            // if object is wanted but impossible, throw an exception
1696
            if (manual_type == value_t::object and not is_an_object)
1697
            {
1698
                throw std::domain_error("cannot create object from initializer list");
1699
            }
1700
        }
1701
1702
        if (is_an_object)
1703
        {
1704
            // the initializer list is a list of pairs -> create object
1705
            m_type = value_t::object;
1706
            m_value = value_t::object;
1707
1708
            std::for_each(init.begin(), init.end(), [this](const basic_json & element)
1709
            {
1710
                m_value.object->emplace(*(element[0].m_value.string), element[1]);
1711
            });
1712
        }
1713
        else
1714
        {
1715
            // the initializer list describes an array -> create array
1716
            m_type = value_t::array;
1717
            m_value.array = create<array_t>(init);
1718
        }
1719
1720
        assert_invariant();
1721
    }
1722
1723
    /*!
1724
    @brief explicitly create an array from an initializer list
1725
1726
    Creates a JSON array value from a given initializer list. That is, given a
1727
    list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
1728
    initializer list is empty, the empty array `[]` is created.
1729
1730
    @note This function is only needed to express two edge cases that cannot
1731
    be realized with the initializer list constructor (@ref
1732
    basic_json(std::initializer_list<basic_json>, bool, value_t)). These cases
1733
    are:
1734
    1. creating an array whose elements are all pairs whose first element is a
1735
    string -- in this case, the initializer list constructor would create an
1736
    object, taking the first elements as keys
1737
    2. creating an empty array -- passing the empty initializer list to the
1738
    initializer list constructor yields an empty object
1739
1740
    @param[in] init  initializer list with JSON values to create an array from
1741
    (optional)
1742
1743
    @return JSON array value
1744
1745
    @complexity Linear in the size of @a init.
1746
1747
    @liveexample{The following code shows an example for the `array`
1748
    function.,array}
1749
1750
    @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
1751
    create a JSON value from an initializer list
1752
    @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
1753
    value from an initializer list
1754
1755
    @since version 1.0.0
1756
    */
1757
    static basic_json array(std::initializer_list<basic_json> init =
1758
                                std::initializer_list<basic_json>())
1759
    {
1760
        return basic_json(init, false, value_t::array);
1761
    }
1762
1763
    /*!
1764
    @brief explicitly create an object from an initializer list
1765
1766
    Creates a JSON object value from a given initializer list. The initializer
1767
    lists elements must be pairs, and their first elements must be strings. If
1768
    the initializer list is empty, the empty object `{}` is created.
1769
1770
    @note This function is only added for symmetry reasons. In contrast to the
1771
    related function @ref array(std::initializer_list<basic_json>), there are
1772
    no cases which can only be expressed by this function. That is, any
1773
    initializer list @a init can also be passed to the initializer list
1774
    constructor @ref basic_json(std::initializer_list<basic_json>, bool,
1775
    value_t).
1776
1777
    @param[in] init  initializer list to create an object from (optional)
1778
1779
    @return JSON object value
1780
1781
    @throw std::domain_error if @a init is not a pair whose first elements are
1782
    strings; thrown by
1783
    @ref basic_json(std::initializer_list<basic_json>, bool, value_t)
1784
1785
    @complexity Linear in the size of @a init.
1786
1787
    @liveexample{The following code shows an example for the `object`
1788
    function.,object}
1789
1790
    @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
1791
    create a JSON value from an initializer list
1792
    @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
1793
    value from an initializer list
1794
1795
    @since version 1.0.0
1796
    */
1797
    static basic_json object(std::initializer_list<basic_json> init =
1798
                                 std::initializer_list<basic_json>())
1799
    {
1800
        return basic_json(init, false, value_t::object);
1801
    }
1802
1803
    /*!
1804
    @brief construct an array with count copies of given value
1805
1806
    Constructs a JSON array value by creating @a cnt copies of a passed value.
1807
    In case @a cnt is `0`, an empty array is created. As postcondition,
1808
    `std::distance(begin(),end()) == cnt` holds.
1809
1810
    @param[in] cnt  the number of JSON copies of @a val to create
1811
    @param[in] val  the JSON value to copy
1812
1813
    @complexity Linear in @a cnt.
1814
1815
    @liveexample{The following code shows examples for the @ref
1816
    basic_json(size_type\, const basic_json&)
1817
    constructor.,basic_json__size_type_basic_json}
1818
1819
    @since version 1.0.0
1820
    */
1821
    basic_json(size_type cnt, const basic_json& val)
1822
        : m_type(value_t::array)
1823
    {
1824
        m_value.array = create<array_t>(cnt, val);
1825
        assert_invariant();
1826
    }
1827
1828
    /*!
1829
    @brief construct a JSON container given an iterator range
1830
1831
    Constructs the JSON value with the contents of the range `[first, last)`.
1832
    The semantics depends on the different types a JSON value can have:
1833
    - In case of primitive types (number, boolean, or string), @a first must
1834
      be `begin()` and @a last must be `end()`. In this case, the value is
1835
      copied. Otherwise, std::out_of_range is thrown.
1836
    - In case of structured types (array, object), the constructor behaves as
1837
      similar versions for `std::vector`.
1838
    - In case of a null type, std::domain_error is thrown.
1839
1840
    @tparam InputIT an input iterator type (@ref iterator or @ref
1841
    const_iterator)
1842
1843
    @param[in] first begin of the range to copy from (included)
1844
    @param[in] last end of the range to copy from (excluded)
1845
1846
    @pre Iterators @a first and @a last must be initialized.
1847
1848
    @throw std::domain_error if iterators are not compatible; that is, do not
1849
    belong to the same JSON value; example: `"iterators are not compatible"`
1850
    @throw std::out_of_range if iterators are for a primitive type (number,
1851
    boolean, or string) where an out of range error can be detected easily;
1852
    example: `"iterators out of range"`
1853
    @throw std::bad_alloc if allocation for object, array, or string fails
1854
    @throw std::domain_error if called with a null value; example: `"cannot
1855
    use construct with iterators from null"`
1856
1857
    @complexity Linear in distance between @a first and @a last.
1858
1859
    @liveexample{The example below shows several ways to create JSON values by
1860
    specifying a subrange with iterators.,basic_json__InputIt_InputIt}
1861
1862
    @since version 1.0.0
1863
    */
1864
    template <class InputIT, typename
1865
              std::enable_if<
1866
                  std::is_same<InputIT, typename basic_json_t::iterator>::value or
1867
                  std::is_same<InputIT, typename basic_json_t::const_iterator>::value
1868
                  , int>::type
1869
              = 0>
1870
    basic_json(InputIT first, InputIT last)
1871
    {
1872
        assert(first.m_object != nullptr);
1873
        assert(last.m_object != nullptr);
1874
1875
        // make sure iterator fits the current value
1876
        if (first.m_object != last.m_object)
1877
        {
1878
            throw std::domain_error("iterators are not compatible");
1879
        }
1880
1881
        // copy type from first iterator
1882
        m_type = first.m_object->m_type;
1883
1884
        // check if iterator range is complete for primitive values
1885
        switch (m_type)
1886
        {
1887
            case value_t::boolean:
1888
            case value_t::number_float:
1889
            case value_t::number_integer:
1890
            case value_t::number_unsigned:
1891
            case value_t::string:
1892
            {
1893
                if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
1894
                {
1895
                    throw std::out_of_range("iterators out of range");
1896
                }
1897
                break;
1898
            }
1899
1900
            default:
1901
            {
1902
                break;
1903
            }
1904
        }
1905
1906
        switch (m_type)
1907
        {
1908
            case value_t::number_integer:
1909
            {
1910
                m_value.number_integer = first.m_object->m_value.number_integer;
1911
                break;
1912
            }
1913
1914
            case value_t::number_unsigned:
1915
            {
1916
                m_value.number_unsigned = first.m_object->m_value.number_unsigned;
1917
                break;
1918
            }
1919
1920
            case value_t::number_float:
1921
            {
1922
                m_value.number_float = first.m_object->m_value.number_float;
1923
                break;
1924
            }
1925
1926
            case value_t::boolean:
1927
            {
1928
                m_value.boolean = first.m_object->m_value.boolean;
1929
                break;
1930
            }
1931
1932
            case value_t::string:
1933
            {
1934
                m_value = *first.m_object->m_value.string;
1935
                break;
1936
            }
1937
1938
            case value_t::object:
1939
            {
1940
                m_value.object = create<object_t>(first.m_it.object_iterator, last.m_it.object_iterator);
1941
                break;
1942
            }
1943
1944
            case value_t::array:
1945
            {
1946
                m_value.array = create<array_t>(first.m_it.array_iterator, last.m_it.array_iterator);
1947
                break;
1948
            }
1949
1950
            default:
1951
            {
1952
                throw std::domain_error("cannot use construct with iterators from " + first.m_object->type_name());
1953
            }
1954
        }
1955
1956
        assert_invariant();
1957
    }
1958
1959
    /*!
1960
    @brief construct a JSON value given an input stream
1961
1962
    @param[in,out] i  stream to read a serialized JSON value from
1963
    @param[in] cb a parser callback function of type @ref parser_callback_t
1964
    which is used to control the deserialization by filtering unwanted values
1965
    (optional)
1966
1967
    @complexity Linear in the length of the input. The parser is a predictive
1968
    LL(1) parser. The complexity can be higher if the parser callback function
1969
    @a cb has a super-linear complexity.
1970
1971
    @note A UTF-8 byte order mark is silently ignored.
1972
1973
    @liveexample{The example below demonstrates constructing a JSON value from
1974
    a `std::stringstream` with and without callback
1975
    function.,basic_json__istream}
1976
1977
    @since version 2.0.0
1978
    */
1979
    explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr)
1980
    {
1981
        *this = parser(i, cb).parse();
1982
        assert_invariant();
1983
    }
1984
1985
    ///////////////////////////////////////
1986
    // other constructors and destructor //
1987
    ///////////////////////////////////////
1988
1989
    /*!
1990
    @brief copy constructor
1991
1992
    Creates a copy of a given JSON value.
1993
1994
    @param[in] other  the JSON value to copy
1995
1996
    @complexity Linear in the size of @a other.
1997
1998
    @requirement This function helps `basic_json` satisfying the
1999
    [Container](http://en.cppreference.com/w/cpp/concept/Container)
2000
    requirements:
2001
    - The complexity is linear.
2002
    - As postcondition, it holds: `other == basic_json(other)`.
2003
2004
    @throw std::bad_alloc if allocation for object, array, or string fails.
2005
2006
    @liveexample{The following code shows an example for the copy
2007
    constructor.,basic_json__basic_json}
2008
2009
    @since version 1.0.0
2010
    */
2011
    basic_json(const basic_json& other)
2012
        : m_type(other.m_type)
2013
    {
2014
        // check of passed value is valid
2015
        other.assert_invariant();
2016
2017
        switch (m_type)
2018
        {
2019
            case value_t::object:
2020
            {
2021
                m_value = *other.m_value.object;
2022
                break;
2023
            }
2024
2025
            case value_t::array:
2026
            {
2027
                m_value = *other.m_value.array;
2028
                break;
2029
            }
2030
2031
            case value_t::string:
2032
            {
2033
                m_value = *other.m_value.string;
2034
                break;
2035
            }
2036
2037
            case value_t::boolean:
2038
            {
2039
                m_value = other.m_value.boolean;
2040
                break;
2041
            }
2042
2043
            case value_t::number_integer:
2044
            {
2045
                m_value = other.m_value.number_integer;
2046
                break;
2047
            }
2048
2049
            case value_t::number_unsigned:
2050
            {
2051
                m_value = other.m_value.number_unsigned;
2052
                break;
2053
            }
2054
2055
            case value_t::number_float:
2056
            {
2057
                m_value = other.m_value.number_float;
2058
                break;
2059
            }
2060
2061
            default:
2062
            {
2063
                break;
2064
            }
2065
        }
2066
2067
        assert_invariant();
2068
    }
2069
2070
    /*!
2071
    @brief move constructor
2072
2073
    Move constructor. Constructs a JSON value with the contents of the given
2074
    value @a other using move semantics. It "steals" the resources from @a
2075
    other and leaves it as JSON null value.
2076
2077
    @param[in,out] other  value to move to this object
2078
2079
    @post @a other is a JSON null value
2080
2081
    @complexity Constant.
2082
2083
    @liveexample{The code below shows the move constructor explicitly called
2084
    via std::move.,basic_json__moveconstructor}
2085
2086
    @since version 1.0.0
2087
    */
2088
    basic_json(basic_json&& other) noexcept
2089
        : m_type(std::move(other.m_type)),
2090
          m_value(std::move(other.m_value))
2091
    {
2092
        // check that passed value is valid
2093
        other.assert_invariant();
2094
2095
        // invalidate payload
2096
        other.m_type = value_t::null;
2097
        other.m_value = {};
2098
2099
        assert_invariant();
2100
    }
2101
2102
    /*!
2103
    @brief copy assignment
2104
2105
    Copy assignment operator. Copies a JSON value via the "copy and swap"
2106
    strategy: It is expressed in terms of the copy constructor, destructor,
2107
    and the swap() member function.
2108
2109
    @param[in] other  value to copy from
2110
2111
    @complexity Linear.
2112
2113
    @requirement This function helps `basic_json` satisfying the
2114
    [Container](http://en.cppreference.com/w/cpp/concept/Container)
2115
    requirements:
2116
    - The complexity is linear.
2117
2118
    @liveexample{The code below shows and example for the copy assignment. It
2119
    creates a copy of value `a` which is then swapped with `b`. Finally\, the
2120
    copy of `a` (which is the null value after the swap) is
2121
    destroyed.,basic_json__copyassignment}
2122
2123
    @since version 1.0.0
2124
    */
2125
    reference& operator=(basic_json other) noexcept (
2126
        std::is_nothrow_move_constructible<value_t>::value and
2127
        std::is_nothrow_move_assignable<value_t>::value and
2128
        std::is_nothrow_move_constructible<json_value>::value and
2129
        std::is_nothrow_move_assignable<json_value>::value
2130
    )
2131
    {
2132
        // check that passed value is valid
2133
        other.assert_invariant();
2134
2135
        using std::swap;
2136
        swap(m_type, other.m_type);
2137
        swap(m_value, other.m_value);
2138
2139
        assert_invariant();
2140
        return *this;
2141
    }
2142
2143
    /*!
2144
    @brief destructor
2145
2146
    Destroys the JSON value and frees all allocated memory.
2147
2148
    @complexity Linear.
2149
2150
    @requirement This function helps `basic_json` satisfying the
2151
    [Container](http://en.cppreference.com/w/cpp/concept/Container)
2152
    requirements:
2153
    - The complexity is linear.
2154
    - All stored elements are destroyed and all memory is freed.
2155
2156
    @since version 1.0.0
2157
    */
2158
    ~basic_json()
2159
    {
2160
        assert_invariant();
2161
2162
        switch (m_type)
2163
        {
2164
            case value_t::object:
2165
            {
2166
                AllocatorType<object_t> alloc;
2167
                alloc.destroy(m_value.object);
2168
                alloc.deallocate(m_value.object, 1);
2169
                break;
2170
            }
2171
2172
            case value_t::array:
2173
            {
2174
                AllocatorType<array_t> alloc;
2175
                alloc.destroy(m_value.array);
2176
                alloc.deallocate(m_value.array, 1);
2177
                break;
2178
            }
2179
2180
            case value_t::string:
2181
            {
2182
                AllocatorType<string_t> alloc;
2183
                alloc.destroy(m_value.string);
2184
                alloc.deallocate(m_value.string, 1);
2185
                break;
2186
            }
2187
2188
            default:
2189
            {
2190
                // all other types need no specific destructor
2191
                break;
2192
            }
2193
        }
2194
    }
2195
2196
    /// @}
2197
2198
  public:
2199
    ///////////////////////
2200
    // object inspection //
2201
    ///////////////////////
2202
2203
    /// @name object inspection
2204
    /// Functions to inspect the type of a JSON value.
2205
    /// @{
2206
2207
    /*!
2208
    @brief serialization
2209
2210
    Serialization function for JSON values. The function tries to mimic
2211
    Python's `json.dumps()` function, and currently supports its @a indent
2212
    parameter.
2213
2214
    @param[in] indent If indent is nonnegative, then array elements and object
2215
    members will be pretty-printed with that indent level. An indent level of
2216
    `0` will only insert newlines. `-1` (the default) selects the most compact
2217
    representation.
2218
2219
    @return string containing the serialization of the JSON value
2220
2221
    @complexity Linear.
2222
2223
    @liveexample{The following example shows the effect of different @a indent
2224
    parameters to the result of the serialization.,dump}
2225
2226
    @see https://docs.python.org/2/library/json.html#json.dump
2227
2228
    @since version 1.0.0
2229
    */
2230
    string_t dump(const int indent = -1) const
2231
    {
2232
        std::stringstream ss;
2233
        // fix locale problems
2234
        ss.imbue(std::locale(std::locale(), new DecimalSeparator));
2235
2236
        // 6, 15 or 16 digits of precision allows round-trip IEEE 754
2237
        // string->float->string, string->double->string or string->long
2238
        // double->string; to be safe, we read this value from
2239
        // std::numeric_limits<number_float_t>::digits10
2240
        ss.precision(std::numeric_limits<double>::digits10);
2241
2242
        if (indent >= 0)
2243
        {
2244
            dump(ss, true, static_cast<unsigned int>(indent));
2245
        }
2246
        else
2247
        {
2248
            dump(ss, false, 0);
2249
        }
2250
2251
        return ss.str();
2252
    }
2253
2254
    /*!
2255
    @brief return the type of the JSON value (explicit)
2256
2257
    Return the type of the JSON value as a value from the @ref value_t
2258
    enumeration.
2259
2260
    @return the type of the JSON value
2261
2262
    @complexity Constant.
2263
2264
    @exceptionsafety No-throw guarantee: this member function never throws
2265
    exceptions.
2266
2267
    @liveexample{The following code exemplifies `type()` for all JSON
2268
    types.,type}
2269
2270
    @since version 1.0.0
2271
    */
2272
    constexpr value_t type() const noexcept
2273
    {
2274
        return m_type;
2275
    }
2276
2277
    /*!
2278
    @brief return whether type is primitive
2279
2280
    This function returns true iff the JSON type is primitive (string, number,
2281
    boolean, or null).
2282
2283
    @return `true` if type is primitive (string, number, boolean, or null),
2284
    `false` otherwise.
2285
2286
    @complexity Constant.
2287
2288
    @exceptionsafety No-throw guarantee: this member function never throws
2289
    exceptions.
2290
2291
    @liveexample{The following code exemplifies `is_primitive()` for all JSON
2292
    types.,is_primitive}
2293
2294
    @sa @ref is_structured() -- returns whether JSON value is structured
2295
    @sa @ref is_null() -- returns whether JSON value is `null`
2296
    @sa @ref is_string() -- returns whether JSON value is a string
2297
    @sa @ref is_boolean() -- returns whether JSON value is a boolean
2298
    @sa @ref is_number() -- returns whether JSON value is a number
2299
2300
    @since version 1.0.0
2301
    */
2302
    constexpr bool is_primitive() const noexcept
2303
    {
2304
        return is_null() or is_string() or is_boolean() or is_number();
2305
    }
2306
2307
    /*!
2308
    @brief return whether type is structured
2309
2310
    This function returns true iff the JSON type is structured (array or
2311
    object).
2312
2313
    @return `true` if type is structured (array or object), `false` otherwise.
2314
2315
    @complexity Constant.
2316
2317
    @exceptionsafety No-throw guarantee: this member function never throws
2318
    exceptions.
2319
2320
    @liveexample{The following code exemplifies `is_structured()` for all JSON
2321
    types.,is_structured}
2322
2323
    @sa @ref is_primitive() -- returns whether value is primitive
2324
    @sa @ref is_array() -- returns whether value is an array
2325
    @sa @ref is_object() -- returns whether value is an object
2326
2327
    @since version 1.0.0
2328
    */
2329
    constexpr bool is_structured() const noexcept
2330
    {
2331
        return is_array() or is_object();
2332
    }
2333
2334
    /*!
2335
    @brief return whether value is null
2336
2337
    This function returns true iff the JSON value is null.
2338
2339
    @return `true` if type is null, `false` otherwise.
2340
2341
    @complexity Constant.
2342
2343
    @exceptionsafety No-throw guarantee: this member function never throws
2344
    exceptions.
2345
2346
    @liveexample{The following code exemplifies `is_null()` for all JSON
2347
    types.,is_null}
2348
2349
    @since version 1.0.0
2350
    */
2351
    constexpr bool is_null() const noexcept
2352
    {
2353
        return m_type == value_t::null;
2354
    }
2355
2356
    /*!
2357
    @brief return whether value is a boolean
2358
2359
    This function returns true iff the JSON value is a boolean.
2360
2361
    @return `true` if type is boolean, `false` otherwise.
2362
2363
    @complexity Constant.
2364
2365
    @exceptionsafety No-throw guarantee: this member function never throws
2366
    exceptions.
2367
2368
    @liveexample{The following code exemplifies `is_boolean()` for all JSON
2369
    types.,is_boolean}
2370
2371
    @since version 1.0.0
2372
    */
2373
    constexpr bool is_boolean() const noexcept
2374
    {
2375
        return m_type == value_t::boolean;
2376
    }
2377
2378
    /*!
2379
    @brief return whether value is a number
2380
2381
    This function returns true iff the JSON value is a number. This includes
2382
    both integer and floating-point values.
2383
2384
    @return `true` if type is number (regardless whether integer, unsigned
2385
    integer or floating-type), `false` otherwise.
2386
2387
    @complexity Constant.
2388
2389
    @exceptionsafety No-throw guarantee: this member function never throws
2390
    exceptions.
2391
2392
    @liveexample{The following code exemplifies `is_number()` for all JSON
2393
    types.,is_number}
2394
2395
    @sa @ref is_number_integer() -- check if value is an integer or unsigned
2396
    integer number
2397
    @sa @ref is_number_unsigned() -- check if value is an unsigned integer
2398
    number
2399
    @sa @ref is_number_float() -- check if value is a floating-point number
2400
2401
    @since version 1.0.0
2402
    */
2403
    constexpr bool is_number() const noexcept
2404
    {
2405
        return is_number_integer() or is_number_float();
2406
    }
2407
2408
    /*!
2409
    @brief return whether value is an integer number
2410
2411
    This function returns true iff the JSON value is an integer or unsigned
2412
    integer number. This excludes floating-point values.
2413
2414
    @return `true` if type is an integer or unsigned integer number, `false`
2415
    otherwise.
2416
2417
    @complexity Constant.
2418
2419
    @exceptionsafety No-throw guarantee: this member function never throws
2420
    exceptions.
2421
2422
    @liveexample{The following code exemplifies `is_number_integer()` for all
2423
    JSON types.,is_number_integer}
2424
2425
    @sa @ref is_number() -- check if value is a number
2426
    @sa @ref is_number_unsigned() -- check if value is an unsigned integer
2427
    number
2428
    @sa @ref is_number_float() -- check if value is a floating-point number
2429
2430
    @since version 1.0.0
2431
    */
2432
    constexpr bool is_number_integer() const noexcept
2433
    {
2434
        return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
2435
    }
2436
2437
    /*!
2438
    @brief return whether value is an unsigned integer number
2439
2440
    This function returns true iff the JSON value is an unsigned integer
2441
    number. This excludes floating-point and (signed) integer values.
2442
2443
    @return `true` if type is an unsigned integer number, `false` otherwise.
2444
2445
    @complexity Constant.
2446
2447
    @exceptionsafety No-throw guarantee: this member function never throws
2448
    exceptions.
2449
2450
    @liveexample{The following code exemplifies `is_number_unsigned()` for all
2451
    JSON types.,is_number_unsigned}
2452
2453
    @sa @ref is_number() -- check if value is a number
2454
    @sa @ref is_number_integer() -- check if value is an integer or unsigned
2455
    integer number
2456
    @sa @ref is_number_float() -- check if value is a floating-point number
2457
2458
    @since version 2.0.0
2459
    */
2460
    constexpr bool is_number_unsigned() const noexcept
2461
    {
2462
        return m_type == value_t::number_unsigned;
2463
    }
2464
2465
    /*!
2466
    @brief return whether value is a floating-point number
2467
2468
    This function returns true iff the JSON value is a floating-point number.
2469
    This excludes integer and unsigned integer values.
2470
2471
    @return `true` if type is a floating-point number, `false` otherwise.
2472
2473
    @complexity Constant.
2474
2475
    @exceptionsafety No-throw guarantee: this member function never throws
2476
    exceptions.
2477
2478
    @liveexample{The following code exemplifies `is_number_float()` for all
2479
    JSON types.,is_number_float}
2480
2481
    @sa @ref is_number() -- check if value is number
2482
    @sa @ref is_number_integer() -- check if value is an integer number
2483
    @sa @ref is_number_unsigned() -- check if value is an unsigned integer
2484
    number
2485
2486
    @since version 1.0.0
2487
    */
2488
    constexpr bool is_number_float() const noexcept
2489
    {
2490
        return m_type == value_t::number_float;
2491
    }
2492
2493
    /*!
2494
    @brief return whether value is an object
2495
2496
    This function returns true iff the JSON value is an object.
2497
2498
    @return `true` if type is object, `false` otherwise.
2499
2500
    @complexity Constant.
2501
2502
    @exceptionsafety No-throw guarantee: this member function never throws
2503
    exceptions.
2504
2505
    @liveexample{The following code exemplifies `is_object()` for all JSON
2506
    types.,is_object}
2507
2508
    @since version 1.0.0
2509
    */
2510
    constexpr bool is_object() const noexcept
2511
    {
2512
        return m_type == value_t::object;
2513
    }
2514
2515
    /*!
2516
    @brief return whether value is an array
2517
2518
    This function returns true iff the JSON value is an array.
2519
2520
    @return `true` if type is array, `false` otherwise.
2521
2522
    @complexity Constant.
2523
2524
    @exceptionsafety No-throw guarantee: this member function never throws
2525
    exceptions.
2526
2527
    @liveexample{The following code exemplifies `is_array()` for all JSON
2528
    types.,is_array}
2529
2530
    @since version 1.0.0
2531
    */
2532
    constexpr bool is_array() const noexcept
2533
    {
2534
        return m_type == value_t::array;
2535
    }
2536
2537
    /*!
2538
    @brief return whether value is a string
2539
2540
    This function returns true iff the JSON value is a string.
2541
2542
    @return `true` if type is string, `false` otherwise.
2543
2544
    @complexity Constant.
2545
2546
    @exceptionsafety No-throw guarantee: this member function never throws
2547
    exceptions.
2548
2549
    @liveexample{The following code exemplifies `is_string()` for all JSON
2550
    types.,is_string}
2551
2552
    @since version 1.0.0
2553
    */
2554
    constexpr bool is_string() const noexcept
2555
    {
2556
        return m_type == value_t::string;
2557
    }
2558
2559
    /*!
2560
    @brief return whether value is discarded
2561
2562
    This function returns true iff the JSON value was discarded during parsing
2563
    with a callback function (see @ref parser_callback_t).
2564
2565
    @note This function will always be `false` for JSON values after parsing.
2566
    That is, discarded values can only occur during parsing, but will be
2567
    removed when inside a structured value or replaced by null in other cases.
2568
2569
    @return `true` if type is discarded, `false` otherwise.
2570
2571
    @complexity Constant.
2572
2573
    @exceptionsafety No-throw guarantee: this member function never throws
2574
    exceptions.
2575
2576
    @liveexample{The following code exemplifies `is_discarded()` for all JSON
2577
    types.,is_discarded}
2578
2579
    @since version 1.0.0
2580
    */
2581
    constexpr bool is_discarded() const noexcept
2582
    {
2583
        return m_type == value_t::discarded;
2584
    }
2585
2586
    /*!
2587
    @brief return the type of the JSON value (implicit)
2588
2589
    Implicitly return the type of the JSON value as a value from the @ref
2590
    value_t enumeration.
2591
2592
    @return the type of the JSON value
2593
2594
    @complexity Constant.
2595
2596
    @exceptionsafety No-throw guarantee: this member function never throws
2597
    exceptions.
2598
2599
    @liveexample{The following code exemplifies the @ref value_t operator for
2600
    all JSON types.,operator__value_t}
2601
2602
    @since version 1.0.0
2603
    */
2604
    constexpr operator value_t() const noexcept
2605
    {
2606
        return m_type;
2607
    }
2608
2609
    /// @}
2610
2611
  private:
2612
    //////////////////
2613
    // value access //
2614
    //////////////////
2615
2616
    /// get an object (explicit)
2617
    template <class T, typename
2618
              std::enable_if<
2619
                  std::is_convertible<typename object_t::key_type, typename T::key_type>::value and
2620
                  std::is_convertible<basic_json_t, typename T::mapped_type>::value
2621
                  , int>::type = 0>
2622
    T get_impl(T*) const
2623
    {
2624
        if (is_object())
2625
        {
2626
            return T(m_value.object->begin(), m_value.object->end());
2627
        }
2628
        else
2629
        {
2630
            throw std::domain_error("type must be object, but is " + type_name());
2631
        }
2632
    }
2633
2634
    /// get an object (explicit)
2635
    object_t get_impl(object_t*) const
2636
    {
2637
        if (is_object())
2638
        {
2639
            return *(m_value.object);
2640
        }
2641
        else
2642
        {
2643
            throw std::domain_error("type must be object, but is " + type_name());
2644
        }
2645
    }
2646
2647
    /// get an array (explicit)
2648
    template <class T, typename
2649
              std::enable_if<
2650
                  std::is_convertible<basic_json_t, typename T::value_type>::value and
2651
                  not std::is_same<basic_json_t, typename T::value_type>::value and
2652
                  not std::is_arithmetic<T>::value and
2653
                  not std::is_convertible<std::string, T>::value and
2654
                  not has_mapped_type<T>::value
2655
                  , int>::type = 0>
2656
    T get_impl(T*) const
2657
    {
2658
        if (is_array())
2659
        {
2660
            T to_vector;
2661
            std::transform(m_value.array->begin(), m_value.array->end(),
2662
                           std::inserter(to_vector, to_vector.end()), [](basic_json i)
2663
            {
2664
                return i.get<typename T::value_type>();
2665
            });
2666
            return to_vector;
2667
        }
2668
        else
2669
        {
2670
            throw std::domain_error("type must be array, but is " + type_name());
2671
        }
2672
    }
2673
2674
    /// get an array (explicit)
2675
    template <class T, typename
2676
              std::enable_if<
2677
                  std::is_convertible<basic_json_t, T>::value and
2678
                  not std::is_same<basic_json_t, T>::value
2679
                  , int>::type = 0>
2680
    std::vector<T> get_impl(std::vector<T>*) const
2681
    {
2682
        if (is_array())
2683
        {
2684
            std::vector<T> to_vector;
2685
            to_vector.reserve(m_value.array->size());
2686
            std::transform(m_value.array->begin(), m_value.array->end(),
2687
                           std::inserter(to_vector, to_vector.end()), [](basic_json i)
2688
            {
2689
                return i.get<T>();
2690
            });
2691
            return to_vector;
2692
        }
2693
        else
2694
        {
2695
            throw std::domain_error("type must be array, but is " + type_name());
2696
        }
2697
    }
2698
2699
    /// get an array (explicit)
2700
    template <class T, typename
2701
              std::enable_if<
2702
                  std::is_same<basic_json, typename T::value_type>::value and
2703
                  not has_mapped_type<T>::value
2704
                  , int>::type = 0>
2705
    T get_impl(T*) const
2706
    {
2707
        if (is_array())
2708
        {
2709
            return T(m_value.array->begin(), m_value.array->end());
2710
        }
2711
        else
2712
        {
2713
            throw std::domain_error("type must be array, but is " + type_name());
2714
        }
2715
    }
2716
2717
    /// get an array (explicit)
2718
    array_t get_impl(array_t*) const
2719
    {
2720
        if (is_array())
2721
        {
2722
            return *(m_value.array);
2723
        }
2724
        else
2725
        {
2726
            throw std::domain_error("type must be array, but is " + type_name());
2727
        }
2728
    }
2729
2730
    /// get a string (explicit)
2731
    template <typename T, typename
2732
              std::enable_if<
2733
                  std::is_convertible<string_t, T>::value
2734
                  , int>::type = 0>
2735
    T get_impl(T*) const
2736
    {
2737
        if (is_string())
2738
        {
2739
            return *m_value.string;
2740
        }
2741
        else
2742
        {
2743
            throw std::domain_error("type must be string, but is " + type_name());
2744
        }
2745
    }
2746
2747
    /// get a number (explicit)
2748
    template<typename T, typename
2749
             std::enable_if<
2750
                 std::is_arithmetic<T>::value
2751
                 , int>::type = 0>
2752
    T get_impl(T*) const
2753
    {
2754
        switch (m_type)
2755
        {
2756
            case value_t::number_integer:
2757
            {
2758
                return static_cast<T>(m_value.number_integer);
2759
            }
2760
2761
            case value_t::number_unsigned:
2762
            {
2763
                return static_cast<T>(m_value.number_unsigned);
2764
            }
2765
2766
            case value_t::number_float:
2767
            {
2768
                return static_cast<T>(m_value.number_float);
2769
            }
2770
2771
            default:
2772
            {
2773
                throw std::domain_error("type must be number, but is " + type_name());
2774
            }
2775
        }
2776
    }
2777
2778
    /// get a boolean (explicit)
2779
    constexpr boolean_t get_impl(boolean_t*) const
2780
    {
2781
        return is_boolean()
2782
               ? m_value.boolean
2783
               : throw std::domain_error("type must be boolean, but is " + type_name());
2784
    }
2785
2786
    /// get a pointer to the value (object)
2787
    object_t* get_impl_ptr(object_t*) noexcept
2788
    {
2789
        return is_object() ? m_value.object : nullptr;
2790
    }
2791
2792
    /// get a pointer to the value (object)
2793
    constexpr const object_t* get_impl_ptr(const object_t*) const noexcept
2794
    {
2795
        return is_object() ? m_value.object : nullptr;
2796
    }
2797
2798
    /// get a pointer to the value (array)
2799
    array_t* get_impl_ptr(array_t*) noexcept
2800
    {
2801
        return is_array() ? m_value.array : nullptr;
2802
    }
2803
2804
    /// get a pointer to the value (array)
2805
    constexpr const array_t* get_impl_ptr(const array_t*) const noexcept
2806
    {
2807
        return is_array() ? m_value.array : nullptr;
2808
    }
2809
2810
    /// get a pointer to the value (string)
2811
    string_t* get_impl_ptr(string_t*) noexcept
2812
    {
2813
        return is_string() ? m_value.string : nullptr;
2814
    }
2815
2816
    /// get a pointer to the value (string)
2817
    constexpr const string_t* get_impl_ptr(const string_t*) const noexcept
2818
    {
2819
        return is_string() ? m_value.string : nullptr;
2820
    }
2821
2822
    /// get a pointer to the value (boolean)
2823
    boolean_t* get_impl_ptr(boolean_t*) noexcept
2824
    {
2825
        return is_boolean() ? &m_value.boolean : nullptr;
2826
    }
2827
2828
    /// get a pointer to the value (boolean)
2829
    constexpr const boolean_t* get_impl_ptr(const boolean_t*) const noexcept
2830
    {
2831
        return is_boolean() ? &m_value.boolean : nullptr;
2832
    }
2833
2834
    /// get a pointer to the value (integer number)
2835
    number_integer_t* get_impl_ptr(number_integer_t*) noexcept
2836
    {
2837
        return is_number_integer() ? &m_value.number_integer : nullptr;
2838
    }
2839
2840
    /// get a pointer to the value (integer number)
2841
    constexpr const number_integer_t* get_impl_ptr(const number_integer_t*) const noexcept
2842
    {
2843
        return is_number_integer() ? &m_value.number_integer : nullptr;
2844
    }
2845
2846
    /// get a pointer to the value (unsigned number)
2847
    number_unsigned_t* get_impl_ptr(number_unsigned_t*) noexcept
2848
    {
2849
        return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
2850
    }
2851
2852
    /// get a pointer to the value (unsigned number)
2853
    constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t*) const noexcept
2854
    {
2855
        return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
2856
    }
2857
2858
    /// get a pointer to the value (floating-point number)
2859
    number_float_t* get_impl_ptr(number_float_t*) noexcept
2860
    {
2861
        return is_number_float() ? &m_value.number_float : nullptr;
2862
    }
2863
2864
    /// get a pointer to the value (floating-point number)
2865
    constexpr const number_float_t* get_impl_ptr(const number_float_t*) const noexcept
2866
    {
2867
        return is_number_float() ? &m_value.number_float : nullptr;
2868
    }
2869
2870
    /*!
2871
    @brief helper function to implement get_ref()
2872
2873
    This funcion helps to implement get_ref() without code duplication for
2874
    const and non-const overloads
2875
2876
    @tparam ThisType will be deduced as `basic_json` or `const basic_json`
2877
2878
    @throw std::domain_error if ReferenceType does not match underlying value
2879
    type of the current JSON
2880
    */
2881
    template<typename ReferenceType, typename ThisType>
2882
    static ReferenceType get_ref_impl(ThisType& obj)
2883
    {
2884
        // helper type
2885
        using PointerType = typename std::add_pointer<ReferenceType>::type;
2886
2887
        // delegate the call to get_ptr<>()
2888
        auto ptr = obj.template get_ptr<PointerType>();
2889
2890
        if (ptr != nullptr)
2891
        {
2892
            return *ptr;
2893
        }
2894
        else
2895
        {
2896
            throw std::domain_error("incompatible ReferenceType for get_ref, actual type is " +
2897
                                    obj.type_name());
2898
        }
2899
    }
2900
2901
  public:
2902
2903
    /// @name value access
2904
    /// Direct access to the stored value of a JSON value.
2905
    /// @{
2906
2907
    /*!
2908
    @brief get a value (explicit)
2909
2910
    Explicit type conversion between the JSON value and a compatible value.
2911
2912
    @tparam ValueType non-pointer type compatible to the JSON value, for
2913
    instance `int` for JSON integer numbers, `bool` for JSON booleans, or
2914
    `std::vector` types for JSON arrays
2915
2916
    @return copy of the JSON value, converted to type @a ValueType
2917
2918
    @throw std::domain_error in case passed type @a ValueType is incompatible
2919
    to JSON; example: `"type must be object, but is null"`
2920
2921
    @complexity Linear in the size of the JSON value.
2922
2923
    @liveexample{The example below shows several conversions from JSON values
2924
    to other types. There a few things to note: (1) Floating-point numbers can
2925
    be converted to integers\, (2) A JSON array can be converted to a standard
2926
    `std::vector<short>`\, (3) A JSON object can be converted to C++
2927
    associative containers such as `std::unordered_map<std::string\,
2928
    json>`.,get__ValueType_const}
2929
2930
    @internal
2931
    The idea of using a casted null pointer to choose the correct
2932
    implementation is from <http://stackoverflow.com/a/8315197/266378>.
2933
    @endinternal
2934
2935
    @sa @ref operator ValueType() const for implicit conversion
2936
    @sa @ref get() for pointer-member access
2937
2938
    @since version 1.0.0
2939
    */
2940
    template<typename ValueType, typename
2941
             std::enable_if<
2942
                 not std::is_pointer<ValueType>::value
2943
                 , int>::type = 0>
2944
    ValueType get() const
2945
    {
2946
        return get_impl(static_cast<ValueType*>(nullptr));
2947
    }
2948
2949
    /*!
2950
    @brief get a pointer value (explicit)
2951
2952
    Explicit pointer access to the internally stored JSON value. No copies are
2953
    made.
2954
2955
    @warning The pointer becomes invalid if the underlying JSON object
2956
    changes.
2957
2958
    @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
2959
    object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
2960
    @ref number_unsigned_t, or @ref number_float_t.
2961
2962
    @return pointer to the internally stored JSON value if the requested
2963
    pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
2964
2965
    @complexity Constant.
2966
2967
    @liveexample{The example below shows how pointers to internal values of a
2968
    JSON value can be requested. Note that no type conversions are made and a
2969
    `nullptr` is returned if the value and the requested pointer type does not
2970
    match.,get__PointerType}
2971
2972
    @sa @ref get_ptr() for explicit pointer-member access
2973
2974
    @since version 1.0.0
2975
    */
2976
    template<typename PointerType, typename
2977
             std::enable_if<
2978
                 std::is_pointer<PointerType>::value
2979
                 , int>::type = 0>
2980
    PointerType get() noexcept
2981
    {
2982
        // delegate the call to get_ptr
2983
        return get_ptr<PointerType>();
2984
    }
2985
2986
    /*!
2987
    @brief get a pointer value (explicit)
2988
    @copydoc get()
2989
    */
2990
    template<typename PointerType, typename
2991
             std::enable_if<
2992
                 std::is_pointer<PointerType>::value
2993
                 , int>::type = 0>
2994
    constexpr const PointerType get() const noexcept
2995
    {
2996
        // delegate the call to get_ptr
2997
        return get_ptr<PointerType>();
2998
    }
2999
3000
    /*!
3001
    @brief get a pointer value (implicit)
3002
3003
    Implicit pointer access to the internally stored JSON value. No copies are
3004
    made.
3005
3006
    @warning Writing data to the pointee of the result yields an undefined
3007
    state.
3008
3009
    @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
3010
    object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
3011
    @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
3012
    assertion.
3013
3014
    @return pointer to the internally stored JSON value if the requested
3015
    pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
3016
3017
    @complexity Constant.
3018
3019
    @liveexample{The example below shows how pointers to internal values of a
3020
    JSON value can be requested. Note that no type conversions are made and a
3021
    `nullptr` is returned if the value and the requested pointer type does not
3022
    match.,get_ptr}
3023
3024
    @since version 1.0.0
3025
    */
3026
    template<typename PointerType, typename
3027
             std::enable_if<
3028
                 std::is_pointer<PointerType>::value
3029
                 , int>::type = 0>
3030
    PointerType get_ptr() noexcept
3031
    {
3032
        // get the type of the PointerType (remove pointer and const)
3033
        using pointee_t = typename std::remove_const<typename
3034
                          std::remove_pointer<typename
3035
                          std::remove_const<PointerType>::type>::type>::type;
3036
        // make sure the type matches the allowed types
3037
        static_assert(
3038
            std::is_same<object_t, pointee_t>::value
3039
            or std::is_same<array_t, pointee_t>::value
3040
            or std::is_same<string_t, pointee_t>::value
3041
            or std::is_same<boolean_t, pointee_t>::value
3042
            or std::is_same<number_integer_t, pointee_t>::value
3043
            or std::is_same<number_unsigned_t, pointee_t>::value
3044
            or std::is_same<number_float_t, pointee_t>::value
3045
            , "incompatible pointer type");
3046
3047
        // delegate the call to get_impl_ptr<>()
3048
        return get_impl_ptr(static_cast<PointerType>(nullptr));
3049
    }
3050
3051
    /*!
3052
    @brief get a pointer value (implicit)
3053
    @copydoc get_ptr()
3054
    */
3055
    template<typename PointerType, typename
3056
             std::enable_if<
3057
                 std::is_pointer<PointerType>::value
3058
                 and std::is_const<typename std::remove_pointer<PointerType>::type>::value
3059
                 , int>::type = 0>
3060
    constexpr const PointerType get_ptr() const noexcept
3061
    {
3062
        // get the type of the PointerType (remove pointer and const)
3063
        using pointee_t = typename std::remove_const<typename
3064
                          std::remove_pointer<typename
3065
                          std::remove_const<PointerType>::type>::type>::type;
3066
        // make sure the type matches the allowed types
3067
        static_assert(
3068
            std::is_same<object_t, pointee_t>::value
3069
            or std::is_same<array_t, pointee_t>::value
3070
            or std::is_same<string_t, pointee_t>::value
3071
            or std::is_same<boolean_t, pointee_t>::value
3072
            or std::is_same<number_integer_t, pointee_t>::value
3073
            or std::is_same<number_unsigned_t, pointee_t>::value
3074
            or std::is_same<number_float_t, pointee_t>::value
3075
            , "incompatible pointer type");
3076
3077
        // delegate the call to get_impl_ptr<>() const
3078
        return get_impl_ptr(static_cast<const PointerType>(nullptr));
3079
    }
3080
3081
    /*!
3082
    @brief get a reference value (implicit)
3083
3084
    Implict reference access to the internally stored JSON value. No copies
3085
    are made.
3086
3087
    @warning Writing data to the referee of the result yields an undefined
3088
    state.
3089
3090
    @tparam ReferenceType reference type; must be a reference to @ref array_t,
3091
    @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
3092
    @ref number_float_t. Enforced by static assertion.
3093
3094
    @return reference to the internally stored JSON value if the requested
3095
    reference type @a ReferenceType fits to the JSON value; throws
3096
    std::domain_error otherwise
3097
3098
    @throw std::domain_error in case passed type @a ReferenceType is
3099
    incompatible with the stored JSON value
3100
3101
    @complexity Constant.
3102
3103
    @liveexample{The example shows several calls to `get_ref()`.,get_ref}
3104
3105
    @since version 1.1.0
3106
    */
3107
    template<typename ReferenceType, typename
3108
             std::enable_if<
3109
                 std::is_reference<ReferenceType>::value
3110
                 , int>::type = 0>
3111
    ReferenceType get_ref()
3112
    {
3113
        // delegate call to get_ref_impl
3114
        return get_ref_impl<ReferenceType>(*this);
3115
    }
3116
3117
    /*!
3118
    @brief get a reference value (implicit)
3119
    @copydoc get_ref()
3120
    */
3121
    template<typename ReferenceType, typename
3122
             std::enable_if<
3123
                 std::is_reference<ReferenceType>::value
3124
                 and std::is_const<typename std::remove_reference<ReferenceType>::type>::value
3125
                 , int>::type = 0>
3126
    ReferenceType get_ref() const
3127
    {
3128
        // delegate call to get_ref_impl
3129
        return get_ref_impl<ReferenceType>(*this);
3130
    }
3131
3132
    /*!
3133
    @brief get a value (implicit)
3134
3135
    Implicit type conversion between the JSON value and a compatible value.
3136
    The call is realized by calling @ref get() const.
3137
3138
    @tparam ValueType non-pointer type compatible to the JSON value, for
3139
    instance `int` for JSON integer numbers, `bool` for JSON booleans, or
3140
    `std::vector` types for JSON arrays. The character type of @ref string_t
3141
    as well as an initializer list of this type is excluded to avoid
3142
    ambiguities as these types implicitly convert to `std::string`.
3143
3144
    @return copy of the JSON value, converted to type @a ValueType
3145
3146
    @throw std::domain_error in case passed type @a ValueType is incompatible
3147
    to JSON, thrown by @ref get() const
3148
3149
    @complexity Linear in the size of the JSON value.
3150
3151
    @liveexample{The example below shows several conversions from JSON values
3152
    to other types. There a few things to note: (1) Floating-point numbers can
3153
    be converted to integers\, (2) A JSON array can be converted to a standard
3154
    `std::vector<short>`\, (3) A JSON object can be converted to C++
3155
    associative containers such as `std::unordered_map<std::string\,
3156
    json>`.,operator__ValueType}
3157
3158
    @since version 1.0.0
3159
    */
3160
    template < typename ValueType, typename
3161
               std::enable_if <
3162
                   not std::is_pointer<ValueType>::value
3163
                   and not std::is_same<ValueType, typename string_t::value_type>::value
3164
#ifndef _MSC_VER  // Fix for issue #167 operator<< abiguity under VS2015
3165
                   and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
3166
#endif
3167
                   , int >::type = 0 >
3168
    operator ValueType() const
3169
    {
3170
        // delegate the call to get<>() const
3171
        return get<ValueType>();
3172
    }
3173
3174
    /// @}
3175
3176
3177
    ////////////////////
3178
    // element access //
3179
    ////////////////////
3180
3181
    /// @name element access
3182
    /// Access to the JSON value.
3183
    /// @{
3184
3185
    /*!
3186
    @brief access specified array element with bounds checking
3187
3188
    Returns a reference to the element at specified location @a idx, with
3189
    bounds checking.
3190
3191
    @param[in] idx  index of the element to access
3192
3193
    @return reference to the element at index @a idx
3194
3195
    @throw std::domain_error if the JSON value is not an array; example:
3196
    `"cannot use at() with string"`
3197
    @throw std::out_of_range if the index @a idx is out of range of the array;
3198
    that is, `idx >= size()`; example: `"array index 7 is out of range"`
3199
3200
    @complexity Constant.
3201
3202
    @liveexample{The example below shows how array elements can be read and
3203
    written using `at()`.,at__size_type}
3204
3205
    @since version 1.0.0
3206
    */
3207
    reference at(size_type idx)
3208
    {
3209
        // at only works for arrays
3210
        if (is_array())
3211
        {
3212
            try
3213
            {
3214
                return m_value.array->at(idx);
3215
            }
3216
            catch (std::out_of_range&)
3217
            {
3218
                // create better exception explanation
3219
                throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
3220
            }
3221
        }
3222
        else
3223
        {
3224
            throw std::domain_error("cannot use at() with " + type_name());
3225
        }
3226
    }
3227
3228
    /*!
3229
    @brief access specified array element with bounds checking
3230
3231
    Returns a const reference to the element at specified location @a idx,
3232
    with bounds checking.
3233
3234
    @param[in] idx  index of the element to access
3235
3236
    @return const reference to the element at index @a idx
3237
3238
    @throw std::domain_error if the JSON value is not an array; example:
3239
    `"cannot use at() with string"`
3240
    @throw std::out_of_range if the index @a idx is out of range of the array;
3241
    that is, `idx >= size()`; example: `"array index 7 is out of range"`
3242
3243
    @complexity Constant.
3244
3245
    @liveexample{The example below shows how array elements can be read using
3246
    `at()`.,at__size_type_const}
3247
3248
    @since version 1.0.0
3249
    */
3250
    const_reference at(size_type idx) const
3251
    {
3252
        // at only works for arrays
3253
        if (is_array())
3254
        {
3255
            try
3256
            {
3257
                return m_value.array->at(idx);
3258
            }
3259
            catch (std::out_of_range&)
3260
            {
3261
                // create better exception explanation
3262
                throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
3263
            }
3264
        }
3265
        else
3266
        {
3267
            throw std::domain_error("cannot use at() with " + type_name());
3268
        }
3269
    }
3270
3271
    /*!
3272
    @brief access specified object element with bounds checking
3273
3274
    Returns a reference to the element at with specified key @a key, with
3275
    bounds checking.
3276
3277
    @param[in] key  key of the element to access
3278
3279
    @return reference to the element at key @a key
3280
3281
    @throw std::domain_error if the JSON value is not an object; example:
3282
    `"cannot use at() with boolean"`
3283
    @throw std::out_of_range if the key @a key is is not stored in the object;
3284
    that is, `find(key) == end()`; example: `"key "the fast" not found"`
3285
3286
    @complexity Logarithmic in the size of the container.
3287
3288
    @liveexample{The example below shows how object elements can be read and
3289
    written using `at()`.,at__object_t_key_type}
3290
3291
    @sa @ref operator[](const typename object_t::key_type&) for unchecked
3292
    access by reference
3293
    @sa @ref value() for access by value with a default value
3294
3295
    @since version 1.0.0
3296
    */
3297
    reference at(const typename object_t::key_type& key)
3298
    {
3299
        // at only works for objects
3300
        if (is_object())
3301
        {
3302
            try
3303
            {
3304
                return m_value.object->at(key);
3305
            }
3306
            catch (std::out_of_range&)
3307
            {
3308
                // create better exception explanation
3309
                throw std::out_of_range("key '" + key + "' not found");
3310
            }
3311
        }
3312
        else
3313
        {
3314
            throw std::domain_error("cannot use at() with " + type_name());
3315
        }
3316
    }
3317
3318
    /*!
3319
    @brief access specified object element with bounds checking
3320
3321
    Returns a const reference to the element at with specified key @a key,
3322
    with bounds checking.
3323
3324
    @param[in] key  key of the element to access
3325
3326
    @return const reference to the element at key @a key
3327
3328
    @throw std::domain_error if the JSON value is not an object; example:
3329
    `"cannot use at() with boolean"`
3330
    @throw std::out_of_range if the key @a key is is not stored in the object;
3331
    that is, `find(key) == end()`; example: `"key "the fast" not found"`
3332
3333
    @complexity Logarithmic in the size of the container.
3334
3335
    @liveexample{The example below shows how object elements can be read using
3336
    `at()`.,at__object_t_key_type_const}
3337
3338
    @sa @ref operator[](const typename object_t::key_type&) for unchecked
3339
    access by reference
3340
    @sa @ref value() for access by value with a default value
3341
3342
    @since version 1.0.0
3343
    */
3344
    const_reference at(const typename object_t::key_type& key) const
3345
    {
3346
        // at only works for objects
3347
        if (is_object())
3348
        {
3349
            try
3350
            {
3351
                return m_value.object->at(key);
3352
            }
3353
            catch (std::out_of_range&)
3354
            {
3355
                // create better exception explanation
3356
                throw std::out_of_range("key '" + key + "' not found");
3357
            }
3358
        }
3359
        else
3360
        {
3361
            throw std::domain_error("cannot use at() with " + type_name());
3362
        }
3363
    }
3364
3365
    /*!
3366
    @brief access specified array element
3367
3368
    Returns a reference to the element at specified location @a idx.
3369
3370
    @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
3371
    then the array is silently filled up with `null` values to make `idx` a
3372
    valid reference to the last stored element.
3373
3374
    @param[in] idx  index of the element to access
3375
3376
    @return reference to the element at index @a idx
3377
3378
    @throw std::domain_error if JSON is not an array or null; example:
3379
    `"cannot use operator[] with string"`
3380
3381
    @complexity Constant if @a idx is in the range of the array. Otherwise
3382
    linear in `idx - size()`.
3383
3384
    @liveexample{The example below shows how array elements can be read and
3385
    written using `[]` operator. Note the addition of `null`
3386
    values.,operatorarray__size_type}
3387
3388
    @since version 1.0.0
3389
    */
3390
    reference operator[](size_type idx)
3391
    {
3392
        // implicitly convert null value to an empty array
3393
        if (is_null())
3394
        {
3395
            m_type = value_t::array;
3396
            m_value.array = create<array_t>();
3397
            assert_invariant();
3398
        }
3399
3400
        // operator[] only works for arrays
3401
        if (is_array())
3402
        {
3403
            // fill up array with null values if given idx is outside range
3404
            if (idx >= m_value.array->size())
3405
            {
3406
                m_value.array->insert(m_value.array->end(),
3407
                                      idx - m_value.array->size() + 1,
3408
                                      basic_json());
3409
            }
3410
3411
            return m_value.array->operator[](idx);
3412
        }
3413
        else
3414
        {
3415
            throw std::domain_error("cannot use operator[] with " + type_name());
3416
        }
3417
    }
3418
3419
    /*!
3420
    @brief access specified array element
3421
3422
    Returns a const reference to the element at specified location @a idx.
3423
3424
    @param[in] idx  index of the element to access
3425
3426
    @return const reference to the element at index @a idx
3427
3428
    @throw std::domain_error if JSON is not an array; example: `"cannot use
3429
    operator[] with null"`
3430
3431
    @complexity Constant.
3432
3433
    @liveexample{The example below shows how array elements can be read using
3434
    the `[]` operator.,operatorarray__size_type_const}
3435
3436
    @since version 1.0.0
3437
    */
3438
    const_reference operator[](size_type idx) const
3439
    {
3440
        // const operator[] only works for arrays
3441
        if (is_array())
3442
        {
3443
            return m_value.array->operator[](idx);
3444
        }
3445
        else
3446
        {
3447
            throw std::domain_error("cannot use operator[] with " + type_name());
3448
        }
3449
    }
3450
3451
    /*!
3452
    @brief access specified object element
3453
3454
    Returns a reference to the element at with specified key @a key.
3455
3456
    @note If @a key is not found in the object, then it is silently added to
3457
    the object and filled with a `null` value to make `key` a valid reference.
3458
    In case the value was `null` before, it is converted to an object.
3459
3460
    @param[in] key  key of the element to access
3461
3462
    @return reference to the element at key @a key
3463
3464
    @throw std::domain_error if JSON is not an object or null; example:
3465
    `"cannot use operator[] with string"`
3466
3467
    @complexity Logarithmic in the size of the container.
3468
3469
    @liveexample{The example below shows how object elements can be read and
3470
    written using the `[]` operator.,operatorarray__key_type}
3471
3472
    @sa @ref at(const typename object_t::key_type&) for access by reference
3473
    with range checking
3474
    @sa @ref value() for access by value with a default value
3475
3476
    @since version 1.0.0
3477
    */
3478
    reference operator[](const typename object_t::key_type& key)
3479
    {
3480
        // implicitly convert null value to an empty object
3481
        if (is_null())
3482
        {
3483
            m_type = value_t::object;
3484
            m_value.object = create<object_t>();
3485
            assert_invariant();
3486
        }
3487
3488
        // operator[] only works for objects
3489
        if (is_object())
3490
        {
3491
            return m_value.object->operator[](key);
3492
        }
3493
        else
3494
        {
3495
            throw std::domain_error("cannot use operator[] with " + type_name());
3496
        }
3497
    }
3498
3499
    /*!
3500
    @brief read-only access specified object element
3501
3502
    Returns a const reference to the element at with specified key @a key. No
3503
    bounds checking is performed.
3504
3505
    @warning If the element with key @a key does not exist, the behavior is
3506
    undefined.
3507
3508
    @param[in] key  key of the element to access
3509
3510
    @return const reference to the element at key @a key
3511
3512
    @throw std::domain_error if JSON is not an object; example: `"cannot use
3513
    operator[] with null"`
3514
3515
    @complexity Logarithmic in the size of the container.
3516
3517
    @liveexample{The example below shows how object elements can be read using
3518
    the `[]` operator.,operatorarray__key_type_const}
3519
3520
    @sa @ref at(const typename object_t::key_type&) for access by reference
3521
    with range checking
3522
    @sa @ref value() for access by value with a default value
3523
3524
    @since version 1.0.0
3525
    */
3526
    const_reference operator[](const typename object_t::key_type& key) const
3527
    {
3528
        // const operator[] only works for objects
3529
        if (is_object())
3530
        {
3531
            assert(m_value.object->find(key) != m_value.object->end());
3532
            return m_value.object->find(key)->second;
3533
        }
3534
        else
3535
        {
3536
            throw std::domain_error("cannot use operator[] with " + type_name());
3537
        }
3538
    }
3539
3540
    /*!
3541
    @brief access specified object element
3542
3543
    Returns a reference to the element at with specified key @a key.
3544
3545
    @note If @a key is not found in the object, then it is silently added to
3546
    the object and filled with a `null` value to make `key` a valid reference.
3547
    In case the value was `null` before, it is converted to an object.
3548
3549
    @param[in] key  key of the element to access
3550
3551
    @return reference to the element at key @a key
3552
3553
    @throw std::domain_error if JSON is not an object or null; example:
3554
    `"cannot use operator[] with string"`
3555
3556
    @complexity Logarithmic in the size of the container.
3557
3558
    @liveexample{The example below shows how object elements can be read and
3559
    written using the `[]` operator.,operatorarray__key_type}
3560
3561
    @sa @ref at(const typename object_t::key_type&) for access by reference
3562
    with range checking
3563
    @sa @ref value() for access by value with a default value
3564
3565
    @since version 1.0.0
3566
    */
3567
    template<typename T, std::size_t n>
3568
    reference operator[](T * (&key)[n])
3569
    {
3570
        return operator[](static_cast<const T>(key));
3571
    }
3572
3573
    /*!
3574
    @brief read-only access specified object element
3575
3576
    Returns a const reference to the element at with specified key @a key. No
3577
    bounds checking is performed.
3578
3579
    @warning If the element with key @a key does not exist, the behavior is
3580
    undefined.
3581
3582
    @note This function is required for compatibility reasons with Clang.
3583
3584
    @param[in] key  key of the element to access
3585
3586
    @return const reference to the element at key @a key
3587
3588
    @throw std::domain_error if JSON is not an object; example: `"cannot use
3589
    operator[] with null"`
3590
3591
    @complexity Logarithmic in the size of the container.
3592
3593
    @liveexample{The example below shows how object elements can be read using
3594
    the `[]` operator.,operatorarray__key_type_const}
3595
3596
    @sa @ref at(const typename object_t::key_type&) for access by reference
3597
    with range checking
3598
    @sa @ref value() for access by value with a default value
3599
3600
    @since version 1.0.0
3601
    */
3602
    template<typename T, std::size_t n>
3603
    const_reference operator[](T * (&key)[n]) const
3604
    {
3605
        return operator[](static_cast<const T>(key));
3606
    }
3607
3608
    /*!
3609
    @brief access specified object element
3610
3611
    Returns a reference to the element at with specified key @a key.
3612
3613
    @note If @a key is not found in the object, then it is silently added to
3614
    the object and filled with a `null` value to make `key` a valid reference.
3615
    In case the value was `null` before, it is converted to an object.
3616
3617
    @param[in] key  key of the element to access
3618
3619
    @return reference to the element at key @a key
3620
3621
    @throw std::domain_error if JSON is not an object or null; example:
3622
    `"cannot use operator[] with string"`
3623
3624
    @complexity Logarithmic in the size of the container.
3625
3626
    @liveexample{The example below shows how object elements can be read and
3627
    written using the `[]` operator.,operatorarray__key_type}
3628
3629
    @sa @ref at(const typename object_t::key_type&) for access by reference
3630
    with range checking
3631
    @sa @ref value() for access by value with a default value
3632
3633
    @since version 1.1.0
3634
    */
3635
    template<typename T>
3636
    reference operator[](T* key)
3637
    {
3638
        // implicitly convert null to object
3639
        if (is_null())
3640
        {
3641
            m_type = value_t::object;
3642
            m_value = value_t::object;
3643
            assert_invariant();
3644
        }
3645
3646
        // at only works for objects
3647
        if (is_object())
3648
        {
3649
            return m_value.object->operator[](key);
3650
        }
3651
        else
3652
        {
3653
            throw std::domain_error("cannot use operator[] with " + type_name());
3654
        }
3655
    }
3656
3657
    /*!
3658
    @brief read-only access specified object element
3659
3660
    Returns a const reference to the element at with specified key @a key. No
3661
    bounds checking is performed.
3662
3663
    @warning If the element with key @a key does not exist, the behavior is
3664
    undefined.
3665
3666
    @param[in] key  key of the element to access
3667
3668
    @return const reference to the element at key @a key
3669
3670
    @throw std::domain_error if JSON is not an object; example: `"cannot use
3671
    operator[] with null"`
3672
3673
    @complexity Logarithmic in the size of the container.
3674
3675
    @liveexample{The example below shows how object elements can be read using
3676
    the `[]` operator.,operatorarray__key_type_const}
3677
3678
    @sa @ref at(const typename object_t::key_type&) for access by reference
3679
    with range checking
3680
    @sa @ref value() for access by value with a default value
3681
3682
    @since version 1.1.0
3683
    */
3684
    template<typename T>
3685
    const_reference operator[](T* key) const
3686
    {
3687
        // at only works for objects
3688
        if (is_object())
3689
        {
3690
            assert(m_value.object->find(key) != m_value.object->end());
3691
            return m_value.object->find(key)->second;
3692
        }
3693
        else
3694
        {
3695
            throw std::domain_error("cannot use operator[] with " + type_name());
3696
        }
3697
    }
3698
3699
    /*!
3700
    @brief access specified object element with default value
3701
3702
    Returns either a copy of an object's element at the specified key @a key
3703
    or a given default value if no element with key @a key exists.
3704
3705
    The function is basically equivalent to executing
3706
    @code {.cpp}
3707
    try {
3708
        return at(key);
3709
    } catch(std::out_of_range) {
3710
        return default_value;
3711
    }
3712
    @endcode
3713
3714
    @note Unlike @ref at(const typename object_t::key_type&), this function
3715
    does not throw if the given key @a key was not found.
3716
3717
    @note Unlike @ref operator[](const typename object_t::key_type& key), this
3718
    function does not implicitly add an element to the position defined by @a
3719
    key. This function is furthermore also applicable to const objects.
3720
3721
    @param[in] key  key of the element to access
3722
    @param[in] default_value  the value to return if @a key is not found
3723
3724
    @tparam ValueType type compatible to JSON values, for instance `int` for
3725
    JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
3726
    JSON arrays. Note the type of the expected value at @a key and the default
3727
    value @a default_value must be compatible.
3728
3729
    @return copy of the element at key @a key or @a default_value if @a key
3730
    is not found
3731
3732
    @throw std::domain_error if JSON is not an object; example: `"cannot use
3733
    value() with null"`
3734
3735
    @complexity Logarithmic in the size of the container.
3736
3737
    @liveexample{The example below shows how object elements can be queried
3738
    with a default value.,basic_json__value}
3739
3740
    @sa @ref at(const typename object_t::key_type&) for access by reference
3741
    with range checking
3742
    @sa @ref operator[](const typename object_t::key_type&) for unchecked
3743
    access by reference
3744
3745
    @since version 1.0.0
3746
    */
3747
    template <class ValueType, typename
3748
              std::enable_if<
3749
                  std::is_convertible<basic_json_t, ValueType>::value
3750
                  , int>::type = 0>
3751
    ValueType value(const typename object_t::key_type& key, ValueType default_value) const
3752
    {
3753
        // at only works for objects
3754
        if (is_object())
3755
        {
3756
            // if key is found, return value and given default value otherwise
3757
            const auto it = find(key);
3758
            if (it != end())
3759
            {
3760
                return *it;
3761
            }
3762
            else
3763
            {
3764
                return default_value;
3765
            }
3766
        }
3767
        else
3768
        {
3769
            throw std::domain_error("cannot use value() with " + type_name());
3770
        }
3771
    }
3772
3773
    /*!
3774
    @brief overload for a default value of type const char*
3775
    @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
3776
    */
3777
    string_t value(const typename object_t::key_type& key, const char* default_value) const
3778
    {
3779
        return value(key, string_t(default_value));
3780
    }
3781
3782
    /*!
3783
    @brief access specified object element via JSON Pointer with default value
3784
3785
    Returns either a copy of an object's element at the specified key @a key
3786
    or a given default value if no element with key @a key exists.
3787
3788
    The function is basically equivalent to executing
3789
    @code {.cpp}
3790
    try {
3791
        return at(ptr);
3792
    } catch(std::out_of_range) {
3793
        return default_value;
3794
    }
3795
    @endcode
3796
3797
    @note Unlike @ref at(const json_pointer&), this function does not throw
3798
    if the given key @a key was not found.
3799
3800
    @param[in] ptr  a JSON pointer to the element to access
3801
    @param[in] default_value  the value to return if @a ptr found no value
3802
3803
    @tparam ValueType type compatible to JSON values, for instance `int` for
3804
    JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
3805
    JSON arrays. Note the type of the expected value at @a key and the default
3806
    value @a default_value must be compatible.
3807
3808
    @return copy of the element at key @a key or @a default_value if @a key
3809
    is not found
3810
3811
    @throw std::domain_error if JSON is not an object; example: `"cannot use
3812
    value() with null"`
3813
3814
    @complexity Logarithmic in the size of the container.
3815
3816
    @liveexample{The example below shows how object elements can be queried
3817
    with a default value.,basic_json__value_ptr}
3818
3819
    @sa @ref operator[](const json_pointer&) for unchecked access by reference
3820
3821
    @since version 2.0.2
3822
    */
3823
    template <class ValueType, typename
3824
              std::enable_if<
3825
                  std::is_convertible<basic_json_t, ValueType>::value
3826
                  , int>::type = 0>
3827
    ValueType value(const json_pointer& ptr, ValueType default_value) const
3828
    {
3829
        // at only works for objects
3830
        if (is_object())
3831
        {
3832
            // if pointer resolves a value, return it or use default value
3833
            try
3834
            {
3835
                return ptr.get_checked(this);
3836
            }
3837
            catch (std::out_of_range&)
3838
            {
3839
                return default_value;
3840
            }
3841
        }
3842
        else
3843
        {
3844
            throw std::domain_error("cannot use value() with " + type_name());
3845
        }
3846
    }
3847
3848
    /*!
3849
    @brief overload for a default value of type const char*
3850
    @copydoc basic_json::value(const json_pointer&, ValueType) const
3851
    */
3852
    string_t value(const json_pointer& ptr, const char* default_value) const
3853
    {
3854
        return value(ptr, string_t(default_value));
3855
    }
3856
3857
    /*!
3858
    @brief access the first element
3859
3860
    Returns a reference to the first element in the container. For a JSON
3861
    container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
3862
3863
    @return In case of a structured type (array or object), a reference to the
3864
    first element is returned. In cast of number, string, or boolean values, a
3865
    reference to the value is returned.
3866
3867
    @complexity Constant.
3868
3869
    @pre The JSON value must not be `null` (would throw `std::out_of_range`)
3870
    or an empty array or object (undefined behavior, guarded by assertions).
3871
    @post The JSON value remains unchanged.
3872
3873
    @throw std::out_of_range when called on `null` value
3874
3875
    @liveexample{The following code shows an example for `front()`.,front}
3876
3877
    @sa @ref back() -- access the last element
3878
3879
    @since version 1.0.0
3880
    */
3881
    reference front()
3882
    {
3883
        return *begin();
3884
    }
3885
3886
    /*!
3887
    @copydoc basic_json::front()
3888
    */
3889
    const_reference front() const
3890
    {
3891
        return *cbegin();
3892
    }
3893
3894
    /*!
3895
    @brief access the last element
3896
3897
    Returns a reference to the last element in the container. For a JSON
3898
    container `c`, the expression `c.back()` is equivalent to
3899
    @code {.cpp}
3900
    auto tmp = c.end();
3901
    --tmp;
3902
    return *tmp;
3903
    @endcode
3904
3905
    @return In case of a structured type (array or object), a reference to the
3906
    last element is returned. In cast of number, string, or boolean values, a
3907
    reference to the value is returned.
3908
3909
    @complexity Constant.
3910
3911
    @pre The JSON value must not be `null` (would throw `std::out_of_range`)
3912
    or an empty array or object (undefined behavior, guarded by assertions).
3913
    @post The JSON value remains unchanged.
3914
3915
    @throw std::out_of_range when called on `null` value.
3916
3917
    @liveexample{The following code shows an example for `back()`.,back}
3918
3919
    @sa @ref front() -- access the first element
3920
3921
    @since version 1.0.0
3922
    */
3923
    reference back()
3924
    {
3925
        auto tmp = end();
3926
        --tmp;
3927
        return *tmp;
3928
    }
3929
3930
    /*!
3931
    @copydoc basic_json::back()
3932
    */
3933
    const_reference back() const
3934
    {
3935
        auto tmp = cend();
3936
        --tmp;
3937
        return *tmp;
3938
    }
3939
3940
    /*!
3941
    @brief remove element given an iterator
3942
3943
    Removes the element specified by iterator @a pos. The iterator @a pos must
3944
    be valid and dereferenceable. Thus the `end()` iterator (which is valid,
3945
    but is not dereferenceable) cannot be used as a value for @a pos.
3946
3947
    If called on a primitive type other than `null`, the resulting JSON value
3948
    will be `null`.
3949
3950
    @param[in] pos iterator to the element to remove
3951
    @return Iterator following the last removed element. If the iterator @a
3952
    pos refers to the last element, the `end()` iterator is returned.
3953
3954
    @tparam InteratorType an @ref iterator or @ref const_iterator
3955
3956
    @post Invalidates iterators and references at or after the point of the
3957
    erase, including the `end()` iterator.
3958
3959
    @throw std::domain_error if called on a `null` value; example: `"cannot
3960
    use erase() with null"`
3961
    @throw std::domain_error if called on an iterator which does not belong to
3962
    the current JSON value; example: `"iterator does not fit current value"`
3963
    @throw std::out_of_range if called on a primitive type with invalid
3964
    iterator (i.e., any iterator which is not `begin()`); example: `"iterator
3965
    out of range"`
3966
3967
    @complexity The complexity depends on the type:
3968
    - objects: amortized constant
3969
    - arrays: linear in distance between pos and the end of the container
3970
    - strings: linear in the length of the string
3971
    - other types: constant
3972
3973
    @liveexample{The example shows the result of `erase()` for different JSON
3974
    types.,erase__IteratorType}
3975
3976
    @sa @ref erase(InteratorType, InteratorType) -- removes the elements in
3977
    the given range
3978
    @sa @ref erase(const typename object_t::key_type&) -- removes the element
3979
    from an object at the given key
3980
    @sa @ref erase(const size_type) -- removes the element from an array at
3981
    the given index
3982
3983
    @since version 1.0.0
3984
    */
3985
    template <class InteratorType, typename
3986
              std::enable_if<
3987
                  std::is_same<InteratorType, typename basic_json_t::iterator>::value or
3988
                  std::is_same<InteratorType, typename basic_json_t::const_iterator>::value
3989
                  , int>::type
3990
              = 0>
3991
    InteratorType erase(InteratorType pos)
3992
    {
3993
        // make sure iterator fits the current value
3994
        if (this != pos.m_object)
3995
        {
3996
            throw std::domain_error("iterator does not fit current value");
3997
        }
3998
3999
        InteratorType result = end();
4000
4001
        switch (m_type)
4002
        {
4003
            case value_t::boolean:
4004
            case value_t::number_float:
4005
            case value_t::number_integer:
4006
            case value_t::number_unsigned:
4007
            case value_t::string:
4008
            {
4009
                if (not pos.m_it.primitive_iterator.is_begin())
4010
                {
4011
                    throw std::out_of_range("iterator out of range");
4012
                }
4013
4014
                if (is_string())
4015
                {
4016
                    AllocatorType<string_t> alloc;
4017
                    alloc.destroy(m_value.string);
4018
                    alloc.deallocate(m_value.string, 1);
4019
                    m_value.string = nullptr;
4020
                }
4021
4022
                m_type = value_t::null;
4023
                assert_invariant();
4024
                break;
4025
            }
4026
4027
            case value_t::object:
4028
            {
4029
                result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
4030
                break;
4031
            }
4032
4033
            case value_t::array:
4034
            {
4035
                result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
4036
                break;
4037
            }
4038
4039
            default:
4040
            {
4041
                throw std::domain_error("cannot use erase() with " + type_name());
4042
            }
4043
        }
4044
4045
        return result;
4046
    }
4047
4048
    /*!
4049
    @brief remove elements given an iterator range
4050
4051
    Removes the element specified by the range `[first; last)`. The iterator
4052
    @a first does not need to be dereferenceable if `first == last`: erasing
4053
    an empty range is a no-op.
4054
4055
    If called on a primitive type other than `null`, the resulting JSON value
4056
    will be `null`.
4057
4058
    @param[in] first iterator to the beginning of the range to remove
4059
    @param[in] last iterator past the end of the range to remove
4060
    @return Iterator following the last removed element. If the iterator @a
4061
    second refers to the last element, the `end()` iterator is returned.
4062
4063
    @tparam InteratorType an @ref iterator or @ref const_iterator
4064
4065
    @post Invalidates iterators and references at or after the point of the
4066
    erase, including the `end()` iterator.
4067
4068
    @throw std::domain_error if called on a `null` value; example: `"cannot
4069
    use erase() with null"`
4070
    @throw std::domain_error if called on iterators which does not belong to
4071
    the current JSON value; example: `"iterators do not fit current value"`
4072
    @throw std::out_of_range if called on a primitive type with invalid
4073
    iterators (i.e., if `first != begin()` and `last != end()`); example:
4074
    `"iterators out of range"`
4075
4076
    @complexity The complexity depends on the type:
4077
    - objects: `log(size()) + std::distance(first, last)`
4078
    - arrays: linear in the distance between @a first and @a last, plus linear
4079
      in the distance between @a last and end of the container
4080
    - strings: linear in the length of the string
4081
    - other types: constant
4082
4083
    @liveexample{The example shows the result of `erase()` for different JSON
4084
    types.,erase__IteratorType_IteratorType}
4085
4086
    @sa @ref erase(InteratorType) -- removes the element at a given position
4087
    @sa @ref erase(const typename object_t::key_type&) -- removes the element
4088
    from an object at the given key
4089
    @sa @ref erase(const size_type) -- removes the element from an array at
4090
    the given index
4091
4092
    @since version 1.0.0
4093
    */
4094
    template <class InteratorType, typename
4095
              std::enable_if<
4096
                  std::is_same<InteratorType, typename basic_json_t::iterator>::value or
4097
                  std::is_same<InteratorType, typename basic_json_t::const_iterator>::value
4098
                  , int>::type
4099
              = 0>
4100
    InteratorType erase(InteratorType first, InteratorType last)
4101
    {
4102
        // make sure iterator fits the current value
4103
        if (this != first.m_object or this != last.m_object)
4104
        {
4105
            throw std::domain_error("iterators do not fit current value");
4106
        }
4107
4108
        InteratorType result = end();
4109
4110
        switch (m_type)
4111
        {
4112
            case value_t::boolean:
4113
            case value_t::number_float:
4114
            case value_t::number_integer:
4115
            case value_t::number_unsigned:
4116
            case value_t::string:
4117
            {
4118
                if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
4119
                {
4120
                    throw std::out_of_range("iterators out of range");
4121
                }
4122
4123
                if (is_string())
4124
                {
4125
                    AllocatorType<string_t> alloc;
4126
                    alloc.destroy(m_value.string);
4127
                    alloc.deallocate(m_value.string, 1);
4128
                    m_value.string = nullptr;
4129
                }
4130
4131
                m_type = value_t::null;
4132
                assert_invariant();
4133
                break;
4134
            }
4135
4136
            case value_t::object:
4137
            {
4138
                result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
4139
                                              last.m_it.object_iterator);
4140
                break;
4141
            }
4142
4143
            case value_t::array:
4144
            {
4145
                result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
4146
                                             last.m_it.array_iterator);
4147
                break;
4148
            }
4149
4150
            default:
4151
            {
4152
                throw std::domain_error("cannot use erase() with " + type_name());
4153
            }
4154
        }
4155
4156
        return result;
4157
    }
4158
4159
    /*!
4160
    @brief remove element from a JSON object given a key
4161
4162
    Removes elements from a JSON object with the key value @a key.
4163
4164
    @param[in] key value of the elements to remove
4165
4166
    @return Number of elements removed. If @a ObjectType is the default
4167
    `std::map` type, the return value will always be `0` (@a key was not
4168
    found) or `1` (@a key was found).
4169
4170
    @post References and iterators to the erased elements are invalidated.
4171
    Other references and iterators are not affected.
4172
4173
    @throw std::domain_error when called on a type other than JSON object;
4174
    example: `"cannot use erase() with null"`
4175
4176
    @complexity `log(size()) + count(key)`
4177
4178
    @liveexample{The example shows the effect of `erase()`.,erase__key_type}
4179
4180
    @sa @ref erase(InteratorType) -- removes the element at a given position
4181
    @sa @ref erase(InteratorType, InteratorType) -- removes the elements in
4182
    the given range
4183
    @sa @ref erase(const size_type) -- removes the element from an array at
4184
    the given index
4185
4186
    @since version 1.0.0
4187
    */
4188
    size_type erase(const typename object_t::key_type& key)
4189
    {
4190
        // this erase only works for objects
4191
        if (is_object())
4192
        {
4193
            return m_value.object->erase(key);
4194
        }
4195
        else
4196
        {
4197
            throw std::domain_error("cannot use erase() with " + type_name());
4198
        }
4199
    }
4200
4201
    /*!
4202
    @brief remove element from a JSON array given an index
4203
4204
    Removes element from a JSON array at the index @a idx.
4205
4206
    @param[in] idx index of the element to remove
4207
4208
    @throw std::domain_error when called on a type other than JSON array;
4209
    example: `"cannot use erase() with null"`
4210
    @throw std::out_of_range when `idx >= size()`; example: `"array index 17
4211
    is out of range"`
4212
4213
    @complexity Linear in distance between @a idx and the end of the container.
4214
4215
    @liveexample{The example shows the effect of `erase()`.,erase__size_type}
4216
4217
    @sa @ref erase(InteratorType) -- removes the element at a given position
4218
    @sa @ref erase(InteratorType, InteratorType) -- removes the elements in
4219
    the given range
4220
    @sa @ref erase(const typename object_t::key_type&) -- removes the element
4221
    from an object at the given key
4222
4223
    @since version 1.0.0
4224
    */
4225
    void erase(const size_type idx)
4226
    {
4227
        // this erase only works for arrays
4228
        if (is_array())
4229
        {
4230
            if (idx >= size())
4231
            {
4232
                throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
4233
            }
4234
4235
            m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
4236
        }
4237
        else
4238
        {
4239
            throw std::domain_error("cannot use erase() with " + type_name());
4240
        }
4241
    }
4242
4243
    /// @}
4244
4245
4246
    ////////////
4247
    // lookup //
4248
    ////////////
4249
4250
    /// @name lookup
4251
    /// @{
4252
4253
    /*!
4254
    @brief find an element in a JSON object
4255
4256
    Finds an element in a JSON object with key equivalent to @a key. If the
4257
    element is not found or the JSON value is not an object, end() is
4258
    returned.
4259
4260
    @param[in] key key value of the element to search for
4261
4262
    @return Iterator to an element with key equivalent to @a key. If no such
4263
    element is found, past-the-end (see end()) iterator is returned.
4264
4265
    @complexity Logarithmic in the size of the JSON object.
4266
4267
    @liveexample{The example shows how `find()` is used.,find__key_type}
4268
4269
    @since version 1.0.0
4270
    */
4271
    iterator find(typename object_t::key_type key)
4272
    {
4273
        auto result = end();
4274
4275
        if (is_object())
4276
        {
4277
            result.m_it.object_iterator = m_value.object->find(key);
4278
        }
4279
4280
        return result;
4281
    }
4282
4283
    /*!
4284
    @brief find an element in a JSON object
4285
    @copydoc find(typename object_t::key_type)
4286
    */
4287
    const_iterator find(typename object_t::key_type key) const
4288
    {
4289
        auto result = cend();
4290
4291
        if (is_object())
4292
        {
4293
            result.m_it.object_iterator = m_value.object->find(key);
4294
        }
4295
4296
        return result;
4297
    }
4298
4299
    /*!
4300
    @brief returns the number of occurrences of a key in a JSON object
4301
4302
    Returns the number of elements with key @a key. If ObjectType is the
4303
    default `std::map` type, the return value will always be `0` (@a key was
4304
    not found) or `1` (@a key was found).
4305
4306
    @param[in] key key value of the element to count
4307
4308
    @return Number of elements with key @a key. If the JSON value is not an
4309
    object, the return value will be `0`.
4310
4311
    @complexity Logarithmic in the size of the JSON object.
4312
4313
    @liveexample{The example shows how `count()` is used.,count}
4314
4315
    @since version 1.0.0
4316
    */
4317
    size_type count(typename object_t::key_type key) const
4318
    {
4319
        // return 0 for all nonobject types
4320
        return is_object() ? m_value.object->count(key) : 0;
4321
    }
4322
4323
    /// @}
4324
4325
4326
    ///////////////
4327
    // iterators //
4328
    ///////////////
4329
4330
    /// @name iterators
4331
    /// @{
4332
4333
    /*!
4334
    @brief returns an iterator to the first element
4335
4336
    Returns an iterator to the first element.
4337
4338
    @image html range-begin-end.svg "Illustration from cppreference.com"
4339
4340
    @return iterator to the first element
4341
4342
    @complexity Constant.
4343
4344
    @requirement This function helps `basic_json` satisfying the
4345
    [Container](http://en.cppreference.com/w/cpp/concept/Container)
4346
    requirements:
4347
    - The complexity is constant.
4348
4349
    @liveexample{The following code shows an example for `begin()`.,begin}
4350
4351
    @sa @ref cbegin() -- returns a const iterator to the beginning
4352
    @sa @ref end() -- returns an iterator to the end
4353
    @sa @ref cend() -- returns a const iterator to the end
4354
4355
    @since version 1.0.0
4356
    */
4357
    iterator begin() noexcept
4358
    {
4359
        iterator result(this);
4360
        result.set_begin();
4361
        return result;
4362
    }
4363
4364
    /*!
4365
    @copydoc basic_json::cbegin()
4366
    */
4367
    const_iterator begin() const noexcept
4368
    {
4369
        return cbegin();
4370
    }
4371
4372
    /*!
4373
    @brief returns a const iterator to the first element
4374
4375
    Returns a const iterator to the first element.
4376
4377
    @image html range-begin-end.svg "Illustration from cppreference.com"
4378
4379
    @return const iterator to the first element
4380
4381
    @complexity Constant.
4382
4383
    @requirement This function helps `basic_json` satisfying the
4384
    [Container](http://en.cppreference.com/w/cpp/concept/Container)
4385
    requirements:
4386
    - The complexity is constant.
4387
    - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
4388
4389
    @liveexample{The following code shows an example for `cbegin()`.,cbegin}
4390
4391
    @sa @ref begin() -- returns an iterator to the beginning
4392
    @sa @ref end() -- returns an iterator to the end
4393
    @sa @ref cend() -- returns a const iterator to the end
4394
4395
    @since version 1.0.0
4396
    */
4397
    const_iterator cbegin() const noexcept
4398
    {
4399
        const_iterator result(this);
4400
        result.set_begin();
4401
        return result;
4402
    }
4403
4404
    /*!
4405
    @brief returns an iterator to one past the last element
4406
4407
    Returns an iterator to one past the last element.
4408
4409
    @image html range-begin-end.svg "Illustration from cppreference.com"
4410
4411
    @return iterator one past the last element
4412
4413
    @complexity Constant.
4414
4415
    @requirement This function helps `basic_json` satisfying the
4416
    [Container](http://en.cppreference.com/w/cpp/concept/Container)
4417
    requirements:
4418
    - The complexity is constant.
4419
4420
    @liveexample{The following code shows an example for `end()`.,end}
4421
4422
    @sa @ref cend() -- returns a const iterator to the end
4423
    @sa @ref begin() -- returns an iterator to the beginning
4424
    @sa @ref cbegin() -- returns a const iterator to the beginning
4425
4426
    @since version 1.0.0
4427
    */
4428
    iterator end() noexcept
4429
    {
4430
        iterator result(this);
4431
        result.set_end();
4432
        return result;
4433
    }
4434
4435
    /*!
4436
    @copydoc basic_json::cend()
4437
    */
4438
    const_iterator end() const noexcept
4439
    {
4440
        return cend();
4441
    }
4442
4443
    /*!
4444
    @brief returns a const iterator to one past the last element
4445
4446
    Returns a const iterator to one past the last element.
4447
4448
    @image html range-begin-end.svg "Illustration from cppreference.com"
4449
4450
    @return const iterator one past the last element
4451
4452
    @complexity Constant.
4453
4454
    @requirement This function helps `basic_json` satisfying the
4455
    [Container](http://en.cppreference.com/w/cpp/concept/Container)
4456
    requirements:
4457
    - The complexity is constant.
4458
    - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
4459
4460
    @liveexample{The following code shows an example for `cend()`.,cend}
4461
4462
    @sa @ref end() -- returns an iterator to the end
4463
    @sa @ref begin() -- returns an iterator to the beginning
4464
    @sa @ref cbegin() -- returns a const iterator to the beginning
4465
4466
    @since version 1.0.0
4467
    */
4468
    const_iterator cend() const noexcept
4469
    {
4470
        const_iterator result(this);
4471
        result.set_end();
4472
        return result;
4473
    }
4474
4475
    /*!
4476
    @brief returns an iterator to the reverse-beginning
4477
4478
    Returns an iterator to the reverse-beginning; that is, the last element.
4479
4480
    @image html range-rbegin-rend.svg "Illustration from cppreference.com"
4481
4482
    @complexity Constant.
4483
4484
    @requirement This function helps `basic_json` satisfying the
4485
    [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
4486
    requirements:
4487
    - The complexity is constant.
4488
    - Has the semantics of `reverse_iterator(end())`.
4489
4490
    @liveexample{The following code shows an example for `rbegin()`.,rbegin}
4491
4492
    @sa @ref crbegin() -- returns a const reverse iterator to the beginning
4493
    @sa @ref rend() -- returns a reverse iterator to the end
4494
    @sa @ref crend() -- returns a const reverse iterator to the end
4495
4496
    @since version 1.0.0
4497
    */
4498
    reverse_iterator rbegin() noexcept
4499
    {
4500
        return reverse_iterator(end());
4501
    }
4502
4503
    /*!
4504
    @copydoc basic_json::crbegin()
4505
    */
4506
    const_reverse_iterator rbegin() const noexcept
4507
    {
4508
        return crbegin();
4509
    }
4510
4511
    /*!
4512
    @brief returns an iterator to the reverse-end
4513
4514
    Returns an iterator to the reverse-end; that is, one before the first
4515
    element.
4516
4517
    @image html range-rbegin-rend.svg "Illustration from cppreference.com"
4518
4519
    @complexity Constant.
4520
4521
    @requirement This function helps `basic_json` satisfying the
4522
    [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
4523
    requirements:
4524
    - The complexity is constant.
4525
    - Has the semantics of `reverse_iterator(begin())`.
4526
4527
    @liveexample{The following code shows an example for `rend()`.,rend}
4528
4529
    @sa @ref crend() -- returns a const reverse iterator to the end
4530
    @sa @ref rbegin() -- returns a reverse iterator to the beginning
4531
    @sa @ref crbegin() -- returns a const reverse iterator to the beginning
4532
4533
    @since version 1.0.0
4534
    */
4535
    reverse_iterator rend() noexcept
4536
    {
4537
        return reverse_iterator(begin());
4538
    }
4539
4540
    /*!
4541
    @copydoc basic_json::crend()
4542
    */
4543
    const_reverse_iterator rend() const noexcept
4544
    {
4545
        return crend();
4546
    }
4547
4548
    /*!
4549
    @brief returns a const reverse iterator to the last element
4550
4551
    Returns a const iterator to the reverse-beginning; that is, the last
4552
    element.
4553
4554
    @image html range-rbegin-rend.svg "Illustration from cppreference.com"
4555
4556
    @complexity Constant.
4557
4558
    @requirement This function helps `basic_json` satisfying the
4559
    [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
4560
    requirements:
4561
    - The complexity is constant.
4562
    - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
4563
4564
    @liveexample{The following code shows an example for `crbegin()`.,crbegin}
4565
4566
    @sa @ref rbegin() -- returns a reverse iterator to the beginning
4567
    @sa @ref rend() -- returns a reverse iterator to the end
4568
    @sa @ref crend() -- returns a const reverse iterator to the end
4569
4570
    @since version 1.0.0
4571
    */
4572
    const_reverse_iterator crbegin() const noexcept
4573
    {
4574
        return const_reverse_iterator(cend());
4575
    }
4576
4577
    /*!
4578
    @brief returns a const reverse iterator to one before the first
4579
4580
    Returns a const reverse iterator to the reverse-end; that is, one before
4581
    the first element.
4582
4583
    @image html range-rbegin-rend.svg "Illustration from cppreference.com"
4584
4585
    @complexity Constant.
4586
4587
    @requirement This function helps `basic_json` satisfying the
4588
    [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
4589
    requirements:
4590
    - The complexity is constant.
4591
    - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
4592
4593
    @liveexample{The following code shows an example for `crend()`.,crend}
4594
4595
    @sa @ref rend() -- returns a reverse iterator to the end
4596
    @sa @ref rbegin() -- returns a reverse iterator to the beginning
4597
    @sa @ref crbegin() -- returns a const reverse iterator to the beginning
4598
4599
    @since version 1.0.0
4600
    */
4601
    const_reverse_iterator crend() const noexcept
4602
    {
4603
        return const_reverse_iterator(cbegin());
4604
    }
4605
4606
  private:
4607
    // forward declaration
4608
    template<typename IteratorType> class iteration_proxy;
4609
4610
  public:
4611
    /*!
4612
    @brief wrapper to access iterator member functions in range-based for
4613
4614
    This function allows to access @ref iterator::key() and @ref
4615
    iterator::value() during range-based for loops. In these loops, a
4616
    reference to the JSON values is returned, so there is no access to the
4617
    underlying iterator.
4618
4619
    @note The name of this function is not yet final and may change in the
4620
    future.
4621
    */
4622
    static iteration_proxy<iterator> iterator_wrapper(reference cont)
4623
    {
4624
        return iteration_proxy<iterator>(cont);
4625
    }
4626
4627
    /*!
4628
    @copydoc iterator_wrapper(reference)
4629
    */
4630
    static iteration_proxy<const_iterator> iterator_wrapper(const_reference cont)
4631
    {
4632
        return iteration_proxy<const_iterator>(cont);
4633
    }
4634
4635
    /// @}
4636
4637
4638
    //////////////
4639
    // capacity //
4640
    //////////////
4641
4642
    /// @name capacity
4643
    /// @{
4644
4645
    /*!
4646
    @brief checks whether the container is empty
4647
4648
    Checks if a JSON value has no elements.
4649
4650
    @return The return value depends on the different types and is
4651
            defined as follows:
4652
            Value type  | return value
4653
            ----------- | -------------
4654
            null        | `true`
4655
            boolean     | `false`
4656
            string      | `false`
4657
            number      | `false`
4658
            object      | result of function `object_t::empty()`
4659
            array       | result of function `array_t::empty()`
4660
4661
    @note This function does not return whether a string stored as JSON value
4662
    is empty - it returns whether the JSON container itself is empty which is
4663
    false in the case of a string.
4664
4665
    @complexity Constant, as long as @ref array_t and @ref object_t satisfy
4666
    the Container concept; that is, their `empty()` functions have constant
4667
    complexity.
4668
4669
    @requirement This function helps `basic_json` satisfying the
4670
    [Container](http://en.cppreference.com/w/cpp/concept/Container)
4671
    requirements:
4672
    - The complexity is constant.
4673
    - Has the semantics of `begin() == end()`.
4674
4675
    @liveexample{The following code uses `empty()` to check if a JSON
4676
    object contains any elements.,empty}
4677
4678
    @sa @ref size() -- returns the number of elements
4679
4680
    @since version 1.0.0
4681
    */
4682
    bool empty() const noexcept
4683
    {
4684
        switch (m_type)
4685
        {
4686
            case value_t::null:
4687
            {
4688
                // null values are empty
4689
                return true;
4690
            }
4691
4692
            case value_t::array:
4693
            {
4694
                // delegate call to array_t::empty()
4695
                return m_value.array->empty();
4696
            }
4697
4698
            case value_t::object:
4699
            {
4700
                // delegate call to object_t::empty()
4701
                return m_value.object->empty();
4702
            }
4703
4704
            default:
4705
            {
4706
                // all other types are nonempty
4707
                return false;
4708
            }
4709
        }
4710
    }
4711
4712
    /*!
4713
    @brief returns the number of elements
4714
4715
    Returns the number of elements in a JSON value.
4716
4717
    @return The return value depends on the different types and is
4718
            defined as follows:
4719
            Value type  | return value
4720
            ----------- | -------------
4721
            null        | `0`
4722
            boolean     | `1`
4723
            string      | `1`
4724
            number      | `1`
4725
            object      | result of function object_t::size()
4726
            array       | result of function array_t::size()
4727
4728
    @note This function does not return the length of a string stored as JSON
4729
    value - it returns the number of elements in the JSON value which is 1 in
4730
    the case of a string.
4731
4732
    @complexity Constant, as long as @ref array_t and @ref object_t satisfy
4733
    the Container concept; that is, their size() functions have constant
4734
    complexity.
4735
4736
    @requirement This function helps `basic_json` satisfying the
4737
    [Container](http://en.cppreference.com/w/cpp/concept/Container)
4738
    requirements:
4739
    - The complexity is constant.
4740
    - Has the semantics of `std::distance(begin(), end())`.
4741
4742
    @liveexample{The following code calls `size()` on the different value
4743
    types.,size}
4744
4745
    @sa @ref empty() -- checks whether the container is empty
4746
    @sa @ref max_size() -- returns the maximal number of elements
4747
4748
    @since version 1.0.0
4749
    */
4750
    size_type size() const noexcept
4751
    {
4752
        switch (m_type)
4753
        {
4754
            case value_t::null:
4755
            {
4756
                // null values are empty
4757
                return 0;
4758
            }
4759
4760
            case value_t::array:
4761
            {
4762
                // delegate call to array_t::size()
4763
                return m_value.array->size();
4764
            }
4765
4766
            case value_t::object:
4767
            {
4768
                // delegate call to object_t::size()
4769
                return m_value.object->size();
4770
            }
4771
4772
            default:
4773
            {
4774
                // all other types have size 1
4775
                return 1;
4776
            }
4777
        }
4778
    }
4779
4780
    /*!
4781
    @brief returns the maximum possible number of elements
4782
4783
    Returns the maximum number of elements a JSON value is able to hold due to
4784
    system or library implementation limitations, i.e. `std::distance(begin(),
4785
    end())` for the JSON value.
4786
4787
    @return The return value depends on the different types and is
4788
            defined as follows:
4789
            Value type  | return value
4790
            ----------- | -------------
4791
            null        | `0` (same as `size()`)
4792
            boolean     | `1` (same as `size()`)
4793
            string      | `1` (same as `size()`)
4794
            number      | `1` (same as `size()`)
4795
            object      | result of function `object_t::max_size()`
4796
            array       | result of function `array_t::max_size()`
4797
4798
    @complexity Constant, as long as @ref array_t and @ref object_t satisfy
4799
    the Container concept; that is, their `max_size()` functions have constant
4800
    complexity.
4801
4802
    @requirement This function helps `basic_json` satisfying the
4803
    [Container](http://en.cppreference.com/w/cpp/concept/Container)
4804
    requirements:
4805
    - The complexity is constant.
4806
    - Has the semantics of returning `b.size()` where `b` is the largest
4807
      possible JSON value.
4808
4809
    @liveexample{The following code calls `max_size()` on the different value
4810
    types. Note the output is implementation specific.,max_size}
4811
4812
    @sa @ref size() -- returns the number of elements
4813
4814
    @since version 1.0.0
4815
    */
4816
    size_type max_size() const noexcept
4817
    {
4818
        switch (m_type)
4819
        {
4820
            case value_t::array:
4821
            {
4822
                // delegate call to array_t::max_size()
4823
                return m_value.array->max_size();
4824
            }
4825
4826
            case value_t::object:
4827
            {
4828
                // delegate call to object_t::max_size()
4829
                return m_value.object->max_size();
4830
            }
4831
4832
            default:
4833
            {
4834
                // all other types have max_size() == size()
4835
                return size();
4836
            }
4837
        }
4838
    }
4839
4840
    /// @}
4841
4842
4843
    ///////////////
4844
    // modifiers //
4845
    ///////////////
4846
4847
    /// @name modifiers
4848
    /// @{
4849
4850
    /*!
4851
    @brief clears the contents
4852
4853
    Clears the content of a JSON value and resets it to the default value as
4854
    if @ref basic_json(value_t) would have been called:
4855
4856
    Value type  | initial value
4857
    ----------- | -------------
4858
    null        | `null`
4859
    boolean     | `false`
4860
    string      | `""`
4861
    number      | `0`
4862
    object      | `{}`
4863
    array       | `[]`
4864
4865
    @note Floating-point numbers are set to `0.0` which will be serialized to
4866
    `0`. The vale type remains @ref number_float_t.
4867
4868
    @complexity Linear in the size of the JSON value.
4869
4870
    @liveexample{The example below shows the effect of `clear()` to different
4871
    JSON types.,clear}
4872
4873
    @since version 1.0.0
4874
    */
4875
    void clear() noexcept
4876
    {
4877
        switch (m_type)
4878
        {
4879
            case value_t::number_integer:
4880
            {
4881
                m_value.number_integer = 0;
4882
                break;
4883
            }
4884
4885
            case value_t::number_unsigned:
4886
            {
4887
                m_value.number_unsigned = 0;
4888
                break;
4889
            }
4890
4891
            case value_t::number_float:
4892
            {
4893
                m_value.number_float = 0.0;
4894
                break;
4895
            }
4896
4897
            case value_t::boolean:
4898
            {
4899
                m_value.boolean = false;
4900
                break;
4901
            }
4902
4903
            case value_t::string:
4904
            {
4905
                m_value.string->clear();
4906
                break;
4907
            }
4908
4909
            case value_t::array:
4910
            {
4911
                m_value.array->clear();
4912
                break;
4913
            }
4914
4915
            case value_t::object:
4916
            {
4917
                m_value.object->clear();
4918
                break;
4919
            }
4920
4921
            default:
4922
            {
4923
                break;
4924
            }
4925
        }
4926
    }
4927
4928
    /*!
4929
    @brief add an object to an array
4930
4931
    Appends the given element @a val to the end of the JSON value. If the
4932
    function is called on a JSON null value, an empty array is created before
4933
    appending @a val.
4934
4935
    @param[in] val the value to add to the JSON array
4936
4937
    @throw std::domain_error when called on a type other than JSON array or
4938
    null; example: `"cannot use push_back() with number"`
4939
4940
    @complexity Amortized constant.
4941
4942
    @liveexample{The example shows how `push_back()` and `+=` can be used to
4943
    add elements to a JSON array. Note how the `null` value was silently
4944
    converted to a JSON array.,push_back}
4945
4946
    @since version 1.0.0
4947
    */
4948
    void push_back(basic_json&& val)
4949
    {
4950
        // push_back only works for null objects or arrays
4951
        if (not(is_null() or is_array()))
4952
        {
4953
            throw std::domain_error("cannot use push_back() with " + type_name());
4954
        }
4955
4956
        // transform null object into an array
4957
        if (is_null())
4958
        {
4959
            m_type = value_t::array;
4960
            m_value = value_t::array;
4961
            assert_invariant();
4962
        }
4963
4964
        // add element to array (move semantics)
4965
        m_value.array->push_back(std::move(val));
4966
        // invalidate object
4967
        val.m_type = value_t::null;
4968
    }
4969
4970
    /*!
4971
    @brief add an object to an array
4972
    @copydoc push_back(basic_json&&)
4973
    */
4974
    reference operator+=(basic_json&& val)
4975
    {
4976
        push_back(std::move(val));
4977
        return *this;
4978
    }
4979
4980
    /*!
4981
    @brief add an object to an array
4982
    @copydoc push_back(basic_json&&)
4983
    */
4984
    void push_back(const basic_json& val)
4985
    {
4986
        // push_back only works for null objects or arrays
4987
        if (not(is_null() or is_array()))
4988
        {
4989
            throw std::domain_error("cannot use push_back() with " + type_name());
4990
        }
4991
4992
        // transform null object into an array
4993
        if (is_null())
4994
        {
4995
            m_type = value_t::array;
4996
            m_value = value_t::array;
4997
            assert_invariant();
4998
        }
4999
5000
        // add element to array
5001
        m_value.array->push_back(val);
5002
    }
5003
5004
    /*!
5005
    @brief add an object to an array
5006
    @copydoc push_back(basic_json&&)
5007
    */
5008
    reference operator+=(const basic_json& val)
5009
    {
5010
        push_back(val);
5011
        return *this;
5012
    }
5013
5014
    /*!
5015
    @brief add an object to an object
5016
5017
    Inserts the given element @a val to the JSON object. If the function is
5018
    called on a JSON null value, an empty object is created before inserting
5019
    @a val.
5020
5021
    @param[in] val the value to add to the JSON object
5022
5023
    @throw std::domain_error when called on a type other than JSON object or
5024
    null; example: `"cannot use push_back() with number"`
5025
5026
    @complexity Logarithmic in the size of the container, O(log(`size()`)).
5027
5028
    @liveexample{The example shows how `push_back()` and `+=` can be used to
5029
    add elements to a JSON object. Note how the `null` value was silently
5030
    converted to a JSON object.,push_back__object_t__value}
5031
5032
    @since version 1.0.0
5033
    */
5034
    void push_back(const typename object_t::value_type& val)
5035
    {
5036
        // push_back only works for null objects or objects
5037
        if (not(is_null() or is_object()))
5038
        {
5039
            throw std::domain_error("cannot use push_back() with " + type_name());
5040
        }
5041
5042
        // transform null object into an object
5043
        if (is_null())
5044
        {
5045
            m_type = value_t::object;
5046
            m_value = value_t::object;
5047
            assert_invariant();
5048
        }
5049
5050
        // add element to array
5051
        m_value.object->insert(val);
5052
    }
5053
5054
    /*!
5055
    @brief add an object to an object
5056
    @copydoc push_back(const typename object_t::value_type&)
5057
    */
5058
    reference operator+=(const typename object_t::value_type& val)
5059
    {
5060
        push_back(val);
5061
        return *this;
5062
    }
5063
5064
    /*!
5065
    @brief add an object to an object
5066
5067
    This function allows to use `push_back` with an initializer list. In case
5068
5069
    1. the current value is an object,
5070
    2. the initializer list @a init contains only two elements, and
5071
    3. the first element of @a init is a string,
5072
5073
    @a init is converted into an object element and added using
5074
    @ref push_back(const typename object_t::value_type&). Otherwise, @a init
5075
    is converted to a JSON value and added using @ref push_back(basic_json&&).
5076
5077
    @param init  an initializer list
5078
5079
    @complexity Linear in the size of the initializer list @a init.
5080
5081
    @note This function is required to resolve an ambiguous overload error,
5082
          because pairs like `{"key", "value"}` can be both interpreted as
5083
          `object_t::value_type` or `std::initializer_list<basic_json>`, see
5084
          https://github.com/nlohmann/json/issues/235 for more information.
5085
5086
    @liveexample{The example shows how initializer lists are treated as
5087
    objects when possible.,push_back__initializer_list}
5088
    */
5089
    void push_back(std::initializer_list<basic_json> init)
5090
    {
5091
        if (is_object() and init.size() == 2 and init.begin()->is_string())
5092
        {
5093
            const string_t key = *init.begin();
5094
            push_back(typename object_t::value_type(key, *(init.begin() + 1)));
5095
        }
5096
        else
5097
        {
5098
            push_back(basic_json(init));
5099
        }
5100
    }
5101
5102
    /*!
5103
    @brief add an object to an object
5104
    @copydoc push_back(std::initializer_list<basic_json>)
5105
    */
5106
    reference operator+=(std::initializer_list<basic_json> init)
5107
    {
5108
        push_back(init);
5109
        return *this;
5110
    }
5111
5112
    /*!
5113
    @brief inserts element
5114
5115
    Inserts element @a val before iterator @a pos.
5116
5117
    @param[in] pos iterator before which the content will be inserted; may be
5118
    the end() iterator
5119
    @param[in] val element to insert
5120
    @return iterator pointing to the inserted @a val.
5121
5122
    @throw std::domain_error if called on JSON values other than arrays;
5123
    example: `"cannot use insert() with string"`
5124
    @throw std::domain_error if @a pos is not an iterator of *this; example:
5125
    `"iterator does not fit current value"`
5126
5127
    @complexity Constant plus linear in the distance between pos and end of the
5128
    container.
5129
5130
    @liveexample{The example shows how `insert()` is used.,insert}
5131
5132
    @since version 1.0.0
5133
    */
5134
    iterator insert(const_iterator pos, const basic_json& val)
5135
    {
5136
        // insert only works for arrays
5137
        if (is_array())
5138
        {
5139
            // check if iterator pos fits to this JSON value
5140
            if (pos.m_object != this)
5141
            {
5142
                throw std::domain_error("iterator does not fit current value");
5143
            }
5144
5145
            // insert to array and return iterator
5146
            iterator result(this);
5147
            result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
5148
            return result;
5149
        }
5150
        else
5151
        {
5152
            throw std::domain_error("cannot use insert() with " + type_name());
5153
        }
5154
    }
5155
5156
    /*!
5157
    @brief inserts element
5158
    @copydoc insert(const_iterator, const basic_json&)
5159
    */
5160
    iterator insert(const_iterator pos, basic_json&& val)
5161
    {
5162
        return insert(pos, val);
5163
    }
5164
5165
    /*!
5166
    @brief inserts elements
5167
5168
    Inserts @a cnt copies of @a val before iterator @a pos.
5169
5170
    @param[in] pos iterator before which the content will be inserted; may be
5171
    the end() iterator
5172
    @param[in] cnt number of copies of @a val to insert
5173
    @param[in] val element to insert
5174
    @return iterator pointing to the first element inserted, or @a pos if
5175
    `cnt==0`
5176
5177
    @throw std::domain_error if called on JSON values other than arrays;
5178
    example: `"cannot use insert() with string"`
5179
    @throw std::domain_error if @a pos is not an iterator of *this; example:
5180
    `"iterator does not fit current value"`
5181
5182
    @complexity Linear in @a cnt plus linear in the distance between @a pos
5183
    and end of the container.
5184
5185
    @liveexample{The example shows how `insert()` is used.,insert__count}
5186
5187
    @since version 1.0.0
5188
    */
5189
    iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
5190
    {
5191
        // insert only works for arrays
5192
        if (is_array())
5193
        {
5194
            // check if iterator pos fits to this JSON value
5195
            if (pos.m_object != this)
5196
            {
5197
                throw std::domain_error("iterator does not fit current value");
5198
            }
5199
5200
            // insert to array and return iterator
5201
            iterator result(this);
5202
            result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
5203
            return result;
5204
        }
5205
        else
5206
        {
5207
            throw std::domain_error("cannot use insert() with " + type_name());
5208
        }
5209
    }
5210
5211
    /*!
5212
    @brief inserts elements
5213
5214
    Inserts elements from range `[first, last)` before iterator @a pos.
5215
5216
    @param[in] pos iterator before which the content will be inserted; may be
5217
    the end() iterator
5218
    @param[in] first begin of the range of elements to insert
5219
    @param[in] last end of the range of elements to insert
5220
5221
    @throw std::domain_error if called on JSON values other than arrays;
5222
    example: `"cannot use insert() with string"`
5223
    @throw std::domain_error if @a pos is not an iterator of *this; example:
5224
    `"iterator does not fit current value"`
5225
    @throw std::domain_error if @a first and @a last do not belong to the same
5226
    JSON value; example: `"iterators do not fit"`
5227
    @throw std::domain_error if @a first or @a last are iterators into
5228
    container for which insert is called; example: `"passed iterators may not
5229
    belong to container"`
5230
5231
    @return iterator pointing to the first element inserted, or @a pos if
5232
    `first==last`
5233
5234
    @complexity Linear in `std::distance(first, last)` plus linear in the
5235
    distance between @a pos and end of the container.
5236
5237
    @liveexample{The example shows how `insert()` is used.,insert__range}
5238
5239
    @since version 1.0.0
5240
    */
5241
    iterator insert(const_iterator pos, const_iterator first, const_iterator last)
5242
    {
5243
        // insert only works for arrays
5244
        if (not is_array())
5245
        {
5246
            throw std::domain_error("cannot use insert() with " + type_name());
5247
        }
5248
5249
        // check if iterator pos fits to this JSON value
5250
        if (pos.m_object != this)
5251
        {
5252
            throw std::domain_error("iterator does not fit current value");
5253
        }
5254
5255
        // check if range iterators belong to the same JSON object
5256
        if (first.m_object != last.m_object)
5257
        {
5258
            throw std::domain_error("iterators do not fit");
5259
        }
5260
5261
        if (first.m_object == this or last.m_object == this)
5262
        {
5263
            throw std::domain_error("passed iterators may not belong to container");
5264
        }
5265
5266
        // insert to array and return iterator
5267
        iterator result(this);
5268
        result.m_it.array_iterator = m_value.array->insert(
5269
                                         pos.m_it.array_iterator,
5270
                                         first.m_it.array_iterator,
5271
                                         last.m_it.array_iterator);
5272
        return result;
5273
    }
5274
5275
    /*!
5276
    @brief inserts elements
5277
5278
    Inserts elements from initializer list @a ilist before iterator @a pos.
5279
5280
    @param[in] pos iterator before which the content will be inserted; may be
5281
    the end() iterator
5282
    @param[in] ilist initializer list to insert the values from
5283
5284
    @throw std::domain_error if called on JSON values other than arrays;
5285
    example: `"cannot use insert() with string"`
5286
    @throw std::domain_error if @a pos is not an iterator of *this; example:
5287
    `"iterator does not fit current value"`
5288
5289
    @return iterator pointing to the first element inserted, or @a pos if
5290
    `ilist` is empty
5291
5292
    @complexity Linear in `ilist.size()` plus linear in the distance between
5293
    @a pos and end of the container.
5294
5295
    @liveexample{The example shows how `insert()` is used.,insert__ilist}
5296
5297
    @since version 1.0.0
5298
    */
5299
    iterator insert(const_iterator pos, std::initializer_list<basic_json> ilist)
5300
    {
5301
        // insert only works for arrays
5302
        if (not is_array())
5303
        {
5304
            throw std::domain_error("cannot use insert() with " + type_name());
5305
        }
5306
5307
        // check if iterator pos fits to this JSON value
5308
        if (pos.m_object != this)
5309
        {
5310
            throw std::domain_error("iterator does not fit current value");
5311
        }
5312
5313
        // insert to array and return iterator
5314
        iterator result(this);
5315
        result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist);
5316
        return result;
5317
    }
5318
5319
    /*!
5320
    @brief exchanges the values
5321
5322
    Exchanges the contents of the JSON value with those of @a other. Does not
5323
    invoke any move, copy, or swap operations on individual elements. All
5324
    iterators and references remain valid. The past-the-end iterator is
5325
    invalidated.
5326
5327
    @param[in,out] other JSON value to exchange the contents with
5328
5329
    @complexity Constant.
5330
5331
    @liveexample{The example below shows how JSON values can be swapped with
5332
    `swap()`.,swap__reference}
5333
5334
    @since version 1.0.0
5335
    */
5336
    void swap(reference other) noexcept (
5337
        std::is_nothrow_move_constructible<value_t>::value and
5338
        std::is_nothrow_move_assignable<value_t>::value and
5339
        std::is_nothrow_move_constructible<json_value>::value and
5340
        std::is_nothrow_move_assignable<json_value>::value
5341
    )
5342
    {
5343
        std::swap(m_type, other.m_type);
5344
        std::swap(m_value, other.m_value);
5345
        assert_invariant();
5346
    }
5347
5348
    /*!
5349
    @brief exchanges the values
5350
5351
    Exchanges the contents of a JSON array with those of @a other. Does not
5352
    invoke any move, copy, or swap operations on individual elements. All
5353
    iterators and references remain valid. The past-the-end iterator is
5354
    invalidated.
5355
5356
    @param[in,out] other array to exchange the contents with
5357
5358
    @throw std::domain_error when JSON value is not an array; example: `"cannot
5359
    use swap() with string"`
5360
5361
    @complexity Constant.
5362
5363
    @liveexample{The example below shows how arrays can be swapped with
5364
    `swap()`.,swap__array_t}
5365
5366
    @since version 1.0.0
5367
    */
5368
    void swap(array_t& other)
5369
    {
5370
        // swap only works for arrays
5371
        if (is_array())
5372
        {
5373
            std::swap(*(m_value.array), other);
5374
        }
5375
        else
5376
        {
5377
            throw std::domain_error("cannot use swap() with " + type_name());
5378
        }
5379
    }
5380
5381
    /*!
5382
    @brief exchanges the values
5383
5384
    Exchanges the contents of a JSON object with those of @a other. Does not
5385
    invoke any move, copy, or swap operations on individual elements. All
5386
    iterators and references remain valid. The past-the-end iterator is
5387
    invalidated.
5388
5389
    @param[in,out] other object to exchange the contents with
5390
5391
    @throw std::domain_error when JSON value is not an object; example:
5392
    `"cannot use swap() with string"`
5393
5394
    @complexity Constant.
5395
5396
    @liveexample{The example below shows how objects can be swapped with
5397
    `swap()`.,swap__object_t}
5398
5399
    @since version 1.0.0
5400
    */
5401
    void swap(object_t& other)
5402
    {
5403
        // swap only works for objects
5404
        if (is_object())
5405
        {
5406
            std::swap(*(m_value.object), other);
5407
        }
5408
        else
5409
        {
5410
            throw std::domain_error("cannot use swap() with " + type_name());
5411
        }
5412
    }
5413
5414
    /*!
5415
    @brief exchanges the values
5416
5417
    Exchanges the contents of a JSON string with those of @a other. Does not
5418
    invoke any move, copy, or swap operations on individual elements. All
5419
    iterators and references remain valid. The past-the-end iterator is
5420
    invalidated.
5421
5422
    @param[in,out] other string to exchange the contents with
5423
5424
    @throw std::domain_error when JSON value is not a string; example: `"cannot
5425
    use swap() with boolean"`
5426
5427
    @complexity Constant.
5428
5429
    @liveexample{The example below shows how strings can be swapped with
5430
    `swap()`.,swap__string_t}
5431
5432
    @since version 1.0.0
5433
    */
5434
    void swap(string_t& other)
5435
    {
5436
        // swap only works for strings
5437
        if (is_string())
5438
        {
5439
            std::swap(*(m_value.string), other);
5440
        }
5441
        else
5442
        {
5443
            throw std::domain_error("cannot use swap() with " + type_name());
5444
        }
5445
    }
5446
5447
    /// @}
5448
5449
5450
    //////////////////////////////////////////
5451
    // lexicographical comparison operators //
5452
    //////////////////////////////////////////
5453
5454
    /// @name lexicographical comparison operators
5455
    /// @{
5456
5457
  private:
5458
    /*!
5459
    @brief comparison operator for JSON types
5460
5461
    Returns an ordering that is similar to Python:
5462
    - order: null < boolean < number < object < array < string
5463
    - furthermore, each type is not smaller than itself
5464
5465
    @since version 1.0.0
5466
    */
5467
    friend bool operator<(const value_t lhs, const value_t rhs) noexcept
5468
    {
5469
        static constexpr std::array<uint8_t, 8> order = {{
5470
                0, // null
5471
                3, // object
5472
                4, // array
5473
                5, // string
5474
                1, // boolean
5475
                2, // integer
5476
                2, // unsigned
5477
                2, // float
5478
            }
5479
        };
5480
5481
        // discarded values are not comparable
5482
        if (lhs == value_t::discarded or rhs == value_t::discarded)
5483
        {
5484
            return false;
5485
        }
5486
5487
        return order[static_cast<std::size_t>(lhs)] < order[static_cast<std::size_t>(rhs)];
5488
    }
5489
5490
  public:
5491
    /*!
5492
    @brief comparison: equal
5493
5494
    Compares two JSON values for equality according to the following rules:
5495
    - Two JSON values are equal if (1) they are from the same type and (2)
5496
      their stored values are the same.
5497
    - Integer and floating-point numbers are automatically converted before
5498
      comparison. Floating-point numbers are compared indirectly: two
5499
      floating-point numbers `f1` and `f2` are considered equal if neither
5500
      `f1 > f2` nor `f2 > f1` holds.
5501
    - Two JSON null values are equal.
5502
5503
    @param[in] lhs  first JSON value to consider
5504
    @param[in] rhs  second JSON value to consider
5505
    @return whether the values @a lhs and @a rhs are equal
5506
5507
    @complexity Linear.
5508
5509
    @liveexample{The example demonstrates comparing several JSON
5510
    types.,operator__equal}
5511
5512
    @since version 1.0.0
5513
    */
5514
    friend bool operator==(const_reference lhs, const_reference rhs) noexcept
5515
    {
5516
        const auto lhs_type = lhs.type();
5517
        const auto rhs_type = rhs.type();
5518
5519
        if (lhs_type == rhs_type)
5520
        {
5521
            switch (lhs_type)
5522
            {
5523
                case value_t::array:
5524
                {
5525
                    return *lhs.m_value.array == *rhs.m_value.array;
5526
                }
5527
                case value_t::object:
5528
                {
5529
                    return *lhs.m_value.object == *rhs.m_value.object;
5530
                }
5531
                case value_t::null:
5532
                {
5533
                    return true;
5534
                }
5535
                case value_t::string:
5536
                {
5537
                    return *lhs.m_value.string == *rhs.m_value.string;
5538
                }
5539
                case value_t::boolean:
5540
                {
5541
                    return lhs.m_value.boolean == rhs.m_value.boolean;
5542
                }
5543
                case value_t::number_integer:
5544
                {
5545
                    return lhs.m_value.number_integer == rhs.m_value.number_integer;
5546
                }
5547
                case value_t::number_unsigned:
5548
                {
5549
                    return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
5550
                }
5551
                case value_t::number_float:
5552
                {
5553
                    return lhs.m_value.number_float == rhs.m_value.number_float;
5554
                }
5555
                default:
5556
                {
5557
                    return false;
5558
                }
5559
            }
5560
        }
5561
        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
5562
        {
5563
            return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
5564
        }
5565
        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
5566
        {
5567
            return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
5568
        }
5569
        else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
5570
        {
5571
            return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
5572
        }
5573
        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
5574
        {
5575
            return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
5576
        }
5577
        else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
5578
        {
5579
            return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
5580
        }
5581
        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
5582
        {
5583
            return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
5584
        }
5585
5586
        return false;
5587
    }
5588
5589
    /*!
5590
    @brief comparison: equal
5591
5592
    The functions compares the given JSON value against a null pointer. As the
5593
    null pointer can be used to initialize a JSON value to null, a comparison
5594
    of JSON value @a v with a null pointer should be equivalent to call
5595
    `v.is_null()`.
5596
5597
    @param[in] v  JSON value to consider
5598
    @return whether @a v is null
5599
5600
    @complexity Constant.
5601
5602
    @liveexample{The example compares several JSON types to the null pointer.
5603
    ,operator__equal__nullptr_t}
5604
5605
    @since version 1.0.0
5606
    */
5607
    friend bool operator==(const_reference v, std::nullptr_t) noexcept
5608
    {
5609
        return v.is_null();
5610
    }
5611
5612
    /*!
5613
    @brief comparison: equal
5614
    @copydoc operator==(const_reference, std::nullptr_t)
5615
    */
5616
    friend bool operator==(std::nullptr_t, const_reference v) noexcept
5617
    {
5618
        return v.is_null();
5619
    }
5620
5621
    /*!
5622
    @brief comparison: not equal
5623
5624
    Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
5625
5626
    @param[in] lhs  first JSON value to consider
5627
    @param[in] rhs  second JSON value to consider
5628
    @return whether the values @a lhs and @a rhs are not equal
5629
5630
    @complexity Linear.
5631
5632
    @liveexample{The example demonstrates comparing several JSON
5633
    types.,operator__notequal}
5634
5635
    @since version 1.0.0
5636
    */
5637
    friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
5638
    {
5639
        return not (lhs == rhs);
5640
    }
5641
5642
    /*!
5643
    @brief comparison: not equal
5644
5645
    The functions compares the given JSON value against a null pointer. As the
5646
    null pointer can be used to initialize a JSON value to null, a comparison
5647
    of JSON value @a v with a null pointer should be equivalent to call
5648
    `not v.is_null()`.
5649
5650
    @param[in] v  JSON value to consider
5651
    @return whether @a v is not null
5652
5653
    @complexity Constant.
5654
5655
    @liveexample{The example compares several JSON types to the null pointer.
5656
    ,operator__notequal__nullptr_t}
5657
5658
    @since version 1.0.0
5659
    */
5660
    friend bool operator!=(const_reference v, std::nullptr_t) noexcept
5661
    {
5662
        return not v.is_null();
5663
    }
5664
5665
    /*!
5666
    @brief comparison: not equal
5667
    @copydoc operator!=(const_reference, std::nullptr_t)
5668
    */
5669
    friend bool operator!=(std::nullptr_t, const_reference v) noexcept
5670
    {
5671
        return not v.is_null();
5672
    }
5673
5674
    /*!
5675
    @brief comparison: less than
5676
5677
    Compares whether one JSON value @a lhs is less than another JSON value @a
5678
    rhs according to the following rules:
5679
    - If @a lhs and @a rhs have the same type, the values are compared using
5680
      the default `<` operator.
5681
    - Integer and floating-point numbers are automatically converted before
5682
      comparison
5683
    - In case @a lhs and @a rhs have different types, the values are ignored
5684
      and the order of the types is considered, see
5685
      @ref operator<(const value_t, const value_t).
5686
5687
    @param[in] lhs  first JSON value to consider
5688
    @param[in] rhs  second JSON value to consider
5689
    @return whether @a lhs is less than @a rhs
5690
5691
    @complexity Linear.
5692
5693
    @liveexample{The example demonstrates comparing several JSON
5694
    types.,operator__less}
5695
5696
    @since version 1.0.0
5697
    */
5698
    friend bool operator<(const_reference lhs, const_reference rhs) noexcept
5699
    {
5700
        const auto lhs_type = lhs.type();
5701
        const auto rhs_type = rhs.type();
5702
5703
        if (lhs_type == rhs_type)
5704
        {
5705
            switch (lhs_type)
5706
            {
5707
                case value_t::array:
5708
                {
5709
                    return *lhs.m_value.array < *rhs.m_value.array;
5710
                }
5711
                case value_t::object:
5712
                {
5713
                    return *lhs.m_value.object < *rhs.m_value.object;
5714
                }
5715
                case value_t::null:
5716
                {
5717
                    return false;
5718
                }
5719
                case value_t::string:
5720
                {
5721
                    return *lhs.m_value.string < *rhs.m_value.string;
5722
                }
5723
                case value_t::boolean:
5724
                {
5725
                    return lhs.m_value.boolean < rhs.m_value.boolean;
5726
                }
5727
                case value_t::number_integer:
5728
                {
5729
                    return lhs.m_value.number_integer < rhs.m_value.number_integer;
5730
                }
5731
                case value_t::number_unsigned:
5732
                {
5733
                    return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
5734
                }
5735
                case value_t::number_float:
5736
                {
5737
                    return lhs.m_value.number_float < rhs.m_value.number_float;
5738
                }
5739
                default:
5740
                {
5741
                    return false;
5742
                }
5743
            }
5744
        }
5745
        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
5746
        {
5747
            return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
5748
        }
5749
        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
5750
        {
5751
            return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
5752
        }
5753
        else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
5754
        {
5755
            return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
5756
        }
5757
        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
5758
        {
5759
            return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
5760
        }
5761
        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
5762
        {
5763
            return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
5764
        }
5765
        else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
5766
        {
5767
            return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
5768
        }
5769
5770
        // We only reach this line if we cannot compare values. In that case,
5771
        // we compare types. Note we have to call the operator explicitly,
5772
        // because MSVC has problems otherwise.
5773
        return operator<(lhs_type, rhs_type);
5774
    }
5775
5776
    /*!
5777
    @brief comparison: less than or equal
5778
5779
    Compares whether one JSON value @a lhs is less than or equal to another
5780
    JSON value by calculating `not (rhs < lhs)`.
5781
5782
    @param[in] lhs  first JSON value to consider
5783
    @param[in] rhs  second JSON value to consider
5784
    @return whether @a lhs is less than or equal to @a rhs
5785
5786
    @complexity Linear.
5787
5788
    @liveexample{The example demonstrates comparing several JSON
5789
    types.,operator__greater}
5790
5791
    @since version 1.0.0
5792
    */
5793
    friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
5794
    {
5795
        return not (rhs < lhs);
5796
    }
5797
5798
    /*!
5799
    @brief comparison: greater than
5800
5801
    Compares whether one JSON value @a lhs is greater than another
5802
    JSON value by calculating `not (lhs <= rhs)`.
5803
5804
    @param[in] lhs  first JSON value to consider
5805
    @param[in] rhs  second JSON value to consider
5806
    @return whether @a lhs is greater than to @a rhs
5807
5808
    @complexity Linear.
5809
5810
    @liveexample{The example demonstrates comparing several JSON
5811
    types.,operator__lessequal}
5812
5813
    @since version 1.0.0
5814
    */
5815
    friend bool operator>(const_reference lhs, const_reference rhs) noexcept
5816
    {
5817
        return not (lhs <= rhs);
5818
    }
5819
5820
    /*!
5821
    @brief comparison: greater than or equal
5822
5823
    Compares whether one JSON value @a lhs is greater than or equal to another
5824
    JSON value by calculating `not (lhs < rhs)`.
5825
5826
    @param[in] lhs  first JSON value to consider
5827
    @param[in] rhs  second JSON value to consider
5828
    @return whether @a lhs is greater than or equal to @a rhs
5829
5830
    @complexity Linear.
5831
5832
    @liveexample{The example demonstrates comparing several JSON
5833
    types.,operator__greaterequal}
5834
5835
    @since version 1.0.0
5836
    */
5837
    friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
5838
    {
5839
        return not (lhs < rhs);
5840
    }
5841
5842
    /// @}
5843
5844
5845
    ///////////////////
5846
    // serialization //
5847
    ///////////////////
5848
5849
    /// @name serialization
5850
    /// @{
5851
5852
    /*!
5853
    @brief serialize to stream
5854
5855
    Serialize the given JSON value @a j to the output stream @a o. The JSON
5856
    value will be serialized using the @ref dump member function. The
5857
    indentation of the output can be controlled with the member variable
5858
    `width` of the output stream @a o. For instance, using the manipulator
5859
    `std::setw(4)` on @a o sets the indentation level to `4` and the
5860
    serialization result is the same as calling `dump(4)`.
5861
5862
    @note During serializaion, the locale and the precision of the output
5863
    stream @a o are changed. The original values are restored when the
5864
    function returns.
5865
5866
    @param[in,out] o  stream to serialize to
5867
    @param[in] j  JSON value to serialize
5868
5869
    @return the stream @a o
5870
5871
    @complexity Linear.
5872
5873
    @liveexample{The example below shows the serialization with different
5874
    parameters to `width` to adjust the indentation level.,operator_serialize}
5875
5876
    @since version 1.0.0
5877
    */
5878
    friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
5879
    {
5880
        // read width member and use it as indentation parameter if nonzero
5881
        const bool pretty_print = (o.width() > 0);
5882
        const auto indentation = (pretty_print ? o.width() : 0);
5883
5884
        // reset width to 0 for subsequent calls to this stream
5885
        o.width(0);
5886
5887
        // fix locale problems
5888
        const auto old_locale = o.imbue(std::locale(std::locale(), new DecimalSeparator));
5889
        // set precision
5890
5891
        // 6, 15 or 16 digits of precision allows round-trip IEEE 754
5892
        // string->float->string, string->double->string or string->long
5893
        // double->string; to be safe, we read this value from
5894
        // std::numeric_limits<number_float_t>::digits10
5895
        const auto old_precision = o.precision(std::numeric_limits<double>::digits10);
5896
5897
        // do the actual serialization
5898
        j.dump(o, pretty_print, static_cast<unsigned int>(indentation));
5899
5900
        // reset locale and precision
5901
        o.imbue(old_locale);
5902
        o.precision(old_precision);
5903
        return o;
5904
    }
5905
5906
    /*!
5907
    @brief serialize to stream
5908
    @copydoc operator<<(std::ostream&, const basic_json&)
5909
    */
5910
    friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
5911
    {
5912
        return o << j;
5913
    }
5914
5915
    /// @}
5916
5917
5918
    /////////////////////
5919
    // deserialization //
5920
    /////////////////////
5921
5922
    /// @name deserialization
5923
    /// @{
5924
5925
    /*!
5926
    @brief deserialize from string
5927
5928
    @param[in] s  string to read a serialized JSON value from
5929
    @param[in] cb a parser callback function of type @ref parser_callback_t
5930
    which is used to control the deserialization by filtering unwanted values
5931
    (optional)
5932
5933
    @return result of the deserialization
5934
5935
    @complexity Linear in the length of the input. The parser is a predictive
5936
    LL(1) parser. The complexity can be higher if the parser callback function
5937
    @a cb has a super-linear complexity.
5938
5939
    @note A UTF-8 byte order mark is silently ignored.
5940
5941
    @liveexample{The example below demonstrates the `parse()` function with
5942
    and without callback function.,parse__string__parser_callback_t}
5943
5944
    @sa @ref parse(std::istream&, const parser_callback_t) for a version that
5945
    reads from an input stream
5946
5947
    @since version 1.0.0
5948
    */
5949
    static basic_json parse(const string_t& s,
5950
                            const parser_callback_t cb = nullptr)
5951
    {
5952
        return parser(s, cb).parse();
5953
    }
5954
5955
    /*!
5956
    @brief deserialize from stream
5957
5958
    @param[in,out] i  stream to read a serialized JSON value from
5959
    @param[in] cb a parser callback function of type @ref parser_callback_t
5960
    which is used to control the deserialization by filtering unwanted values
5961
    (optional)
5962
5963
    @return result of the deserialization
5964
5965
    @complexity Linear in the length of the input. The parser is a predictive
5966
    LL(1) parser. The complexity can be higher if the parser callback function
5967
    @a cb has a super-linear complexity.
5968
5969
    @note A UTF-8 byte order mark is silently ignored.
5970
5971
    @liveexample{The example below demonstrates the `parse()` function with
5972
    and without callback function.,parse__istream__parser_callback_t}
5973
5974
    @sa @ref parse(const string_t&, const parser_callback_t) for a version
5975
    that reads from a string
5976
5977
    @since version 1.0.0
5978
    */
5979
    static basic_json parse(std::istream& i,
5980
                            const parser_callback_t cb = nullptr)
5981
    {
5982
        return parser(i, cb).parse();
5983
    }
5984
5985
    /*!
5986
    @copydoc parse(std::istream&, const parser_callback_t)
5987
    */
5988
    static basic_json parse(std::istream&& i,
5989
                            const parser_callback_t cb = nullptr)
5990
    {
5991
        return parser(i, cb).parse();
5992
    }
5993
5994
    /*!
5995
    @brief deserialize from stream
5996
5997
    Deserializes an input stream to a JSON value.
5998
5999
    @param[in,out] i  input stream to read a serialized JSON value from
6000
    @param[in,out] j  JSON value to write the deserialized input to
6001
6002
    @throw std::invalid_argument in case of parse errors
6003
6004
    @complexity Linear in the length of the input. The parser is a predictive
6005
    LL(1) parser.
6006
6007
    @note A UTF-8 byte order mark is silently ignored.
6008
6009
    @liveexample{The example below shows how a JSON value is constructed by
6010
    reading a serialization from a stream.,operator_deserialize}
6011
6012
    @sa parse(std::istream&, const parser_callback_t) for a variant with a
6013
    parser callback function to filter values while parsing
6014
6015
    @since version 1.0.0
6016
    */
6017
    friend std::istream& operator<<(basic_json& j, std::istream& i)
6018
    {
6019
        j = parser(i).parse();
6020
        return i;
6021
    }
6022
6023
    /*!
6024
    @brief deserialize from stream
6025
    @copydoc operator<<(basic_json&, std::istream&)
6026
    */
6027
    friend std::istream& operator>>(std::istream& i, basic_json& j)
6028
    {
6029
        j = parser(i).parse();
6030
        return i;
6031
    }
6032
6033
    /// @}
6034
6035
6036
  private:
6037
    ///////////////////////////
6038
    // convenience functions //
6039
    ///////////////////////////
6040
6041
    /*!
6042
    @brief return the type as string
6043
6044
    Returns the type name as string to be used in error messages - usually to
6045
    indicate that a function was called on a wrong JSON type.
6046
6047
    @return basically a string representation of a the @ref m_type member
6048
6049
    @complexity Constant.
6050
6051
    @since version 1.0.0
6052
    */
6053
    std::string type_name() const
6054
    {
6055
        switch (m_type)
6056
        {
6057
            case value_t::null:
6058
                return "null";
6059
            case value_t::object:
6060
                return "object";
6061
            case value_t::array:
6062
                return "array";
6063
            case value_t::string:
6064
                return "string";
6065
            case value_t::boolean:
6066
                return "boolean";
6067
            case value_t::discarded:
6068
                return "discarded";
6069
            default:
6070
                return "number";
6071
        }
6072
    }
6073
6074
    /*!
6075
    @brief calculates the extra space to escape a JSON string
6076
6077
    @param[in] s  the string to escape
6078
    @return the number of characters required to escape string @a s
6079
6080
    @complexity Linear in the length of string @a s.
6081
    */
6082
    static std::size_t extra_space(const string_t& s) noexcept
6083
    {
6084
        return std::accumulate(s.begin(), s.end(), size_t{},
6085
                               [](size_t res, typename string_t::value_type c)
6086
        {
6087
            switch (c)
6088
            {
6089
                case '"':
6090
                case '\\':
6091
                case '\b':
6092
                case '\f':
6093
                case '\n':
6094
                case '\r':
6095
                case '\t':
6096
                {
6097
                    // from c (1 byte) to \x (2 bytes)
6098
                    return res + 1;
6099
                }
6100
6101
                default:
6102
                {
6103
                    if (c >= 0x00 and c <= 0x1f)
6104
                    {
6105
                        // from c (1 byte) to \uxxxx (6 bytes)
6106
                        return res + 5;
6107
                    }
6108
                    else
6109
                    {
6110
                        return res;
6111
                    }
6112
                }
6113
            }
6114
        });
6115
    }
6116
6117
    /*!
6118
    @brief escape a string
6119
6120
    Escape a string by replacing certain special characters by a sequence of
6121
    an escape character (backslash) and another character and other control
6122
    characters by a sequence of "\u" followed by a four-digit hex
6123
    representation.
6124
6125
    @param[in] s  the string to escape
6126
    @return  the escaped string
6127
6128
    @complexity Linear in the length of string @a s.
6129
    */
6130
    static string_t escape_string(const string_t& s)
6131
    {
6132
        const auto space = extra_space(s);
6133
        if (space == 0)
6134
        {
6135
            return s;
6136
        }
6137
6138
        // create a result string of necessary size
6139
        string_t result(s.size() + space, '\\');
6140
        std::size_t pos = 0;
6141
6142
        for (const auto& c : s)
6143
        {
6144
            switch (c)
6145
            {
6146
                // quotation mark (0x22)
6147
                case '"':
6148
                {
6149
                    result[pos + 1] = '"';
6150
                    pos += 2;
6151
                    break;
6152
                }
6153
6154
                // reverse solidus (0x5c)
6155
                case '\\':
6156
                {
6157
                    // nothing to change
6158
                    pos += 2;
6159
                    break;
6160
                }
6161
6162
                // backspace (0x08)
6163
                case '\b':
6164
                {
6165
                    result[pos + 1] = 'b';
6166
                    pos += 2;
6167
                    break;
6168
                }
6169
6170
                // formfeed (0x0c)
6171
                case '\f':
6172
                {
6173
                    result[pos + 1] = 'f';
6174
                    pos += 2;
6175
                    break;
6176
                }
6177
6178
                // newline (0x0a)
6179
                case '\n':
6180
                {
6181
                    result[pos + 1] = 'n';
6182
                    pos += 2;
6183
                    break;
6184
                }
6185
6186
                // carriage return (0x0d)
6187
                case '\r':
6188
                {
6189
                    result[pos + 1] = 'r';
6190
                    pos += 2;
6191
                    break;
6192
                }
6193
6194
                // horizontal tab (0x09)
6195
                case '\t':
6196
                {
6197
                    result[pos + 1] = 't';
6198
                    pos += 2;
6199
                    break;
6200
                }
6201
6202
                default:
6203
                {
6204
                    if (c >= 0x00 and c <= 0x1f)
6205
                    {
6206
                        // convert a number 0..15 to its hex representation
6207
                        // (0..f)
6208
                        static const char hexify[16] =
6209
                        {
6210
                            '0', '1', '2', '3', '4', '5', '6', '7',
6211
                            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
6212
                        };
6213
6214
                        // print character c as \uxxxx
6215
                        for (const char m :
6216
                    { 'u', '0', '0', hexify[c >> 4], hexify[c & 0x0f]
6217
                        })
6218
                        {
6219
                            result[++pos] = m;
6220
                        }
6221
6222
                        ++pos;
6223
                    }
6224
                    else
6225
                    {
6226
                        // all other characters are added as-is
6227
                        result[pos++] = c;
6228
                    }
6229
                    break;
6230
                }
6231
            }
6232
        }
6233
6234
        return result;
6235
    }
6236
6237
    /*!
6238
    @brief internal implementation of the serialization function
6239
6240
    This function is called by the public member function dump and organizes
6241
    the serialization internally. The indentation level is propagated as
6242
    additional parameter. In case of arrays and objects, the function is
6243
    called recursively. Note that
6244
6245
    - strings and object keys are escaped using `escape_string()`
6246
    - integer numbers are converted implicitly via `operator<<`
6247
    - floating-point numbers are converted to a string using `"%g"` format
6248
6249
    @param[out] o              stream to write to
6250
    @param[in] pretty_print    whether the output shall be pretty-printed
6251
    @param[in] indent_step     the indent level
6252
    @param[in] current_indent  the current indent level (only used internally)
6253
    */
6254
    void dump(std::ostream& o,
6255
              const bool pretty_print,
6256
              const unsigned int indent_step,
6257
              const unsigned int current_indent = 0) const
6258
    {
6259
        // variable to hold indentation for recursive calls
6260
        unsigned int new_indent = current_indent;
6261
6262
        switch (m_type)
6263
        {
6264
            case value_t::object:
6265
            {
6266
                if (m_value.object->empty())
6267
                {
6268
                    o << "{}";
6269
                    return;
6270
                }
6271
6272
                o << "{";
6273
6274
                // increase indentation
6275
                if (pretty_print)
6276
                {
6277
                    new_indent += indent_step;
6278
                    o << "\n";
6279
                }
6280
6281
                for (auto i = m_value.object->cbegin(); i != m_value.object->cend(); ++i)
6282
                {
6283
                    if (i != m_value.object->cbegin())
6284
                    {
6285
                        o << (pretty_print ? ",\n" : ",");
6286
                    }
6287
                    o << string_t(new_indent, ' ') << "\""
6288
                      << escape_string(i->first) << "\":"
6289
                      << (pretty_print ? " " : "");
6290
                    i->second.dump(o, pretty_print, indent_step, new_indent);
6291
                }
6292
6293
                // decrease indentation
6294
                if (pretty_print)
6295
                {
6296
                    new_indent -= indent_step;
6297
                    o << "\n";
6298
                }
6299
6300
                o << string_t(new_indent, ' ') + "}";
6301
                return;
6302
            }
6303
6304
            case value_t::array:
6305
            {
6306
                if (m_value.array->empty())
6307
                {
6308
                    o << "[]";
6309
                    return;
6310
                }
6311
6312
                o << "[";
6313
6314
                // increase indentation
6315
                if (pretty_print)
6316
                {
6317
                    new_indent += indent_step;
6318
                    o << "\n";
6319
                }
6320
6321
                for (auto i = m_value.array->cbegin(); i != m_value.array->cend(); ++i)
6322
                {
6323
                    if (i != m_value.array->cbegin())
6324
                    {
6325
                        o << (pretty_print ? ",\n" : ",");
6326
                    }
6327
                    o << string_t(new_indent, ' ');
6328
                    i->dump(o, pretty_print, indent_step, new_indent);
6329
                }
6330
6331
                // decrease indentation
6332
                if (pretty_print)
6333
                {
6334
                    new_indent -= indent_step;
6335
                    o << "\n";
6336
                }
6337
6338
                o << string_t(new_indent, ' ') << "]";
6339
                return;
6340
            }
6341
6342
            case value_t::string:
6343
            {
6344
                o << string_t("\"") << escape_string(*m_value.string) << "\"";
6345
                return;
6346
            }
6347
6348
            case value_t::boolean:
6349
            {
6350
                o << (m_value.boolean ? "true" : "false");
6351
                return;
6352
            }
6353
6354
            case value_t::number_integer:
6355
            {
6356
                o << m_value.number_integer;
6357
                return;
6358
            }
6359
6360
            case value_t::number_unsigned:
6361
            {
6362
                o << m_value.number_unsigned;
6363
                return;
6364
            }
6365
6366
            case value_t::number_float:
6367
            {
6368
                if (m_value.number_float == 0)
6369
                {
6370
                    // special case for zero to get "0.0"/"-0.0"
6371
                    o << (std::signbit(m_value.number_float) ? "-0.0" : "0.0");
6372
                }
6373
                else
6374
                {
6375
                    o << m_value.number_float;
6376
                }
6377
                return;
6378
            }
6379
6380
            case value_t::discarded:
6381
            {
6382
                o << "<discarded>";
6383
                return;
6384
            }
6385
6386
            case value_t::null:
6387
            {
6388
                o << "null";
6389
                return;
6390
            }
6391
        }
6392
    }
6393
6394
  private:
6395
    //////////////////////
6396
    // member variables //
6397
    //////////////////////
6398
6399
    /// the type of the current element
6400
    value_t m_type = value_t::null;
6401
6402
    /// the value of the current element
6403
    json_value m_value = {};
6404
6405
6406
  private:
6407
    ///////////////
6408
    // iterators //
6409
    ///////////////
6410
6411
    /*!
6412
    @brief an iterator for primitive JSON types
6413
6414
    This class models an iterator for primitive JSON types (boolean, number,
6415
    string). It's only purpose is to allow the iterator/const_iterator classes
6416
    to "iterate" over primitive values. Internally, the iterator is modeled by
6417
    a `difference_type` variable. Value begin_value (`0`) models the begin,
6418
    end_value (`1`) models past the end.
6419
    */
6420
    class primitive_iterator_t
6421
    {
6422
      public:
6423
        /// set iterator to a defined beginning
6424
        void set_begin() noexcept
6425
        {
6426
            m_it = begin_value;
6427
        }
6428
6429
        /// set iterator to a defined past the end
6430
        void set_end() noexcept
6431
        {
6432
            m_it = end_value;
6433
        }
6434
6435
        /// return whether the iterator can be dereferenced
6436
        constexpr bool is_begin() const noexcept
6437
        {
6438
            return (m_it == begin_value);
6439
        }
6440
6441
        /// return whether the iterator is at end
6442
        constexpr bool is_end() const noexcept
6443
        {
6444
            return (m_it == end_value);
6445
        }
6446
6447
        /// return reference to the value to change and compare
6448
        operator difference_type& () noexcept
6449
        {
6450
            return m_it;
6451
        }
6452
6453
        /// return value to compare
6454
        constexpr operator difference_type () const noexcept
6455
        {
6456
            return m_it;
6457
        }
6458
6459
      private:
6460
        static constexpr difference_type begin_value = 0;
6461
        static constexpr difference_type end_value = begin_value + 1;
6462
6463
        /// iterator as signed integer type
6464
        difference_type m_it = std::numeric_limits<std::ptrdiff_t>::denorm_min();
6465
    };
6466
6467
    /*!
6468
    @brief an iterator value
6469
6470
    @note This structure could easily be a union, but MSVC currently does not
6471
    allow unions members with complex constructors, see
6472
    https://github.com/nlohmann/json/pull/105.
6473
    */
6474
    struct internal_iterator
6475
    {
6476
        /// iterator for JSON objects
6477
        typename object_t::iterator object_iterator;
6478
        /// iterator for JSON arrays
6479
        typename array_t::iterator array_iterator;
6480
        /// generic iterator for all other types
6481
        primitive_iterator_t primitive_iterator;
6482
6483
        /// create an uninitialized internal_iterator
6484
        internal_iterator() noexcept
6485
            : object_iterator(), array_iterator(), primitive_iterator()
6486
        {}
6487
    };
6488
6489
    /// proxy class for the iterator_wrapper functions
6490
    template<typename IteratorType>
6491
    class iteration_proxy
6492
    {
6493
      private:
6494
        /// helper class for iteration
6495
        class iteration_proxy_internal
6496
        {
6497
          private:
6498
            /// the iterator
6499
            IteratorType anchor;
6500
            /// an index for arrays (used to create key names)
6501
            size_t array_index = 0;
6502
6503
          public:
6504
            explicit iteration_proxy_internal(IteratorType it) noexcept
6505
                : anchor(it)
6506
            {}
6507
6508
            /// dereference operator (needed for range-based for)
6509
            iteration_proxy_internal& operator*()
6510
            {
6511
                return *this;
6512
            }
6513
6514
            /// increment operator (needed for range-based for)
6515
            iteration_proxy_internal& operator++()
6516
            {
6517
                ++anchor;
6518
                ++array_index;
6519
6520
                return *this;
6521
            }
6522
6523
            /// inequality operator (needed for range-based for)
6524
            bool operator!= (const iteration_proxy_internal& o) const
6525
            {
6526
                return anchor != o.anchor;
6527
            }
6528
6529
            /// return key of the iterator
6530
            typename basic_json::string_t key() const
6531
            {
6532
                assert(anchor.m_object != nullptr);
6533
6534
                switch (anchor.m_object->type())
6535
                {
6536
                    // use integer array index as key
6537
                    case value_t::array:
6538
                    {
6539
                        return std::to_string(array_index);
6540
                    }
6541
6542
                    // use key from the object
6543
                    case value_t::object:
6544
                    {
6545
                        return anchor.key();
6546
                    }
6547
6548
                    // use an empty key for all primitive types
6549
                    default:
6550
                    {
6551
                        return "";
6552
                    }
6553
                }
6554
            }
6555
6556
            /// return value of the iterator
6557
            typename IteratorType::reference value() const
6558
            {
6559
                return anchor.value();
6560
            }
6561
        };
6562
6563
        /// the container to iterate
6564
        typename IteratorType::reference container;
6565
6566
      public:
6567
        /// construct iteration proxy from a container
6568
        explicit iteration_proxy(typename IteratorType::reference cont)
6569
            : container(cont)
6570
        {}
6571
6572
        /// return iterator begin (needed for range-based for)
6573
        iteration_proxy_internal begin() noexcept
6574
        {
6575
            return iteration_proxy_internal(container.begin());
6576
        }
6577
6578
        /// return iterator end (needed for range-based for)
6579
        iteration_proxy_internal end() noexcept
6580
        {
6581
            return iteration_proxy_internal(container.end());
6582
        }
6583
    };
6584
6585
  public:
6586
    /*!
6587
    @brief a const random access iterator for the @ref basic_json class
6588
6589
    This class implements a const iterator for the @ref basic_json class. From
6590
    this class, the @ref iterator class is derived.
6591
6592
    @note An iterator is called *initialized* when a pointer to a JSON value
6593
          has been set (e.g., by a constructor or a copy assignment). If the
6594
          iterator is default-constructed, it is *uninitialized* and most
6595
          methods are undefined. The library uses assertions to detect calls
6596
          on uninitialized iterators.
6597
6598
    @requirement The class satisfies the following concept requirements:
6599
    - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
6600
      The iterator that can be moved to point (forward and backward) to any
6601
      element in constant time.
6602
6603
    @since version 1.0.0
6604
    */
6605
    class const_iterator : public std::iterator<std::random_access_iterator_tag, const basic_json>
6606
    {
6607
        /// allow basic_json to access private members
6608
        friend class basic_json;
6609
6610
      public:
6611
        /// the type of the values when the iterator is dereferenced
6612
        using value_type = typename basic_json::value_type;
6613
        /// a type to represent differences between iterators
6614
        using difference_type = typename basic_json::difference_type;
6615
        /// defines a pointer to the type iterated over (value_type)
6616
        using pointer = typename basic_json::const_pointer;
6617
        /// defines a reference to the type iterated over (value_type)
6618
        using reference = typename basic_json::const_reference;
6619
        /// the category of the iterator
6620
        using iterator_category = std::bidirectional_iterator_tag;
6621
6622
        /// default constructor
6623
        const_iterator() = default;
6624
6625
        /*!
6626
        @brief constructor for a given JSON instance
6627
        @param[in] object  pointer to a JSON object for this iterator
6628
        @pre object != nullptr
6629
        @post The iterator is initialized; i.e. `m_object != nullptr`.
6630
        */
6631
        explicit const_iterator(pointer object) noexcept
6632
            : m_object(object)
6633
        {
6634
            assert(m_object != nullptr);
6635
6636
            switch (m_object->m_type)
6637
            {
6638
                case basic_json::value_t::object:
6639
                {
6640
                    m_it.object_iterator = typename object_t::iterator();
6641
                    break;
6642
                }
6643
6644
                case basic_json::value_t::array:
6645
                {
6646
                    m_it.array_iterator = typename array_t::iterator();
6647
                    break;
6648
                }
6649
6650
                default:
6651
                {
6652
                    m_it.primitive_iterator = primitive_iterator_t();
6653
                    break;
6654
                }
6655
            }
6656
        }
6657
6658
        /*!
6659
        @brief copy constructor given a non-const iterator
6660
        @param[in] other  iterator to copy from
6661
        @note It is not checked whether @a other is initialized.
6662
        */
6663
        explicit const_iterator(const iterator& other) noexcept
6664
            : m_object(other.m_object)
6665
        {
6666
            if (m_object != nullptr)
6667
            {
6668
                switch (m_object->m_type)
6669
                {
6670
                    case basic_json::value_t::object:
6671
                    {
6672
                        m_it.object_iterator = other.m_it.object_iterator;
6673
                        break;
6674
                    }
6675
6676
                    case basic_json::value_t::array:
6677
                    {
6678
                        m_it.array_iterator = other.m_it.array_iterator;
6679
                        break;
6680
                    }
6681
6682
                    default:
6683
                    {
6684
                        m_it.primitive_iterator = other.m_it.primitive_iterator;
6685
                        break;
6686
                    }
6687
                }
6688
            }
6689
        }
6690
6691
        /*!
6692
        @brief copy constructor
6693
        @param[in] other  iterator to copy from
6694
        @note It is not checked whether @a other is initialized.
6695
        */
6696
        const_iterator(const const_iterator& other) noexcept
6697
            : m_object(other.m_object), m_it(other.m_it)
6698
        {}
6699
6700
        /*!
6701
        @brief copy assignment
6702
        @param[in,out] other  iterator to copy from
6703
        @note It is not checked whether @a other is initialized.
6704
        */
6705
        const_iterator& operator=(const_iterator other) noexcept(
6706
            std::is_nothrow_move_constructible<pointer>::value and
6707
            std::is_nothrow_move_assignable<pointer>::value and
6708
            std::is_nothrow_move_constructible<internal_iterator>::value and
6709
            std::is_nothrow_move_assignable<internal_iterator>::value
6710
        )
6711
        {
6712
            std::swap(m_object, other.m_object);
6713
            std::swap(m_it, other.m_it);
6714
            return *this;
6715
        }
6716
6717
      private:
6718
        /*!
6719
        @brief set the iterator to the first value
6720
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
6721
        */
6722
        void set_begin() noexcept
6723
        {
6724
            assert(m_object != nullptr);
6725
6726
            switch (m_object->m_type)
6727
            {
6728
                case basic_json::value_t::object:
6729
                {
6730
                    m_it.object_iterator = m_object->m_value.object->begin();
6731
                    break;
6732
                }
6733
6734
                case basic_json::value_t::array:
6735
                {
6736
                    m_it.array_iterator = m_object->m_value.array->begin();
6737
                    break;
6738
                }
6739
6740
                case basic_json::value_t::null:
6741
                {
6742
                    // set to end so begin()==end() is true: null is empty
6743
                    m_it.primitive_iterator.set_end();
6744
                    break;
6745
                }
6746
6747
                default:
6748
                {
6749
                    m_it.primitive_iterator.set_begin();
6750
                    break;
6751
                }
6752
            }
6753
        }
6754
6755
        /*!
6756
        @brief set the iterator past the last value
6757
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
6758
        */
6759
        void set_end() noexcept
6760
        {
6761
            assert(m_object != nullptr);
6762
6763
            switch (m_object->m_type)
6764
            {
6765
                case basic_json::value_t::object:
6766
                {
6767
                    m_it.object_iterator = m_object->m_value.object->end();
6768
                    break;
6769
                }
6770
6771
                case basic_json::value_t::array:
6772
                {
6773
                    m_it.array_iterator = m_object->m_value.array->end();
6774
                    break;
6775
                }
6776
6777
                default:
6778
                {
6779
                    m_it.primitive_iterator.set_end();
6780
                    break;
6781
                }
6782
            }
6783
        }
6784
6785
      public:
6786
        /*!
6787
        @brief return a reference to the value pointed to by the iterator
6788
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
6789
        */
6790
        reference operator*() const
6791
        {
6792
            assert(m_object != nullptr);
6793
6794
            switch (m_object->m_type)
6795
            {
6796
                case basic_json::value_t::object:
6797
                {
6798
                    assert(m_it.object_iterator != m_object->m_value.object->end());
6799
                    return m_it.object_iterator->second;
6800
                }
6801
6802
                case basic_json::value_t::array:
6803
                {
6804
                    assert(m_it.array_iterator != m_object->m_value.array->end());
6805
                    return *m_it.array_iterator;
6806
                }
6807
6808
                case basic_json::value_t::null:
6809
                {
6810
                    throw std::out_of_range("cannot get value");
6811
                }
6812
6813
                default:
6814
                {
6815
                    if (m_it.primitive_iterator.is_begin())
6816
                    {
6817
                        return *m_object;
6818
                    }
6819
                    else
6820
                    {
6821
                        throw std::out_of_range("cannot get value");
6822
                    }
6823
                }
6824
            }
6825
        }
6826
6827
        /*!
6828
        @brief dereference the iterator
6829
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
6830
        */
6831
        pointer operator->() const
6832
        {
6833
            assert(m_object != nullptr);
6834
6835
            switch (m_object->m_type)
6836
            {
6837
                case basic_json::value_t::object:
6838
                {
6839
                    assert(m_it.object_iterator != m_object->m_value.object->end());
6840
                    return &(m_it.object_iterator->second);
6841
                }
6842
6843
                case basic_json::value_t::array:
6844
                {
6845
                    assert(m_it.array_iterator != m_object->m_value.array->end());
6846
                    return &*m_it.array_iterator;
6847
                }
6848
6849
                default:
6850
                {
6851
                    if (m_it.primitive_iterator.is_begin())
6852
                    {
6853
                        return m_object;
6854
                    }
6855
                    else
6856
                    {
6857
                        throw std::out_of_range("cannot get value");
6858
                    }
6859
                }
6860
            }
6861
        }
6862
6863
        /*!
6864
        @brief post-increment (it++)
6865
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
6866
        */
6867
        const_iterator operator++(int)
6868
        {
6869
            auto result = *this;
6870
            ++(*this);
6871
            return result;
6872
        }
6873
6874
        /*!
6875
        @brief pre-increment (++it)
6876
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
6877
        */
6878
        const_iterator& operator++()
6879
        {
6880
            assert(m_object != nullptr);
6881
6882
            switch (m_object->m_type)
6883
            {
6884
                case basic_json::value_t::object:
6885
                {
6886
                    std::advance(m_it.object_iterator, 1);
6887
                    break;
6888
                }
6889
6890
                case basic_json::value_t::array:
6891
                {
6892
                    std::advance(m_it.array_iterator, 1);
6893
                    break;
6894
                }
6895
6896
                default:
6897
                {
6898
                    ++m_it.primitive_iterator;
6899
                    break;
6900
                }
6901
            }
6902
6903
            return *this;
6904
        }
6905
6906
        /*!
6907
        @brief post-decrement (it--)
6908
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
6909
        */
6910
        const_iterator operator--(int)
6911
        {
6912
            auto result = *this;
6913
            --(*this);
6914
            return result;
6915
        }
6916
6917
        /*!
6918
        @brief pre-decrement (--it)
6919
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
6920
        */
6921
        const_iterator& operator--()
6922
        {
6923
            assert(m_object != nullptr);
6924
6925
            switch (m_object->m_type)
6926
            {
6927
                case basic_json::value_t::object:
6928
                {
6929
                    std::advance(m_it.object_iterator, -1);
6930
                    break;
6931
                }
6932
6933
                case basic_json::value_t::array:
6934
                {
6935
                    std::advance(m_it.array_iterator, -1);
6936
                    break;
6937
                }
6938
6939
                default:
6940
                {
6941
                    --m_it.primitive_iterator;
6942
                    break;
6943
                }
6944
            }
6945
6946
            return *this;
6947
        }
6948
6949
        /*!
6950
        @brief  comparison: equal
6951
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
6952
        */
6953
        bool operator==(const const_iterator& other) const
6954
        {
6955
            // if objects are not the same, the comparison is undefined
6956
            if (m_object != other.m_object)
6957
            {
6958
                throw std::domain_error("cannot compare iterators of different containers");
6959
            }
6960
6961
            assert(m_object != nullptr);
6962
6963
            switch (m_object->m_type)
6964
            {
6965
                case basic_json::value_t::object:
6966
                {
6967
                    return (m_it.object_iterator == other.m_it.object_iterator);
6968
                }
6969
6970
                case basic_json::value_t::array:
6971
                {
6972
                    return (m_it.array_iterator == other.m_it.array_iterator);
6973
                }
6974
6975
                default:
6976
                {
6977
                    return (m_it.primitive_iterator == other.m_it.primitive_iterator);
6978
                }
6979
            }
6980
        }
6981
6982
        /*!
6983
        @brief  comparison: not equal
6984
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
6985
        */
6986
        bool operator!=(const const_iterator& other) const
6987
        {
6988
            return not operator==(other);
6989
        }
6990
6991
        /*!
6992
        @brief  comparison: smaller
6993
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
6994
        */
6995
        bool operator<(const const_iterator& other) const
6996
        {
6997
            // if objects are not the same, the comparison is undefined
6998
            if (m_object != other.m_object)
6999
            {
7000
                throw std::domain_error("cannot compare iterators of different containers");
7001
            }
7002
7003
            assert(m_object != nullptr);
7004
7005
            switch (m_object->m_type)
7006
            {
7007
                case basic_json::value_t::object:
7008
                {
7009
                    throw std::domain_error("cannot compare order of object iterators");
7010
                }
7011
7012
                case basic_json::value_t::array:
7013
                {
7014
                    return (m_it.array_iterator < other.m_it.array_iterator);
7015
                }
7016
7017
                default:
7018
                {
7019
                    return (m_it.primitive_iterator < other.m_it.primitive_iterator);
7020
                }
7021
            }
7022
        }
7023
7024
        /*!
7025
        @brief  comparison: less than or equal
7026
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
7027
        */
7028
        bool operator<=(const const_iterator& other) const
7029
        {
7030
            return not other.operator < (*this);
7031
        }
7032
7033
        /*!
7034
        @brief  comparison: greater than
7035
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
7036
        */
7037
        bool operator>(const const_iterator& other) const
7038
        {
7039
            return not operator<=(other);
7040
        }
7041
7042
        /*!
7043
        @brief  comparison: greater than or equal
7044
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
7045
        */
7046
        bool operator>=(const const_iterator& other) const
7047
        {
7048
            return not operator<(other);
7049
        }
7050
7051
        /*!
7052
        @brief  add to iterator
7053
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
7054
        */
7055
        const_iterator& operator+=(difference_type i)
7056
        {
7057
            assert(m_object != nullptr);
7058
7059
            switch (m_object->m_type)
7060
            {
7061
                case basic_json::value_t::object:
7062
                {
7063
                    throw std::domain_error("cannot use offsets with object iterators");
7064
                }
7065
7066
                case basic_json::value_t::array:
7067
                {
7068
                    std::advance(m_it.array_iterator, i);
7069
                    break;
7070
                }
7071
7072
                default:
7073
                {
7074
                    m_it.primitive_iterator += i;
7075
                    break;
7076
                }
7077
            }
7078
7079
            return *this;
7080
        }
7081
7082
        /*!
7083
        @brief  subtract from iterator
7084
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
7085
        */
7086
        const_iterator& operator-=(difference_type i)
7087
        {
7088
            return operator+=(-i);
7089
        }
7090
7091
        /*!
7092
        @brief  add to iterator
7093
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
7094
        */
7095
        const_iterator operator+(difference_type i)
7096
        {
7097
            auto result = *this;
7098
            result += i;
7099
            return result;
7100
        }
7101
7102
        /*!
7103
        @brief  subtract from iterator
7104
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
7105
        */
7106
        const_iterator operator-(difference_type i)
7107
        {
7108
            auto result = *this;
7109
            result -= i;
7110
            return result;
7111
        }
7112
7113
        /*!
7114
        @brief  return difference
7115
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
7116
        */
7117
        difference_type operator-(const const_iterator& other) const
7118
        {
7119
            assert(m_object != nullptr);
7120
7121
            switch (m_object->m_type)
7122
            {
7123
                case basic_json::value_t::object:
7124
                {
7125
                    throw std::domain_error("cannot use offsets with object iterators");
7126
                }
7127
7128
                case basic_json::value_t::array:
7129
                {
7130
                    return m_it.array_iterator - other.m_it.array_iterator;
7131
                }
7132
7133
                default:
7134
                {
7135
                    return m_it.primitive_iterator - other.m_it.primitive_iterator;
7136
                }
7137
            }
7138
        }
7139
7140
        /*!
7141
        @brief  access to successor
7142
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
7143
        */
7144
        reference operator[](difference_type n) const
7145
        {
7146
            assert(m_object != nullptr);
7147
7148
            switch (m_object->m_type)
7149
            {
7150
                case basic_json::value_t::object:
7151
                {
7152
                    throw std::domain_error("cannot use operator[] for object iterators");
7153
                }
7154
7155
                case basic_json::value_t::array:
7156
                {
7157
                    return *std::next(m_it.array_iterator, n);
7158
                }
7159
7160
                case basic_json::value_t::null:
7161
                {
7162
                    throw std::out_of_range("cannot get value");
7163
                }
7164
7165
                default:
7166
                {
7167
                    if (m_it.primitive_iterator == -n)
7168
                    {
7169
                        return *m_object;
7170
                    }
7171
                    else
7172
                    {
7173
                        throw std::out_of_range("cannot get value");
7174
                    }
7175
                }
7176
            }
7177
        }
7178
7179
        /*!
7180
        @brief  return the key of an object iterator
7181
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
7182
        */
7183
        typename object_t::key_type key() const
7184
        {
7185
            assert(m_object != nullptr);
7186
7187
            if (m_object->is_object())
7188
            {
7189
                return m_it.object_iterator->first;
7190
            }
7191
            else
7192
            {
7193
                throw std::domain_error("cannot use key() for non-object iterators");
7194
            }
7195
        }
7196
7197
        /*!
7198
        @brief  return the value of an iterator
7199
        @pre The iterator is initialized; i.e. `m_object != nullptr`.
7200
        */
7201
        reference value() const
7202
        {
7203
            return operator*();
7204
        }
7205
7206
      private:
7207
        /// associated JSON instance
7208
        pointer m_object = nullptr;
7209
        /// the actual iterator of the associated instance
7210
        internal_iterator m_it = internal_iterator();
7211
    };
7212
7213
    /*!
7214
    @brief a mutable random access iterator for the @ref basic_json class
7215
7216
    @requirement The class satisfies the following concept requirements:
7217
    - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
7218
      The iterator that can be moved to point (forward and backward) to any
7219
      element in constant time.
7220
    - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
7221
      It is possible to write to the pointed-to element.
7222
7223
    @since version 1.0.0
7224
    */
7225
    class iterator : public const_iterator
7226
    {
7227
      public:
7228
        using base_iterator = const_iterator;
7229
        using pointer = typename basic_json::pointer;
7230
        using reference = typename basic_json::reference;
7231
7232
        /// default constructor
7233
        iterator() = default;
7234
7235
        /// constructor for a given JSON instance
7236
        explicit iterator(pointer object) noexcept
7237
            : base_iterator(object)
7238
        {}
7239
7240
        /// copy constructor
7241
        iterator(const iterator& other) noexcept
7242
            : base_iterator(other)
7243
        {}
7244
7245
        /// copy assignment
7246
        iterator& operator=(iterator other) noexcept(
7247
            std::is_nothrow_move_constructible<pointer>::value and
7248
            std::is_nothrow_move_assignable<pointer>::value and
7249
            std::is_nothrow_move_constructible<internal_iterator>::value and
7250
            std::is_nothrow_move_assignable<internal_iterator>::value
7251
        )
7252
        {
7253
            base_iterator::operator=(other);
7254
            return *this;
7255
        }
7256
7257
        /// return a reference to the value pointed to by the iterator
7258
        reference operator*() const
7259
        {
7260
            return const_cast<reference>(base_iterator::operator*());
7261
        }
7262
7263
        /// dereference the iterator
7264
        pointer operator->() const
7265
        {
7266
            return const_cast<pointer>(base_iterator::operator->());
7267
        }
7268
7269
        /// post-increment (it++)
7270
        iterator operator++(int)
7271
        {
7272
            iterator result = *this;
7273
            base_iterator::operator++();
7274
            return result;
7275
        }
7276
7277
        /// pre-increment (++it)
7278
        iterator& operator++()
7279
        {
7280
            base_iterator::operator++();
7281
            return *this;
7282
        }
7283
7284
        /// post-decrement (it--)
7285
        iterator operator--(int)
7286
        {
7287
            iterator result = *this;
7288
            base_iterator::operator--();
7289
            return result;
7290
        }
7291
7292
        /// pre-decrement (--it)
7293
        iterator& operator--()
7294
        {
7295
            base_iterator::operator--();
7296
            return *this;
7297
        }
7298
7299
        /// add to iterator
7300
        iterator& operator+=(difference_type i)
7301
        {
7302
            base_iterator::operator+=(i);
7303
            return *this;
7304
        }
7305
7306
        /// subtract from iterator
7307
        iterator& operator-=(difference_type i)
7308
        {
7309
            base_iterator::operator-=(i);
7310
            return *this;
7311
        }
7312
7313
        /// add to iterator
7314
        iterator operator+(difference_type i)
7315
        {
7316
            auto result = *this;
7317
            result += i;
7318
            return result;
7319
        }
7320
7321
        /// subtract from iterator
7322
        iterator operator-(difference_type i)
7323
        {
7324
            auto result = *this;
7325
            result -= i;
7326
            return result;
7327
        }
7328
7329
        /// return difference
7330
        difference_type operator-(const iterator& other) const
7331
        {
7332
            return base_iterator::operator-(other);
7333
        }
7334
7335
        /// access to successor
7336
        reference operator[](difference_type n) const
7337
        {
7338
            return const_cast<reference>(base_iterator::operator[](n));
7339
        }
7340
7341
        /// return the value of an iterator
7342
        reference value() const
7343
        {
7344
            return const_cast<reference>(base_iterator::value());
7345
        }
7346
    };
7347
7348
    /*!
7349
    @brief a template for a reverse iterator class
7350
7351
    @tparam Base the base iterator type to reverse. Valid types are @ref
7352
    iterator (to create @ref reverse_iterator) and @ref const_iterator (to
7353
    create @ref const_reverse_iterator).
7354
7355
    @requirement The class satisfies the following concept requirements:
7356
    - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
7357
      The iterator that can be moved to point (forward and backward) to any
7358
      element in constant time.
7359
    - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
7360
      It is possible to write to the pointed-to element (only if @a Base is
7361
      @ref iterator).
7362
7363
    @since version 1.0.0
7364
    */
7365
    template<typename Base>
7366
    class json_reverse_iterator : public std::reverse_iterator<Base>
7367
    {
7368
      public:
7369
        /// shortcut to the reverse iterator adaptor
7370
        using base_iterator = std::reverse_iterator<Base>;
7371
        /// the reference type for the pointed-to element
7372
        using reference = typename Base::reference;
7373
7374
        /// create reverse iterator from iterator
7375
        json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
7376
            : base_iterator(it)
7377
        {}
7378
7379
        /// create reverse iterator from base class
7380
        json_reverse_iterator(const base_iterator& it) noexcept
7381
            : base_iterator(it)
7382
        {}
7383
7384
        /// post-increment (it++)
7385
        json_reverse_iterator operator++(int)
7386
        {
7387
            return base_iterator::operator++(1);
7388
        }
7389
7390
        /// pre-increment (++it)
7391
        json_reverse_iterator& operator++()
7392
        {
7393
            base_iterator::operator++();
7394
            return *this;
7395
        }
7396
7397
        /// post-decrement (it--)
7398
        json_reverse_iterator operator--(int)
7399
        {
7400
            return base_iterator::operator--(1);
7401
        }
7402
7403
        /// pre-decrement (--it)
7404
        json_reverse_iterator& operator--()
7405
        {
7406
            base_iterator::operator--();
7407
            return *this;
7408
        }
7409
7410
        /// add to iterator
7411
        json_reverse_iterator& operator+=(difference_type i)
7412
        {
7413
            base_iterator::operator+=(i);
7414
            return *this;
7415
        }
7416
7417
        /// add to iterator
7418
        json_reverse_iterator operator+(difference_type i) const
7419
        {
7420
            auto result = *this;
7421
            result += i;
7422
            return result;
7423
        }
7424
7425
        /// subtract from iterator
7426
        json_reverse_iterator operator-(difference_type i) const
7427
        {
7428
            auto result = *this;
7429
            result -= i;
7430
            return result;
7431
        }
7432
7433
        /// return difference
7434
        difference_type operator-(const json_reverse_iterator& other) const
7435
        {
7436
            return this->base() - other.base();
7437
        }
7438
7439
        /// access to successor
7440
        reference operator[](difference_type n) const
7441
        {
7442
            return *(this->operator+(n));
7443
        }
7444
7445
        /// return the key of an object iterator
7446
        typename object_t::key_type key() const
7447
        {
7448
            auto it = --this->base();
7449
            return it.key();
7450
        }
7451
7452
        /// return the value of an iterator
7453
        reference value() const
7454
        {
7455
            auto it = --this->base();
7456
            return it.operator * ();
7457
        }
7458
    };
7459
7460
7461
  private:
7462
    //////////////////////
7463
    // lexer and parser //
7464
    //////////////////////
7465
7466
    /*!
7467
    @brief lexical analysis
7468
7469
    This class organizes the lexical analysis during JSON deserialization. The
7470
    core of it is a scanner generated by [re2c](http://re2c.org) that
7471
    processes a buffer and recognizes tokens according to RFC 7159.
7472
    */
7473
    class lexer
7474
    {
7475
      public:
7476
        /// token types for the parser
7477
        enum class token_type
7478
        {
7479
            uninitialized,   ///< indicating the scanner is uninitialized
7480
            literal_true,    ///< the `true` literal
7481
            literal_false,   ///< the `false` literal
7482
            literal_null,    ///< the `null` literal
7483
            value_string,    ///< a string -- use get_string() for actual value
7484
            value_number,    ///< a number -- use get_number() for actual value
7485
            begin_array,     ///< the character for array begin `[`
7486
            begin_object,    ///< the character for object begin `{`
7487
            end_array,       ///< the character for array end `]`
7488
            end_object,      ///< the character for object end `}`
7489
            name_separator,  ///< the name separator `:`
7490
            value_separator, ///< the value separator `,`
7491
            parse_error,     ///< indicating a parse error
7492
            end_of_input     ///< indicating the end of the input buffer
7493
        };
7494
7495
        /// the char type to use in the lexer
7496
        using lexer_char_t = unsigned char;
7497
7498
        /// constructor with a given buffer
7499
        explicit lexer(const string_t& s) noexcept
7500
            : m_stream(nullptr), m_buffer(s)
7501
        {
7502
            m_content = reinterpret_cast<const lexer_char_t*>(m_buffer.c_str());
7503
            assert(m_content != nullptr);
7504
            m_start = m_cursor = m_content;
7505
            m_limit = m_content + s.size();
7506
        }
7507
7508
        /// constructor with a given stream
7509
        explicit lexer(std::istream* s) noexcept
7510
            : m_stream(s), m_buffer()
7511
        {
7512
            assert(m_stream != nullptr);
7513
            std::getline(*m_stream, m_buffer);
7514
            m_content = reinterpret_cast<const lexer_char_t*>(m_buffer.c_str());
7515
            assert(m_content != nullptr);
7516
            m_start = m_cursor = m_content;
7517
            m_limit = m_content + m_buffer.size();
7518
        }
7519
7520
        /// default constructor
7521
        lexer() = default;
7522
7523
        // switch off unwanted functions
7524
        lexer(const lexer&) = delete;
7525
        lexer operator=(const lexer&) = delete;
7526
7527
        /*!
7528
        @brief create a string from one or two Unicode code points
7529
7530
        There are two cases: (1) @a codepoint1 is in the Basic Multilingual
7531
        Plane (U+0000 through U+FFFF) and @a codepoint2 is 0, or (2)
7532
        @a codepoint1 and @a codepoint2 are a UTF-16 surrogate pair to
7533
        represent a code point above U+FFFF.
7534
7535
        @param[in] codepoint1  the code point (can be high surrogate)
7536
        @param[in] codepoint2  the code point (can be low surrogate or 0)
7537
7538
        @return string representation of the code point; the length of the
7539
        result string is between 1 and 4 characters.
7540
7541
        @throw std::out_of_range if code point is > 0x10ffff; example: `"code
7542
        points above 0x10FFFF are invalid"`
7543
        @throw std::invalid_argument if the low surrogate is invalid; example:
7544
        `""missing or wrong low surrogate""`
7545
7546
        @complexity Constant.
7547
7548
        @see <http://en.wikipedia.org/wiki/UTF-8#Sample_code>
7549
        */
7550
        static string_t to_unicode(const std::size_t codepoint1,
7551
                                   const std::size_t codepoint2 = 0)
7552
        {
7553
            // calculate the code point from the given code points
7554
            std::size_t codepoint = codepoint1;
7555
7556
            // check if codepoint1 is a high surrogate
7557
            if (codepoint1 >= 0xD800 and codepoint1 <= 0xDBFF)
7558
            {
7559
                // check if codepoint2 is a low surrogate
7560
                if (codepoint2 >= 0xDC00 and codepoint2 <= 0xDFFF)
7561
                {
7562
                    codepoint =
7563
                        // high surrogate occupies the most significant 22 bits
7564
                        (codepoint1 << 10)
7565
                        // low surrogate occupies the least significant 15 bits
7566
                        + codepoint2
7567
                        // there is still the 0xD800, 0xDC00 and 0x10000 noise
7568
                        // in the result so we have to subtract with:
7569
                        // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
7570
                        - 0x35FDC00;
7571
                }
7572
                else
7573
                {
7574
                    throw std::invalid_argument("missing or wrong low surrogate");
7575
                }
7576
            }
7577
7578
            string_t result;
7579
7580
            if (codepoint < 0x80)
7581
            {
7582
                // 1-byte characters: 0xxxxxxx (ASCII)
7583
                result.append(1, static_cast<typename string_t::value_type>(codepoint));
7584
            }
7585
            else if (codepoint <= 0x7ff)
7586
            {
7587
                // 2-byte characters: 110xxxxx 10xxxxxx
7588
                result.append(1, static_cast<typename string_t::value_type>(0xC0 | ((codepoint >> 6) & 0x1F)));
7589
                result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
7590
            }
7591
            else if (codepoint <= 0xffff)
7592
            {
7593
                // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
7594
                result.append(1, static_cast<typename string_t::value_type>(0xE0 | ((codepoint >> 12) & 0x0F)));
7595
                result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
7596
                result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
7597
            }
7598
            else if (codepoint <= 0x10ffff)
7599
            {
7600
                // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
7601
                result.append(1, static_cast<typename string_t::value_type>(0xF0 | ((codepoint >> 18) & 0x07)));
7602
                result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 12) & 0x3F)));
7603
                result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
7604
                result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
7605
            }
7606
            else
7607
            {
7608
                throw std::out_of_range("code points above 0x10FFFF are invalid");
7609
            }
7610
7611
            return result;
7612
        }
7613
7614
        /// return name of values of type token_type (only used for errors)
7615
        static std::string token_type_name(const token_type t)
7616
        {
7617
            switch (t)
7618
            {
7619
                case token_type::uninitialized:
7620
                    return "<uninitialized>";
7621
                case token_type::literal_true:
7622
                    return "true literal";
7623
                case token_type::literal_false:
7624
                    return "false literal";
7625
                case token_type::literal_null:
7626
                    return "null literal";
7627
                case token_type::value_string:
7628
                    return "string literal";
7629
                case token_type::value_number:
7630
                    return "number literal";
7631
                case token_type::begin_array:
7632
                    return "'['";
7633
                case token_type::begin_object:
7634
                    return "'{'";
7635
                case token_type::end_array:
7636
                    return "']'";
7637
                case token_type::end_object:
7638
                    return "'}'";
7639
                case token_type::name_separator:
7640
                    return "':'";
7641
                case token_type::value_separator:
7642
                    return "','";
7643
                case token_type::parse_error:
7644
                    return "<parse error>";
7645
                case token_type::end_of_input:
7646
                    return "end of input";
7647
                default:
7648
                {
7649
                    // catch non-enum values
7650
                    return "unknown token"; // LCOV_EXCL_LINE
7651
                }
7652
            }
7653
        }
7654
7655
        /*!
7656
        This function implements a scanner for JSON. It is specified using
7657
        regular expressions that try to follow RFC 7159 as close as possible.
7658
        These regular expressions are then translated into a minimized
7659
        deterministic finite automaton (DFA) by the tool
7660
        [re2c](http://re2c.org). As a result, the translated code for this
7661
        function consists of a large block of code with `goto` jumps.
7662
7663
        @return the class of the next token read from the buffer
7664
7665
        @complexity Linear in the length of the input.\n
7666
7667
        Proposition: The loop below will always terminate for finite input.\n
7668
7669
        Proof (by contradiction): Assume a finite input. To loop forever, the
7670
        loop must never hit code with a `break` statement. The only code
7671
        snippets without a `break` statement are the continue statements for
7672
        whitespace and byte-order-marks. To loop forever, the input must be an
7673
        infinite sequence of whitespace or byte-order-marks. This contradicts
7674
        the assumption of finite input, q.e.d.
7675
        */
7676
        token_type scan() noexcept
7677
        {
7678
            while (true)
7679
            {
7680
                // pointer for backtracking information
7681
                m_marker = nullptr;
7682
7683
                // remember the begin of the token
7684
                m_start = m_cursor;
7685
                assert(m_start != nullptr);
7686
7687
7688
                {
7689
                    lexer_char_t yych;
7690
                    unsigned int yyaccept = 0;
7691
                    static const unsigned char yybm[] =
7692
                    {
7693
                        0,   0,   0,   0,   0,   0,   0,   0,
7694
                        0,  32,  32,   0,   0,  32,   0,   0,
7695
                        0,   0,   0,   0,   0,   0,   0,   0,
7696
                        0,   0,   0,   0,   0,   0,   0,   0,
7697
                        160, 128,   0, 128, 128, 128, 128, 128,
7698
                        128, 128, 128, 128, 128, 128, 128, 128,
7699
                        192, 192, 192, 192, 192, 192, 192, 192,
7700
                        192, 192, 128, 128, 128, 128, 128, 128,
7701
                        128, 128, 128, 128, 128, 128, 128, 128,
7702
                        128, 128, 128, 128, 128, 128, 128, 128,
7703
                        128, 128, 128, 128, 128, 128, 128, 128,
7704
                        128, 128, 128, 128,   0, 128, 128, 128,
7705
                        128, 128, 128, 128, 128, 128, 128, 128,
7706
                        128, 128, 128, 128, 128, 128, 128, 128,
7707
                        128, 128, 128, 128, 128, 128, 128, 128,
7708
                        128, 128, 128, 128, 128, 128, 128, 128,
7709
                        128, 128, 128, 128, 128, 128, 128, 128,
7710
                        128, 128, 128, 128, 128, 128, 128, 128,
7711
                        128, 128, 128, 128, 128, 128, 128, 128,
7712
                        128, 128, 128, 128, 128, 128, 128, 128,
7713
                        128, 128, 128, 128, 128, 128, 128, 128,
7714
                        128, 128, 128, 128, 128, 128, 128, 128,
7715
                        128, 128, 128, 128, 128, 128, 128, 128,
7716
                        128, 128, 128, 128, 128, 128, 128, 128,
7717
                        128, 128, 128, 128, 128, 128, 128, 128,
7718
                        128, 128, 128, 128, 128, 128, 128, 128,
7719
                        128, 128, 128, 128, 128, 128, 128, 128,
7720
                        128, 128, 128, 128, 128, 128, 128, 128,
7721
                        128, 128, 128, 128, 128, 128, 128, 128,
7722
                        128, 128, 128, 128, 128, 128, 128, 128,
7723
                        128, 128, 128, 128, 128, 128, 128, 128,
7724
                        128, 128, 128, 128, 128, 128, 128, 128,
7725
                    };
7726
                    if ((m_limit - m_cursor) < 5)
7727
                    {
7728
                        yyfill();    // LCOV_EXCL_LINE;
7729
                    }
7730
                    yych = *m_cursor;
7731
                    if (yybm[0 + yych] & 32)
7732
                    {
7733
                        goto basic_json_parser_6;
7734
                    }
7735
                    if (yych <= '\\')
7736
                    {
7737
                        if (yych <= '-')
7738
                        {
7739
                            if (yych <= '"')
7740
                            {
7741
                                if (yych <= 0x00)
7742
                                {
7743
                                    goto basic_json_parser_2;
7744
                                }
7745
                                if (yych <= '!')
7746
                                {
7747
                                    goto basic_json_parser_4;
7748
                                }
7749
                                goto basic_json_parser_9;
7750
                            }
7751
                            else
7752
                            {
7753
                                if (yych <= '+')
7754
                                {
7755
                                    goto basic_json_parser_4;
7756
                                }
7757
                                if (yych <= ',')
7758
                                {
7759
                                    goto basic_json_parser_10;
7760
                                }
7761
                                goto basic_json_parser_12;
7762
                            }
7763
                        }
7764
                        else
7765
                        {
7766
                            if (yych <= '9')
7767
                            {
7768
                                if (yych <= '/')
7769
                                {
7770
                                    goto basic_json_parser_4;
7771
                                }
7772
                                if (yych <= '0')
7773
                                {
7774
                                    goto basic_json_parser_13;
7775
                                }
7776
                                goto basic_json_parser_15;
7777
                            }
7778
                            else
7779
                            {
7780
                                if (yych <= ':')
7781
                                {
7782
                                    goto basic_json_parser_17;
7783
                                }
7784
                                if (yych == '[')
7785
                                {
7786
                                    goto basic_json_parser_19;
7787
                                }
7788
                                goto basic_json_parser_4;
7789
                            }
7790
                        }
7791
                    }
7792
                    else
7793
                    {
7794
                        if (yych <= 't')
7795
                        {
7796
                            if (yych <= 'f')
7797
                            {
7798
                                if (yych <= ']')
7799
                                {
7800
                                    goto basic_json_parser_21;
7801
                                }
7802
                                if (yych <= 'e')
7803
                                {
7804
                                    goto basic_json_parser_4;
7805
                                }
7806
                                goto basic_json_parser_23;
7807
                            }
7808
                            else
7809
                            {
7810
                                if (yych == 'n')
7811
                                {
7812
                                    goto basic_json_parser_24;
7813
                                }
7814
                                if (yych <= 's')
7815
                                {
7816
                                    goto basic_json_parser_4;
7817
                                }
7818
                                goto basic_json_parser_25;
7819
                            }
7820
                        }
7821
                        else
7822
                        {
7823
                            if (yych <= '|')
7824
                            {
7825
                                if (yych == '{')
7826
                                {
7827
                                    goto basic_json_parser_26;
7828
                                }
7829
                                goto basic_json_parser_4;
7830
                            }
7831
                            else
7832
                            {
7833
                                if (yych <= '}')
7834
                                {
7835
                                    goto basic_json_parser_28;
7836
                                }
7837
                                if (yych == 0xEF)
7838
                                {
7839
                                    goto basic_json_parser_30;
7840
                                }
7841
                                goto basic_json_parser_4;
7842
                            }
7843
                        }
7844
                    }
7845
basic_json_parser_2:
7846
                    ++m_cursor;
7847
                    {
7848
                        last_token_type = token_type::end_of_input;
7849
                        break;
7850
                    }
7851
basic_json_parser_4:
7852
                    ++m_cursor;
7853
basic_json_parser_5:
7854
                    {
7855
                        last_token_type = token_type::parse_error;
7856
                        break;
7857
                    }
7858
basic_json_parser_6:
7859
                    ++m_cursor;
7860
                    if (m_limit <= m_cursor)
7861
                    {
7862
                        yyfill();    // LCOV_EXCL_LINE;
7863
                    }
7864
                    yych = *m_cursor;
7865
                    if (yybm[0 + yych] & 32)
7866
                    {
7867
                        goto basic_json_parser_6;
7868
                    }
7869
                    {
7870
                        continue;
7871
                    }
7872
basic_json_parser_9:
7873
                    yyaccept = 0;
7874
                    yych = *(m_marker = ++m_cursor);
7875
                    if (yych <= 0x1F)
7876
                    {
7877
                        goto basic_json_parser_5;
7878
                    }
7879
                    goto basic_json_parser_32;
7880
basic_json_parser_10:
7881
                    ++m_cursor;
7882
                    {
7883
                        last_token_type = token_type::value_separator;
7884
                        break;
7885
                    }
7886
basic_json_parser_12:
7887
                    yych = *++m_cursor;
7888
                    if (yych <= '/')
7889
                    {
7890
                        goto basic_json_parser_5;
7891
                    }
7892
                    if (yych <= '0')
7893
                    {
7894
                        goto basic_json_parser_13;
7895
                    }
7896
                    if (yych <= '9')
7897
                    {
7898
                        goto basic_json_parser_15;
7899
                    }
7900
                    goto basic_json_parser_5;
7901
basic_json_parser_13:
7902
                    yyaccept = 1;
7903
                    yych = *(m_marker = ++m_cursor);
7904
                    if (yych <= 'D')
7905
                    {
7906
                        if (yych == '.')
7907
                        {
7908
                            goto basic_json_parser_37;
7909
                        }
7910
                    }
7911
                    else
7912
                    {
7913
                        if (yych <= 'E')
7914
                        {
7915
                            goto basic_json_parser_38;
7916
                        }
7917
                        if (yych == 'e')
7918
                        {
7919
                            goto basic_json_parser_38;
7920
                        }
7921
                    }
7922
basic_json_parser_14:
7923
                    {
7924
                        last_token_type = token_type::value_number;
7925
                        break;
7926
                    }
7927
basic_json_parser_15:
7928
                    yyaccept = 1;
7929
                    m_marker = ++m_cursor;
7930
                    if ((m_limit - m_cursor) < 3)
7931
                    {
7932
                        yyfill();    // LCOV_EXCL_LINE;
7933
                    }
7934
                    yych = *m_cursor;
7935
                    if (yybm[0 + yych] & 64)
7936
                    {
7937
                        goto basic_json_parser_15;
7938
                    }
7939
                    if (yych <= 'D')
7940
                    {
7941
                        if (yych == '.')
7942
                        {
7943
                            goto basic_json_parser_37;
7944
                        }
7945
                        goto basic_json_parser_14;
7946
                    }
7947
                    else
7948
                    {
7949
                        if (yych <= 'E')
7950
                        {
7951
                            goto basic_json_parser_38;
7952
                        }
7953
                        if (yych == 'e')
7954
                        {
7955
                            goto basic_json_parser_38;
7956
                        }
7957
                        goto basic_json_parser_14;
7958
                    }
7959
basic_json_parser_17:
7960
                    ++m_cursor;
7961
                    {
7962
                        last_token_type = token_type::name_separator;
7963
                        break;
7964
                    }
7965
basic_json_parser_19:
7966
                    ++m_cursor;
7967
                    {
7968
                        last_token_type = token_type::begin_array;
7969
                        break;
7970
                    }
7971
basic_json_parser_21:
7972
                    ++m_cursor;
7973
                    {
7974
                        last_token_type = token_type::end_array;
7975
                        break;
7976
                    }
7977
basic_json_parser_23:
7978
                    yyaccept = 0;
7979
                    yych = *(m_marker = ++m_cursor);
7980
                    if (yych == 'a')
7981
                    {
7982
                        goto basic_json_parser_39;
7983
                    }
7984
                    goto basic_json_parser_5;
7985
basic_json_parser_24:
7986
                    yyaccept = 0;
7987
                    yych = *(m_marker = ++m_cursor);
7988
                    if (yych == 'u')
7989
                    {
7990
                        goto basic_json_parser_40;
7991
                    }
7992
                    goto basic_json_parser_5;
7993
basic_json_parser_25:
7994
                    yyaccept = 0;
7995
                    yych = *(m_marker = ++m_cursor);
7996
                    if (yych == 'r')
7997
                    {
7998
                        goto basic_json_parser_41;
7999
                    }
8000
                    goto basic_json_parser_5;
8001
basic_json_parser_26:
8002
                    ++m_cursor;
8003
                    {
8004
                        last_token_type = token_type::begin_object;
8005
                        break;
8006
                    }
8007
basic_json_parser_28:
8008
                    ++m_cursor;
8009
                    {
8010
                        last_token_type = token_type::end_object;
8011
                        break;
8012
                    }
8013
basic_json_parser_30:
8014
                    yyaccept = 0;
8015
                    yych = *(m_marker = ++m_cursor);
8016
                    if (yych == 0xBB)
8017
                    {
8018
                        goto basic_json_parser_42;
8019
                    }
8020
                    goto basic_json_parser_5;
8021
basic_json_parser_31:
8022
                    ++m_cursor;
8023
                    if (m_limit <= m_cursor)
8024
                    {
8025
                        yyfill();    // LCOV_EXCL_LINE;
8026
                    }
8027
                    yych = *m_cursor;
8028
basic_json_parser_32:
8029
                    if (yybm[0 + yych] & 128)
8030
                    {
8031
                        goto basic_json_parser_31;
8032
                    }
8033
                    if (yych <= 0x1F)
8034
                    {
8035
                        goto basic_json_parser_33;
8036
                    }
8037
                    if (yych <= '"')
8038
                    {
8039
                        goto basic_json_parser_34;
8040
                    }
8041
                    goto basic_json_parser_36;
8042
basic_json_parser_33:
8043
                    m_cursor = m_marker;
8044
                    if (yyaccept == 0)
8045
                    {
8046
                        goto basic_json_parser_5;
8047
                    }
8048
                    else
8049
                    {
8050
                        goto basic_json_parser_14;
8051
                    }
8052
basic_json_parser_34:
8053
                    ++m_cursor;
8054
                    {
8055
                        last_token_type = token_type::value_string;
8056
                        break;
8057
                    }
8058
basic_json_parser_36:
8059
                    ++m_cursor;
8060
                    if (m_limit <= m_cursor)
8061
                    {
8062
                        yyfill();    // LCOV_EXCL_LINE;
8063
                    }
8064
                    yych = *m_cursor;
8065
                    if (yych <= 'e')
8066
                    {
8067
                        if (yych <= '/')
8068
                        {
8069
                            if (yych == '"')
8070
                            {
8071
                                goto basic_json_parser_31;
8072
                            }
8073
                            if (yych <= '.')
8074
                            {
8075
                                goto basic_json_parser_33;
8076
                            }
8077
                            goto basic_json_parser_31;
8078
                        }
8079
                        else
8080
                        {
8081
                            if (yych <= '\\')
8082
                            {
8083
                                if (yych <= '[')
8084
                                {
8085
                                    goto basic_json_parser_33;
8086
                                }
8087
                                goto basic_json_parser_31;
8088
                            }
8089
                            else
8090
                            {
8091
                                if (yych == 'b')
8092
                                {
8093
                                    goto basic_json_parser_31;
8094
                                }
8095
                                goto basic_json_parser_33;
8096
                            }
8097
                        }
8098
                    }
8099
                    else
8100
                    {
8101
                        if (yych <= 'q')
8102
                        {
8103
                            if (yych <= 'f')
8104
                            {
8105
                                goto basic_json_parser_31;
8106
                            }
8107
                            if (yych == 'n')
8108
                            {
8109
                                goto basic_json_parser_31;
8110
                            }
8111
                            goto basic_json_parser_33;
8112
                        }
8113
                        else
8114
                        {
8115
                            if (yych <= 's')
8116
                            {
8117
                                if (yych <= 'r')
8118
                                {
8119
                                    goto basic_json_parser_31;
8120
                                }
8121
                                goto basic_json_parser_33;
8122
                            }
8123
                            else
8124
                            {
8125
                                if (yych <= 't')
8126
                                {
8127
                                    goto basic_json_parser_31;
8128
                                }
8129
                                if (yych <= 'u')
8130
                                {
8131
                                    goto basic_json_parser_43;
8132
                                }
8133
                                goto basic_json_parser_33;
8134
                            }
8135
                        }
8136
                    }
8137
basic_json_parser_37:
8138
                    yych = *++m_cursor;
8139
                    if (yych <= '/')
8140
                    {
8141
                        goto basic_json_parser_33;
8142
                    }
8143
                    if (yych <= '9')
8144
                    {
8145
                        goto basic_json_parser_44;
8146
                    }
8147
                    goto basic_json_parser_33;
8148
basic_json_parser_38:
8149
                    yych = *++m_cursor;
8150
                    if (yych <= ',')
8151
                    {
8152
                        if (yych == '+')
8153
                        {
8154
                            goto basic_json_parser_46;
8155
                        }
8156
                        goto basic_json_parser_33;
8157
                    }
8158
                    else
8159
                    {
8160
                        if (yych <= '-')
8161
                        {
8162
                            goto basic_json_parser_46;
8163
                        }
8164
                        if (yych <= '/')
8165
                        {
8166
                            goto basic_json_parser_33;
8167
                        }
8168
                        if (yych <= '9')
8169
                        {
8170
                            goto basic_json_parser_47;
8171
                        }
8172
                        goto basic_json_parser_33;
8173
                    }
8174
basic_json_parser_39:
8175
                    yych = *++m_cursor;
8176
                    if (yych == 'l')
8177
                    {
8178
                        goto basic_json_parser_49;
8179
                    }
8180
                    goto basic_json_parser_33;
8181
basic_json_parser_40:
8182
                    yych = *++m_cursor;
8183
                    if (yych == 'l')
8184
                    {
8185
                        goto basic_json_parser_50;
8186
                    }
8187
                    goto basic_json_parser_33;
8188
basic_json_parser_41:
8189
                    yych = *++m_cursor;
8190
                    if (yych == 'u')
8191
                    {
8192
                        goto basic_json_parser_51;
8193
                    }
8194
                    goto basic_json_parser_33;
8195
basic_json_parser_42:
8196
                    yych = *++m_cursor;
8197
                    if (yych == 0xBF)
8198
                    {
8199
                        goto basic_json_parser_52;
8200
                    }
8201
                    goto basic_json_parser_33;
8202
basic_json_parser_43:
8203
                    ++m_cursor;
8204
                    if (m_limit <= m_cursor)
8205
                    {
8206
                        yyfill();    // LCOV_EXCL_LINE;
8207
                    }
8208
                    yych = *m_cursor;
8209
                    if (yych <= '@')
8210
                    {
8211
                        if (yych <= '/')
8212
                        {
8213
                            goto basic_json_parser_33;
8214
                        }
8215
                        if (yych <= '9')
8216
                        {
8217
                            goto basic_json_parser_54;
8218
                        }
8219
                        goto basic_json_parser_33;
8220
                    }
8221
                    else
8222
                    {
8223
                        if (yych <= 'F')
8224
                        {
8225
                            goto basic_json_parser_54;
8226
                        }
8227
                        if (yych <= '`')
8228
                        {
8229
                            goto basic_json_parser_33;
8230
                        }
8231
                        if (yych <= 'f')
8232
                        {
8233
                            goto basic_json_parser_54;
8234
                        }
8235
                        goto basic_json_parser_33;
8236
                    }
8237
basic_json_parser_44:
8238
                    yyaccept = 1;
8239
                    m_marker = ++m_cursor;
8240
                    if ((m_limit - m_cursor) < 3)
8241
                    {
8242
                        yyfill();    // LCOV_EXCL_LINE;
8243
                    }
8244
                    yych = *m_cursor;
8245
                    if (yych <= 'D')
8246
                    {
8247
                        if (yych <= '/')
8248
                        {
8249
                            goto basic_json_parser_14;
8250
                        }
8251
                        if (yych <= '9')
8252
                        {
8253
                            goto basic_json_parser_44;
8254
                        }
8255
                        goto basic_json_parser_14;
8256
                    }
8257
                    else
8258
                    {
8259
                        if (yych <= 'E')
8260
                        {
8261
                            goto basic_json_parser_38;
8262
                        }
8263
                        if (yych == 'e')
8264
                        {
8265
                            goto basic_json_parser_38;
8266
                        }
8267
                        goto basic_json_parser_14;
8268
                    }
8269
basic_json_parser_46:
8270
                    yych = *++m_cursor;
8271
                    if (yych <= '/')
8272
                    {
8273
                        goto basic_json_parser_33;
8274
                    }
8275
                    if (yych >= ':')
8276
                    {
8277
                        goto basic_json_parser_33;
8278
                    }
8279
basic_json_parser_47:
8280
                    ++m_cursor;
8281
                    if (m_limit <= m_cursor)
8282
                    {
8283
                        yyfill();    // LCOV_EXCL_LINE;
8284
                    }
8285
                    yych = *m_cursor;
8286
                    if (yych <= '/')
8287
                    {
8288
                        goto basic_json_parser_14;
8289
                    }
8290
                    if (yych <= '9')
8291
                    {
8292
                        goto basic_json_parser_47;
8293
                    }
8294
                    goto basic_json_parser_14;
8295
basic_json_parser_49:
8296
                    yych = *++m_cursor;
8297
                    if (yych == 's')
8298
                    {
8299
                        goto basic_json_parser_55;
8300
                    }
8301
                    goto basic_json_parser_33;
8302
basic_json_parser_50:
8303
                    yych = *++m_cursor;
8304
                    if (yych == 'l')
8305
                    {
8306
                        goto basic_json_parser_56;
8307
                    }
8308
                    goto basic_json_parser_33;
8309
basic_json_parser_51:
8310
                    yych = *++m_cursor;
8311
                    if (yych == 'e')
8312
                    {
8313
                        goto basic_json_parser_58;
8314
                    }
8315
                    goto basic_json_parser_33;
8316
basic_json_parser_52:
8317
                    ++m_cursor;
8318
                    {
8319
                        continue;
8320
                    }
8321
basic_json_parser_54:
8322
                    ++m_cursor;
8323
                    if (m_limit <= m_cursor)
8324
                    {
8325
                        yyfill();    // LCOV_EXCL_LINE;
8326
                    }
8327
                    yych = *m_cursor;
8328
                    if (yych <= '@')
8329
                    {
8330
                        if (yych <= '/')
8331
                        {
8332
                            goto basic_json_parser_33;
8333
                        }
8334
                        if (yych <= '9')
8335
                        {
8336
                            goto basic_json_parser_60;
8337
                        }
8338
                        goto basic_json_parser_33;
8339
                    }
8340
                    else
8341
                    {
8342
                        if (yych <= 'F')
8343
                        {
8344
                            goto basic_json_parser_60;
8345
                        }
8346
                        if (yych <= '`')
8347
                        {
8348
                            goto basic_json_parser_33;
8349
                        }
8350
                        if (yych <= 'f')
8351
                        {
8352
                            goto basic_json_parser_60;
8353
                        }
8354
                        goto basic_json_parser_33;
8355
                    }
8356
basic_json_parser_55:
8357
                    yych = *++m_cursor;
8358
                    if (yych == 'e')
8359
                    {
8360
                        goto basic_json_parser_61;
8361
                    }
8362
                    goto basic_json_parser_33;
8363
basic_json_parser_56:
8364
                    ++m_cursor;
8365
                    {
8366
                        last_token_type = token_type::literal_null;
8367
                        break;
8368
                    }
8369
basic_json_parser_58:
8370
                    ++m_cursor;
8371
                    {
8372
                        last_token_type = token_type::literal_true;
8373
                        break;
8374
                    }
8375
basic_json_parser_60:
8376
                    ++m_cursor;
8377
                    if (m_limit <= m_cursor)
8378
                    {
8379
                        yyfill();    // LCOV_EXCL_LINE;
8380
                    }
8381
                    yych = *m_cursor;
8382
                    if (yych <= '@')
8383
                    {
8384
                        if (yych <= '/')
8385
                        {
8386
                            goto basic_json_parser_33;
8387
                        }
8388
                        if (yych <= '9')
8389
                        {
8390
                            goto basic_json_parser_63;
8391
                        }
8392
                        goto basic_json_parser_33;
8393
                    }
8394
                    else
8395
                    {
8396
                        if (yych <= 'F')
8397
                        {
8398
                            goto basic_json_parser_63;
8399
                        }
8400
                        if (yych <= '`')
8401
                        {
8402
                            goto basic_json_parser_33;
8403
                        }
8404
                        if (yych <= 'f')
8405
                        {
8406
                            goto basic_json_parser_63;
8407
                        }
8408
                        goto basic_json_parser_33;
8409
                    }
8410
basic_json_parser_61:
8411
                    ++m_cursor;
8412
                    {
8413
                        last_token_type = token_type::literal_false;
8414
                        break;
8415
                    }
8416
basic_json_parser_63:
8417
                    ++m_cursor;
8418
                    if (m_limit <= m_cursor)
8419
                    {
8420
                        yyfill();    // LCOV_EXCL_LINE;
8421
                    }
8422
                    yych = *m_cursor;
8423
                    if (yych <= '@')
8424
                    {
8425
                        if (yych <= '/')
8426
                        {
8427
                            goto basic_json_parser_33;
8428
                        }
8429
                        if (yych <= '9')
8430
                        {
8431
                            goto basic_json_parser_31;
8432
                        }
8433
                        goto basic_json_parser_33;
8434
                    }
8435
                    else
8436
                    {
8437
                        if (yych <= 'F')
8438
                        {
8439
                            goto basic_json_parser_31;
8440
                        }
8441
                        if (yych <= '`')
8442
                        {
8443
                            goto basic_json_parser_33;
8444
                        }
8445
                        if (yych <= 'f')
8446
                        {
8447
                            goto basic_json_parser_31;
8448
                        }
8449
                        goto basic_json_parser_33;
8450
                    }
8451
                }
8452
8453
            }
8454
8455
            return last_token_type;
8456
        }
8457
8458
        /// append data from the stream to the internal buffer
8459
        void yyfill() noexcept
8460
        {
8461
            if (m_stream == nullptr or not * m_stream)
8462
            {
8463
                return;
8464
            }
8465
8466
            const auto offset_start = m_start - m_content;
8467
            const auto offset_marker = m_marker - m_start;
8468
            const auto offset_cursor = m_cursor - m_start;
8469
8470
            m_buffer.erase(0, static_cast<size_t>(offset_start));
8471
            std::string line;
8472
            assert(m_stream != nullptr);
8473
            std::getline(*m_stream, line);
8474
            m_buffer += "\n" + line; // add line with newline symbol
8475
8476
            m_content = reinterpret_cast<const lexer_char_t*>(m_buffer.c_str());
8477
            assert(m_content != nullptr);
8478
            m_start  = m_content;
8479
            m_marker = m_start + offset_marker;
8480
            m_cursor = m_start + offset_cursor;
8481
            m_limit  = m_start + m_buffer.size() - 1;
8482
        }
8483
8484
        /// return string representation of last read token
8485
        string_t get_token_string() const
8486
        {
8487
            assert(m_start != nullptr);
8488
            return string_t(reinterpret_cast<typename string_t::const_pointer>(m_start),
8489
                            static_cast<size_t>(m_cursor - m_start));
8490
        }
8491
8492
        /*!
8493
        @brief return string value for string tokens
8494
8495
        The function iterates the characters between the opening and closing
8496
        quotes of the string value. The complete string is the range
8497
        [m_start,m_cursor). Consequently, we iterate from m_start+1 to
8498
        m_cursor-1.
8499
8500
        We differentiate two cases:
8501
8502
        1. Escaped characters. In this case, a new character is constructed
8503
           according to the nature of the escape. Some escapes create new
8504
           characters (e.g., `"\\n"` is replaced by `"\n"`), some are copied
8505
           as is (e.g., `"\\\\"`). Furthermore, Unicode escapes of the shape
8506
           `"\\uxxxx"` need special care. In this case, to_unicode takes care
8507
           of the construction of the values.
8508
        2. Unescaped characters are copied as is.
8509
8510
        @pre `m_cursor - m_start >= 2`, meaning the length of the last token
8511
        is at least 2 bytes which is trivially true for any string (which
8512
        consists of at least two quotes).
8513
8514
            " c1 c2 c3 ... "
8515
            ^                ^
8516
            m_start          m_cursor
8517
8518
        @complexity Linear in the length of the string.\n
8519
8520
        Lemma: The loop body will always terminate.\n
8521
8522
        Proof (by contradiction): Assume the loop body does not terminate. As
8523
        the loop body does not contain another loop, one of the called
8524
        functions must never return. The called functions are `std::strtoul`
8525
        and to_unicode. Neither function can loop forever, so the loop body
8526
        will never loop forever which contradicts the assumption that the loop
8527
        body does not terminate, q.e.d.\n
8528
8529
        Lemma: The loop condition for the for loop is eventually false.\n
8530
8531
        Proof (by contradiction): Assume the loop does not terminate. Due to
8532
        the above lemma, this can only be due to a tautological loop
8533
        condition; that is, the loop condition i < m_cursor - 1 must always be
8534
        true. Let x be the change of i for any loop iteration. Then
8535
        m_start + 1 + x < m_cursor - 1 must hold to loop indefinitely. This
8536
        can be rephrased to m_cursor - m_start - 2 > x. With the
8537
        precondition, we x <= 0, meaning that the loop condition holds
8538
        indefinitly if i is always decreased. However, observe that the value
8539
        of i is strictly increasing with each iteration, as it is incremented
8540
        by 1 in the iteration expression and never decremented inside the loop
8541
        body. Hence, the loop condition will eventually be false which
8542
        contradicts the assumption that the loop condition is a tautology,
8543
        q.e.d.
8544
8545
        @return string value of current token without opening and closing
8546
        quotes
8547
        @throw std::out_of_range if to_unicode fails
8548
        */
8549
        string_t get_string() const
8550
        {
8551
            assert(m_cursor - m_start >= 2);
8552
8553
            string_t result;
8554
            result.reserve(static_cast<size_t>(m_cursor - m_start - 2));
8555
8556
            // iterate the result between the quotes
8557
            for (const lexer_char_t* i = m_start + 1; i < m_cursor - 1; ++i)
8558
            {
8559
                // process escaped characters
8560
                if (*i == '\\')
8561
                {
8562
                    // read next character
8563
                    ++i;
8564
8565
                    switch (*i)
8566
                    {
8567
                        // the default escapes
8568
                        case 't':
8569
                        {
8570
                            result += "\t";
8571
                            break;
8572
                        }
8573
                        case 'b':
8574
                        {
8575
                            result += "\b";
8576
                            break;
8577
                        }
8578
                        case 'f':
8579
                        {
8580
                            result += "\f";
8581
                            break;
8582
                        }
8583
                        case 'n':
8584
                        {
8585
                            result += "\n";
8586
                            break;
8587
                        }
8588
                        case 'r':
8589
                        {
8590
                            result += "\r";
8591
                            break;
8592
                        }
8593
                        case '\\':
8594
                        {
8595
                            result += "\\";
8596
                            break;
8597
                        }
8598
                        case '/':
8599
                        {
8600
                            result += "/";
8601
                            break;
8602
                        }
8603
                        case '"':
8604
                        {
8605
                            result += "\"";
8606
                            break;
8607
                        }
8608
8609
                        // unicode
8610
                        case 'u':
8611
                        {
8612
                            // get code xxxx from uxxxx
8613
                            auto codepoint = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>(i + 1),
8614
                                                          4).c_str(), nullptr, 16);
8615
8616
                            // check if codepoint is a high surrogate
8617
                            if (codepoint >= 0xD800 and codepoint <= 0xDBFF)
8618
                            {
8619
                                // make sure there is a subsequent unicode
8620
                                if ((i + 6 >= m_limit) or * (i + 5) != '\\' or * (i + 6) != 'u')
8621
                                {
8622
                                    throw std::invalid_argument("missing low surrogate");
8623
                                }
8624
8625
                                // get code yyyy from uxxxx\uyyyy
8626
                                auto codepoint2 = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>
8627
                                                               (i + 7), 4).c_str(), nullptr, 16);
8628
                                result += to_unicode(codepoint, codepoint2);
8629
                                // skip the next 10 characters (xxxx\uyyyy)
8630
                                i += 10;
8631
                            }
8632
                            else
8633
                            {
8634
                                // add unicode character(s)
8635
                                result += to_unicode(codepoint);
8636
                                // skip the next four characters (xxxx)
8637
                                i += 4;
8638
                            }
8639
                            break;
8640
                        }
8641
                    }
8642
                }
8643
                else
8644
                {
8645
                    // all other characters are just copied to the end of the
8646
                    // string
8647
                    result.append(1, static_cast<typename string_t::value_type>(*i));
8648
                }
8649
            }
8650
8651
            return result;
8652
        }
8653
8654
        /*!
8655
        @brief parse floating point number
8656
8657
        This function (and its overloads) serves to select the most approprate
8658
        standard floating point number parsing function based on the type
8659
        supplied via the first parameter.  Set this to @a
8660
        static_cast<number_float_t*>(nullptr).
8661
8662
        @param[in] type  the @ref number_float_t in use
8663
8664
        @param[in,out] endptr recieves a pointer to the first character after
8665
        the number
8666
8667
        @return the floating point number
8668
        */
8669
        long double str_to_float_t(long double* /* type */, char** endptr) const
8670
        {
8671
            return std::strtold(reinterpret_cast<typename string_t::const_pointer>(m_start), endptr);
8672
        }
8673
8674
        /*!
8675
        @brief parse floating point number
8676
8677
        This function (and its overloads) serves to select the most approprate
8678
        standard floating point number parsing function based on the type
8679
        supplied via the first parameter.  Set this to @a
8680
        static_cast<number_float_t*>(nullptr).
8681
8682
        @param[in] type  the @ref number_float_t in use
8683
8684
        @param[in,out] endptr  recieves a pointer to the first character after
8685
        the number
8686
8687
        @return the floating point number
8688
        */
8689
        double str_to_float_t(double* /* type */, char** endptr) const
8690
        {
8691
            return std::strtod(reinterpret_cast<typename string_t::const_pointer>(m_start), endptr);
8692
        }
8693
8694
        /*!
8695
        @brief parse floating point number
8696
8697
        This function (and its overloads) serves to select the most approprate
8698
        standard floating point number parsing function based on the type
8699
        supplied via the first parameter.  Set this to @a
8700
        static_cast<number_float_t*>(nullptr).
8701
8702
        @param[in] type  the @ref number_float_t in use
8703
8704
        @param[in,out] endptr  recieves a pointer to the first character after
8705
        the number
8706
8707
        @return the floating point number
8708
        */
8709
        float str_to_float_t(float* /* type */, char** endptr) const
8710
        {
8711
            return std::strtof(reinterpret_cast<typename string_t::const_pointer>(m_start), endptr);
8712
        }
8713
8714
        /*!
8715
        @brief return number value for number tokens
8716
8717
        This function translates the last token into the most appropriate
8718
        number type (either integer, unsigned integer or floating point),
8719
        which is passed back to the caller via the result parameter.
8720
8721
        This function parses the integer component up to the radix point or
8722
        exponent while collecting information about the 'floating point
8723
        representation', which it stores in the result parameter. If there is
8724
        no radix point or exponent, and the number can fit into a @ref
8725
        number_integer_t or @ref number_unsigned_t then it sets the result
8726
        parameter accordingly.
8727
8728
        If the number is a floating point number the number is then parsed
8729
        using @a std:strtod (or @a std:strtof or @a std::strtold).
8730
8731
        @param[out] result  @ref basic_json object to receive the number, or
8732
        NAN if the conversion read past the current token. The latter case
8733
        needs to be treated by the caller function.
8734
        */
8735
        void get_number(basic_json& result) const
8736
        {
8737
            assert(m_start != nullptr);
8738
8739
            const lexer::lexer_char_t* curptr = m_start;
8740
8741
            // accumulate the integer conversion result (unsigned for now)
8742
            number_unsigned_t value = 0;
8743
8744
            // maximum absolute value of the relevant integer type
8745
            number_unsigned_t max;
8746
8747
            // temporarily store the type to avoid unecessary bitfield access
8748
            value_t type;
8749
8750
            // look for sign
8751
            if (*curptr == '-')
8752
            {
8753
                type = value_t::number_integer;
8754
                max = static_cast<uint64_t>((std::numeric_limits<number_integer_t>::max)()) + 1;
8755
                curptr++;
8756
            }
8757
            else
8758
            {
8759
                type = value_t::number_unsigned;
8760
                max = static_cast<uint64_t>((std::numeric_limits<number_unsigned_t>::max)());
8761
            }
8762
8763
            // count the significant figures
8764
            for (; curptr < m_cursor; curptr++)
8765
            {
8766
                // quickly skip tests if a digit
8767
                if (*curptr < '0' || *curptr > '9')
8768
                {
8769
                    if (*curptr == '.')
8770
                    {
8771
                        // don't count '.' but change to float
8772
                        type = value_t::number_float;
8773
                        continue;
8774
                    }
8775
                    // assume exponent (if not then will fail parse): change to
8776
                    // float, stop counting and record exponent details
8777
                    type = value_t::number_float;
8778
                    break;
8779
                }
8780
8781
                // skip if definitely not an integer
8782
                if (type != value_t::number_float)
8783
                {
8784
                    // multiply last value by ten and add the new digit
8785
                    auto temp = value * 10 + *curptr - '0';
8786
8787
                    // test for overflow
8788
                    if (temp < value || temp > max)
8789
                    {
8790
                        // overflow
8791
                        type = value_t::number_float;
8792
                    }
8793
                    else
8794
                    {
8795
                        // no overflow - save it
8796
                        value = temp;
8797
                    }
8798
                }
8799
            }
8800
8801
            // save the value (if not a float)
8802
            if (type == value_t::number_unsigned)
8803
            {
8804
                result.m_value.number_unsigned = value;
8805
            }
8806
            else if (type == value_t::number_integer)
8807
            {
8808
                result.m_value.number_integer = -static_cast<number_integer_t>(value);
8809
            }
8810
            else
8811
            {
8812
                // parse with strtod
8813
                result.m_value.number_float = str_to_float_t(static_cast<number_float_t*>(nullptr), NULL);
8814
            }
8815
8816
            // save the type
8817
            result.m_type = type;
8818
        }
8819
8820
      private:
8821
        /// optional input stream
8822
        std::istream* m_stream = nullptr;
8823
        /// the buffer
8824
        string_t m_buffer;
8825
        /// the buffer pointer
8826
        const lexer_char_t* m_content = nullptr;
8827
        /// pointer to the beginning of the current symbol
8828
        const lexer_char_t* m_start = nullptr;
8829
        /// pointer for backtracking information
8830
        const lexer_char_t* m_marker = nullptr;
8831
        /// pointer to the current symbol
8832
        const lexer_char_t* m_cursor = nullptr;
8833
        /// pointer to the end of the buffer
8834
        const lexer_char_t* m_limit = nullptr;
8835
        /// the last token type
8836
        token_type last_token_type = token_type::end_of_input;
8837
    };
8838
8839
    /*!
8840
    @brief syntax analysis
8841
8842
    This class implements a recursive decent parser.
8843
    */
8844
    class parser
8845
    {
8846
      public:
8847
        /// constructor for strings
8848
        parser(const string_t& s, const parser_callback_t cb = nullptr) noexcept
8849
            : callback(cb), m_lexer(s)
8850
        {
8851
            // read first token
8852
            get_token();
8853
        }
8854
8855
        /// a parser reading from an input stream
8856
        parser(std::istream& _is, const parser_callback_t cb = nullptr) noexcept
8857
            : callback(cb), m_lexer(&_is)
8858
        {
8859
            // read first token
8860
            get_token();
8861
        }
8862
8863
        /// public parser interface
8864
        basic_json parse()
8865
        {
8866
            basic_json result = parse_internal(true);
8867
            result.assert_invariant();
8868
8869
            expect(lexer::token_type::end_of_input);
8870
8871
            // return parser result and replace it with null in case the
8872
            // top-level value was discarded by the callback function
8873
            return result.is_discarded() ? basic_json() : std::move(result);
8874
        }
8875
8876
      private:
8877
        /// the actual parser
8878
        basic_json parse_internal(bool keep)
8879
        {
8880
            auto result = basic_json(value_t::discarded);
8881
8882
            switch (last_token)
8883
            {
8884
                case lexer::token_type::begin_object:
8885
                {
8886
                    if (keep and (not callback or (keep = callback(depth++, parse_event_t::object_start, result))))
8887
                    {
8888
                        // explicitly set result to object to cope with {}
8889
                        result.m_type = value_t::object;
8890
                        result.m_value = value_t::object;
8891
                    }
8892
8893
                    // read next token
8894
                    get_token();
8895
8896
                    // closing } -> we are done
8897
                    if (last_token == lexer::token_type::end_object)
8898
                    {
8899
                        get_token();
8900
                        if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
8901
                        {
8902
                            result = basic_json(value_t::discarded);
8903
                        }
8904
                        return result;
8905
                    }
8906
8907
                    // no comma is expected here
8908
                    unexpect(lexer::token_type::value_separator);
8909
8910
                    // otherwise: parse key-value pairs
8911
                    do
8912
                    {
8913
                        // ugly, but could be fixed with loop reorganization
8914
                        if (last_token == lexer::token_type::value_separator)
8915
                        {
8916
                            get_token();
8917
                        }
8918
8919
                        // store key
8920
                        expect(lexer::token_type::value_string);
8921
                        const auto key = m_lexer.get_string();
8922
8923
                        bool keep_tag = false;
8924
                        if (keep)
8925
                        {
8926
                            if (callback)
8927
                            {
8928
                                basic_json k(key);
8929
                                keep_tag = callback(depth, parse_event_t::key, k);
8930
                            }
8931
                            else
8932
                            {
8933
                                keep_tag = true;
8934
                            }
8935
                        }
8936
8937
                        // parse separator (:)
8938
                        get_token();
8939
                        expect(lexer::token_type::name_separator);
8940
8941
                        // parse and add value
8942
                        get_token();
8943
                        auto value = parse_internal(keep);
8944
                        if (keep and keep_tag and not value.is_discarded())
8945
                        {
8946
                            result[key] = std::move(value);
8947
                        }
8948
                    }
8949
                    while (last_token == lexer::token_type::value_separator);
8950
8951
                    // closing }
8952
                    expect(lexer::token_type::end_object);
8953
                    get_token();
8954
                    if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
8955
                    {
8956
                        result = basic_json(value_t::discarded);
8957
                    }
8958
8959
                    return result;
8960
                }
8961
8962
                case lexer::token_type::begin_array:
8963
                {
8964
                    if (keep and (not callback or (keep = callback(depth++, parse_event_t::array_start, result))))
8965
                    {
8966
                        // explicitly set result to object to cope with []
8967
                        result.m_type = value_t::array;
8968
                        result.m_value = value_t::array;
8969
                    }
8970
8971
                    // read next token
8972
                    get_token();
8973
8974
                    // closing ] -> we are done
8975
                    if (last_token == lexer::token_type::end_array)
8976
                    {
8977
                        get_token();
8978
                        if (callback and not callback(--depth, parse_event_t::array_end, result))
8979
                        {
8980
                            result = basic_json(value_t::discarded);
8981
                        }
8982
                        return result;
8983
                    }
8984
8985
                    // no comma is expected here
8986
                    unexpect(lexer::token_type::value_separator);
8987
8988
                    // otherwise: parse values
8989
                    do
8990
                    {
8991
                        // ugly, but could be fixed with loop reorganization
8992
                        if (last_token == lexer::token_type::value_separator)
8993
                        {
8994
                            get_token();
8995
                        }
8996
8997
                        // parse value
8998
                        auto value = parse_internal(keep);
8999
                        if (keep and not value.is_discarded())
9000
                        {
9001
                            result.push_back(std::move(value));
9002
                        }
9003
                    }
9004
                    while (last_token == lexer::token_type::value_separator);
9005
9006
                    // closing ]
9007
                    expect(lexer::token_type::end_array);
9008
                    get_token();
9009
                    if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
9010
                    {
9011
                        result = basic_json(value_t::discarded);
9012
                    }
9013
9014
                    return result;
9015
                }
9016
9017
                case lexer::token_type::literal_null:
9018
                {
9019
                    get_token();
9020
                    result.m_type = value_t::null;
9021
                    break;
9022
                }
9023
9024
                case lexer::token_type::value_string:
9025
                {
9026
                    const auto s = m_lexer.get_string();
9027
                    get_token();
9028
                    result = basic_json(s);
9029
                    break;
9030
                }
9031
9032
                case lexer::token_type::literal_true:
9033
                {
9034
                    get_token();
9035
                    result.m_type = value_t::boolean;
9036
                    result.m_value = true;
9037
                    break;
9038
                }
9039
9040
                case lexer::token_type::literal_false:
9041
                {
9042
                    get_token();
9043
                    result.m_type = value_t::boolean;
9044
                    result.m_value = false;
9045
                    break;
9046
                }
9047
9048
                case lexer::token_type::value_number:
9049
                {
9050
                    m_lexer.get_number(result);
9051
                    get_token();
9052
                    break;
9053
                }
9054
9055
                default:
9056
                {
9057
                    // the last token was unexpected
9058
                    unexpect(last_token);
9059
                }
9060
            }
9061
9062
            if (keep and callback and not callback(depth, parse_event_t::value, result))
9063
            {
9064
                result = basic_json(value_t::discarded);
9065
            }
9066
            return result;
9067
        }
9068
9069
        /// get next token from lexer
9070
        typename lexer::token_type get_token() noexcept
9071
        {
9072
            last_token = m_lexer.scan();
9073
            return last_token;
9074
        }
9075
9076
        void expect(typename lexer::token_type t) const
9077
        {
9078
            if (t != last_token)
9079
            {
9080
                std::string error_msg = "parse error - unexpected ";
9081
                error_msg += (last_token == lexer::token_type::parse_error ? ("'" +  m_lexer.get_token_string() +
9082
                              "'") :
9083
                              lexer::token_type_name(last_token));
9084
                error_msg += "; expected " + lexer::token_type_name(t);
9085
                throw std::invalid_argument(error_msg);
9086
            }
9087
        }
9088
9089
        void unexpect(typename lexer::token_type t) const
9090
        {
9091
            if (t == last_token)
9092
            {
9093
                std::string error_msg = "parse error - unexpected ";
9094
                error_msg += (last_token == lexer::token_type::parse_error ? ("'" +  m_lexer.get_token_string() +
9095
                              "'") :
9096
                              lexer::token_type_name(last_token));
9097
                throw std::invalid_argument(error_msg);
9098
            }
9099
        }
9100
9101
      private:
9102
        /// current level of recursion
9103
        int depth = 0;
9104
        /// callback function
9105
        const parser_callback_t callback = nullptr;
9106
        /// the type of the last read token
9107
        typename lexer::token_type last_token = lexer::token_type::uninitialized;
9108
        /// the lexer
9109
        lexer m_lexer;
9110
    };
9111
9112
  public:
9113
    /*!
9114
    @brief JSON Pointer
9115
9116
    A JSON pointer defines a string syntax for identifying a specific value
9117
    within a JSON document. It can be used with functions `at` and
9118
    `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
9119
9120
    @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
9121
9122
    @since version 2.0.0
9123
    */
9124
    class json_pointer
9125
    {
9126
        /// allow basic_json to access private members
9127
        friend class basic_json;
9128
9129
      public:
9130
        /*!
9131
        @brief create JSON pointer
9132
9133
        Create a JSON pointer according to the syntax described in
9134
        [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
9135
9136
        @param[in] s  string representing the JSON pointer; if omitted, the
9137
                      empty string is assumed which references the whole JSON
9138
                      value
9139
9140
        @throw std::domain_error if reference token is nonempty and does not
9141
        begin with a slash (`/`); example: `"JSON pointer must be empty or
9142
        begin with /"`
9143
        @throw std::domain_error if a tilde (`~`) is not followed by `0`
9144
        (representing `~`) or `1` (representing `/`); example: `"escape error:
9145
        ~ must be followed with 0 or 1"`
9146
9147
        @liveexample{The example shows the construction several valid JSON
9148
        pointers as well as the exceptional behavior.,json_pointer}
9149
9150
        @since version 2.0.0
9151
        */
9152
        explicit json_pointer(const std::string& s = "")
9153
            : reference_tokens(split(s))
9154
        {}
9155
9156
        /*!
9157
        @brief return a string representation of the JSON pointer
9158
9159
        @invariant For each JSON pointer `ptr`, it holds:
9160
        @code {.cpp}
9161
        ptr == json_pointer(ptr.to_string());
9162
        @endcode
9163
9164
        @return a string representation of the JSON pointer
9165
9166
        @liveexample{The example shows the result of `to_string`.,
9167
        json_pointer__to_string}
9168
9169
        @since version 2.0.0
9170
        */
9171
        std::string to_string() const noexcept
9172
        {
9173
            return std::accumulate(reference_tokens.begin(),
9174
                                   reference_tokens.end(), std::string{},
9175
                                   [](const std::string & a, const std::string & b)
9176
            {
9177
                return a + "/" + escape(b);
9178
            });
9179
        }
9180
9181
        /// @copydoc to_string()
9182
        operator std::string() const
9183
        {
9184
            return to_string();
9185
        }
9186
9187
      private:
9188
        /// remove and return last reference pointer
9189
        std::string pop_back()
9190
        {
9191
            if (is_root())
9192
            {
9193
                throw std::domain_error("JSON pointer has no parent");
9194
            }
9195
9196
            auto last = reference_tokens.back();
9197
            reference_tokens.pop_back();
9198
            return last;
9199
        }
9200
9201
        /// return whether pointer points to the root document
9202
        bool is_root() const
9203
        {
9204
            return reference_tokens.empty();
9205
        }
9206
9207
        json_pointer top() const
9208
        {
9209
            if (is_root())
9210
            {
9211
                throw std::domain_error("JSON pointer has no parent");
9212
            }
9213
9214
            json_pointer result = *this;
9215
            result.reference_tokens = {reference_tokens[0]};
9216
            return result;
9217
        }
9218
9219
        /*!
9220
        @brief create and return a reference to the pointed to value
9221
9222
        @complexity Linear in the number of reference tokens.
9223
        */
9224
        reference get_and_create(reference j) const
9225
        {
9226
            pointer result = &j;
9227
9228
            // in case no reference tokens exist, return a reference to the
9229
            // JSON value j which will be overwritten by a primitive value
9230
            for (const auto& reference_token : reference_tokens)
9231
            {
9232
                switch (result->m_type)
9233
                {
9234
                    case value_t::null:
9235
                    {
9236
                        if (reference_token == "0")
9237
                        {
9238
                            // start a new array if reference token is 0
9239
                            result = &result->operator[](0);
9240
                        }
9241
                        else
9242
                        {
9243
                            // start a new object otherwise
9244
                            result = &result->operator[](reference_token);
9245
                        }
9246
                        break;
9247
                    }
9248
9249
                    case value_t::object:
9250
                    {
9251
                        // create an entry in the object
9252
                        result = &result->operator[](reference_token);
9253
                        break;
9254
                    }
9255
9256
                    case value_t::array:
9257
                    {
9258
                        // create an entry in the array
9259
                        result = &result->operator[](static_cast<size_type>(std::stoi(reference_token)));
9260
                        break;
9261
                    }
9262
9263
                    /*
9264
                    The following code is only reached if there exists a
9265
                    reference token _and_ the current value is primitive. In
9266
                    this case, we have an error situation, because primitive
9267
                    values may only occur as single value; that is, with an
9268
                    empty list of reference tokens.
9269
                    */
9270
                    default:
9271
                    {
9272
                        throw std::domain_error("invalid value to unflatten");
9273
                    }
9274
                }
9275
            }
9276
9277
            return *result;
9278
        }
9279
9280
        /*!
9281
        @brief return a reference to the pointed to value
9282
9283
        @param[in] ptr  a JSON value
9284
9285
        @return reference to the JSON value pointed to by the JSON pointer
9286
9287
        @complexity Linear in the length of the JSON pointer.
9288
9289
        @throw std::out_of_range      if the JSON pointer can not be resolved
9290
        @throw std::domain_error      if an array index begins with '0'
9291
        @throw std::invalid_argument  if an array index was not a number
9292
        */
9293
        reference get_unchecked(pointer ptr) const
9294
        {
9295
            for (const auto& reference_token : reference_tokens)
9296
            {
9297
                switch (ptr->m_type)
9298
                {
9299
                    case value_t::object:
9300
                    {
9301
                        // use unchecked object access
9302
                        ptr = &ptr->operator[](reference_token);
9303
                        break;
9304
                    }
9305
9306
                    case value_t::array:
9307
                    {
9308
                        // error condition (cf. RFC 6901, Sect. 4)
9309
                        if (reference_token.size() > 1 and reference_token[0] == '0')
9310
                        {
9311
                            throw std::domain_error("array index must not begin with '0'");
9312
                        }
9313
9314
                        if (reference_token == "-")
9315
                        {
9316
                            // explicityly treat "-" as index beyond the end
9317
                            ptr = &ptr->operator[](ptr->m_value.array->size());
9318
                        }
9319
                        else
9320
                        {
9321
                            // convert array index to number; unchecked access
9322
                            ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token)));
9323
                        }
9324
                        break;
9325
                    }
9326
9327
                    default:
9328
                    {
9329
                        throw std::out_of_range("unresolved reference token '" + reference_token + "'");
9330
                    }
9331
                }
9332
            }
9333
9334
            return *ptr;
9335
        }
9336
9337
        reference get_checked(pointer ptr) const
9338
        {
9339
            for (const auto& reference_token : reference_tokens)
9340
            {
9341
                switch (ptr->m_type)
9342
                {
9343
                    case value_t::object:
9344
                    {
9345
                        // note: at performs range check
9346
                        ptr = &ptr->at(reference_token);
9347
                        break;
9348
                    }
9349
9350
                    case value_t::array:
9351
                    {
9352
                        if (reference_token == "-")
9353
                        {
9354
                            // "-" always fails the range check
9355
                            throw std::out_of_range("array index '-' (" +
9356
                                                    std::to_string(ptr->m_value.array->size()) +
9357
                                                    ") is out of range");
9358
                        }
9359
9360
                        // error condition (cf. RFC 6901, Sect. 4)
9361
                        if (reference_token.size() > 1 and reference_token[0] == '0')
9362
                        {
9363
                            throw std::domain_error("array index must not begin with '0'");
9364
                        }
9365
9366
                        // note: at performs range check
9367
                        ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
9368
                        break;
9369
                    }
9370
9371
                    default:
9372
                    {
9373
                        throw std::out_of_range("unresolved reference token '" + reference_token + "'");
9374
                    }
9375
                }
9376
            }
9377
9378
            return *ptr;
9379
        }
9380
9381
        /*!
9382
        @brief return a const reference to the pointed to value
9383
9384
        @param[in] ptr  a JSON value
9385
9386
        @return const reference to the JSON value pointed to by the JSON
9387
                pointer
9388
        */
9389
        const_reference get_unchecked(const_pointer ptr) const
9390
        {
9391
            for (const auto& reference_token : reference_tokens)
9392
            {
9393
                switch (ptr->m_type)
9394
                {
9395
                    case value_t::object:
9396
                    {
9397
                        // use unchecked object access
9398
                        ptr = &ptr->operator[](reference_token);
9399
                        break;
9400
                    }
9401
9402
                    case value_t::array:
9403
                    {
9404
                        if (reference_token == "-")
9405
                        {
9406
                            // "-" cannot be used for const access
9407
                            throw std::out_of_range("array index '-' (" +
9408
                                                    std::to_string(ptr->m_value.array->size()) +
9409
                                                    ") is out of range");
9410
                        }
9411
9412
                        // error condition (cf. RFC 6901, Sect. 4)
9413
                        if (reference_token.size() > 1 and reference_token[0] == '0')
9414
                        {
9415
                            throw std::domain_error("array index must not begin with '0'");
9416
                        }
9417
9418
                        // use unchecked array access
9419
                        ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token)));
9420
                        break;
9421
                    }
9422
9423
                    default:
9424
                    {
9425
                        throw std::out_of_range("unresolved reference token '" + reference_token + "'");
9426
                    }
9427
                }
9428
            }
9429
9430
            return *ptr;
9431
        }
9432
9433
        const_reference get_checked(const_pointer ptr) const
9434
        {
9435
            for (const auto& reference_token : reference_tokens)
9436
            {
9437
                switch (ptr->m_type)
9438
                {
9439
                    case value_t::object:
9440
                    {
9441
                        // note: at performs range check
9442
                        ptr = &ptr->at(reference_token);
9443
                        break;
9444
                    }
9445
9446
                    case value_t::array:
9447
                    {
9448
                        if (reference_token == "-")
9449
                        {
9450
                            // "-" always fails the range check
9451
                            throw std::out_of_range("array index '-' (" +
9452
                                                    std::to_string(ptr->m_value.array->size()) +
9453
                                                    ") is out of range");
9454
                        }
9455
9456
                        // error condition (cf. RFC 6901, Sect. 4)
9457
                        if (reference_token.size() > 1 and reference_token[0] == '0')
9458
                        {
9459
                            throw std::domain_error("array index must not begin with '0'");
9460
                        }
9461
9462
                        // note: at performs range check
9463
                        ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
9464
                        break;
9465
                    }
9466
9467
                    default:
9468
                    {
9469
                        throw std::out_of_range("unresolved reference token '" + reference_token + "'");
9470
                    }
9471
                }
9472
            }
9473
9474
            return *ptr;
9475
        }
9476
9477
        /// split the string input to reference tokens
9478
        static std::vector<std::string> split(std::string reference_string)
9479
        {
9480
            std::vector<std::string> result;
9481
9482
            // special case: empty reference string -> no reference tokens
9483
            if (reference_string.empty())
9484
            {
9485
                return result;
9486
            }
9487
9488
            // check if nonempty reference string begins with slash
9489
            if (reference_string[0] != '/')
9490
            {
9491
                throw std::domain_error("JSON pointer must be empty or begin with '/'");
9492
            }
9493
9494
            // extract the reference tokens:
9495
            // - slash: position of the last read slash (or end of string)
9496
            // - start: position after the previous slash
9497
            for (
9498
                // search for the first slash after the first character
9499
                size_t slash = reference_string.find_first_of("/", 1),
9500
                // set the beginning of the first reference token
9501
                start = 1;
9502
                // we can stop if start == string::npos+1 = 0
9503
                start != 0;
9504
                // set the beginning of the next reference token
9505
                // (will eventually be 0 if slash == std::string::npos)
9506
                start = slash + 1,
9507
                // find next slash
9508
                slash = reference_string.find_first_of("/", start))
9509
            {
9510
                // use the text between the beginning of the reference token
9511
                // (start) and the last slash (slash).
9512
                auto reference_token = reference_string.substr(start, slash - start);
9513
9514
                // check reference tokens are properly escaped
9515
                for (size_t pos = reference_token.find_first_of("~");
9516
                        pos != std::string::npos;
9517
                        pos = reference_token.find_first_of("~", pos + 1))
9518
                {
9519
                    assert(reference_token[pos] == '~');
9520
9521
                    // ~ must be followed by 0 or 1
9522
                    if (pos == reference_token.size() - 1 or
9523
                            (reference_token[pos + 1] != '0' and
9524
                             reference_token[pos + 1] != '1'))
9525
                    {
9526
                        throw std::domain_error("escape error: '~' must be followed with '0' or '1'");
9527
                    }
9528
                }
9529
9530
                // finally, store the reference token
9531
                unescape(reference_token);
9532
                result.push_back(reference_token);
9533
            }
9534
9535
            return result;
9536
        }
9537
9538
      private:
9539
        /*!
9540
        @brief replace all occurrences of a substring by another string
9541
9542
        @param[in,out] s  the string to manipulate
9543
        @param[in]     f  the substring to replace with @a t
9544
        @param[in]     t  the string to replace @a f
9545
9546
        @return The string @a s where all occurrences of @a f are replaced
9547
                with @a t.
9548
9549
        @pre The search string @a f must not be empty.
9550
9551
        @since version 2.0.0
9552
        */
9553
        static void replace_substring(std::string& s,
9554
                                      const std::string& f,
9555
                                      const std::string& t)
9556
        {
9557
            assert(not f.empty());
9558
9559
            for (
9560
                size_t pos = s.find(f);         // find first occurrence of f
9561
                pos != std::string::npos;       // make sure f was found
9562
                s.replace(pos, f.size(), t),    // replace with t
9563
                pos = s.find(f, pos + t.size()) // find next occurrence of f
9564
            );
9565
        }
9566
9567
        /// escape tilde and slash
9568
        static std::string escape(std::string s)
9569
        {
9570
            // escape "~"" to "~0" and "/" to "~1"
9571
            replace_substring(s, "~", "~0");
9572
            replace_substring(s, "/", "~1");
9573
            return s;
9574
        }
9575
9576
        /// unescape tilde and slash
9577
        static void unescape(std::string& s)
9578
        {
9579
            // first transform any occurrence of the sequence '~1' to '/'
9580
            replace_substring(s, "~1", "/");
9581
            // then transform any occurrence of the sequence '~0' to '~'
9582
            replace_substring(s, "~0", "~");
9583
        }
9584
9585
        /*!
9586
        @param[in] reference_string  the reference string to the current value
9587
        @param[in] value             the value to consider
9588
        @param[in,out] result        the result object to insert values to
9589
9590
        @note Empty objects or arrays are flattened to `null`.
9591
        */
9592
        static void flatten(const std::string& reference_string,
9593
                            const basic_json& value,
9594
                            basic_json& result)
9595
        {
9596
            switch (value.m_type)
9597
            {
9598
                case value_t::array:
9599
                {
9600
                    if (value.m_value.array->empty())
9601
                    {
9602
                        // flatten empty array as null
9603
                        result[reference_string] = nullptr;
9604
                    }
9605
                    else
9606
                    {
9607
                        // iterate array and use index as reference string
9608
                        for (size_t i = 0; i < value.m_value.array->size(); ++i)
9609
                        {
9610
                            flatten(reference_string + "/" + std::to_string(i),
9611
                                    value.m_value.array->operator[](i), result);
9612
                        }
9613
                    }
9614
                    break;
9615
                }
9616
9617
                case value_t::object:
9618
                {
9619
                    if (value.m_value.object->empty())
9620
                    {
9621
                        // flatten empty object as null
9622
                        result[reference_string] = nullptr;
9623
                    }
9624
                    else
9625
                    {
9626
                        // iterate object and use keys as reference string
9627
                        for (const auto& element : *value.m_value.object)
9628
                        {
9629
                            flatten(reference_string + "/" + escape(element.first),
9630
                                    element.second, result);
9631
                        }
9632
                    }
9633
                    break;
9634
                }
9635
9636
                default:
9637
                {
9638
                    // add primitive value with its reference string
9639
                    result[reference_string] = value;
9640
                    break;
9641
                }
9642
            }
9643
        }
9644
9645
        /*!
9646
        @param[in] value  flattened JSON
9647
9648
        @return unflattened JSON
9649
        */
9650
        static basic_json unflatten(const basic_json& value)
9651
        {
9652
            if (not value.is_object())
9653
            {
9654
                throw std::domain_error("only objects can be unflattened");
9655
            }
9656
9657
            basic_json result;
9658
9659
            // iterate the JSON object values
9660
            for (const auto& element : *value.m_value.object)
9661
            {
9662
                if (not element.second.is_primitive())
9663
                {
9664
                    throw std::domain_error("values in object must be primitive");
9665
                }
9666
9667
                // assign value to reference pointed to by JSON pointer; Note
9668
                // that if the JSON pointer is "" (i.e., points to the whole
9669
                // value), function get_and_create returns a reference to
9670
                // result itself. An assignment will then create a primitive
9671
                // value.
9672
                json_pointer(element.first).get_and_create(result) = element.second;
9673
            }
9674
9675
            return result;
9676
        }
9677
9678
      private:
9679
        /// the reference tokens
9680
        std::vector<std::string> reference_tokens {};
9681
    };
9682
9683
    //////////////////////////
9684
    // JSON Pointer support //
9685
    //////////////////////////
9686
9687
    /// @name JSON Pointer functions
9688
    /// @{
9689
9690
    /*!
9691
    @brief access specified element via JSON Pointer
9692
9693
    Uses a JSON pointer to retrieve a reference to the respective JSON value.
9694
    No bound checking is performed. Similar to @ref operator[](const typename
9695
    object_t::key_type&), `null` values are created in arrays and objects if
9696
    necessary.
9697
9698
    In particular:
9699
    - If the JSON pointer points to an object key that does not exist, it
9700
      is created an filled with a `null` value before a reference to it
9701
      is returned.
9702
    - If the JSON pointer points to an array index that does not exist, it
9703
      is created an filled with a `null` value before a reference to it
9704
      is returned. All indices between the current maximum and the given
9705
      index are also filled with `null`.
9706
    - The special value `-` is treated as a synonym for the index past the
9707
      end.
9708
9709
    @param[in] ptr  a JSON pointer
9710
9711
    @return reference to the element pointed to by @a ptr
9712
9713
    @complexity Constant.
9714
9715
    @throw std::out_of_range      if the JSON pointer can not be resolved
9716
    @throw std::domain_error      if an array index begins with '0'
9717
    @throw std::invalid_argument  if an array index was not a number
9718
9719
    @liveexample{The behavior is shown in the example.,operatorjson_pointer}
9720
9721
    @since version 2.0.0
9722
    */
9723
    reference operator[](const json_pointer& ptr)
9724
    {
9725
        return ptr.get_unchecked(this);
9726
    }
9727
9728
    /*!
9729
    @brief access specified element via JSON Pointer
9730
9731
    Uses a JSON pointer to retrieve a reference to the respective JSON value.
9732
    No bound checking is performed. The function does not change the JSON
9733
    value; no `null` values are created. In particular, the the special value
9734
    `-` yields an exception.
9735
9736
    @param[in] ptr  JSON pointer to the desired element
9737
9738
    @return const reference to the element pointed to by @a ptr
9739
9740
    @complexity Constant.
9741
9742
    @throw std::out_of_range      if the JSON pointer can not be resolved
9743
    @throw std::domain_error      if an array index begins with '0'
9744
    @throw std::invalid_argument  if an array index was not a number
9745
9746
    @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
9747
9748
    @since version 2.0.0
9749
    */
9750
    const_reference operator[](const json_pointer& ptr) const
9751
    {
9752
        return ptr.get_unchecked(this);
9753
    }
9754
9755
    /*!
9756
    @brief access specified element via JSON Pointer
9757
9758
    Returns a reference to the element at with specified JSON pointer @a ptr,
9759
    with bounds checking.
9760
9761
    @param[in] ptr  JSON pointer to the desired element
9762
9763
    @return reference to the element pointed to by @a ptr
9764
9765
    @complexity Constant.
9766
9767
    @throw std::out_of_range      if the JSON pointer can not be resolved
9768
    @throw std::domain_error      if an array index begins with '0'
9769
    @throw std::invalid_argument  if an array index was not a number
9770
9771
    @liveexample{The behavior is shown in the example.,at_json_pointer}
9772
9773
    @since version 2.0.0
9774
    */
9775
    reference at(const json_pointer& ptr)
9776
    {
9777
        return ptr.get_checked(this);
9778
    }
9779
9780
    /*!
9781
    @brief access specified element via JSON Pointer
9782
9783
    Returns a const reference to the element at with specified JSON pointer @a
9784
    ptr, with bounds checking.
9785
9786
    @param[in] ptr  JSON pointer to the desired element
9787
9788
    @return reference to the element pointed to by @a ptr
9789
9790
    @complexity Constant.
9791
9792
    @throw std::out_of_range      if the JSON pointer can not be resolved
9793
    @throw std::domain_error      if an array index begins with '0'
9794
    @throw std::invalid_argument  if an array index was not a number
9795
9796
    @liveexample{The behavior is shown in the example.,at_json_pointer_const}
9797
9798
    @since version 2.0.0
9799
    */
9800
    const_reference at(const json_pointer& ptr) const
9801
    {
9802
        return ptr.get_checked(this);
9803
    }
9804
9805
    /*!
9806
    @brief return flattened JSON value
9807
9808
    The function creates a JSON object whose keys are JSON pointers (see [RFC
9809
    6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
9810
    primitive. The original JSON value can be restored using the @ref
9811
    unflatten() function.
9812
9813
    @return an object that maps JSON pointers to primitve values
9814
9815
    @note Empty objects and arrays are flattened to `null` and will not be
9816
          reconstructed correctly by the @ref unflatten() function.
9817
9818
    @complexity Linear in the size the JSON value.
9819
9820
    @liveexample{The following code shows how a JSON object is flattened to an
9821
    object whose keys consist of JSON pointers.,flatten}
9822
9823
    @sa @ref unflatten() for the reverse function
9824
9825
    @since version 2.0.0
9826
    */
9827
    basic_json flatten() const
9828
    {
9829
        basic_json result(value_t::object);
9830
        json_pointer::flatten("", *this, result);
9831
        return result;
9832
    }
9833
9834
    /*!
9835
    @brief unflatten a previously flattened JSON value
9836
9837
    The function restores the arbitrary nesting of a JSON value that has been
9838
    flattened before using the @ref flatten() function. The JSON value must
9839
    meet certain constraints:
9840
    1. The value must be an object.
9841
    2. The keys must be JSON pointers (see
9842
       [RFC 6901](https://tools.ietf.org/html/rfc6901))
9843
    3. The mapped values must be primitive JSON types.
9844
9845
    @return the original JSON from a flattened version
9846
9847
    @note Empty objects and arrays are flattened by @ref flatten() to `null`
9848
          values and can not unflattened to their original type. Apart from
9849
          this example, for a JSON value `j`, the following is always true:
9850
          `j == j.flatten().unflatten()`.
9851
9852
    @complexity Linear in the size the JSON value.
9853
9854
    @liveexample{The following code shows how a flattened JSON object is
9855
    unflattened into the original nested JSON object.,unflatten}
9856
9857
    @sa @ref flatten() for the reverse function
9858
9859
    @since version 2.0.0
9860
    */
9861
    basic_json unflatten() const
9862
    {
9863
        return json_pointer::unflatten(*this);
9864
    }
9865
9866
    /// @}
9867
9868
    //////////////////////////
9869
    // JSON Patch functions //
9870
    //////////////////////////
9871
9872
    /// @name JSON Patch functions
9873
    /// @{
9874
9875
    /*!
9876
    @brief applies a JSON patch
9877
9878
    [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
9879
    expressing a sequence of operations to apply to a JSON) document. With
9880
    this funcion, a JSON Patch is applied to the current JSON value by
9881
    executing all operations from the patch.
9882
9883
    @param[in] json_patch  JSON patch document
9884
    @return patched document
9885
9886
    @note The application of a patch is atomic: Either all operations succeed
9887
          and the patched document is returned or an exception is thrown. In
9888
          any case, the original value is not changed: the patch is applied
9889
          to a copy of the value.
9890
9891
    @throw std::out_of_range if a JSON pointer inside the patch could not
9892
    be resolved successfully in the current JSON value; example: `"key baz
9893
    not found"`
9894
    @throw invalid_argument if the JSON patch is malformed (e.g., mandatory
9895
    attributes are missing); example: `"operation add must have member path"`
9896
9897
    @complexity Linear in the size of the JSON value and the length of the
9898
    JSON patch. As usually only a fraction of the JSON value is affected by
9899
    the patch, the complexity can usually be neglected.
9900
9901
    @liveexample{The following code shows how a JSON patch is applied to a
9902
    value.,patch}
9903
9904
    @sa @ref diff -- create a JSON patch by comparing two JSON values
9905
9906
    @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
9907
    @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
9908
9909
    @since version 2.0.0
9910
    */
9911
    basic_json patch(const basic_json& json_patch) const
9912
    {
9913
        // make a working copy to apply the patch to
9914
        basic_json result = *this;
9915
9916
        // the valid JSON Patch operations
9917
        enum class patch_operations {add, remove, replace, move, copy, test, invalid};
9918
9919
        const auto get_op = [](const std::string op)
9920
        {
9921
            if (op == "add")
9922
            {
9923
                return patch_operations::add;
9924
            }
9925
            if (op == "remove")
9926
            {
9927
                return patch_operations::remove;
9928
            }
9929
            if (op == "replace")
9930
            {
9931
                return patch_operations::replace;
9932
            }
9933
            if (op == "move")
9934
            {
9935
                return patch_operations::move;
9936
            }
9937
            if (op == "copy")
9938
            {
9939
                return patch_operations::copy;
9940
            }
9941
            if (op == "test")
9942
            {
9943
                return patch_operations::test;
9944
            }
9945
9946
            return patch_operations::invalid;
9947
        };
9948
9949
        // wrapper for "add" operation; add value at ptr
9950
        const auto operation_add = [&result](json_pointer & ptr, basic_json val)
9951
        {
9952
            // adding to the root of the target document means replacing it
9953
            if (ptr.is_root())
9954
            {
9955
                result = val;
9956
            }
9957
            else
9958
            {
9959
                // make sure the top element of the pointer exists
9960
                json_pointer top_pointer = ptr.top();
9961
                if (top_pointer != ptr)
9962
                {
9963
                    basic_json& x = result.at(top_pointer);
9964
                }
9965
9966
                // get reference to parent of JSON pointer ptr
9967
                const auto last_path = ptr.pop_back();
9968
                basic_json& parent = result[ptr];
9969
9970
                switch (parent.m_type)
9971
                {
9972
                    case value_t::null:
9973
                    case value_t::object:
9974
                    {
9975
                        // use operator[] to add value
9976
                        parent[last_path] = val;
9977
                        break;
9978
                    }
9979
9980
                    case value_t::array:
9981
                    {
9982
                        if (last_path == "-")
9983
                        {
9984
                            // special case: append to back
9985
                            parent.push_back(val);
9986
                        }
9987
                        else
9988
                        {
9989
                            const auto idx = std::stoi(last_path);
9990
                            if (static_cast<size_type>(idx) > parent.size())
9991
                            {
9992
                                // avoid undefined behavior
9993
                                throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
9994
                            }
9995
                            else
9996
                            {
9997
                                // default case: insert add offset
9998
                                parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
9999
                            }
10000
                        }
10001
                        break;
10002
                    }
10003
10004
                    default:
10005
                    {
10006
                        // if there exists a parent it cannot be primitive
10007
                        assert(false);  // LCOV_EXCL_LINE
10008
                    }
10009
                }
10010
            }
10011
        };
10012
10013
        // wrapper for "remove" operation; remove value at ptr
10014
        const auto operation_remove = [&result](json_pointer & ptr)
10015
        {
10016
            // get reference to parent of JSON pointer ptr
10017
            const auto last_path = ptr.pop_back();
10018
            basic_json& parent = result.at(ptr);
10019
10020
            // remove child
10021
            if (parent.is_object())
10022
            {
10023
                // perform range check
10024
                auto it = parent.find(last_path);
10025
                if (it != parent.end())
10026
                {
10027
                    parent.erase(it);
10028
                }
10029
                else
10030
                {
10031
                    throw std::out_of_range("key '" + last_path + "' not found");
10032
                }
10033
            }
10034
            else if (parent.is_array())
10035
            {
10036
                // note erase performs range check
10037
                parent.erase(static_cast<size_type>(std::stoi(last_path)));
10038
            }
10039
        };
10040
10041
        // type check
10042
        if (not json_patch.is_array())
10043
        {
10044
            // a JSON patch must be an array of objects
10045
            throw std::invalid_argument("JSON patch must be an array of objects");
10046
        }
10047
10048
        // iterate and apply th eoperations
10049
        for (const auto& val : json_patch)
10050
        {
10051
            // wrapper to get a value for an operation
10052
            const auto get_value = [&val](const std::string & op,
10053
                                          const std::string & member,
10054
                                          bool string_type) -> basic_json&
10055
            {
10056
                // find value
10057
                auto it = val.m_value.object->find(member);
10058
10059
                // context-sensitive error message
10060
                const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
10061
10062
                // check if desired value is present
10063
                if (it == val.m_value.object->end())
10064
                {
10065
                    throw std::invalid_argument(error_msg + " must have member '" + member + "'");
10066
                }
10067
10068
                // check if result is of type string
10069
                if (string_type and not it->second.is_string())
10070
                {
10071
                    throw std::invalid_argument(error_msg + " must have string member '" + member + "'");
10072
                }
10073
10074
                // no error: return value
10075
                return it->second;
10076
            };
10077
10078
            // type check
10079
            if (not val.is_object())
10080
            {
10081
                throw std::invalid_argument("JSON patch must be an array of objects");
10082
            }
10083
10084
            // collect mandatory members
10085
            const std::string op = get_value("op", "op", true);
10086
            const std::string path = get_value(op, "path", true);
10087
            json_pointer ptr(path);
10088
10089
            switch (get_op(op))
10090
            {
10091
                case patch_operations::add:
10092
                {
10093
                    operation_add(ptr, get_value("add", "value", false));
10094
                    break;
10095
                }
10096
10097
                case patch_operations::remove:
10098
                {
10099
                    operation_remove(ptr);
10100
                    break;
10101
                }
10102
10103
                case patch_operations::replace:
10104
                {
10105
                    // the "path" location must exist - use at()
10106
                    result.at(ptr) = get_value("replace", "value", false);
10107
                    break;
10108
                }
10109
10110
                case patch_operations::move:
10111
                {
10112
                    const std::string from_path = get_value("move", "from", true);
10113
                    json_pointer from_ptr(from_path);
10114
10115
                    // the "from" location must exist - use at()
10116
                    basic_json v = result.at(from_ptr);
10117
10118
                    // The move operation is functionally identical to a
10119
                    // "remove" operation on the "from" location, followed
10120
                    // immediately by an "add" operation at the target
10121
                    // location with the value that was just removed.
10122
                    operation_remove(from_ptr);
10123
                    operation_add(ptr, v);
10124
                    break;
10125
                }
10126
10127
                case patch_operations::copy:
10128
                {
10129
                    const std::string from_path = get_value("copy", "from", true);;
10130
                    const json_pointer from_ptr(from_path);
10131
10132
                    // the "from" location must exist - use at()
10133
                    result[ptr] = result.at(from_ptr);
10134
                    break;
10135
                }
10136
10137
                case patch_operations::test:
10138
                {
10139
                    bool success = false;
10140
                    try
10141
                    {
10142
                        // check if "value" matches the one at "path"
10143
                        // the "path" location must exist - use at()
10144
                        success = (result.at(ptr) == get_value("test", "value", false));
10145
                    }
10146
                    catch (std::out_of_range&)
10147
                    {
10148
                        // ignore out of range errors: success remains false
10149
                    }
10150
10151
                    // throw an exception if test fails
10152
                    if (not success)
10153
                    {
10154
                        throw std::domain_error("unsuccessful: " + val.dump());
10155
                    }
10156
10157
                    break;
10158
                }
10159
10160
                case patch_operations::invalid:
10161
                {
10162
                    // op must be "add", "remove", "replace", "move", "copy", or
10163
                    // "test"
10164
                    throw std::invalid_argument("operation value '" + op + "' is invalid");
10165
                }
10166
            }
10167
        }
10168
10169
        return result;
10170
    }
10171
10172
    /*!
10173
    @brief creates a diff as a JSON patch
10174
10175
    Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
10176
    be changed into the value @a target by calling @ref patch function.
10177
10178
    @invariant For two JSON values @a source and @a target, the following code
10179
    yields always `true`:
10180
    @code {.cpp}
10181
    source.patch(diff(source, target)) == target;
10182
    @endcode
10183
10184
    @note Currently, only `remove`, `add`, and `replace` operations are
10185
          generated.
10186
10187
    @param[in] source  JSON value to copare from
10188
    @param[in] target  JSON value to copare against
10189
    @param[in] path    helper value to create JSON pointers
10190
10191
    @return a JSON patch to convert the @a source to @a target
10192
10193
    @complexity Linear in the lengths of @a source and @a target.
10194
10195
    @liveexample{The following code shows how a JSON patch is created as a
10196
    diff for two JSON values.,diff}
10197
10198
    @sa @ref patch -- apply a JSON patch
10199
10200
    @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
10201
10202
    @since version 2.0.0
10203
    */
10204
    static basic_json diff(const basic_json& source,
10205
                           const basic_json& target,
10206
                           std::string path = "")
10207
    {
10208
        // the patch
10209
        basic_json result(value_t::array);
10210
10211
        // if the values are the same, return empty patch
10212
        if (source == target)
10213
        {
10214
            return result;
10215
        }
10216
10217
        if (source.type() != target.type())
10218
        {
10219
            // different types: replace value
10220
            result.push_back(
10221
            {
10222
                {"op", "replace"},
10223
                {"path", path},
10224
                {"value", target}
10225
            });
10226
        }
10227
        else
10228
        {
10229
            switch (source.type())
10230
            {
10231
                case value_t::array:
10232
                {
10233
                    // first pass: traverse common elements
10234
                    size_t i = 0;
10235
                    while (i < source.size() and i < target.size())
10236
                    {
10237
                        // recursive call to compare array values at index i
10238
                        auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
10239
                        result.insert(result.end(), temp_diff.begin(), temp_diff.end());
10240
                        ++i;
10241
                    }
10242
10243
                    // i now reached the end of at least one array
10244
                    // in a second pass, traverse the remaining elements
10245
10246
                    // remove my remaining elements
10247
                    const auto end_index = static_cast<difference_type>(result.size());
10248
                    while (i < source.size())
10249
                    {
10250
                        // add operations in reverse order to avoid invalid
10251
                        // indices
10252
                        result.insert(result.begin() + end_index, object(
10253
                        {
10254
                            {"op", "remove"},
10255
                            {"path", path + "/" + std::to_string(i)}
10256
                        }));
10257
                        ++i;
10258
                    }
10259
10260
                    // add other remaining elements
10261
                    while (i < target.size())
10262
                    {
10263
                        result.push_back(
10264
                        {
10265
                            {"op", "add"},
10266
                            {"path", path + "/" + std::to_string(i)},
10267
                            {"value", target[i]}
10268
                        });
10269
                        ++i;
10270
                    }
10271
10272
                    break;
10273
                }
10274
10275
                case value_t::object:
10276
                {
10277
                    // first pass: traverse this object's elements
10278
                    for (auto it = source.begin(); it != source.end(); ++it)
10279
                    {
10280
                        // escape the key name to be used in a JSON patch
10281
                        const auto key = json_pointer::escape(it.key());
10282
10283
                        if (target.find(it.key()) != target.end())
10284
                        {
10285
                            // recursive call to compare object values at key it
10286
                            auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
10287
                            result.insert(result.end(), temp_diff.begin(), temp_diff.end());
10288
                        }
10289
                        else
10290
                        {
10291
                            // found a key that is not in o -> remove it
10292
                            result.push_back(object(
10293
                            {
10294
                                {"op", "remove"},
10295
                                {"path", path + "/" + key}
10296
                            }));
10297
                        }
10298
                    }
10299
10300
                    // second pass: traverse other object's elements
10301
                    for (auto it = target.begin(); it != target.end(); ++it)
10302
                    {
10303
                        if (source.find(it.key()) == source.end())
10304
                        {
10305
                            // found a key that is not in this -> add it
10306
                            const auto key = json_pointer::escape(it.key());
10307
                            result.push_back(
10308
                            {
10309
                                {"op", "add"},
10310
                                {"path", path + "/" + key},
10311
                                {"value", it.value()}
10312
                            });
10313
                        }
10314
                    }
10315
10316
                    break;
10317
                }
10318
10319
                default:
10320
                {
10321
                    // both primitive type: replace value
10322
                    result.push_back(
10323
                    {
10324
                        {"op", "replace"},
10325
                        {"path", path},
10326
                        {"value", target}
10327
                    });
10328
                    break;
10329
                }
10330
            }
10331
        }
10332
10333
        return result;
10334
    }
10335
10336
    /// @}
10337
};
10338
10339
10340
/////////////
10341
// presets //
10342
/////////////
10343
10344
/*!
10345
@brief default JSON class
10346
10347
This type is the default specialization of the @ref basic_json class which
10348
uses the standard template types.
10349
10350
@since version 1.0.0
10351
*/
10352
using json = basic_json<>;
10353
}
10354
10355
10356
///////////////////////
10357
// nonmember support //
10358
///////////////////////
10359
10360
// specialization of std::swap, and std::hash
10361
namespace std
10362
{
10363
/*!
10364
@brief exchanges the values of two JSON objects
10365
10366
@since version 1.0.0
10367
*/
10368
template <>
10369
inline void swap(nlohmann::json& j1,
10370
                 nlohmann::json& j2) noexcept(
10371
                     is_nothrow_move_constructible<nlohmann::json>::value and
10372
                     is_nothrow_move_assignable<nlohmann::json>::value
10373
                 )
10374
{
10375
    j1.swap(j2);
10376
}
10377
10378
/// hash value for JSON objects
10379
template <>
10380
struct hash<nlohmann::json>
10381
{
10382
    /*!
10383
    @brief return a hash value for a JSON object
10384
10385
    @since version 1.0.0
10386
    */
10387
    std::size_t operator()(const nlohmann::json& j) const
10388
    {
10389
        // a naive hashing via the string representation
10390
        const auto& h = hash<nlohmann::json::string_t>();
10391
        return h(j.dump());
10392
    }
10393
};
10394
}
10395
10396
/*!
10397
@brief user-defined string literal for JSON values
10398
10399
This operator implements a user-defined string literal for JSON objects. It
10400
can be used by adding `"_json"` to a string literal and returns a JSON object
10401
if no parse error occurred.
10402
10403
@param[in] s  a string representation of a JSON object
10404
@return a JSON object
10405
10406
@since version 1.0.0
10407
*/
10408
inline nlohmann::json operator "" _json(const char* s, std::size_t)
10409
{
10410
    return nlohmann::json::parse(reinterpret_cast<const nlohmann::json::string_t::value_type*>(s));
10411
}
10412
10413
/*!
10414
@brief user-defined string literal for JSON pointer
10415
10416
This operator implements a user-defined string literal for JSON Pointers. It
10417
can be used by adding `"_json"` to a string literal and returns a JSON pointer
10418
object if no parse error occurred.
10419
10420
@param[in] s  a string representation of a JSON Pointer
10421
@return a JSON pointer object
10422
10423
@since version 2.0.0
10424
*/
10425
inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t)
10426
{
10427
    return nlohmann::json::json_pointer(s);
10428
}
10429
10430
// restore GCC/clang diagnostic settings
10431
#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
10432
    #pragma GCC diagnostic pop
10433
#endif
10434
10435
#endif